Socket
Socket
Sign inDemoInstall

shiki-twoslash

Package Overview
Dependencies
Maintainers
2
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 1.1.0 to 1.2.0

10

dist/index.d.ts

@@ -7,6 +7,4 @@ import { Highlighter, HighlighterOptions } from "shiki";

import { tsconfigJSONRenderer } from "./renderers/tsconfig";
export declare type ShikiTwoslashSettings = {
useNodeModules?: true;
nodeModulesTypesPath?: string;
};
/** The possible user config, a combination of all shiki and twoslash options */
export declare type UserConfigSettings = HighlighterOptions & TwoSlashOptions;
/**

@@ -28,3 +26,3 @@ * Creates a Shiki highlighter, this is an async call because of the call to WASM to get the regex parser set up.

* @param lang the language to use in highlighting
* @param info additional metadata which lives after the codefence lang (e.g. ["twoslash"])
* @param info additional metadata which lives after the code-fence lang (e.g. ["twoslash"])
* @param highlighter optional, but you should use it, highlighter

@@ -37,3 +35,3 @@ * @param twoslash optional, but required when info contains 'twoslash' as a string

*/
export declare const runTwoSlash: (code: string, lang: string, settings?: ShikiTwoslashSettings, twoslashDefaults?: TwoSlashOptions) => TwoSlashReturn;
export declare const runTwoSlash: (code: string, lang: string, settings?: UserConfigSettings) => TwoSlashReturn;
export { parseCodeFenceInfo } from "./parseCodeFenceInfo";

@@ -40,0 +38,0 @@ /** Set of renderers if you want to explicitly call one instead of using renderCodeToHTML */

78

dist/shiki-twoslash.cjs.development.js

@@ -7,22 +7,3 @@ 'use strict';

var twoslash = require('@typescript/twoslash');
var vfs = require('@typescript/vfs');
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
// Based on https://github.com/andrewbranch/gatsby-remark-vscode/blob/7bf5c036a58652c1f45d27c5874557f7b531102c/src/index.js

@@ -345,3 +326,5 @@ // which is MIT https://github.com/andrewbranch/gatsby-remark-vscode/blob/7bf5c036a58652c1f45d27c5874557f7b531102c/LICENSE

var hl = shouldHighlightLine(codefenceMeta);
html += "<pre class=\"shiki twoslash lsp\">";
var bg = options.bg || "#fff";
var fg = options.fg || "black";
html += "<pre class=\"shiki twoslash lsp\" style=\"background-color: " + bg + "; color: " + fg + "\">";

@@ -521,3 +504,5 @@ if (options.langId) {

var html = "";
html += "<pre class=\"shiki\">";
var bg = options.bg || "#fff";
var fg = options.fg || "black";
html += "<pre class=\"shiki\" style=\"background-color: " + bg + "; color: " + fg + "\">";

@@ -538,3 +523,5 @@ if (options.langId) {

var html = "";
html += "<pre class=\"shiki\">";
var bg = options.bg || "#fff";
var fg = options.fg || "black";
html += "<pre class=\"shiki\" style=\"background-color: " + bg + "; color: " + fg + "\">";

@@ -700,3 +687,5 @@ if (options.langId) {

var html = "";
html += "<pre class=\"shiki tsconfig lsp\">";
var bg = options.bg || "#fff";
var fg = options.fg || "black";
html += "<pre class=\"shiki tsconfig lsp\" style=\"background-color: " + bg + "; color: " + fg + "\">";

@@ -763,3 +752,3 @@ if (options.langId) {

* @param lang the language to use in highlighting
* @param info additional metadata which lives after the codefence lang (e.g. ["twoslash"])
* @param info additional metadata which lives after the code-fence lang (e.g. ["twoslash"])
* @param highlighter optional, but you should use it, highlighter

@@ -802,5 +791,3 @@ * @param twoslash optional, but required when info contains 'twoslash' as a string

});
}; // Basically so that we can store this once, then re-use it in the same process
var nodeModulesMap = undefined;
};
/**

@@ -810,3 +797,3 @@ * Runs Twoslash over the code passed in with a particular language as the default file.

var runTwoSlash = function runTwoSlash(code, lang, settings, twoslashDefaults) {
var runTwoSlash = function runTwoSlash(code, lang, settings) {
if (settings === void 0) {

@@ -816,36 +803,11 @@ settings = {};

if (twoslashDefaults === void 0) {
twoslashDefaults = {};
}
var map = undefined; // Shiki doesn't respect json5 as an input, so switch it
// Shiki doesn't respect json5 as an input, so switch it
// to json, which can handle comments in the syntax highlight
var replacer = {
json5: "json"
json5: "json",
yml: "yaml"
}; // @ts-ignore
if (replacer[lang]) lang = replacer[lang]; // Add @types to the fsmap
if (settings.useNodeModules) {
// we don't want a hard dep on TS, so that browsers can run this code)
var laterESVersion = 6; // Save node modules into a cached object which we re-create from (emits can edit the map)
if (nodeModulesMap) {
map = new Map(nodeModulesMap);
} else {
map = vfs.createDefaultMapFromNodeModules({
target: laterESVersion
});
nodeModulesMap = map;
} // Maybe it's worth only doing the imports in the file, but that would break dts deps
// const imports = parseFileForModuleReferences(code).filter((mod) => !mod.startsWith("."))
vfs.addAllFilesFromFolder(map, settings.nodeModulesTypesPath || "node_modules/@types");
}
var results = twoslash.twoslasher(code, lang, _extends({}, twoslashDefaults, {
fsMap: map
}));
if (replacer[lang]) lang = replacer[lang];
var results = twoslash.twoslasher(code, lang, settings);
return results;

@@ -852,0 +814,0 @@ };

@@ -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 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,"&lt;").replace(/⇏/g,"&gt;").replace(/⇯/g,"&apos;")};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,"&lt;").replace(/>/g,"&gt;")}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}))};
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("shiki"),t=require("@typescript/twoslash"),n=/[a-z0-9-–—_+#]/i,r=/\s/,i=/[0-9-.]/,o=/[0-9-.e]/;function a(e,t){return void 0!==e&&t.test(e)}function s(e,t){var s=t.replace("twoslash",""),c=0,l={},p="",d=[e,s].filter(Boolean).join(" ");b(),h()||"{"===f()||(p=y());var u=c;return b(),h()||"{"!==f()||(l=S()),h()||u!==c?{languageName:p,meta:l}:g("Invalid character in language name: '"+f()+"'");function f(){return h()?g("Unexpected end of input"):d[c]}function h(){return c>=d.length}function g(e){throw new Error("Failed parsing code fence header '"+d+"' at position "+c+": "+e)}function m(e){if(h()||f()!==e)return g("Expected '"+e+"'");c++}function y(e){void 0===e&&(e="Expected identifier, but got nothing");for(var t="";!h()&&a(f(),n);)t+=f(),c++;return t||g(e)}function b(){for(;!h()&&a(f(),r);)c++}function v(){switch(f()){case"{":return S();case"'":case'"':return function(){var e,t="",n=f();for(c++;;){var r=(e=void 0,"\\"===(e=f())&&(c++,e+=f()),c++,e);if(r===n)break;t+=r.replace(/\\/,"")}return t}()}return a(f(),i)?function(){var e=f();for(c++;!h()&&a(f(),o);)e+=f(),c++;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("{"),b();!h()&&"}"!==f();){var t=y(),n=!0;b(),":"===f()&&(c++,b(),n=v(),b()),e[t]=n,","===f()&&c++,b()}return m("}"),e}}var c=function(e){return!!Object.keys(e).find((function(e){return!!e.includes("-")||NaN!==parseInt(e)}))},l=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)}},p=function(e,t,n,r){return e.slice(0,t)+r+e.slice(t+Math.abs(n))},d=function(e){return e.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯")},u=function(e){return e.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")},f=function(e){return e.replace(/⇍/g,"&lt;").replace(/⇏/g,"&gt;").replace(/⇯/g,"&apos;")};function h(e){var t={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+t[e]+";"}))}function g(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function m(e,t,n,r){var i="",o=c(r),a=l(r);i+='<pre class="shiki twoslash lsp" style="background-color: '+(t.bg||"#fff")+"; color: "+(t.fg||"black")+'">',t.langId&&(i+='<div class="language-id">'+t.langId+"</div>"),i+="<div class='code-container'><code>";var s=y(n.errors,(function(e){return e.line}))||new Map,m=y(n.staticQuickInfos,(function(e){return e.line}))||new Map,b=y(n.queries,(function(e){return e.line-1}))||new Map,v=0;return e.forEach((function(t,n){var r=s.get(n)||[],c=m.get(n)||[],l=b.get(n)||[];if(0===t.length&&0===n)v+=1;else if(0===t.length)v+=1,i+="\n";else{var f=o?a(n)?" highlight":" dim":"";i+="<div class='line"+f+"'>";var y=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(y)),a=c.filter(n(y)),s=l.filter(n(y)),f=[].concat(o,a,s).sort((function(e,t){return(e.start||0)-(t.start||0)}));t+=f.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=p(i,e.index,0,e.text)})),r&&(i="⇍data-err⇏"+i+"⇍/data-err⇏"),u(h(i))}(f.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=h(e.text)),t})),e.content):d(e.content),i+='<span style="color: '+e.color+'">'+t+"</span>",y+=e.content.length,v+=e.content.length})),i+="</div>",v+=1}if(r.length){var S=r.map((function(e){return g(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>"}l.length&&(l.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=f(i.replace(/\n*$/,"")),i+="</code><a href='"+n.playgroundURL+"'>Try</a></div></pre>"}function y(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 b(e,t){var n="";return n+='<pre class="shiki" style="background-color: '+(t.bg||"#fff")+"; color: "+(t.fg||"black")+'">',t.langId&&(n+='<div class="language-id">'+t.langId+"</div>"),n+="<div class='code-container'><code>",(n=(n+=g(e)).replace(/\n*$/,""))+"</code></div></pre>"}function v(e,t){var n="";return n+='<pre class="shiki" style="background-color: '+(t.bg||"#fff")+"; color: "+(t.fg||"black")+'">',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+'">'+g(e.content)+"</span>"})),n+="</div>")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var S={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."},w=function(e){return!!e.explanation&&e.explanation.find((function(e){return e.scopes.find((function(e){return e.scopeName.includes("support.type.property-name")}))}))},k=function(e){if('"'!==e.content)return e.content.slice(1,e.content.length-1)in S};function x(e,t){var n="";return n+='<pre class="shiki tsconfig lsp" style="background-color: '+(t.bg||"#fff")+"; color: "+(t.fg||"black")+'">',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(w(e)&&k(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=\""+S[t]+'">'+g(t)+'</data-lsp></a>"</span>'}else n+='<span style="color: '+e.color+'">'+g(e.content)+"</span>"})),n+="</div>")})),n=n.replace(/\n*$/,""),n+="</code></div></pre>"}var E=null,I={plainTextRenderer:b,defaultShikiRenderer:v,twoslashRenderer:m,tsconfigJSONRenderer:x};exports.createShikiHighlighter=function(t){return E?Promise.resolve(E):e.getHighlighter(t).then((function(e){return E=e}))},exports.parseCodeFenceInfo=s,exports.renderCodeToHTML=function(e,t,n,r,i,o){if(!i&&!E)throw new Error("The highlighter object hasn't been initialised via `setupHighLighter` yet in render-shiki-twoslash");var a,c=i||E;try{a=c.codeToThemedTokens(e,t)}catch(t){return b(e,r||{})}return n.includes("twoslash")&&o?m(a,r||{},o,s(t,(n&&"string"==typeof n?n:n.join(" "))||"").meta):t&&t.startsWith("json")&&n.includes("tsconfig")?x(a,r||{}):v(a,{langId:t})},exports.renderers=I,exports.runTwoSlash=function(e,n,r){void 0===r&&(r={});var i={json5:"json",yml:"yaml"};return i[n]&&(n=i[n]),t.twoslasher(e,n,r)};
//# sourceMappingURL=shiki-twoslash.cjs.production.min.js.map
import { getHighlighter } from 'shiki';
import { twoslasher } from '@typescript/twoslash';
import { createDefaultMapFromNodeModules, addAllFilesFromFolder } from '@typescript/vfs';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
// Based on https://github.com/andrewbranch/gatsby-remark-vscode/blob/7bf5c036a58652c1f45d27c5874557f7b531102c/src/index.js

@@ -340,3 +321,5 @@ // which is MIT https://github.com/andrewbranch/gatsby-remark-vscode/blob/7bf5c036a58652c1f45d27c5874557f7b531102c/LICENSE

var hl = shouldHighlightLine(codefenceMeta);
html += "<pre class=\"shiki twoslash lsp\">";
var bg = options.bg || "#fff";
var fg = options.fg || "black";
html += "<pre class=\"shiki twoslash lsp\" style=\"background-color: " + bg + "; color: " + fg + "\">";

@@ -516,3 +499,5 @@ if (options.langId) {

var html = "";
html += "<pre class=\"shiki\">";
var bg = options.bg || "#fff";
var fg = options.fg || "black";
html += "<pre class=\"shiki\" style=\"background-color: " + bg + "; color: " + fg + "\">";

@@ -533,3 +518,5 @@ if (options.langId) {

var html = "";
html += "<pre class=\"shiki\">";
var bg = options.bg || "#fff";
var fg = options.fg || "black";
html += "<pre class=\"shiki\" style=\"background-color: " + bg + "; color: " + fg + "\">";

@@ -695,3 +682,5 @@ if (options.langId) {

var html = "";
html += "<pre class=\"shiki tsconfig lsp\">";
var bg = options.bg || "#fff";
var fg = options.fg || "black";
html += "<pre class=\"shiki tsconfig lsp\" style=\"background-color: " + bg + "; color: " + fg + "\">";

@@ -758,3 +747,3 @@ if (options.langId) {

* @param lang the language to use in highlighting
* @param info additional metadata which lives after the codefence lang (e.g. ["twoslash"])
* @param info additional metadata which lives after the code-fence lang (e.g. ["twoslash"])
* @param highlighter optional, but you should use it, highlighter

@@ -797,5 +786,3 @@ * @param twoslash optional, but required when info contains 'twoslash' as a string

});
}; // Basically so that we can store this once, then re-use it in the same process
var nodeModulesMap = undefined;
};
/**

@@ -805,3 +792,3 @@ * Runs Twoslash over the code passed in with a particular language as the default file.

var runTwoSlash = function runTwoSlash(code, lang, settings, twoslashDefaults) {
var runTwoSlash = function runTwoSlash(code, lang, settings) {
if (settings === void 0) {

@@ -811,36 +798,11 @@ settings = {};

if (twoslashDefaults === void 0) {
twoslashDefaults = {};
}
var map = undefined; // Shiki doesn't respect json5 as an input, so switch it
// Shiki doesn't respect json5 as an input, so switch it
// to json, which can handle comments in the syntax highlight
var replacer = {
json5: "json"
json5: "json",
yml: "yaml"
}; // @ts-ignore
if (replacer[lang]) lang = replacer[lang]; // Add @types to the fsmap
if (settings.useNodeModules) {
// we don't want a hard dep on TS, so that browsers can run this code)
var laterESVersion = 6; // Save node modules into a cached object which we re-create from (emits can edit the map)
if (nodeModulesMap) {
map = new Map(nodeModulesMap);
} else {
map = createDefaultMapFromNodeModules({
target: laterESVersion
});
nodeModulesMap = map;
} // Maybe it's worth only doing the imports in the file, but that would break dts deps
// const imports = parseFileForModuleReferences(code).filter((mod) => !mod.startsWith("."))
addAllFilesFromFolder(map, settings.nodeModulesTypesPath || "node_modules/@types");
}
var results = twoslasher(code, lang, _extends({}, twoslashDefaults, {
fsMap: map
}));
if (replacer[lang]) lang = replacer[lang];
var results = twoslasher(code, lang, settings);
return results;

@@ -847,0 +809,0 @@ };

{
"name": "shiki-twoslash",
"version": "1.1.0",
"version": "1.2.0",
"license": "MIT",

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

"dependencies": {
"@typescript/twoslash": "1.1.4",
"@typescript/twoslash": "1.1.5",
"@typescript/vfs": "1.3.2",

@@ -34,0 +34,0 @@ "shiki": "^0.9.1",

@@ -13,2 +13,71 @@ ### shiki-twoslash

### User Settings
The config which a user passes is an intersection of Shiki's [`HighlighterOptions`](https://unpkg.com/shiki/dist/index.d.ts)
```ts
interface HighlighterOptions {
theme?: IThemeRegistration
langs?: (Lang | ILanguageRegistration)[]
themes?: IThemeRegistration[]
/**
* Paths for loading themes and langs. Relative to the package's root.
*/
paths?: IHighlighterPaths
}
```
With twoslash's [`TwoSlashOptions`](https://unpkg.com/@typescript/twoslash/dist/index.d.ts)
```ts
export interface TwoSlashOptions {
/** Allows setting any of the handbook options from outside the function, useful if you don't want LSP identifiers */
defaultOptions?: Partial<ExampleOptions>
/** Allows setting any of the compiler options from outside the function */
defaultCompilerOptions?: CompilerOptions
/** Allows applying custom transformers to the emit result, only useful with the showEmit output */
customTransformers?: CustomTransformers
/** An optional copy of the TypeScript import, if missing it will be require'd. */
tsModule?: TS
/** An optional copy of the lz-string import, if missing it will be require'd. */
lzstringModule?: LZ
/**
* An optional Map object which is passed into @typescript/vfs - if you are using twoslash on the
* web then you'll need this to set up your lib *.d.ts files. If missing, it will use your fs.
*/
fsMap?: Map<string, string>
/** The cwd for the folder which the virtual fs should be overlaid on top of when using local fs, opts to process.cwd() if not present */
vfsRoot?: string
}
```
Most people will want to set a `theme`, and _maybe_ `vfsRoot` if they want to do twoslash with custom libraries in a monorepo:
```ts
{
resolve: "gatsby-remark-shiki-twoslash",
options: {
theme: "github-light",
vfsRoot: path.join(__dirname, "..", "..")
},
}
```
### Common Use Case
##### Node Types in a Code Sample
To get the Node globals set up, import them via an inline triple-slash reference:
````
```ts twoslash
/// <reference types="node" />
import { execSync } from "child_process"
const files = execSync("git status --porcelain", { encoding: "utf8" })
files.length
```
````
This applies to other projects which use globals, like Jest etc. If you think that's ugly, that's OK, you can use `// ---cut---` to trim the user-visible output.
### API

@@ -23,5 +92,5 @@

```ts
async function visitor(highlighterOpts, shikiOpts) {
const highlighter = await createShikiHighlighter(highlighterOpts)
visit(markdownAST, "code", visitor(highlighter, shikiOpts))
async function visitor(highlighterOpts) {
const highlighter = await createShikiHighlighter(userOpts)
visit(markdownAST, "code", visitor(highlighter, userOpts))
}

@@ -28,0 +97,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