shiki-twoslash
Advanced tools
Comparing version 1.0.0 to 1.1.0
@@ -36,2 +36,3 @@ import { Highlighter, HighlighterOptions } from "shiki"; | ||
export declare const runTwoSlash: (code: string, lang: string, settings?: ShikiTwoslashSettings, twoslashDefaults?: TwoSlashOptions) => TwoSlashReturn; | ||
export { parseCodeFenceInfo } from "./parseCodeFenceInfo"; | ||
/** Set of renderers if you want to explicitly call one instead of using renderCodeToHTML */ | ||
@@ -38,0 +39,0 @@ export declare const renderers: { |
declare type Lines = import("shiki").IThemedToken[][]; | ||
declare type TwoSlash = import("@typescript/twoslash").TwoSlashReturn; | ||
import { HtmlRendererOptions } from "./plain"; | ||
export declare function twoslashRenderer(lines: Lines, options: HtmlRendererOptions, twoslash: TwoSlash): string; | ||
export declare function twoslashRenderer(lines: Lines, options: HtmlRendererOptions, twoslash: TwoSlash, codefenceMeta: any): string; | ||
export {}; |
@@ -27,2 +27,228 @@ 'use strict'; | ||
// Based on https://github.com/andrewbranch/gatsby-remark-vscode/blob/7bf5c036a58652c1f45d27c5874557f7b531102c/src/index.js | ||
// which is MIT https://github.com/andrewbranch/gatsby-remark-vscode/blob/7bf5c036a58652c1f45d27c5874557f7b531102c/LICENSE | ||
// Only difference is conversion to TypeScript, and a replace at the top | ||
var identifierPattern = /[a-z0-9-–—_+#]/i; | ||
var triviaPattern = /\s/; | ||
var startOfNumberPattern = /[0-9-.]/; | ||
var numberPattern = /[0-9-.e]/; | ||
function testRegex(input, pattern) { | ||
if (input === undefined) return false; | ||
return pattern.test(input); | ||
} | ||
/** Takes the language and a meta-string and offers a useful object for looking at params */ | ||
function parseCodeFenceInfo(lang, fullMetaString) { | ||
// Heh | ||
var metaString = fullMetaString.replace("twoslash", ""); | ||
var pos = 0; | ||
var meta = {}; | ||
var languageName = ""; | ||
var input = [lang, metaString].filter(Boolean).join(" "); | ||
skipTrivia(); | ||
if (!isEnd() && current() !== "{") { | ||
languageName = parseIdentifier(); | ||
} | ||
var languageNameEnd = pos; | ||
skipTrivia(); | ||
if (!isEnd() && current() === "{") { | ||
meta = parseObject(); | ||
} | ||
if (!isEnd() && languageNameEnd === pos) { | ||
return fail("Invalid character in language name: '" + current() + "'"); | ||
} | ||
return { | ||
languageName: languageName, | ||
meta: meta | ||
}; | ||
function current() { | ||
if (isEnd()) { | ||
return fail("Unexpected end of input"); | ||
} | ||
return input[pos]; | ||
} | ||
function isEnd() { | ||
return pos >= input.length; | ||
} | ||
function fail(message) { | ||
throw new Error("Failed parsing code fence header '" + input + "' at position " + pos + ": " + message); | ||
} | ||
function scanExpected(expected) { | ||
if (isEnd() || current() !== expected) { | ||
return fail("Expected '" + expected + "'"); | ||
} | ||
pos++; | ||
} | ||
function parseIdentifier(errorMessage) { | ||
if (errorMessage === void 0) { | ||
errorMessage = "Expected identifier, but got nothing"; | ||
} | ||
var identifier = ""; | ||
while (!isEnd() && testRegex(current(), identifierPattern)) { | ||
identifier += current(); | ||
pos++; | ||
} | ||
if (!identifier) { | ||
return fail(errorMessage); | ||
} | ||
return identifier; | ||
} | ||
function skipTrivia() { | ||
while (!isEnd() && testRegex(current(), triviaPattern)) { | ||
pos++; | ||
} | ||
} | ||
function parseChar() { | ||
var _char = current(); | ||
if (_char === "\\") { | ||
pos++; | ||
_char += current(); | ||
} | ||
pos++; | ||
return _char; | ||
} | ||
function parseString() { | ||
var str = ""; | ||
var quote = current(); | ||
pos++; | ||
while (true) { | ||
var _char2 = parseChar(); | ||
if (_char2 === quote) break; | ||
str += _char2.replace(/\\/, ""); | ||
} | ||
return str; | ||
} | ||
function parseNumber() { | ||
var numStr = current(); | ||
pos++; | ||
while (!isEnd() && testRegex(current(), numberPattern)) { | ||
numStr += current(); | ||
pos++; | ||
} | ||
return parseFloat(numStr); | ||
} | ||
function parseBoolean() { | ||
var identifier = parseIdentifier("Expected expression, but got nothing"); | ||
switch (identifier) { | ||
case "true": | ||
return true; | ||
case "false": | ||
return false; | ||
case "": | ||
return fail("Expected expression, but got nothing"); | ||
default: | ||
return fail("Unrecognized input '" + identifier + "'"); | ||
} | ||
} | ||
function parseExpression() { | ||
switch (current()) { | ||
case "{": | ||
return parseObject(); | ||
case "'": | ||
case '"': | ||
return parseString(); | ||
} | ||
if (testRegex(current(), startOfNumberPattern)) { | ||
return parseNumber(); | ||
} | ||
return parseBoolean(); | ||
} | ||
function parseObject() { | ||
var obj = {}; | ||
scanExpected("{"); | ||
skipTrivia(); | ||
while (!isEnd() && current() !== "}") { | ||
var key = parseIdentifier(); | ||
var value = true; | ||
skipTrivia(); | ||
if (current() === ":") { | ||
pos++; | ||
skipTrivia(); | ||
value = parseExpression(); | ||
skipTrivia(); | ||
} | ||
obj[key] = value; | ||
if (current() === ",") pos++; | ||
skipTrivia(); | ||
} | ||
scanExpected("}"); | ||
return obj; | ||
} | ||
} | ||
/** Does anything in the object imply that we should highlight any lines? */ | ||
var shouldBeHighlightable = function shouldBeHighlightable(meta) { | ||
return !!Object.keys(meta).find(function (key) { | ||
if (key.includes("-")) return true; | ||
if (parseInt(key) !== NaN) return true; | ||
return false; | ||
}); | ||
}; | ||
/** Returns a func for figuring out if this line should be highlighted */ | ||
var shouldHighlightLine = function shouldHighlightLine(meta) { | ||
var lines = []; | ||
Object.keys(meta).find(function (key) { | ||
if (parseInt(key) !== NaN) lines.push(parseInt(key)); | ||
if (key.includes("-")) { | ||
var _key$split = key.split("-"), | ||
first = _key$split[0], | ||
last = _key$split[1]; | ||
var lastIndex = parseInt(last) + 1; | ||
for (var i = parseInt(first); i < lastIndex; i++) { | ||
lines.push(i); | ||
} | ||
} | ||
}); | ||
return function (line) { | ||
return lines.includes(line); | ||
}; | ||
}; | ||
var splice = function splice(str, idx, rem, newString) { | ||
@@ -105,3 +331,3 @@ return str.slice(0, idx) + newString + str.slice(idx + Math.abs(rem)); | ||
// 1: Syntax highlight info from shiki | ||
// 2: Twoslash metadata like errors, indentifiers etc | ||
// 2: Twoslash metadata like errors, identifiers etc | ||
// Because shiki gives use a set of lines to work from, then the first thing which happens | ||
@@ -116,4 +342,6 @@ // is converting twoslash data into the same format. | ||
function twoslashRenderer(lines, options, twoslash) { | ||
function twoslashRenderer(lines, options, twoslash, codefenceMeta) { | ||
var html = ""; | ||
var hasHighlight = shouldBeHighlightable(codefenceMeta); | ||
var hl = shouldHighlightLine(codefenceMeta); | ||
html += "<pre class=\"shiki twoslash lsp\">"; | ||
@@ -136,2 +364,7 @@ | ||
}) || new Map(); | ||
/** | ||
* This is the index of the original twoslash code reference, it is not | ||
* related to the HTML output | ||
*/ | ||
var filePos = 0; | ||
@@ -150,4 +383,7 @@ lines.forEach(function (l, i) { | ||
} else { | ||
// Keep track of the position of the current token in a line so we can match it up to the | ||
var hiClass = hasHighlight ? hl(i) ? " highlight" : " dim" : ""; | ||
var prefix = "<div class='line" + hiClass + "'>"; | ||
html += prefix; // Keep track of the position of the current token in a line so we can match it up to the | ||
// errors and lang serv identifiers | ||
var tokenPos = 0; | ||
@@ -176,3 +412,3 @@ l.forEach(function (token) { | ||
end: token.start + token.length - filePos | ||
}; | ||
}; // prettier-ignore | ||
@@ -198,3 +434,4 @@ if ("renderedMessage" in token) range.classes = "err"; | ||
}); | ||
html += "\n"; | ||
html += "</div>"; // This is the \n which the </div> represents | ||
filePos += 1; | ||
@@ -314,8 +551,9 @@ } // Adding error messages to the line after | ||
if (l.length === 0) { | ||
html += "\n"; | ||
html += "<div class='line'></div>"; | ||
} else { | ||
html += "<div class='line'>"; | ||
l.forEach(function (token) { | ||
html += "<span style=\"color: " + token.color + "\">" + escapeHtml(token.content) + "</span>"; | ||
}); | ||
html += "\n"; | ||
html += "</div>"; | ||
} | ||
@@ -475,4 +713,5 @@ }); | ||
if (l.length === 0) { | ||
html += "\n"; | ||
html += "<div class='line'></div>"; | ||
} else { | ||
html += "<div class='line'>"; | ||
l.forEach(function (token) { | ||
@@ -489,3 +728,3 @@ // This means we're looking at a token which could be '"module"', '"', '"compilerOptions"' etc | ||
}); | ||
html += "\n"; | ||
html += "</div>"; | ||
} | ||
@@ -516,11 +755,2 @@ }); | ||
if (storedHighlighter) return Promise.resolve(storedHighlighter); | ||
// shikiTheme = getTheme(theme) | ||
// } catch (error) { | ||
// try { | ||
// shikiTheme = loadTheme(theme) | ||
// } catch (error) { | ||
// throw new Error("Unable to load theme: " + theme + " - " + error.message) | ||
// } | ||
// } | ||
return shiki.getHighlighter(options).then(function (newHighlighter) { | ||
@@ -563,3 +793,5 @@ storedHighlighter = newHighlighter; | ||
if (info.includes("twoslash") && twoslash) { | ||
return twoslashRenderer(tokens, shikiOptions || {}, twoslash); | ||
var metaInfo = info && typeof info === "string" ? info : info.join(" "); | ||
var codefenceMeta = parseCodeFenceInfo(lang, metaInfo || ""); | ||
return twoslashRenderer(tokens, shikiOptions || {}, twoslash, codefenceMeta.meta); | ||
} // TSConfig renderer | ||
@@ -634,2 +866,3 @@ | ||
exports.createShikiHighlighter = createShikiHighlighter; | ||
exports.parseCodeFenceInfo = parseCodeFenceInfo; | ||
exports.renderCodeToHTML = renderCodeToHTML; | ||
@@ -636,0 +869,0 @@ exports.renderers = renderers; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),t=require("@typescript/twoslash"),n=require("@typescript/vfs");function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e}).apply(this,arguments)}var r=function(e,t,n,i){return e.slice(0,t)+i+e.slice(t+Math.abs(n))},o=function(e){return e.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯")},a=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")},s=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")};function l(e){var t={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+t[e]+";"}))}function c(e){return e.replace(/</g,"<").replace(/>/g,">")}function p(e,t,n){var i="";i+='<pre class="shiki twoslash lsp">',t.langId&&(i+='<div class="language-id">'+t.langId+"</div>"),i+="<div class='code-container'><code>";var p=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(t,n){var s=p.get(n)||[],d=u.get(n)||[],g=f.get(n)||[];if(0===t.length&&0===n)h+=1;else if(0===t.length)h+=1,i+="\n";else{var m=0;t.forEach((function(e){var t="",n=function(t){return function(n){return t<=n.character&&t+e.content.length>=n.character+n.length}},c=s.filter(n(m)),p=d.filter(n(m)),u=g.filter(n(m)),f=[].concat(c,p,u).sort((function(e,t){return(e.start||0)-(t.start||0)}));t+=f.length?function(e,t){var n=[],i=!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?i=!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=r(o,e.index,0,e.text)})),i&&(o="⇍data-err⇏"+o+"⇍/data-err⇏"),a(l(o))}(f.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=l(e.text)),t})),e.content):o(e.content),i+='<span style="color: '+e.color+'">'+t+"</span>",m+=e.content.length,h+=e.content.length})),i+="\n",h+=1}if(s.length){var y=s.map((function(e){return c(e.renderedMessage)})).join("</br>"),b=s.map((function(e){return e.code})).join("<br/>");i+='<span class="error"><span>'+y+'</span><span class="code">'+b+"</span></span>",i+='<span class="error-behind">'+y+"</span>"}g.length&&(g.forEach((function(t){switch(t.kind){case"query":var r,o,a,s=(null==(r=(e[n-1]||[])[0])?void 0:r.content)||"",l=s.slice(0,(null==(o=/\S/.exec(s))?void 0:o.index)||0),c=l+"//"+"".padStart(t.offset-2-l.length),p=null==(a=t.text)?void 0:a.split("\n").map((function(e,t){return 0!==t?c+e:e})).join("\n");i+="<span class='query'>"+c+"^ = "+p+"</span>";break;case"completions":if(t.completions){var d=t.completions.filter((function(e){return e.name.startsWith(t.completionsPrefix||"____")})).sort((function(e,t){return e.name.localeCompare(t.name)})).map((function(e){var n,i,r=e.name.substr((null==(n=t.completionsPrefix)?void 0:n.length)||0),o="<span><span class='result-found'>"+(t.completionsPrefix||"")+"</span>"+r+"<span>";return"<li class='"+((null==(i=e.kindModifiers)?void 0:i.split(",").includes("deprecated"))?"deprecated":"")+"'>"+o+"</li>"})).join("");i+="".padStart(t.offset)+"<span class='inline-completions'><ul class='dropdown'>"+d+"</ul></span>"}else i+="<span class='query'>//"+"".padStart(t.offset-2)+"^ - No completions found</span>"}})),i+="\n")})),i=s(i.replace(/\n*$/,"")),i+="</code><a href='"+n.playgroundURL+"'>Try</a></div></pre>"}function d(e,t){var n=new Map;return e.forEach((function(e){var i=t(e),r=n.get(i);r?r.push(e):n.set(i,[e])})),n}function u(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+=c(e)).replace(/\n*$/,""))+"</code></div></pre>"}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>",e.forEach((function(e){0===e.length?n+="\n":(e.forEach((function(e){n+='<span style="color: '+e.color+'">'+c(e.content)+"</span>"})),n+="\n")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var h={compilerOptions:"The set of compiler options for your project",allowJs:"Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files.",allowSyntheticDefaultImports:"Allow 'import x from y' when a module doesn't have a default export.",allowUmdGlobalAccess:"Allow accessing UMD globals from modules.",allowUnreachableCode:"Disable error reporting for unreachable code.",allowUnusedLabels:"Disable error reporting for unused labels.",alwaysStrict:"Ensure 'use strict' is always emitted.",assumeChangesOnlyAffectDirectDependencies:"Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it.",baseUrl:"Specify the base directory to resolve non-relative module names.",charset:"No longer supported. In early versions, manually set the text encoding for reading files.",checkJs:"Enable error reporting in type-checked JavaScript files.",composite:"Enable constraints that allow a TypeScript project to be used with project references.",declaration:"Generate .d.ts files from TypeScript and JavaScript files in your project.",declarationDir:"Specify the output directory for generated declaration files.",declarationMap:"Create sourcemaps for d.ts files.",diagnostics:"Output compiler performance information after building.",disableReferencedProjectLoad:"Reduce the number of projects loaded automatically by TypeScript.",disableSizeLimit:"Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server.",disableSolutionSearching:"Opt a project out of multi-project reference checking when editing.",disableSourceOfProjectReferenceRedirect:"Disable preferring source files instead of declaration files when referencing composite projects",downlevelIteration:"Emit more compliant, but verbose and less performant JavaScript for iteration.",emitBOM:"Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.",emitDeclarationOnly:"Only output d.ts files and not JavaScript files.",emitDecoratorMetadata:"Emit design-type metadata for decorated declarations in source files.",esModuleInterop:"Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility.",exclude:"Filters results from the `include` option.",experimentalDecorators:"Enable experimental support for TC39 stage 2 draft decorators.",explainFiles:"Print files read during the compilation including why it was included.",extendedDiagnostics:"Output more detailed compiler performance information after building.",extends:"Specify one or more path or node module references to base configuration files from which settings are inherited.",fallbackPolling:"Specify what approach the watcher should use if the system runs out of native file watchers.",files:"Include a list of files. This does not support glob patterns, as opposed to `include`.",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 from tslib once per project, instead of including them per-file.",importsNotUsedAsValues:"Specify emit/checking behavior for imports that are only used for types.",include:"Specify a list of glob patterns that match files to be included in compilation.",incremental:"Save .tsbuildinfo files to allow for incremental compilation of projects.",inlineSourceMap:"Include sourcemap files inside the emitted JavaScript.",inlineSources:"Include source code in the sourcemaps inside the emitted JavaScript.",isolatedModules:"Ensure that each file can be safely transpiled without relying on other imports.",jsx:"Specify what JSX code is generated.",jsxFactory:"Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'",jsxFragmentFactory:"Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'.",jsxImportSource:"Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`",keyofStringsOnly:"Make keyof only return strings instead of string, numbers or symbols. Legacy option.",lib:"Specify a set of bundled library declaration files that describe the target runtime environment.",listEmittedFiles:"Print the names of emitted files after a compilation.",listFiles:"Print all of the files read during the compilation.",locale:"Set the language of the messaging from TypeScript. This does not affect emit.",mapRoot:"Specify the location where debugger should locate map files instead of generated locations.",maxNodeModuleJsDepth:"Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`.",module:"Specify what module code is generated.",moduleResolution:"Specify how TypeScript looks up a file from a given module specifier.",newLine:"Set the newline character for emitting files.",noEmit:"Disable emitting file from a compilation.",noEmitHelpers:"Disable generating custom helper functions like `__extends` in compiled output.",noEmitOnError:"Disable emitting files if any type checking errors are reported.",noErrorTruncation:"Disable truncating types in error messages.",noFallthroughCasesInSwitch:"Enable error reporting for fallthrough cases in switch statements.",noImplicitAny:"Enable error reporting for expressions and declarations with an implied `any` type..",noImplicitReturns:"Enable error reporting for codepaths that do not explicitly return in a function.",noImplicitThis:"Enable error reporting when `this` is given the type `any`.",noImplicitUseStrict:"Disable adding 'use strict' directives in emitted JavaScript files.",noLib:"Disable including any library files, including the default lib.d.ts.",noPropertyAccessFromIndexSignature:"Enforces using indexed accessors for keys declared using an indexed type",noResolve:"Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project.",noStrictGenericChecks:"Disable strict checking of generic signatures in function types.",noUncheckedIndexedAccess:"Add `undefined` to a type when accessed using an index.",noUnusedLocals:"Enable error reporting when a local variables aren't read.",noUnusedParameters:"Raise an error when a function parameter isn't read",out:"Deprecated setting. Use `outFile` instead.",outDir:"Specify an output folder for all emitted files.",outFile:"Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output.",paths:"Specify a set of entries that re-map imports to additional lookup locations.",plugins:"Specify a list of language service plugins to include.",preserveConstEnums:"Disable erasing `const enum` declarations in generated code.",preserveSymlinks:"Disable resolving symlinks to their realpath. This correlates to the same flag in node.",preserveWatchOutput:"Disable wiping the console in watch mode",pretty:"Enable color and formatting in output to make compiler errors easier to read",reactNamespace:"Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit.",references:"Specify an array of objects that specify paths for projects. Used in project references.",removeComments:"Disable emitting comments.",resolveJsonModule:"Enable importing .json files",rootDir:"Specify the root folder within your source files.",rootDirs:"Allow multiple folders to be treated as one when resolving modules.",skipDefaultLibCheck:"Skip type checking .d.ts files that are included with TypeScript.",skipLibCheck:"Skip type checking all .d.ts files.",sourceMap:"Create source map files for emitted JavaScript files.",sourceRoot:"Specify the root path for debuggers to find the reference source code.",strict:"Enable all strict type checking options.",strictBindCallApply:"Check that the arguments for `bind`, `call`, and `apply` methods match the original function.",strictFunctionTypes:"When assigning functions, check to ensure parameters and the return values are subtype-compatible.",strictNullChecks:"When type checking, take into account `null` and `undefined`.",strictPropertyInitialization:"Check for class properties that are declared but not set in the constructor.",stripInternal:"Disable emitting declarations that have `@internal` in their JSDoc comments.",suppressExcessPropertyErrors:"Disable reporting of excess property errors during the creation of object literals.",suppressImplicitAnyIndexErrors:"Suppress `noImplicitAny` errors when indexing objects that lack index signatures.",target:"Set the JavaScript language version for emitted JavaScript and include compatible library declarations.",traceResolution:"Log paths used during the `moduleResolution` process.",tsBuildInfoFile:"Specify the folder for .tsbuildinfo incremental compilation files.",typeAcquisition:"Specify options for automatic acquisition of declaration files.",typeRoots:"Specify multiple folders that act like `./node_modules/@types`.",types:"Specify type package names to be included without being referenced in a source file.",useDefineForClassFields:"Emit ECMAScript-standard-compliant class fields.",watchDirectory:"Specify how directories are watched on systems that lack recursive file-watching functionality.",watchFile:"Specify how the TypeScript watch mode works."},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")}))}))},m=function(e){if('"'!==e.content)return e.content.slice(1,e.content.length-1)in h};function y(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)&&m(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=\""+h[t]+'">'+c(t)+'</data-lsp></a>"</span>'}else n+='<span style="color: '+e.color+'">'+c(e.content)+"</span>"})),n+="\n")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var b=null,v=void 0,S={plainTextRenderer:u,defaultShikiRenderer:f,twoslashRenderer:p,tsconfigJSONRenderer:y};exports.createShikiHighlighter=function(t){return b?Promise.resolve(b):e.getHighlighter(t).then((function(e){return b=e}))},exports.renderCodeToHTML=function(e,t,n,i,r,o){if(!r&&!b)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");var a,s=r||b;try{a=s.codeToThemedTokens(e,t)}catch(t){return u(e,i||{})}return n.includes("twoslash")&&o?p(a,i||{},o):t&&t.startsWith("json")&&n.includes("tsconfig")?y(a,i||{}):f(a,{langId:t})},exports.renderers=S,exports.runTwoSlash=function(e,r,o,a){void 0===o&&(o={}),void 0===a&&(a={});var s=void 0,l={json5:"json"};return l[r]&&(r=l[r]),o.useNodeModules&&(v?s=new Map(v):(s=n.createDefaultMapFromNodeModules({target:6}),v=s),n.addAllFilesFromFolder(s,o.nodeModulesTypesPath||"node_modules/@types")),t.twoslasher(e,r,i({},a,{fsMap:s}))}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),t=require("@typescript/twoslash"),n=require("@typescript/vfs");function r(){return(r=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=/[a-z0-9-–—_+#]/i,o=/\s/,a=/[0-9-.]/,s=/[0-9-.e]/;function c(e,t){return void 0!==e&&t.test(e)}function l(e,t){var n=t.replace("twoslash",""),r=0,l={},p="",d=[e,n].filter(Boolean).join(" ");v(),h()||"{"===f()||(p=y());var u=r;return v(),h()||"{"!==f()||(l=S()),h()||u!==r?{languageName:p,meta:l}:g("Invalid character in language name: '"+f()+"'");function f(){return h()?g("Unexpected end of input"):d[r]}function h(){return r>=d.length}function g(e){throw new Error("Failed parsing code fence header '"+d+"' at position "+r+": "+e)}function m(e){if(h()||f()!==e)return g("Expected '"+e+"'");r++}function y(e){void 0===e&&(e="Expected identifier, but got nothing");for(var t="";!h()&&c(f(),i);)t+=f(),r++;return t||g(e)}function v(){for(;!h()&&c(f(),o);)r++}function b(){switch(f()){case"{":return S();case"'":case'"':return function(){var e,t="",n=f();for(r++;;){var i=(e=void 0,"\\"===(e=f())&&(r++,e+=f()),r++,e);if(i===n)break;t+=i.replace(/\\/,"")}return t}()}return c(f(),a)?function(){var e=f();for(r++;!h()&&c(f(),s);)e+=f(),r++;return parseFloat(e)}():function(){var e=y("Expected expression, but got nothing");switch(e){case"true":return!0;case"false":return!1;case"":return g("Expected expression, but got nothing");default:return g("Unrecognized input '"+e+"'")}}()}function S(){var e={};for(m("{"),v();!h()&&"}"!==f();){var t=y(),n=!0;v(),":"===f()&&(r++,v(),n=b(),v()),e[t]=n,","===f()&&r++,v()}return m("}"),e}}var p=function(e){return!!Object.keys(e).find((function(e){return!!e.includes("-")||NaN!==parseInt(e)}))},d=function(e){var t=[];return Object.keys(e).find((function(e){if(NaN!==parseInt(e)&&t.push(parseInt(e)),e.includes("-"))for(var n=e.split("-"),r=n[0],i=parseInt(n[1])+1,o=parseInt(r);o<i;o++)t.push(o)})),function(e){return t.includes(e)}},u=function(e,t,n,r){return e.slice(0,t)+r+e.slice(t+Math.abs(n))},f=function(e){return e.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯")},h=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")},g=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")};function m(e){var t={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+t[e]+";"}))}function y(e){return e.replace(/</g,"<").replace(/>/g,">")}function v(e,t,n,r){var i="",o=p(r),a=d(r);i+='<pre class="shiki twoslash lsp">',t.langId&&(i+='<div class="language-id">'+t.langId+"</div>"),i+="<div class='code-container'><code>";var s=b(n.errors,(function(e){return e.line}))||new Map,c=b(n.staticQuickInfos,(function(e){return e.line}))||new Map,l=b(n.queries,(function(e){return e.line-1}))||new Map,v=0;return e.forEach((function(t,n){var r=s.get(n)||[],p=c.get(n)||[],d=l.get(n)||[];if(0===t.length&&0===n)v+=1;else if(0===t.length)v+=1,i+="\n";else{var g=o?a(n)?" highlight":" dim":"";i+="<div class='line"+g+"'>";var b=0;t.forEach((function(e){var t="",n=function(t){return function(n){return t<=n.character&&t+e.content.length>=n.character+n.length}},o=r.filter(n(b)),a=p.filter(n(b)),s=d.filter(n(b)),c=[].concat(o,a,s).sort((function(e,t){return(e.start||0)-(t.start||0)}));t+=c.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 i=(" "+t).slice(1);return n.sort((function(e,t){return t.index-e.index})).forEach((function(e){i=u(i,e.index,0,e.text)})),r&&(i="⇍data-err⇏"+i+"⇍/data-err⇏"),h(m(i))}(c.map((function(e){var t={begin:e.start-v,end:e.start+e.length-v};return"renderedMessage"in e&&(t.classes="err"),"kind"in e&&(t.classes=e.kind),"targetString"in e&&(t.classes="lsp",t.lsp=m(e.text)),t})),e.content):f(e.content),i+='<span style="color: '+e.color+'">'+t+"</span>",b+=e.content.length,v+=e.content.length})),i+="</div>",v+=1}if(r.length){var S=r.map((function(e){return y(e.renderedMessage)})).join("</br>"),w=r.map((function(e){return e.code})).join("<br/>");i+='<span class="error"><span>'+S+'</span><span class="code">'+w+"</span></span>",i+='<span class="error-behind">'+S+"</span>"}d.length&&(d.forEach((function(t){switch(t.kind){case"query":var r,o,a,s=(null==(r=(e[n-1]||[])[0])?void 0:r.content)||"",c=s.slice(0,(null==(o=/\S/.exec(s))?void 0:o.index)||0),l=c+"//"+"".padStart(t.offset-2-c.length),p=null==(a=t.text)?void 0:a.split("\n").map((function(e,t){return 0!==t?l+e:e})).join("\n");i+="<span class='query'>"+l+"^ = "+p+"</span>";break;case"completions":if(t.completions){var d=t.completions.filter((function(e){return e.name.startsWith(t.completionsPrefix||"____")})).sort((function(e,t){return e.name.localeCompare(t.name)})).map((function(e){var n,r,i=e.name.substr((null==(n=t.completionsPrefix)?void 0:n.length)||0),o="<span><span class='result-found'>"+(t.completionsPrefix||"")+"</span>"+i+"<span>";return"<li class='"+((null==(r=e.kindModifiers)?void 0:r.split(",").includes("deprecated"))?"deprecated":"")+"'>"+o+"</li>"})).join("");i+="".padStart(t.offset)+"<span class='inline-completions'><ul class='dropdown'>"+d+"</ul></span>"}else i+="<span class='query'>//"+"".padStart(t.offset-2)+"^ - No completions found</span>"}})),i+="\n")})),i=g(i.replace(/\n*$/,"")),i+="</code><a href='"+n.playgroundURL+"'>Try</a></div></pre>"}function b(e,t){var n=new Map;return e.forEach((function(e){var r=t(e),i=n.get(r);i?i.push(e):n.set(r,[e])})),n}function S(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+=y(e)).replace(/\n*$/,""))+"</code></div></pre>"}function w(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+="<div class='line'></div>":(n+="<div class='line'>",e.forEach((function(e){n+='<span style="color: '+e.color+'">'+y(e.content)+"</span>"})),n+="</div>")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var x={compilerOptions:"The set of compiler options for your project",allowJs:"Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files.",allowSyntheticDefaultImports:"Allow 'import x from y' when a module doesn't have a default export.",allowUmdGlobalAccess:"Allow accessing UMD globals from modules.",allowUnreachableCode:"Disable error reporting for unreachable code.",allowUnusedLabels:"Disable error reporting for unused labels.",alwaysStrict:"Ensure 'use strict' is always emitted.",assumeChangesOnlyAffectDirectDependencies:"Have recompiles in projects that use `incremental` and `watch` mode assume that changes within a file will only affect files directly depending on it.",baseUrl:"Specify the base directory to resolve non-relative module names.",charset:"No longer supported. In early versions, manually set the text encoding for reading files.",checkJs:"Enable error reporting in type-checked JavaScript files.",composite:"Enable constraints that allow a TypeScript project to be used with project references.",declaration:"Generate .d.ts files from TypeScript and JavaScript files in your project.",declarationDir:"Specify the output directory for generated declaration files.",declarationMap:"Create sourcemaps for d.ts files.",diagnostics:"Output compiler performance information after building.",disableReferencedProjectLoad:"Reduce the number of projects loaded automatically by TypeScript.",disableSizeLimit:"Remove the 20mb cap on total source code size for JavaScript files in the TypeScript language server.",disableSolutionSearching:"Opt a project out of multi-project reference checking when editing.",disableSourceOfProjectReferenceRedirect:"Disable preferring source files instead of declaration files when referencing composite projects",downlevelIteration:"Emit more compliant, but verbose and less performant JavaScript for iteration.",emitBOM:"Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.",emitDeclarationOnly:"Only output d.ts files and not JavaScript files.",emitDecoratorMetadata:"Emit design-type metadata for decorated declarations in source files.",esModuleInterop:"Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility.",exclude:"Filters results from the `include` option.",experimentalDecorators:"Enable experimental support for TC39 stage 2 draft decorators.",explainFiles:"Print files read during the compilation including why it was included.",extendedDiagnostics:"Output more detailed compiler performance information after building.",extends:"Specify one or more path or node module references to base configuration files from which settings are inherited.",fallbackPolling:"Specify what approach the watcher should use if the system runs out of native file watchers.",files:"Include a list of files. This does not support glob patterns, as opposed to `include`.",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 from tslib once per project, instead of including them per-file.",importsNotUsedAsValues:"Specify emit/checking behavior for imports that are only used for types.",include:"Specify a list of glob patterns that match files to be included in compilation.",incremental:"Save .tsbuildinfo files to allow for incremental compilation of projects.",inlineSourceMap:"Include sourcemap files inside the emitted JavaScript.",inlineSources:"Include source code in the sourcemaps inside the emitted JavaScript.",isolatedModules:"Ensure that each file can be safely transpiled without relying on other imports.",jsx:"Specify what JSX code is generated.",jsxFactory:"Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'",jsxFragmentFactory:"Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'.",jsxImportSource:"Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.`",keyofStringsOnly:"Make keyof only return strings instead of string, numbers or symbols. Legacy option.",lib:"Specify a set of bundled library declaration files that describe the target runtime environment.",listEmittedFiles:"Print the names of emitted files after a compilation.",listFiles:"Print all of the files read during the compilation.",locale:"Set the language of the messaging from TypeScript. This does not affect emit.",mapRoot:"Specify the location where debugger should locate map files instead of generated locations.",maxNodeModuleJsDepth:"Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`.",module:"Specify what module code is generated.",moduleResolution:"Specify how TypeScript looks up a file from a given module specifier.",newLine:"Set the newline character for emitting files.",noEmit:"Disable emitting file from a compilation.",noEmitHelpers:"Disable generating custom helper functions like `__extends` in compiled output.",noEmitOnError:"Disable emitting files if any type checking errors are reported.",noErrorTruncation:"Disable truncating types in error messages.",noFallthroughCasesInSwitch:"Enable error reporting for fallthrough cases in switch statements.",noImplicitAny:"Enable error reporting for expressions and declarations with an implied `any` type..",noImplicitReturns:"Enable error reporting for codepaths that do not explicitly return in a function.",noImplicitThis:"Enable error reporting when `this` is given the type `any`.",noImplicitUseStrict:"Disable adding 'use strict' directives in emitted JavaScript files.",noLib:"Disable including any library files, including the default lib.d.ts.",noPropertyAccessFromIndexSignature:"Enforces using indexed accessors for keys declared using an indexed type",noResolve:"Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project.",noStrictGenericChecks:"Disable strict checking of generic signatures in function types.",noUncheckedIndexedAccess:"Add `undefined` to a type when accessed using an index.",noUnusedLocals:"Enable error reporting when a local variables aren't read.",noUnusedParameters:"Raise an error when a function parameter isn't read",out:"Deprecated setting. Use `outFile` instead.",outDir:"Specify an output folder for all emitted files.",outFile:"Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output.",paths:"Specify a set of entries that re-map imports to additional lookup locations.",plugins:"Specify a list of language service plugins to include.",preserveConstEnums:"Disable erasing `const enum` declarations in generated code.",preserveSymlinks:"Disable resolving symlinks to their realpath. This correlates to the same flag in node.",preserveWatchOutput:"Disable wiping the console in watch mode",pretty:"Enable color and formatting in output to make compiler errors easier to read",reactNamespace:"Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit.",references:"Specify an array of objects that specify paths for projects. Used in project references.",removeComments:"Disable emitting comments.",resolveJsonModule:"Enable importing .json files",rootDir:"Specify the root folder within your source files.",rootDirs:"Allow multiple folders to be treated as one when resolving modules.",skipDefaultLibCheck:"Skip type checking .d.ts files that are included with TypeScript.",skipLibCheck:"Skip type checking all .d.ts files.",sourceMap:"Create source map files for emitted JavaScript files.",sourceRoot:"Specify the root path for debuggers to find the reference source code.",strict:"Enable all strict type checking options.",strictBindCallApply:"Check that the arguments for `bind`, `call`, and `apply` methods match the original function.",strictFunctionTypes:"When assigning functions, check to ensure parameters and the return values are subtype-compatible.",strictNullChecks:"When type checking, take into account `null` and `undefined`.",strictPropertyInitialization:"Check for class properties that are declared but not set in the constructor.",stripInternal:"Disable emitting declarations that have `@internal` in their JSDoc comments.",suppressExcessPropertyErrors:"Disable reporting of excess property errors during the creation of object literals.",suppressImplicitAnyIndexErrors:"Suppress `noImplicitAny` errors when indexing objects that lack index signatures.",target:"Set the JavaScript language version for emitted JavaScript and include compatible library declarations.",traceResolution:"Log paths used during the `moduleResolution` process.",tsBuildInfoFile:"Specify the folder for .tsbuildinfo incremental compilation files.",typeAcquisition:"Specify options for automatic acquisition of declaration files.",typeRoots:"Specify multiple folders that act like `./node_modules/@types`.",types:"Specify type package names to be included without being referenced in a source file.",useDefineForClassFields:"Emit ECMAScript-standard-compliant class fields.",watchDirectory:"Specify how directories are watched on systems that lack recursive file-watching functionality.",watchFile:"Specify how the TypeScript watch mode works."},k=function(e){return!!e.explanation&&e.explanation.find((function(e){return e.scopes.find((function(e){return e.scopeName.includes("support.type.property-name")}))}))},E=function(e){if('"'!==e.content)return e.content.slice(1,e.content.length-1)in x};function j(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+="<div class='line'></div>":(n+="<div class='line'>",e.forEach((function(e){if(k(e)&&E(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=\""+x[t]+'">'+y(t)+'</data-lsp></a>"</span>'}else n+='<span style="color: '+e.color+'">'+y(e.content)+"</span>"})),n+="</div>")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var I=null,D=void 0,J={plainTextRenderer:S,defaultShikiRenderer:w,twoslashRenderer:v,tsconfigJSONRenderer:j};exports.createShikiHighlighter=function(t){return I?Promise.resolve(I):e.getHighlighter(t).then((function(e){return I=e}))},exports.parseCodeFenceInfo=l,exports.renderCodeToHTML=function(e,t,n,r,i,o){if(!i&&!I)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");var a,s=i||I;try{a=s.codeToThemedTokens(e,t)}catch(t){return S(e,r||{})}return n.includes("twoslash")&&o?v(a,r||{},o,l(t,(n&&"string"==typeof n?n:n.join(" "))||"").meta):t&&t.startsWith("json")&&n.includes("tsconfig")?j(a,r||{}):w(a,{langId:t})},exports.renderers=J,exports.runTwoSlash=function(e,i,o,a){void 0===o&&(o={}),void 0===a&&(a={});var s=void 0,c={json5:"json"};return c[i]&&(i=c[i]),o.useNodeModules&&(D?s=new Map(D):(s=n.createDefaultMapFromNodeModules({target:6}),D=s),n.addAllFilesFromFolder(s,o.nodeModulesTypesPath||"node_modules/@types")),t.twoslasher(e,i,r({},a,{fsMap:s}))}; | ||
//# sourceMappingURL=shiki-twoslash.cjs.production.min.js.map |
@@ -23,2 +23,228 @@ import { getHighlighter } from 'shiki'; | ||
// Based on https://github.com/andrewbranch/gatsby-remark-vscode/blob/7bf5c036a58652c1f45d27c5874557f7b531102c/src/index.js | ||
// which is MIT https://github.com/andrewbranch/gatsby-remark-vscode/blob/7bf5c036a58652c1f45d27c5874557f7b531102c/LICENSE | ||
// Only difference is conversion to TypeScript, and a replace at the top | ||
var identifierPattern = /[a-z0-9-–—_+#]/i; | ||
var triviaPattern = /\s/; | ||
var startOfNumberPattern = /[0-9-.]/; | ||
var numberPattern = /[0-9-.e]/; | ||
function testRegex(input, pattern) { | ||
if (input === undefined) return false; | ||
return pattern.test(input); | ||
} | ||
/** Takes the language and a meta-string and offers a useful object for looking at params */ | ||
function parseCodeFenceInfo(lang, fullMetaString) { | ||
// Heh | ||
var metaString = fullMetaString.replace("twoslash", ""); | ||
var pos = 0; | ||
var meta = {}; | ||
var languageName = ""; | ||
var input = [lang, metaString].filter(Boolean).join(" "); | ||
skipTrivia(); | ||
if (!isEnd() && current() !== "{") { | ||
languageName = parseIdentifier(); | ||
} | ||
var languageNameEnd = pos; | ||
skipTrivia(); | ||
if (!isEnd() && current() === "{") { | ||
meta = parseObject(); | ||
} | ||
if (!isEnd() && languageNameEnd === pos) { | ||
return fail("Invalid character in language name: '" + current() + "'"); | ||
} | ||
return { | ||
languageName: languageName, | ||
meta: meta | ||
}; | ||
function current() { | ||
if (isEnd()) { | ||
return fail("Unexpected end of input"); | ||
} | ||
return input[pos]; | ||
} | ||
function isEnd() { | ||
return pos >= input.length; | ||
} | ||
function fail(message) { | ||
throw new Error("Failed parsing code fence header '" + input + "' at position " + pos + ": " + message); | ||
} | ||
function scanExpected(expected) { | ||
if (isEnd() || current() !== expected) { | ||
return fail("Expected '" + expected + "'"); | ||
} | ||
pos++; | ||
} | ||
function parseIdentifier(errorMessage) { | ||
if (errorMessage === void 0) { | ||
errorMessage = "Expected identifier, but got nothing"; | ||
} | ||
var identifier = ""; | ||
while (!isEnd() && testRegex(current(), identifierPattern)) { | ||
identifier += current(); | ||
pos++; | ||
} | ||
if (!identifier) { | ||
return fail(errorMessage); | ||
} | ||
return identifier; | ||
} | ||
function skipTrivia() { | ||
while (!isEnd() && testRegex(current(), triviaPattern)) { | ||
pos++; | ||
} | ||
} | ||
function parseChar() { | ||
var _char = current(); | ||
if (_char === "\\") { | ||
pos++; | ||
_char += current(); | ||
} | ||
pos++; | ||
return _char; | ||
} | ||
function parseString() { | ||
var str = ""; | ||
var quote = current(); | ||
pos++; | ||
while (true) { | ||
var _char2 = parseChar(); | ||
if (_char2 === quote) break; | ||
str += _char2.replace(/\\/, ""); | ||
} | ||
return str; | ||
} | ||
function parseNumber() { | ||
var numStr = current(); | ||
pos++; | ||
while (!isEnd() && testRegex(current(), numberPattern)) { | ||
numStr += current(); | ||
pos++; | ||
} | ||
return parseFloat(numStr); | ||
} | ||
function parseBoolean() { | ||
var identifier = parseIdentifier("Expected expression, but got nothing"); | ||
switch (identifier) { | ||
case "true": | ||
return true; | ||
case "false": | ||
return false; | ||
case "": | ||
return fail("Expected expression, but got nothing"); | ||
default: | ||
return fail("Unrecognized input '" + identifier + "'"); | ||
} | ||
} | ||
function parseExpression() { | ||
switch (current()) { | ||
case "{": | ||
return parseObject(); | ||
case "'": | ||
case '"': | ||
return parseString(); | ||
} | ||
if (testRegex(current(), startOfNumberPattern)) { | ||
return parseNumber(); | ||
} | ||
return parseBoolean(); | ||
} | ||
function parseObject() { | ||
var obj = {}; | ||
scanExpected("{"); | ||
skipTrivia(); | ||
while (!isEnd() && current() !== "}") { | ||
var key = parseIdentifier(); | ||
var value = true; | ||
skipTrivia(); | ||
if (current() === ":") { | ||
pos++; | ||
skipTrivia(); | ||
value = parseExpression(); | ||
skipTrivia(); | ||
} | ||
obj[key] = value; | ||
if (current() === ",") pos++; | ||
skipTrivia(); | ||
} | ||
scanExpected("}"); | ||
return obj; | ||
} | ||
} | ||
/** Does anything in the object imply that we should highlight any lines? */ | ||
var shouldBeHighlightable = function shouldBeHighlightable(meta) { | ||
return !!Object.keys(meta).find(function (key) { | ||
if (key.includes("-")) return true; | ||
if (parseInt(key) !== NaN) return true; | ||
return false; | ||
}); | ||
}; | ||
/** Returns a func for figuring out if this line should be highlighted */ | ||
var shouldHighlightLine = function shouldHighlightLine(meta) { | ||
var lines = []; | ||
Object.keys(meta).find(function (key) { | ||
if (parseInt(key) !== NaN) lines.push(parseInt(key)); | ||
if (key.includes("-")) { | ||
var _key$split = key.split("-"), | ||
first = _key$split[0], | ||
last = _key$split[1]; | ||
var lastIndex = parseInt(last) + 1; | ||
for (var i = parseInt(first); i < lastIndex; i++) { | ||
lines.push(i); | ||
} | ||
} | ||
}); | ||
return function (line) { | ||
return lines.includes(line); | ||
}; | ||
}; | ||
var splice = function splice(str, idx, rem, newString) { | ||
@@ -101,3 +327,3 @@ return str.slice(0, idx) + newString + str.slice(idx + Math.abs(rem)); | ||
// 1: Syntax highlight info from shiki | ||
// 2: Twoslash metadata like errors, indentifiers etc | ||
// 2: Twoslash metadata like errors, identifiers etc | ||
// Because shiki gives use a set of lines to work from, then the first thing which happens | ||
@@ -112,4 +338,6 @@ // is converting twoslash data into the same format. | ||
function twoslashRenderer(lines, options, twoslash) { | ||
function twoslashRenderer(lines, options, twoslash, codefenceMeta) { | ||
var html = ""; | ||
var hasHighlight = shouldBeHighlightable(codefenceMeta); | ||
var hl = shouldHighlightLine(codefenceMeta); | ||
html += "<pre class=\"shiki twoslash lsp\">"; | ||
@@ -132,2 +360,7 @@ | ||
}) || new Map(); | ||
/** | ||
* This is the index of the original twoslash code reference, it is not | ||
* related to the HTML output | ||
*/ | ||
var filePos = 0; | ||
@@ -146,4 +379,7 @@ lines.forEach(function (l, i) { | ||
} else { | ||
// Keep track of the position of the current token in a line so we can match it up to the | ||
var hiClass = hasHighlight ? hl(i) ? " highlight" : " dim" : ""; | ||
var prefix = "<div class='line" + hiClass + "'>"; | ||
html += prefix; // Keep track of the position of the current token in a line so we can match it up to the | ||
// errors and lang serv identifiers | ||
var tokenPos = 0; | ||
@@ -172,3 +408,3 @@ l.forEach(function (token) { | ||
end: token.start + token.length - filePos | ||
}; | ||
}; // prettier-ignore | ||
@@ -194,3 +430,4 @@ if ("renderedMessage" in token) range.classes = "err"; | ||
}); | ||
html += "\n"; | ||
html += "</div>"; // This is the \n which the </div> represents | ||
filePos += 1; | ||
@@ -310,8 +547,9 @@ } // Adding error messages to the line after | ||
if (l.length === 0) { | ||
html += "\n"; | ||
html += "<div class='line'></div>"; | ||
} else { | ||
html += "<div class='line'>"; | ||
l.forEach(function (token) { | ||
html += "<span style=\"color: " + token.color + "\">" + escapeHtml(token.content) + "</span>"; | ||
}); | ||
html += "\n"; | ||
html += "</div>"; | ||
} | ||
@@ -471,4 +709,5 @@ }); | ||
if (l.length === 0) { | ||
html += "\n"; | ||
html += "<div class='line'></div>"; | ||
} else { | ||
html += "<div class='line'>"; | ||
l.forEach(function (token) { | ||
@@ -485,3 +724,3 @@ // This means we're looking at a token which could be '"module"', '"', '"compilerOptions"' etc | ||
}); | ||
html += "\n"; | ||
html += "</div>"; | ||
} | ||
@@ -512,11 +751,2 @@ }); | ||
if (storedHighlighter) return Promise.resolve(storedHighlighter); | ||
// shikiTheme = getTheme(theme) | ||
// } catch (error) { | ||
// try { | ||
// shikiTheme = loadTheme(theme) | ||
// } catch (error) { | ||
// throw new Error("Unable to load theme: " + theme + " - " + error.message) | ||
// } | ||
// } | ||
return getHighlighter(options).then(function (newHighlighter) { | ||
@@ -559,3 +789,5 @@ storedHighlighter = newHighlighter; | ||
if (info.includes("twoslash") && twoslash) { | ||
return twoslashRenderer(tokens, shikiOptions || {}, twoslash); | ||
var metaInfo = info && typeof info === "string" ? info : info.join(" "); | ||
var codefenceMeta = parseCodeFenceInfo(lang, metaInfo || ""); | ||
return twoslashRenderer(tokens, shikiOptions || {}, twoslash, codefenceMeta.meta); | ||
} // TSConfig renderer | ||
@@ -629,3 +861,3 @@ | ||
export { createShikiHighlighter, renderCodeToHTML, renderers, runTwoSlash }; | ||
export { createShikiHighlighter, parseCodeFenceInfo, renderCodeToHTML, renderers, runTwoSlash }; | ||
//# sourceMappingURL=shiki-twoslash.esm.js.map |
{ | ||
"name": "shiki-twoslash", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"license": "MIT", | ||
@@ -5,0 +5,0 @@ "homepage": "https://github.com/microsoft/TypeScript-Website", |
@@ -5,3 +5,3 @@ ### shiki-twoslash | ||
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). | ||
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) to provide rich contextual code samples. | ||
@@ -14,6 +14,2 @@ Things it handles: | ||
Useful, but not critical: | ||
- Checking if shiki can handle a code sample: `canHighlightLang` | ||
### API | ||
@@ -108,1 +104,2 @@ | ||
- [gatsby-remark-shiki-twoslash](https://www.npmjs.com/package/gatsby-remark-shiki-twoslash) | ||
- [remark-shiki-twoslash](https://www.npmjs.com/package/remark-shiki-twoslash) |
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
271392
20
1830
103