Socket
Socket
Sign inDemoInstall

shiki-twoslash

Package Overview
Dependencies
Maintainers
1
Versions
46
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

shiki-twoslash - npm Package Compare versions

Comparing version 0.6.2 to 0.7.0

dist/renderers/plain.d.ts

2

dist/dom.js

@@ -58,3 +58,3 @@ "use strict";

// prettier-ignore
var twoslashes = document.querySelectorAll(".shiki.twoslash .code-container code");
var twoslashes = document.querySelectorAll(".shiki.lsp .code-container code");
// Gets triggered on the spans inside the codeblocks

@@ -61,0 +61,0 @@ var hover = function (event) {

import { Highlighter } from "shiki/dist/highlighter";
import { TwoSlashOptions, TwoSlashReturn } from "@typescript/twoslash";
import { twoslashRenderer } from "./renderers/twoslash";
import { plainTextRenderer } from "./renderers/plain";
import { defaultShikiRenderer } from "./renderers/shiki";
import { tsconfigJSONRenderer } from "./renderers/tsconfig";
export declare type ShikiTwoslashSettings = {

@@ -16,9 +20,26 @@ useNodeModules?: true;

*/
export declare const createShikiHighlighter: (options: import("shiki/dist/highlighter").HighlighterOptions) => Highlighter | Promise<Highlighter>;
export declare const defaultShikiTwoslashSettings: ShikiTwoslashSettings;
/** Uses Shiki to render the code to HTML */
export declare const renderCodeToHTML: (code: string, lang: string, highlighter?: Highlighter | undefined, twoslash?: TwoSlashReturn | undefined) => string;
export declare const createShikiHighlighter: (options: import("shiki/dist/highlighter").HighlighterOptions) => Promise<Highlighter>;
/**
* Renders a code sample to HTML, automatically taking into account:
*
* - rendering overrides for twoslash and tsconfig
* - whether the language exists in shiki
*
* @param code the source code to render
* @param lang the language to use in highlighting
* @param info additional metadata which lives after the codefence lang (e.g. ["twoslash"])
* @param highlighter optional, but you should use it, highlighter
* @param twoslash optional, but required when info contains 'twoslash' as a string
*/
export declare const renderCodeToHTML: (code: string, lang: string, info: string[], shikiOptions?: import("shiki/dist/renderer").HtmlRendererOptions | undefined, highlighter?: Highlighter | undefined, twoslash?: TwoSlashReturn | undefined) => string;
/**
* Runs Twoslash over the code passed in with a particular language as the default file.
*/
export declare const runTwoSlash: (code: string, lang: string, settings?: ShikiTwoslashSettings, twoslashDefaults?: TwoSlashOptions) => TwoSlashReturn;
/** Set of renderers if you want to explicitly call one instead of using renderCodeToHTML */
export declare const renderers: {
plainTextRenderer: typeof plainTextRenderer;
defaultShikiRenderer: typeof defaultShikiRenderer;
twoslashRenderer: typeof twoslashRenderer;
tsconfigJSONRenderer: typeof tsconfigJSONRenderer;
};

@@ -99,4 +99,6 @@ 'use strict';

}
function escapeHtml(html) {
return html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
// This started as a JS port of https://github.com/octref/shiki/blob/master/packages/shiki/src/renderer.ts
// What we're trying to do is merge two sets of information into a single tree for HTML

@@ -114,11 +116,5 @@ // 1: Syntax highlight info from shiki

function renderToHTML(lines, options, twoslash) {
// It's a NOOP for us with twoslash, this is basically all
// the other languages
if (!twoslash) {
return plainOleShikiRenderer(lines, options);
}
function twoslashRenderer(lines, options, twoslash) {
var html = "";
html += "<pre class=\"shiki twoslash\">";
html += "<pre class=\"shiki twoslash lsp\">";

@@ -257,9 +253,4 @@ if (options.langId) {

}
function escapeHtml(html) {
return html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
/** Returns a map where all the keys are the value in keyGetter */
function groupBy(list, keyGetter) {

@@ -280,3 +271,5 @@ var map = new Map();

function plainOleShikiRenderer(lines, options) {
/** You don't have a language which shiki twoslash can handle, make a DOM compatible version */
function plainTextRenderer(code, options) {
var html = "";

@@ -290,2 +283,18 @@ html += "<pre class=\"shiki\">";

html += "<div class='code-container'><code>";
html += escapeHtml(code);
html = html.replace(/\n*$/, ""); // Get rid of final new lines
html += "</code></div></pre>";
return html;
}
function defaultShikiRenderer(lines, options) {
var html = "";
html += "<pre class=\"shiki\">";
if (options.langId) {
html += "<div class=\"language-id\">" + options.langId + "</div>";
}
html += "<div class='code-container'><code>";
lines.forEach(function (l) {

@@ -307,2 +316,166 @@ if (l.length === 0) {

var tsconfig = {
compilerOptions: "The set of compiler options for your project",
allowJs: "Let TS include .JS files in imports",
allowSyntheticDefaultImports: "Allow 'import x from y' when a module doesn't have a default export",
allowUmdGlobalAccess: "Assume UMD imports are all globally available",
allowUnreachableCode: "Error when code will never be called",
allowUnusedLabels: "Error when accidentally creating a label",
alwaysStrict: "Ensure 'use strict' is always emitted",
assumeChangesOnlyAffectDirectDependencies: "A drastically faster, but occasionally inaccurate watch mode option.",
baseUrl: "Set a baseurl for relative module names",
charset: "Manually set the text encoding for reading files",
checkJs: "Run the type checker on .js files in your project",
composite: "Used to create multiple build projects",
declaration: "Emit d.ts files for referenced files in the project",
declarationDir: "Set the root directory for d.ts files to go",
declarationMap: "Create sourcemaps for d.ts files",
diagnostics: "Output additional information after a compile",
disableReferencedProjectLoad: "Reduces the number of projects loaded automatically by TypeScript",
disableSizeLimit: "Remove the memory cap on the TypeScript language server",
disableSolutionSearching: " Opt a project out of multi-project reference checking",
disableSourceOfProjectReferenceRedirect: "Use d.ts files as the source of truth for tooling between composite project boundries",
downlevelIteration: "Emit more compliant, but verbose JavaScript for iterating objects",
emitBOM: "Include a byte order mark to output files",
emitDeclarationOnly: "Only output d.ts files and not .js files",
emitDecoratorMetadata: "Adds additional type metadata to decorators in emitted code",
esModuleInterop: "Emit additional JS to ease support for importing commonjs modules",
exclude: "Files or patterns to be skipped from the include option",
experimentalDecorators: "Enable experimental support for TC39 stage 2 decorators",
extendedDiagnostics: "Include a lot of diagnostic information after a compile",
"extends": "Inherit options for a TSConfig",
fallbackPolling: "What the watcher should use if the system runs out of native file watchers",
files: "Include a set list of files, does not support globs",
forceConsistentCasingInFileNames: "Ensure that casing is correct in imports",
generateCpuProfile: "Emit a v8 CPU profile of the compiler run for debugging",
importHelpers: "Allow importing helper functions once per project, instead of including them per-file",
importsNotUsedAsValues: "Controls which syntax you use for importing types",
include: "Files or patterns to include in this project",
incremental: "Save .tsbuildinfo files to allow for incremental compilation of projects",
inlineSourceMap: "Include sourcemap files inside the emitted JavaScript",
inlineSources: "Include sourcemap files inside the emitted JavaScript",
isolatedModules: "Ensure that each file can be safely transpiled without relying on other imports",
jsx: "Control how JSX is emitted",
jsxFactory: "Control the function emitted by JSX",
jsxFragmentFactory: "Specifies what identifiers a JSX fragment should be transformed to",
keyofStringsOnly: "Make keyof only return strings instead of string or numbers",
lib: "Include type definitions you know are available in your JavaScript runtime",
listEmittedFiles: "Print the names of emitted files after a compile",
listFiles: "Print all of the files read during the compilation",
locale: "Set the language of the tsc output",
mapRoot: "Set an external root for sourcemaps",
maxNodeModuleJsDepth: "How deep should TypeScript run type checking in node_modules",
module: "Sets the expected module system for your runtime",
moduleResolution: "Allow TypeScript 1.6 module resolution strategies",
newLine: "Set the newline character",
noEmit: "Do not emit files from a compilation",
noEmitHelpers: "Assume helpers are available in the global runtime",
noEmitOnError: "Only emit files on a successful compile",
noErrorTruncation: "Do not truncate error messages",
noFallthroughCasesInSwitch: "Report errors for fallthrough cases in switch statements.",
noImplicitAny: "Avoid introducing anys inside your codebase when a type could be specified",
noImplicitReturns: "Ensure that all codepaths return in a function",
noImplicitThis: "Raise errors when 'this' would be any",
noImplicitUseStrict: "Disable 'use strict' in the JS emit",
noLib: "Ignore options from lib",
noResolve: "Skip ahead-of-time checking for import and <reference files",
noStrictGenericChecks: "Disable strict checking of generic signatures in functions.",
noUnusedLocals: "Error when a local variable isn't read",
noUnusedParameters: "Error when a parameter isn't used",
out: "Do not use this",
outDir: "Set an output folder for all emitted files",
outFile: "Output a single file of all JS files concatenated",
paths: "A set of locations to look for imports in",
plugins: "A list of language service plugins to include",
preserveConstEnums: "Do not erase `const enum` declarations in generated code",
preserveSymlinks: "Do not resolve symlink paths",
preserveWatchOutput: "Do not wipe the console in watch mode",
pretty: "Use color and formatting to make compiler errors easier to read",
reactNamespace: "Specify the object which 'createElement' is called on in JSX",
references: "Provide a structure for composite projects",
removeComments: "Remove comments in TypeScript from appearing in JavaScript",
resolveJsonModule: "Allow importing .json files",
rootDir: "Sets the root folder within your source files",
rootDirs: "Set multiple root directories",
skipDefaultLibCheck: "use SkipLibCheck instead",
skipLibCheck: "Skip type checking of declaration files",
sourceMap: "Creates source map files for emitted JavaScript files",
sourceRoot: "Sets the root path for debuggers to find the reference source code",
strict: "Enable TypeScript's most in-depth type checking rules",
strictBindCallApply: "Ensure that 'call', 'bind' and 'apply' have the right arguments",
strictFunctionTypes: "Ensure that function parameters are consistent",
strictNullChecks: "Ensure that nullability is respected in the type checker",
strictPropertyInitialization: "Ensure that all class properties match their types after the constructor has finished",
stripInternal: "Remove declarations which have '@internal' in their JSDoc comments",
suppressExcessPropertyErrors: "Allow additional properties being set during creation of types",
suppressImplicitAnyIndexErrors: "Remove the warning when using string indexes to access unknown properties",
target: "Set the supported JavaScript language runtime to transpile to",
traceResolution: "Log out paths when resolving all modules",
tsBuildInfoFile: "Set the folder for .tsbuildinfo files",
typeAcquisition: "Sets of options for Automatic Type Acquisition in JavaScript",
typeRoots: "locations where TypeScript should look for type definitions",
types: "Used to create an allowlist of types to be included in the compile",
useDefineForClassFields: "Use define characteristics for handling class fields",
watchDirectory: "Determine how directories are watched",
watchFile: "What technique should the watcher use"
};
/** Uses tmLanguage scopes to determine what the content of the token is */
var tokenIsJSONKey = function tokenIsJSONKey(token) {
if (!token.explanation) return false;
return token.explanation.find(function (e) {
return e.scopes.find(function (s) {
return s.scopeName.includes("support.type.property-name");
});
});
};
/** Can you look up the token in the tsconfig reference? */
var isKeyInTSConfig = function isKeyInTSConfig(token) {
if (token.content === '"') return;
var name = token.content.slice(1, token.content.length - 1);
return name in tsconfig;
};
/**
* Renders a TSConfig JSON object with additional LSP-ish information
* @param lines the result of shiki highlighting
* @param options shiki display options
*/
function tsconfigJSONRenderer(lines, options) {
var html = "";
html += "<pre class=\"shiki tsconfig lsp\">";
if (options.langId) {
html += "<div class=\"language-id\">" + options.langId + "</div>";
}
html += "<div class='code-container'><code>";
lines.forEach(function (l) {
if (l.length === 0) {
html += "\n";
} else {
l.forEach(function (token) {
// This means we're looking at a token which could be '"module"', '"', '"compilerOptions"' etc
if (tokenIsJSONKey(token) && isKeyInTSConfig(token)) {
var key = token.content.slice(1, token.content.length - 1);
var oneliner = tsconfig[key]; // prettier-ignore
html += "<span style=\"color: " + token.color + "\">\"<a aria-hidden=true href='https://www.typescriptlang.org/tsconfig#" + key + "'><data-lsp lsp=\"" + oneliner + "\">" + escapeHtml(key) + "</data-lsp></a>\"</span>";
} else {
html += "<span style=\"color: " + token.color + "\">" + escapeHtml(token.content) + "</span>";
}
});
html += "\n";
}
});
html = html.replace(/\n*$/, ""); // Get rid of final new lines
html += "</code></div></pre>";
return html;
}
var languages =

@@ -332,3 +505,3 @@ /*#__PURE__*/

var createShikiHighlighter = function createShikiHighlighter(options) {
if (storedHighlighter) return storedHighlighter;
if (storedHighlighter) return Promise.resolve(storedHighlighter);
var settings = options || {};

@@ -356,16 +529,42 @@ var theme = settings.theme || "nord";

};
var defaultShikiTwoslashSettings = {};
/** Uses Shiki to render the code to HTML */
/**
* Renders a code sample to HTML, automatically taking into account:
*
* - rendering overrides for twoslash and tsconfig
* - whether the language exists in shiki
*
* @param code the source code to render
* @param lang the language to use in highlighting
* @param info additional metadata which lives after the codefence lang (e.g. ["twoslash"])
* @param highlighter optional, but you should use it, highlighter
* @param twoslash optional, but required when info contains 'twoslash' as a string
*/
var renderCodeToHTML = function renderCodeToHTML(code, lang, highlighter, twoslash) {
var renderCodeToHTML = function renderCodeToHTML(code, lang, info, shikiOptions, highlighter, twoslash) {
if (!highlighter && !storedHighlighter) {
throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");
}
} // Shiki doesn't know this lang
if (!canHighlightLang(lang)) {
return plainTextRenderer(code, shikiOptions || {});
} // Shiki does know the lang, so tokenize
var renderHighlighter = highlighter || storedHighlighter;
var tokens = renderHighlighter.codeToThemedTokens(code, lang);
var results = renderToHTML(tokens, {
var tokens = renderHighlighter.codeToThemedTokens(code, lang); // Twoslash specific renderer
if (info.includes("twoslash") && twoslash) {
return twoslashRenderer(tokens, shikiOptions || {}, twoslash);
} // TSConfig renderer
if (lang === "json" && info.includes("tsconfig")) {
return tsconfigJSONRenderer(tokens, shikiOptions || {});
} // Otherwise just the normal shiki renderer
return defaultShikiRenderer(tokens, {
langId: lang
}, twoslash);
return results;
});
}; // Basically so that we can store this once, then re-use it in the same process

@@ -380,3 +579,3 @@

if (settings === void 0) {
settings = defaultShikiTwoslashSettings;
settings = {};
}

@@ -420,8 +619,16 @@

};
/** Set of renderers if you want to explicitly call one instead of using renderCodeToHTML */
var renderers = {
plainTextRenderer: plainTextRenderer,
defaultShikiRenderer: defaultShikiRenderer,
twoslashRenderer: twoslashRenderer,
tsconfigJSONRenderer: tsconfigJSONRenderer
};
exports.canHighlightLang = canHighlightLang;
exports.createShikiHighlighter = createShikiHighlighter;
exports.defaultShikiTwoslashSettings = defaultShikiTwoslashSettings;
exports.renderCodeToHTML = renderCodeToHTML;
exports.renderers = renderers;
exports.runTwoSlash = runTwoSlash;
//# sourceMappingURL=shiki-twoslash.cjs.development.js.map

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),n=require("shiki-languages"),t=require("@typescript/twoslash"),r=require("@typescript/vfs");function a(){return(a=Object.assign||function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e}).apply(this,arguments)}function s(e){var n={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+n[e]+";"}))}function o(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function i(e,n){var t=new Map;return e.forEach((function(e){var r=n(e),a=t.get(r);a?a.push(e):t.set(r,[e])})),t}var c=[].concat(n.commonLangIds,n.commonLangAliases,n.otherLangIds),l=null,u={},p=void 0;exports.canHighlightLang=function(e){return c.includes(e)},exports.createShikiHighlighter=function(n){if(l)return l;var t,r=(n||{}).theme||"nord";try{t=e.getTheme(r)}catch(n){try{t=e.loadTheme(r)}catch(e){throw new Error("Unable to load theme: "+r+" - "+e.message)}}return e.getHighlighter({theme:t,langs:c}).then((function(e){return l=e}))},exports.defaultShikiTwoslashSettings=u,exports.renderCodeToHTML=function(e,n,t,r){if(!t&&!l)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");return function(e,n,t){if(!t)return function(e,n){var t="";return t+='<pre class="shiki">',n.langId&&(t+='<div class="language-id">'+n.langId+"</div>"),t+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?t+="\n":(e.forEach((function(e){t+='<span style="color: '+e.color+'">'+o(e.content)+"</span>"})),t+="\n")})),t=t.replace(/\n*$/,""),t+="</code></div></pre>"}(e,n);var r="";r+='<pre class="shiki twoslash">',n.langId&&(r+='<div class="language-id">'+n.langId+"</div>"),r+="<div class='code-container'><code>";var a,c=i(t.errors,(function(e){return e.line}))||new Map,l=i(t.staticQuickInfos,(function(e){return e.line}))||new Map,u=i(t.queries,(function(e){return e.line-1}))||new Map,p=0;return e.forEach((function(e,n){var t=c.get(n)||[],a=l.get(n)||[],i=u.get(n)||[];if(0===e.length&&0===n)p+=1;else if(0===e.length)p+=1,r+="\n";else{var d=0;e.forEach((function(e){var n="",o=function(n){return function(t){return n<=t.character&&n+e.content.length>=t.character+t.length}},c=t.filter(o(d)),l=a.filter(o(d)),u=i.filter(o(d)),h=[].concat(c,l,u).sort((function(e,n){return(e.start||0)-(n.start||0)}));n+=h.length?function(e,n){var t=[],r=!1;e.forEach((function(e){"lsp"===e.classes?(t.push({text:"⇍/data-lsp⇏",index:e.end}),t.push({text:"⇍data-lsp lsp=⇯"+(e.lsp||"")+"⇯⇏",index:e.begin})):"err"===e.classes?r=!0:"query"===e.classes&&(t.push({text:"⇍/data-highlight⇏",index:e.end}),t.push({text:"⇍data-highlight'⇏",index:e.begin}))}));var a=(" "+n).slice(1);return t.sort((function(e,n){return n.index-e.index})).forEach((function(e){var n,t,r;r=e.text,a=(n=a).slice(0,t=e.index)+r+n.slice(t+Math.abs(0))})),r&&(a="⇍data-err⇏"+a+"⇍/data-err⇏"),s(a).replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")}(h.map((function(e){var n={begin:e.start-p,end:e.start+e.length-p};return"renderedMessage"in e&&(n.classes="err"),"kind"in e&&(n.classes=e.kind),"targetString"in e&&(n.classes="lsp",n.lsp=s(e.text)),n})),e.content):e.content.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯"),r+='<span style="color: '+e.color+'">'+n+"</span>",d+=e.content.length,p+=e.content.length})),r+="\n",p+=1}if(t.length){var h=t.map((function(e){return o(e.renderedMessage)})).join("</br>"),g=t.map((function(e){return e.code})).join("<br/>");r+='<span class="error"><span>'+h+'</span><span class="code">'+g+"</span></span>",r+='<span class="error-behind">'+h+"</span>"}i.length&&(i.forEach((function(e){switch(e.kind){case"query":r+="<span class='query'>//"+"".padStart(e.offset-2)+"^ = "+e.text+"</span>";break;case"completions":if(e.completions){var n=e.completions.filter((function(n){return n.name.startsWith(e.completionsPrefix||"____")}));console.log("Prefix: ",e.completionsPrefix);var t=n.sort((function(e,n){return e.name.localeCompare(n.name)})).map((function(n){var t,r=n.name.substr((null===(t=e.completionsPrefix)||void 0===t?void 0:t.length)||0);return"<li><span><span class='result-found'>"+(e.completionsPrefix||"")+"</span>"+r+"<span></li>"})).join("");r+="".padStart(e.offset)+"<span class='inline-completions'><ul class='dropdown'>"+t+"</ul></span>"}else r+="<span class='query'>//"+"".padStart(e.offset-2)+"^ - No completions found</span>"}})),r+="\n")})),a=r.replace(/\n*$/,""),r=a.replace(/⇍/g,"&lt;").replace(/⇏/g,"&gt;").replace(/⇯/g,"&apos;"),r+="</code><a href='"+t.playgroundURL+"'>Try</a></div></pre>"}((t||l).codeToThemedTokens(e,n),{langId:n},r)},exports.runTwoSlash=function(e,n,s,o){void 0===s&&(s=u),void 0===o&&(o={});var i=void 0,c={json5:"json"};return c[n]&&(n=c[n]),s.useNodeModules&&(p?i=new Map(p):(i=r.createDefaultMapFromNodeModules({target:6}),p=i),r.addAllFilesFromFolder(i,s.nodeModulesTypesPath||"node_modules/@types")),t.twoslasher(e,n,a({},o,{fsMap:i}))};
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),t=require("shiki-languages"),n=require("@typescript/twoslash"),r=require("@typescript/vfs");function o(){return(o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var i=function(e,t,n,r){return e.slice(0,t)+r+e.slice(t+Math.abs(n))},s=function(e){return e.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯")},a=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")},l=function(e){return e.replace(/⇍/g,"&lt;").replace(/⇏/g,"&gt;").replace(/⇯/g,"&apos;")};function c(e){var t={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+t[e]+";"}))}function p(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function u(e,t,n){var r="";r+='<pre class="shiki twoslash lsp">',t.langId&&(r+='<div class="language-id">'+t.langId+"</div>"),r+="<div class='code-container'><code>";var o=d(n.errors,(function(e){return e.line}))||new Map,u=d(n.staticQuickInfos,(function(e){return e.line}))||new Map,f=d(n.queries,(function(e){return e.line-1}))||new Map,h=0;return e.forEach((function(e,t){var n=o.get(t)||[],l=u.get(t)||[],d=f.get(t)||[];if(0===e.length&&0===t)h+=1;else if(0===e.length)h+=1,r+="\n";else{var m=0;e.forEach((function(e){var t="",o=function(t){return function(n){return t<=n.character&&t+e.content.length>=n.character+n.length}},p=n.filter(o(m)),u=l.filter(o(m)),f=d.filter(o(m)),g=[].concat(p,u,f).sort((function(e,t){return(e.start||0)-(t.start||0)}));t+=g.length?function(e,t){var n=[],r=!1;e.forEach((function(e){"lsp"===e.classes?(n.push({text:"⇍/data-lsp⇏",index:e.end}),n.push({text:"⇍data-lsp lsp=⇯"+(e.lsp||"")+"⇯⇏",index:e.begin})):"err"===e.classes?r=!0:"query"===e.classes&&(n.push({text:"⇍/data-highlight⇏",index:e.end}),n.push({text:"⇍data-highlight'⇏",index:e.begin}))}));var o=(" "+t).slice(1);return n.sort((function(e,t){return t.index-e.index})).forEach((function(e){o=i(o,e.index,0,e.text)})),r&&(o="⇍data-err⇏"+o+"⇍/data-err⇏"),a(c(o))}(g.map((function(e){var t={begin:e.start-h,end:e.start+e.length-h};return"renderedMessage"in e&&(t.classes="err"),"kind"in e&&(t.classes=e.kind),"targetString"in e&&(t.classes="lsp",t.lsp=c(e.text)),t})),e.content):s(e.content),r+='<span style="color: '+e.color+'">'+t+"</span>",m+=e.content.length,h+=e.content.length})),r+="\n",h+=1}if(n.length){var g=n.map((function(e){return p(e.renderedMessage)})).join("</br>"),y=n.map((function(e){return e.code})).join("<br/>");r+='<span class="error"><span>'+g+'</span><span class="code">'+y+"</span></span>",r+='<span class="error-behind">'+g+"</span>"}d.length&&(d.forEach((function(e){switch(e.kind){case"query":r+="<span class='query'>//"+"".padStart(e.offset-2)+"^ = "+e.text+"</span>";break;case"completions":if(e.completions){var t=e.completions.filter((function(t){return t.name.startsWith(e.completionsPrefix||"____")}));console.log("Prefix: ",e.completionsPrefix);var n=t.sort((function(e,t){return e.name.localeCompare(t.name)})).map((function(t){var n,r=t.name.substr((null===(n=e.completionsPrefix)||void 0===n?void 0:n.length)||0);return"<li><span><span class='result-found'>"+(e.completionsPrefix||"")+"</span>"+r+"<span></li>"})).join("");r+="".padStart(e.offset)+"<span class='inline-completions'><ul class='dropdown'>"+n+"</ul></span>"}else r+="<span class='query'>//"+"".padStart(e.offset-2)+"^ - No completions found</span>"}})),r+="\n")})),r=l(r.replace(/\n*$/,"")),r+="</code><a href='"+n.playgroundURL+"'>Try</a></div></pre>"}function d(e,t){var n=new Map;return e.forEach((function(e){var r=t(e),o=n.get(r);o?o.push(e):n.set(r,[e])})),n}function f(e,t){var n="";return n+='<pre class="shiki">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",(n=(n+=p(e)).replace(/\n*$/,""))+"</code></div></pre>"}function h(e,t){var n="";return n+='<pre class="shiki">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?n+="\n":(e.forEach((function(e){n+='<span style="color: '+e.color+'">'+p(e.content)+"</span>"})),n+="\n")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var m={compilerOptions:"The set of compiler options for your project",allowJs:"Let TS include .JS files in imports",allowSyntheticDefaultImports:"Allow 'import x from y' when a module doesn't have a default export",allowUmdGlobalAccess:"Assume UMD imports are all globally available",allowUnreachableCode:"Error when code will never be called",allowUnusedLabels:"Error when accidentally creating a label",alwaysStrict:"Ensure 'use strict' is always emitted",assumeChangesOnlyAffectDirectDependencies:"A drastically faster, but occasionally inaccurate watch mode option.",baseUrl:"Set a baseurl for relative module names",charset:"Manually set the text encoding for reading files",checkJs:"Run the type checker on .js files in your project",composite:"Used to create multiple build projects",declaration:"Emit d.ts files for referenced files in the project",declarationDir:"Set the root directory for d.ts files to go",declarationMap:"Create sourcemaps for d.ts files",diagnostics:"Output additional information after a compile",disableReferencedProjectLoad:"Reduces the number of projects loaded automatically by TypeScript",disableSizeLimit:"Remove the memory cap on the TypeScript language server",disableSolutionSearching:" Opt a project out of multi-project reference checking",disableSourceOfProjectReferenceRedirect:"Use d.ts files as the source of truth for tooling between composite project boundries",downlevelIteration:"Emit more compliant, but verbose JavaScript for iterating objects",emitBOM:"Include a byte order mark to output files",emitDeclarationOnly:"Only output d.ts files and not .js files",emitDecoratorMetadata:"Adds additional type metadata to decorators in emitted code",esModuleInterop:"Emit additional JS to ease support for importing commonjs modules",exclude:"Files or patterns to be skipped from the include option",experimentalDecorators:"Enable experimental support for TC39 stage 2 decorators",extendedDiagnostics:"Include a lot of diagnostic information after a compile",extends:"Inherit options for a TSConfig",fallbackPolling:"What the watcher should use if the system runs out of native file watchers",files:"Include a set list of files, does not support globs",forceConsistentCasingInFileNames:"Ensure that casing is correct in imports",generateCpuProfile:"Emit a v8 CPU profile of the compiler run for debugging",importHelpers:"Allow importing helper functions once per project, instead of including them per-file",importsNotUsedAsValues:"Controls which syntax you use for importing types",include:"Files or patterns to include in this project",incremental:"Save .tsbuildinfo files to allow for incremental compilation of projects",inlineSourceMap:"Include sourcemap files inside the emitted JavaScript",inlineSources:"Include sourcemap files inside the emitted JavaScript",isolatedModules:"Ensure that each file can be safely transpiled without relying on other imports",jsx:"Control how JSX is emitted",jsxFactory:"Control the function emitted by JSX",jsxFragmentFactory:"Specifies what identifiers a JSX fragment should be transformed to",keyofStringsOnly:"Make keyof only return strings instead of string or numbers",lib:"Include type definitions you know are available in your JavaScript runtime",listEmittedFiles:"Print the names of emitted files after a compile",listFiles:"Print all of the files read during the compilation",locale:"Set the language of the tsc output",mapRoot:"Set an external root for sourcemaps",maxNodeModuleJsDepth:"How deep should TypeScript run type checking in node_modules",module:"Sets the expected module system for your runtime",moduleResolution:"Allow TypeScript 1.6 module resolution strategies",newLine:"Set the newline character",noEmit:"Do not emit files from a compilation",noEmitHelpers:"Assume helpers are available in the global runtime",noEmitOnError:"Only emit files on a successful compile",noErrorTruncation:"Do not truncate error messages",noFallthroughCasesInSwitch:"Report errors for fallthrough cases in switch statements.",noImplicitAny:"Avoid introducing anys inside your codebase when a type could be specified",noImplicitReturns:"Ensure that all codepaths return in a function",noImplicitThis:"Raise errors when 'this' would be any",noImplicitUseStrict:"Disable 'use strict' in the JS emit",noLib:"Ignore options from lib",noResolve:"Skip ahead-of-time checking for import and <reference files",noStrictGenericChecks:"Disable strict checking of generic signatures in functions.",noUnusedLocals:"Error when a local variable isn't read",noUnusedParameters:"Error when a parameter isn't used",out:"Do not use this",outDir:"Set an output folder for all emitted files",outFile:"Output a single file of all JS files concatenated",paths:"A set of locations to look for imports in",plugins:"A list of language service plugins to include",preserveConstEnums:"Do not erase `const enum` declarations in generated code",preserveSymlinks:"Do not resolve symlink paths",preserveWatchOutput:"Do not wipe the console in watch mode",pretty:"Use color and formatting to make compiler errors easier to read",reactNamespace:"Specify the object which 'createElement' is called on in JSX",references:"Provide a structure for composite projects",removeComments:"Remove comments in TypeScript from appearing in JavaScript",resolveJsonModule:"Allow importing .json files",rootDir:"Sets the root folder within your source files",rootDirs:"Set multiple root directories",skipDefaultLibCheck:"use SkipLibCheck instead",skipLibCheck:"Skip type checking of declaration files",sourceMap:"Creates source map files for emitted JavaScript files",sourceRoot:"Sets the root path for debuggers to find the reference source code",strict:"Enable TypeScript's most in-depth type checking rules",strictBindCallApply:"Ensure that 'call', 'bind' and 'apply' have the right arguments",strictFunctionTypes:"Ensure that function parameters are consistent",strictNullChecks:"Ensure that nullability is respected in the type checker",strictPropertyInitialization:"Ensure that all class properties match their types after the constructor has finished",stripInternal:"Remove declarations which have '@internal' in their JSDoc comments",suppressExcessPropertyErrors:"Allow additional properties being set during creation of types",suppressImplicitAnyIndexErrors:"Remove the warning when using string indexes to access unknown properties",target:"Set the supported JavaScript language runtime to transpile to",traceResolution:"Log out paths when resolving all modules",tsBuildInfoFile:"Set the folder for .tsbuildinfo files",typeAcquisition:"Sets of options for Automatic Type Acquisition in JavaScript",typeRoots:"locations where TypeScript should look for type definitions",types:"Used to create an allowlist of types to be included in the compile",useDefineForClassFields:"Use define characteristics for handling class fields",watchDirectory:"Determine how directories are watched",watchFile:"What technique should the watcher use"},g=function(e){return!!e.explanation&&e.explanation.find((function(e){return e.scopes.find((function(e){return e.scopeName.includes("support.type.property-name")}))}))},y=function(e){if('"'!==e.content)return e.content.slice(1,e.content.length-1)in m};function v(e,t){var n="";return n+='<pre class="shiki tsconfig lsp">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?n+="\n":(e.forEach((function(e){if(g(e)&&y(e)){var t=e.content.slice(1,e.content.length-1);n+='<span style="color: '+e.color+'">"<a aria-hidden=true href=\'https://www.typescriptlang.org/tsconfig#'+t+"'><data-lsp lsp=\""+m[t]+'">'+p(t)+'</data-lsp></a>"</span>'}else n+='<span style="color: '+e.color+'">'+p(e.content)+"</span>"})),n+="\n")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var w=[].concat(t.commonLangIds,t.commonLangAliases,t.otherLangIds),b=function(e){return w.includes(e)},S=null,k=void 0,x={plainTextRenderer:f,defaultShikiRenderer:h,twoslashRenderer:u,tsconfigJSONRenderer:v};exports.canHighlightLang=b,exports.createShikiHighlighter=function(t){if(S)return Promise.resolve(S);var n,r=(t||{}).theme||"nord";try{n=e.getTheme(r)}catch(t){try{n=e.loadTheme(r)}catch(e){throw new Error("Unable to load theme: "+r+" - "+e.message)}}return e.getHighlighter({theme:n,langs:w}).then((function(e){return S=e}))},exports.renderCodeToHTML=function(e,t,n,r,o,i){if(!o&&!S)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");if(!b(t))return f(e,r||{});var s=(o||S).codeToThemedTokens(e,t);return n.includes("twoslash")&&i?u(s,r||{},i):"json"===t&&n.includes("tsconfig")?v(s,r||{}):h(s,{langId:t})},exports.renderers=x,exports.runTwoSlash=function(e,t,i,s){void 0===i&&(i={}),void 0===s&&(s={});var a=void 0,l={json5:"json"};return l[t]&&(t=l[t]),i.useNodeModules&&(k?a=new Map(k):(a=r.createDefaultMapFromNodeModules({target:6}),k=a),r.addAllFilesFromFolder(a,i.nodeModulesTypesPath||"node_modules/@types")),n.twoslasher(e,t,o({},s,{fsMap:a}))};
//# sourceMappingURL=shiki-twoslash.cjs.production.min.js.map

@@ -95,4 +95,6 @@ import { getTheme, loadTheme, getHighlighter } from 'shiki';

}
function escapeHtml(html) {
return html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
// This started as a JS port of https://github.com/octref/shiki/blob/master/packages/shiki/src/renderer.ts
// What we're trying to do is merge two sets of information into a single tree for HTML

@@ -110,11 +112,5 @@ // 1: Syntax highlight info from shiki

function renderToHTML(lines, options, twoslash) {
// It's a NOOP for us with twoslash, this is basically all
// the other languages
if (!twoslash) {
return plainOleShikiRenderer(lines, options);
}
function twoslashRenderer(lines, options, twoslash) {
var html = "";
html += "<pre class=\"shiki twoslash\">";
html += "<pre class=\"shiki twoslash lsp\">";

@@ -253,9 +249,4 @@ if (options.langId) {

}
function escapeHtml(html) {
return html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
/** Returns a map where all the keys are the value in keyGetter */
function groupBy(list, keyGetter) {

@@ -276,3 +267,5 @@ var map = new Map();

function plainOleShikiRenderer(lines, options) {
/** You don't have a language which shiki twoslash can handle, make a DOM compatible version */
function plainTextRenderer(code, options) {
var html = "";

@@ -286,2 +279,18 @@ html += "<pre class=\"shiki\">";

html += "<div class='code-container'><code>";
html += escapeHtml(code);
html = html.replace(/\n*$/, ""); // Get rid of final new lines
html += "</code></div></pre>";
return html;
}
function defaultShikiRenderer(lines, options) {
var html = "";
html += "<pre class=\"shiki\">";
if (options.langId) {
html += "<div class=\"language-id\">" + options.langId + "</div>";
}
html += "<div class='code-container'><code>";
lines.forEach(function (l) {

@@ -303,2 +312,166 @@ if (l.length === 0) {

var tsconfig = {
compilerOptions: "The set of compiler options for your project",
allowJs: "Let TS include .JS files in imports",
allowSyntheticDefaultImports: "Allow 'import x from y' when a module doesn't have a default export",
allowUmdGlobalAccess: "Assume UMD imports are all globally available",
allowUnreachableCode: "Error when code will never be called",
allowUnusedLabels: "Error when accidentally creating a label",
alwaysStrict: "Ensure 'use strict' is always emitted",
assumeChangesOnlyAffectDirectDependencies: "A drastically faster, but occasionally inaccurate watch mode option.",
baseUrl: "Set a baseurl for relative module names",
charset: "Manually set the text encoding for reading files",
checkJs: "Run the type checker on .js files in your project",
composite: "Used to create multiple build projects",
declaration: "Emit d.ts files for referenced files in the project",
declarationDir: "Set the root directory for d.ts files to go",
declarationMap: "Create sourcemaps for d.ts files",
diagnostics: "Output additional information after a compile",
disableReferencedProjectLoad: "Reduces the number of projects loaded automatically by TypeScript",
disableSizeLimit: "Remove the memory cap on the TypeScript language server",
disableSolutionSearching: " Opt a project out of multi-project reference checking",
disableSourceOfProjectReferenceRedirect: "Use d.ts files as the source of truth for tooling between composite project boundries",
downlevelIteration: "Emit more compliant, but verbose JavaScript for iterating objects",
emitBOM: "Include a byte order mark to output files",
emitDeclarationOnly: "Only output d.ts files and not .js files",
emitDecoratorMetadata: "Adds additional type metadata to decorators in emitted code",
esModuleInterop: "Emit additional JS to ease support for importing commonjs modules",
exclude: "Files or patterns to be skipped from the include option",
experimentalDecorators: "Enable experimental support for TC39 stage 2 decorators",
extendedDiagnostics: "Include a lot of diagnostic information after a compile",
"extends": "Inherit options for a TSConfig",
fallbackPolling: "What the watcher should use if the system runs out of native file watchers",
files: "Include a set list of files, does not support globs",
forceConsistentCasingInFileNames: "Ensure that casing is correct in imports",
generateCpuProfile: "Emit a v8 CPU profile of the compiler run for debugging",
importHelpers: "Allow importing helper functions once per project, instead of including them per-file",
importsNotUsedAsValues: "Controls which syntax you use for importing types",
include: "Files or patterns to include in this project",
incremental: "Save .tsbuildinfo files to allow for incremental compilation of projects",
inlineSourceMap: "Include sourcemap files inside the emitted JavaScript",
inlineSources: "Include sourcemap files inside the emitted JavaScript",
isolatedModules: "Ensure that each file can be safely transpiled without relying on other imports",
jsx: "Control how JSX is emitted",
jsxFactory: "Control the function emitted by JSX",
jsxFragmentFactory: "Specifies what identifiers a JSX fragment should be transformed to",
keyofStringsOnly: "Make keyof only return strings instead of string or numbers",
lib: "Include type definitions you know are available in your JavaScript runtime",
listEmittedFiles: "Print the names of emitted files after a compile",
listFiles: "Print all of the files read during the compilation",
locale: "Set the language of the tsc output",
mapRoot: "Set an external root for sourcemaps",
maxNodeModuleJsDepth: "How deep should TypeScript run type checking in node_modules",
module: "Sets the expected module system for your runtime",
moduleResolution: "Allow TypeScript 1.6 module resolution strategies",
newLine: "Set the newline character",
noEmit: "Do not emit files from a compilation",
noEmitHelpers: "Assume helpers are available in the global runtime",
noEmitOnError: "Only emit files on a successful compile",
noErrorTruncation: "Do not truncate error messages",
noFallthroughCasesInSwitch: "Report errors for fallthrough cases in switch statements.",
noImplicitAny: "Avoid introducing anys inside your codebase when a type could be specified",
noImplicitReturns: "Ensure that all codepaths return in a function",
noImplicitThis: "Raise errors when 'this' would be any",
noImplicitUseStrict: "Disable 'use strict' in the JS emit",
noLib: "Ignore options from lib",
noResolve: "Skip ahead-of-time checking for import and <reference files",
noStrictGenericChecks: "Disable strict checking of generic signatures in functions.",
noUnusedLocals: "Error when a local variable isn't read",
noUnusedParameters: "Error when a parameter isn't used",
out: "Do not use this",
outDir: "Set an output folder for all emitted files",
outFile: "Output a single file of all JS files concatenated",
paths: "A set of locations to look for imports in",
plugins: "A list of language service plugins to include",
preserveConstEnums: "Do not erase `const enum` declarations in generated code",
preserveSymlinks: "Do not resolve symlink paths",
preserveWatchOutput: "Do not wipe the console in watch mode",
pretty: "Use color and formatting to make compiler errors easier to read",
reactNamespace: "Specify the object which 'createElement' is called on in JSX",
references: "Provide a structure for composite projects",
removeComments: "Remove comments in TypeScript from appearing in JavaScript",
resolveJsonModule: "Allow importing .json files",
rootDir: "Sets the root folder within your source files",
rootDirs: "Set multiple root directories",
skipDefaultLibCheck: "use SkipLibCheck instead",
skipLibCheck: "Skip type checking of declaration files",
sourceMap: "Creates source map files for emitted JavaScript files",
sourceRoot: "Sets the root path for debuggers to find the reference source code",
strict: "Enable TypeScript's most in-depth type checking rules",
strictBindCallApply: "Ensure that 'call', 'bind' and 'apply' have the right arguments",
strictFunctionTypes: "Ensure that function parameters are consistent",
strictNullChecks: "Ensure that nullability is respected in the type checker",
strictPropertyInitialization: "Ensure that all class properties match their types after the constructor has finished",
stripInternal: "Remove declarations which have '@internal' in their JSDoc comments",
suppressExcessPropertyErrors: "Allow additional properties being set during creation of types",
suppressImplicitAnyIndexErrors: "Remove the warning when using string indexes to access unknown properties",
target: "Set the supported JavaScript language runtime to transpile to",
traceResolution: "Log out paths when resolving all modules",
tsBuildInfoFile: "Set the folder for .tsbuildinfo files",
typeAcquisition: "Sets of options for Automatic Type Acquisition in JavaScript",
typeRoots: "locations where TypeScript should look for type definitions",
types: "Used to create an allowlist of types to be included in the compile",
useDefineForClassFields: "Use define characteristics for handling class fields",
watchDirectory: "Determine how directories are watched",
watchFile: "What technique should the watcher use"
};
/** Uses tmLanguage scopes to determine what the content of the token is */
var tokenIsJSONKey = function tokenIsJSONKey(token) {
if (!token.explanation) return false;
return token.explanation.find(function (e) {
return e.scopes.find(function (s) {
return s.scopeName.includes("support.type.property-name");
});
});
};
/** Can you look up the token in the tsconfig reference? */
var isKeyInTSConfig = function isKeyInTSConfig(token) {
if (token.content === '"') return;
var name = token.content.slice(1, token.content.length - 1);
return name in tsconfig;
};
/**
* Renders a TSConfig JSON object with additional LSP-ish information
* @param lines the result of shiki highlighting
* @param options shiki display options
*/
function tsconfigJSONRenderer(lines, options) {
var html = "";
html += "<pre class=\"shiki tsconfig lsp\">";
if (options.langId) {
html += "<div class=\"language-id\">" + options.langId + "</div>";
}
html += "<div class='code-container'><code>";
lines.forEach(function (l) {
if (l.length === 0) {
html += "\n";
} else {
l.forEach(function (token) {
// This means we're looking at a token which could be '"module"', '"', '"compilerOptions"' etc
if (tokenIsJSONKey(token) && isKeyInTSConfig(token)) {
var key = token.content.slice(1, token.content.length - 1);
var oneliner = tsconfig[key]; // prettier-ignore
html += "<span style=\"color: " + token.color + "\">\"<a aria-hidden=true href='https://www.typescriptlang.org/tsconfig#" + key + "'><data-lsp lsp=\"" + oneliner + "\">" + escapeHtml(key) + "</data-lsp></a>\"</span>";
} else {
html += "<span style=\"color: " + token.color + "\">" + escapeHtml(token.content) + "</span>";
}
});
html += "\n";
}
});
html = html.replace(/\n*$/, ""); // Get rid of final new lines
html += "</code></div></pre>";
return html;
}
var languages =

@@ -328,3 +501,3 @@ /*#__PURE__*/

var createShikiHighlighter = function createShikiHighlighter(options) {
if (storedHighlighter) return storedHighlighter;
if (storedHighlighter) return Promise.resolve(storedHighlighter);
var settings = options || {};

@@ -352,16 +525,42 @@ var theme = settings.theme || "nord";

};
var defaultShikiTwoslashSettings = {};
/** Uses Shiki to render the code to HTML */
/**
* Renders a code sample to HTML, automatically taking into account:
*
* - rendering overrides for twoslash and tsconfig
* - whether the language exists in shiki
*
* @param code the source code to render
* @param lang the language to use in highlighting
* @param info additional metadata which lives after the codefence lang (e.g. ["twoslash"])
* @param highlighter optional, but you should use it, highlighter
* @param twoslash optional, but required when info contains 'twoslash' as a string
*/
var renderCodeToHTML = function renderCodeToHTML(code, lang, highlighter, twoslash) {
var renderCodeToHTML = function renderCodeToHTML(code, lang, info, shikiOptions, highlighter, twoslash) {
if (!highlighter && !storedHighlighter) {
throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");
}
} // Shiki doesn't know this lang
if (!canHighlightLang(lang)) {
return plainTextRenderer(code, shikiOptions || {});
} // Shiki does know the lang, so tokenize
var renderHighlighter = highlighter || storedHighlighter;
var tokens = renderHighlighter.codeToThemedTokens(code, lang);
var results = renderToHTML(tokens, {
var tokens = renderHighlighter.codeToThemedTokens(code, lang); // Twoslash specific renderer
if (info.includes("twoslash") && twoslash) {
return twoslashRenderer(tokens, shikiOptions || {}, twoslash);
} // TSConfig renderer
if (lang === "json" && info.includes("tsconfig")) {
return tsconfigJSONRenderer(tokens, shikiOptions || {});
} // Otherwise just the normal shiki renderer
return defaultShikiRenderer(tokens, {
langId: lang
}, twoslash);
return results;
});
}; // Basically so that we can store this once, then re-use it in the same process

@@ -376,3 +575,3 @@

if (settings === void 0) {
settings = defaultShikiTwoslashSettings;
settings = {};
}

@@ -416,4 +615,12 @@

};
/** Set of renderers if you want to explicitly call one instead of using renderCodeToHTML */
export { canHighlightLang, createShikiHighlighter, defaultShikiTwoslashSettings, renderCodeToHTML, runTwoSlash };
var renderers = {
plainTextRenderer: plainTextRenderer,
defaultShikiRenderer: defaultShikiRenderer,
twoslashRenderer: twoslashRenderer,
tsconfigJSONRenderer: tsconfigJSONRenderer
};
export { canHighlightLang, createShikiHighlighter, renderCodeToHTML, renderers, runTwoSlash };
//# sourceMappingURL=shiki-twoslash.esm.js.map

@@ -19,2 +19,3 @@ declare type Range = {

export declare function stripHTML(text: string): string;
export declare function escapeHtml(html: string): string;
export {};
{
"name": "shiki-twoslash",
"version": "0.6.2",
"version": "0.7.0",
"license": "MIT",

@@ -17,2 +17,3 @@ "homepage": "https://github.com/microsoft/TypeScript-Website/",

"prepublishOnly": "yarn build",
"bootstrap": "node scripts/generateTSConfigOneliners.js",
"build": "tsdx build && yarn tsc src/dom.ts --outDir dist",

@@ -31,3 +32,3 @@ "test": "tsdx test",

"@types/jest": "^25.1.3",
"gatsby-remark-shiki-twoslash": "0.6.1",
"gatsby-remark-shiki-twoslash": "0.7.0",
"rehype-stringify": "^6.0.1",

@@ -34,0 +35,0 @@ "tsdx": "^0.12.3",

### shiki-twoslash
> Documentation / made lovely by counting words / maybe we would read!
Provides the API primitives to mix [shiki](https://shiki.matsu.io) with [@typescript/twoslash](https://github.com/microsoft/TypeScript-Website/tree/v2/packages/ts-twoslasher).

@@ -8,6 +10,9 @@

- Shiki bootstrapping: `createShikiHighlighter`
- Checking if shiki can handle a code sample: `canHighlightLang`
- Running Twoslash over code, with caching and DTS lookups: `runTwoSlash`
- Rendering any code sample with Shiki: `renderCodeToHTML`
Useful, but not critical:
- Checking if shiki can handle a code sample: `canHighlightLang`
### API

@@ -30,14 +35,43 @@

Renders source code into HTML via Shiki:
```ts
/**
* Renders a code sample to HTML, automatically taking into account:
*
* - rendering overrides for twoslash and tsconfig
* - whether the language exists in shiki
*
* @param code the source code to render
* @param lang the language to use in highlighting
* @param info additional metadata which lives after the codefence lang (e.g. ["twoslash"])
* @param highlighter optional, but you should use it, highlighter
* @param twoslash optional, but required when info contains 'twoslash' as a string
*/
export declare const renderCodeToHTML: (
code: string,
lang: string,
info: string[],
shikiOptions?: import("shiki/dist/renderer").HtmlRendererOptions | undefined,
highlighter?: Highlighter | undefined,
twoslash?: TwoSlashReturn | undefined
) => string
```
For example:
```ts
const shouldHighlight = lang && canHighlightLang(lang)
if (shouldHighlight) {
const results = renderCodeToHTML(node.value, lang, highlighter)
node.type = "html"
node.children = []
}
const results = renderCodeToHTML(node.value, lang, node.meta || [], {}, highlighter, node.twoslash)
node.type = "html"
node.value = results
node.children = []
```
Uses:
- `renderers.plainTextRenderer` for language which shiki cannot handle
- `renderers.defaultRenderer` for shiki highlighted code samples
- `renderers.twoslashRenderer` for twoslash powered TypeScript code samples
- `renderers.tsconfigJSONRenderer` for extra annotations to JSON which is known to be a TSConfig file
These will be used automatically for you, depending on whether the language is available or what the `info` param is set to.
To get access to the twoslash renderer, you'll need to pass in the results of a twoslash run to `renderCodeToHTML`:

@@ -48,3 +82,10 @@

const twoslashResults = runTwoSlash(code, lang)
const html = renderCodeToHTML(twoslashResults.code, twoslashResults.lang, highlighter)
const results = renderCodeToHTML(
twoslashResults.code,
twoslashResults.lang,
node.meta || ["twoslash"],
{},
highlighter,
node.twoslash
)
```

@@ -51,0 +92,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc