gatsby-remark-shiki-twoslash
Advanced tools
Comparing version 0.5.10 to 0.6.0
"use strict"; | ||
exports.__esModule = true; | ||
exports.setupTwoslashHovers = void 0; | ||
// Gets the position of an element relative to the whole page | ||
@@ -16,13 +17,13 @@ var getAbsoluteElementPos = function (element) { | ||
var resetHover = function () { | ||
var globalPopover = document.getElementById('twoslash-mouse-hover-info'); | ||
var globalPopover = document.getElementById("twoslash-mouse-hover-info"); | ||
if (globalPopover) | ||
globalPopover.style.display = 'none'; | ||
globalPopover.style.display = "none"; | ||
}; | ||
// Get it | ||
var findOrCreateTooltip = function () { | ||
var globalPopover = document.getElementById('twoslash-mouse-hover-info'); | ||
var globalPopover = document.getElementById("twoslash-mouse-hover-info"); | ||
if (!globalPopover) { | ||
globalPopover = document.createElement('div'); | ||
globalPopover.style.position = 'absolute'; | ||
globalPopover.id = 'twoslash-mouse-hover-info'; | ||
globalPopover = document.createElement("div"); | ||
globalPopover.style.position = "absolute"; | ||
globalPopover.id = "twoslash-mouse-hover-info"; | ||
document.body.appendChild(globalPopover); | ||
@@ -32,2 +33,8 @@ } | ||
}; | ||
var getRootRect = function (element) { | ||
if (element.nodeName.toLowerCase() === "pre") { | ||
return element.getBoundingClientRect(); | ||
} | ||
return getRootRect(element.parentElement); | ||
}; | ||
/** | ||
@@ -57,10 +64,10 @@ * Creates the main mouse over popup for LSP info using the DOM API. | ||
var hovered = event.target; | ||
if (hovered.nodeName !== 'DATA-LSP') | ||
if (hovered.nodeName !== "DATA-LSP") | ||
return resetHover(); | ||
var message = hovered.getAttribute('lsp'); | ||
var message = hovered.getAttribute("lsp"); | ||
var position = getAbsoluteElementPos(hovered); | ||
// Create or re-use the current hover dic | ||
// Create or re-use the current hover div | ||
var tooltip = findOrCreateTooltip(); | ||
// Use a textarea to un-htmlencode for presenting to the user | ||
var txt = document.createElement('textarea'); | ||
var txt = document.createElement("textarea"); | ||
txt.innerHTML = message; | ||
@@ -70,10 +77,14 @@ tooltip.textContent = txt.value; | ||
var yOffset = 20; | ||
tooltip.style.display = 'block'; | ||
tooltip.style.display = "block"; | ||
tooltip.style.top = position.top + yOffset + "px"; | ||
tooltip.style.left = position.left + "px"; | ||
// limit the width of the tooltip to the outer container (pre) | ||
var rootRect = getRootRect(hovered); | ||
var relativeLeft = position.left - rootRect.x; | ||
tooltip.style.maxWidth = rootRect.width - relativeLeft + "px"; | ||
}; | ||
twoslashes.forEach(function (codeblock) { | ||
codeblock.addEventListener('mouseover', hover); | ||
codeblock.addEventListener('mouseout', resetHover); | ||
codeblock.addEventListener("mouseover", hover); | ||
codeblock.addEventListener("mouseout", resetHover); | ||
}); | ||
}; |
@@ -10,2 +10,3 @@ 'use strict'; | ||
var twoslash = require('@typescript/twoslash'); | ||
var vfs = require('@typescript/vfs'); | ||
var visit = _interopDefault(require('unist-util-visit')); | ||
@@ -30,16 +31,16 @@ | ||
ranges.forEach(function (r) { | ||
if (r.classes === 'lsp') { | ||
if (r.classes === "lsp") { | ||
actions.push({ | ||
text: '⇍/data-lsp⇏', | ||
text: "⇍/data-lsp⇏", | ||
index: r.end | ||
}); | ||
actions.push({ | ||
text: "\u21CDdata-lsp lsp=\u21EF" + (r.lsp || '') + "\u21EF\u21CF", | ||
text: "\u21CDdata-lsp lsp=\u21EF" + (r.lsp || "") + "\u21EF\u21CF", | ||
index: r.begin | ||
}); | ||
} else if (r.classes === 'err') { | ||
} else if (r.classes === "err") { | ||
hasErrors = true; | ||
} else if (r.classes === 'query') { | ||
} else if (r.classes === "query") { | ||
actions.push({ | ||
text: '⇍/data-highlight⇏', | ||
text: "⇍/data-highlight⇏", | ||
index: r.end | ||
@@ -53,3 +54,3 @@ }); | ||
}); | ||
var html = (' ' + text).slice(1); // Apply all the edits | ||
var html = (" " + text).slice(1); // Apply all the edits | ||
@@ -64,18 +65,22 @@ actions.sort(function (l, r) { | ||
} | ||
var subTripleArrow = function subTripleArrow(str) { | ||
return str.replace(/</g, "⇍").replace(/>/g, "⇏").replace(/'/g, "⇯"); | ||
}; | ||
var replaceTripleArrow = function replaceTripleArrow(str) { | ||
return str.replace(/⇍/g, '<').replace(/⇏/g, '>').replace(/⇯/g, "'"); | ||
return str.replace(/⇍/g, "<").replace(/⇏/g, ">").replace(/⇯/g, "'"); | ||
}; | ||
var replaceTripleArrowEncoded = function replaceTripleArrowEncoded(str) { | ||
return str.replace(/⇍/g, "<").replace(/⇏/g, ">").replace(/⇯/g, "'"); | ||
}; | ||
function stripHTML(text) { | ||
var table = { | ||
'<': 'lt', | ||
'"': 'quot', | ||
"'": 'apos', | ||
'&': 'amp', | ||
'\r': '#10', | ||
'\n': '#13' | ||
"<": "lt", | ||
'"': "quot", | ||
"'": "apos", | ||
"&": "amp", | ||
"\r": "#10", | ||
"\n": "#13" | ||
}; | ||
return text.toString().replace(/[<"'\r\n&]/g, function (chr) { | ||
return '&' + table[chr] + ';'; | ||
return "&" + table[chr] + ";"; | ||
}); | ||
@@ -174,3 +179,3 @@ } | ||
} else { | ||
tokenContent += token.content; | ||
tokenContent += subTripleArrow(token.content); | ||
} | ||
@@ -201,3 +206,31 @@ | ||
queries.forEach(function (query) { | ||
html += "<span class='query'>" + ("//" + "".padStart(query.offset - 2) + "^ = " + query.text) + "</span>"; | ||
switch (query.kind) { | ||
case "query": | ||
{ | ||
html += "<span class='query'>" + ("//" + "".padStart(query.offset - 2) + "^ = " + query.text) + "</span>"; | ||
break; | ||
} | ||
case "completions": | ||
{ | ||
if (!query.completions) { | ||
html += "<span class='query'>" + ("//" + "".padStart(query.offset - 2) + "^ - No completions found") + "</span>"; | ||
} else { | ||
var prefixed = query.completions.filter(function (c) { | ||
return c.name.startsWith(query.completionsPrefix || "____"); | ||
}); | ||
console.log("Prefix: ", query.completionsPrefix); | ||
var lis = prefixed.sort(function (l, r) { | ||
return l.name.localeCompare(r.name); | ||
}).map(function (c) { | ||
var _query$completionsPre; | ||
var after = c.name.substr(((_query$completionsPre = query.completionsPrefix) === null || _query$completionsPre === void 0 ? void 0 : _query$completionsPre.length) || 0); | ||
var name = "<span><span class='result-found'>" + (query.completionsPrefix || "") + "</span>" + after + "<span>"; | ||
return "<li>" + name + "</li>"; | ||
}).join(""); | ||
html += "".padStart(query.offset) + ("<span class='inline-completions'><ul class='dropdown'>" + lis + "</ul></span>"); | ||
} | ||
} | ||
} | ||
}); | ||
@@ -207,3 +240,3 @@ html += "\n"; | ||
}); | ||
html = html.replace(/\n*$/, ""); // Get rid of final new lines | ||
html = replaceTripleArrowEncoded(html.replace(/\n*$/, "")); // Get rid of final new lines | ||
@@ -274,3 +307,3 @@ html += "</code></div></pre>"; | ||
var settings = options || {}; | ||
var theme = settings.theme || 'nord'; | ||
var theme = settings.theme || "nord"; | ||
var shikiTheme; | ||
@@ -284,3 +317,3 @@ | ||
} catch (error) { | ||
throw new Error('Unable to load theme: ' + theme + ' - ' + error.message); | ||
throw new Error("Unable to load theme: " + theme + " - " + error.message); | ||
} | ||
@@ -297,2 +330,4 @@ } | ||
}; | ||
var defaultSettings = {}; | ||
/** | ||
@@ -303,35 +338,43 @@ * The function doing the work of transforming any codeblock samples | ||
var visitor = function visitor(twoslashSettings) { | ||
return function (node) { | ||
var lang = node.lang; | ||
var settings = twoslashSettings || defaultSettings; // Run twoslash | ||
var visitor = function visitor(node) { | ||
var lang = node.lang; | ||
runTwoSlashOnNode(node); // Shiki doesn't respect json5 as an input, so switch it | ||
// to json, which can handle comments in the syntax highlight | ||
runTwoSlashOnNode(settings)(node); // 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' | ||
}; // @ts-ignore | ||
var replacer = { | ||
json5: "json" | ||
}; // @ts-ignore | ||
if (replacer[lang]) lang = replacer[lang]; // Check we can highlight and render | ||
if (replacer[lang]) lang = replacer[lang]; | ||
var shouldDisableTwoslash = process && process.env && !!process.env.TWOSLASH_DISABLE; // Check we can highlight and render | ||
var shouldHighlight = lang && languages.includes(lang); | ||
var shouldHighlight = lang && languages.includes(lang); | ||
if (shouldHighlight) { | ||
var tokens = highlighter.codeToThemedTokens(node.value, lang); | ||
var results = renderToHTML(tokens, { | ||
langId: lang | ||
}, node.twoslash); | ||
node.type = 'html'; | ||
node.value = results; | ||
node.children = []; | ||
} | ||
if (shouldHighlight && !shouldDisableTwoslash) { | ||
var tokens = highlighter.codeToThemedTokens(node.value, lang); | ||
var results = renderToHTML(tokens, { | ||
langId: lang | ||
}, node.twoslash); | ||
node.type = "html"; | ||
node.value = results; | ||
node.children = []; | ||
} | ||
}; | ||
}; | ||
/** The plugin API */ | ||
/** | ||
* The main interface for the remark shiki API, sets up the | ||
* highlighter then runs a visitor across all code tags in | ||
* the markdown running twoslash, then shiki. | ||
* */ | ||
var remarkShiki = function remarkShiki(_ref, settings) { | ||
var remarkShiki = function remarkShiki(_ref, shikiSettings, settings) { | ||
var markdownAST = _ref.markdownAST; | ||
try { | ||
return Promise.resolve(getHighlighterObj(settings)).then(function () { | ||
visit(markdownAST, 'code', visitor); | ||
return Promise.resolve(getHighlighterObj(shikiSettings)).then(function () { | ||
visit(markdownAST, "code", visitor(settings)); | ||
}); | ||
@@ -341,19 +384,36 @@ } catch (e) { | ||
} | ||
}; | ||
}; /////////////////// Mainly for internal use, but tests could use this, not considered public API, so could change | ||
var runTwoSlashOnNode = function runTwoSlashOnNode(node) { | ||
// Run twoslash and replace the main contents if | ||
// the ``` has 'twoslash' after it | ||
if (node.meta && node.meta.includes('twoslash')) { | ||
var results = twoslash.twoslasher(node.value, node.lang); | ||
node.value = results.code; | ||
node.lang = results.extension; | ||
node.twoslash = results; | ||
} | ||
/** @internal */ | ||
var runTwoSlashOnNode = function runTwoSlashOnNode(settings) { | ||
return function (node) { | ||
// Run twoslash and replace the main contents if | ||
// the ``` has 'twoslash' after it | ||
if (node.meta && node.meta.includes("twoslash")) { | ||
var map = undefined; | ||
if (settings.useNodeModules) { | ||
var laterESVersion = 6; // we don't want a hard dep on TS, so that browsers can run this code) | ||
map = vfs.createDefaultMapFromNodeModules({ | ||
target: laterESVersion | ||
}); // Add @types to the fsmap | ||
vfs.addAllFilesFromFolder(map, settings.nodeModulesTypesPath || "node_modules/@types"); | ||
} | ||
var results = twoslash.twoslasher(node.value, node.lang, undefined, undefined, undefined, map); | ||
node.value = results.code; | ||
node.lang = results.extension; | ||
node.twoslash = results; | ||
} | ||
}; | ||
}; | ||
/** Does a twoslash */ | ||
/** Sends the twoslash visitor over the existing MD AST and replaces the code samples inline, does not do highlighting */ | ||
var runTwoSlashAcrossDocument = function runTwoSlashAcrossDocument(_ref2) { | ||
var runTwoSlashAcrossDocument = function runTwoSlashAcrossDocument(_ref2, settings) { | ||
var markdownAST = _ref2.markdownAST; | ||
return visit(markdownAST, 'code', runTwoSlashOnNode); | ||
return visit(markdownAST, "code", runTwoSlashOnNode(settings || defaultSettings)); | ||
}; | ||
@@ -360,0 +420,0 @@ |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,n=require("shiki"),t=require("shiki-languages"),r=require("@typescript/twoslash"),a=(e=require("unist-util-visit"))&&"object"==typeof e&&"default"in e?e.default:e;function s(e){var n={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+n[e]+";"}))}function o(e){return e.replace(/</g,"<").replace(/>/g,">")}function c(e,n){var t=new Map;return e.forEach((function(e){var r=n(e),a=t.get(r);a?a.push(e):t.set(r,[e])})),t}var i=[].concat(t.commonLangIds,t.commonLangAliases,t.otherLangIds),l=null,u=function(e){var n=e.lang;d(e);var t={json5:"json"};if(t[n]&&(n=t[n]),n&&i.includes(n)){var r=function(e,n,t){if(!t)return function(e,n){var t="";return t+='<pre class="shiki">',n.langId&&(t+='<div class="language-id">'+n.langId+"</div>"),t+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?t+="\n":(e.forEach((function(e){t+='<span style="color: '+e.color+'">'+o(e.content)+"</span>"})),t+="\n")})),t=t.replace(/\n*$/,""),t+="</code></div></pre>"}(e,n);var r="";r+='<pre class="shiki twoslash">',n.langId&&(r+='<div class="language-id">'+n.langId+"</div>"),r+="<div class='code-container'><code>";var a=c(t.errors,(function(e){return e.line}))||new Map,i=c(t.staticQuickInfos,(function(e){return e.line}))||new Map,l=c(t.queries,(function(e){return e.line-1}))||new Map,u=0;return e.forEach((function(e,n){var t=a.get(n)||[],c=i.get(n)||[],d=l.get(n)||[];if(0===e.length&&0===n)u+=1;else if(0===e.length)u+=1,r+="\n";else{var h=0;e.forEach((function(e){var n="",a=function(n){return function(t){return n<=t.character&&n+e.content.length>=t.character+t.length}},o=t.filter(a(h)),i=c.filter(a(h)),l=d.filter(a(h)),f=[].concat(o,i,l).sort((function(e,n){return(e.start||0)-(n.start||0)}));n+=f.length?function(e,n){var t=[],r=!1;e.forEach((function(e){"lsp"===e.classes?(t.push({text:"⇍/data-lsp⇏",index:e.end}),t.push({text:"⇍data-lsp lsp=⇯"+(e.lsp||"")+"⇯⇏",index:e.begin})):"err"===e.classes?r=!0:"query"===e.classes&&(t.push({text:"⇍/data-highlight⇏",index:e.end}),t.push({text:"⇍data-highlight'⇏",index:e.begin}))}));var a=(" "+n).slice(1);return t.sort((function(e,n){return n.index-e.index})).forEach((function(e){var n,t,r;r=e.text,a=(n=a).slice(0,t=e.index)+r+n.slice(t+Math.abs(0))})),r&&(a="⇍data-err⇏"+a+"⇍/data-err⇏"),s(a).replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")}(f.map((function(e){var n={begin:e.start-u,end:e.start+e.length-u};return"renderedMessage"in e&&(n.classes="err"),"kind"in e&&(n.classes=e.kind),"targetString"in e&&(n.classes="lsp",n.lsp=s(e.text)),n})),e.content):e.content,r+='<span style="color: '+e.color+'">'+n+"</span>",h+=e.content.length,u+=e.content.length})),r+="\n",u+=1}if(t.length){var f=t.map((function(e){return o(e.renderedMessage)})).join("</br>"),g=t.map((function(e){return e.code})).join("<br/>");r+='<span class="error"><span>'+f+'</span><span class="code">'+g+"</span></span>",r+='<span class="error-behind">'+f+"</span>"}d.length&&(d.forEach((function(e){r+="<span class='query'>//"+"".padStart(e.offset-2)+"^ = "+e.text+"</span>"})),r+="\n")})),r=r.replace(/\n*$/,""),r+="</code></div></pre>"}(l.codeToThemedTokens(e.value,n),{langId:n},e.twoslash);e.type="html",e.value=r,e.children=[]}},d=function(e){if(e.meta&&e.meta.includes("twoslash")){var n=r.twoslasher(e.value,e.lang);e.value=n.code,e.lang=n.extension,e.twoslash=n}};exports.default=function(e,t){var r=e.markdownAST;try{return Promise.resolve(function(e){if(l)return l;var t,r=(e||{}).theme||"nord";try{t=n.getTheme(r)}catch(e){try{t=n.loadTheme(r)}catch(e){throw new Error("Unable to load theme: "+r+" - "+e.message)}}return n.getHighlighter({theme:t,langs:i}).then((function(e){return l=e}))}(t)).then((function(){a(r,"code",u)}))}catch(e){return Promise.reject(e)}},exports.runTwoSlashAcrossDocument=function(e){return a(e.markdownAST,"code",d)},exports.runTwoSlashOnNode=d; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,n=require("shiki"),t=require("shiki-languages"),r=require("@typescript/twoslash"),a=require("@typescript/vfs"),s=(e=require("unist-util-visit"))&&"object"==typeof e&&"default"in e?e.default:e;function o(e){var n={"<":"lt",'"':"quot","'":"apos","&":"amp","\r":"#10","\n":"#13"};return e.toString().replace(/[<"'\r\n&]/g,(function(e){return"&"+n[e]+";"}))}function i(e){return e.replace(/</g,"<").replace(/>/g,">")}function c(e,n){var t=new Map;return e.forEach((function(e){var r=n(e),a=t.get(r);a?a.push(e):t.set(r,[e])})),t}var l=[].concat(t.commonLangIds,t.commonLangAliases,t.otherLangIds),u=null,p={},d=function(e){return function(n){if(n.meta&&n.meta.includes("twoslash")){var t=void 0;e.useNodeModules&&(t=a.createDefaultMapFromNodeModules({target:6}),a.addAllFilesFromFolder(t,e.nodeModulesTypesPath||"node_modules/@types"));var s=r.twoslasher(n.value,n.lang,void 0,void 0,void 0,t);n.value=s.code,n.lang=s.extension,n.twoslash=s}}};exports.default=function(e,t,r){var a=e.markdownAST;try{return Promise.resolve(function(e){if(u)return u;var t,r=(e||{}).theme||"nord";try{t=n.getTheme(r)}catch(e){try{t=n.loadTheme(r)}catch(e){throw new Error("Unable to load theme: "+r+" - "+e.message)}}return n.getHighlighter({theme:t,langs:l}).then((function(e){return u=e}))}(t)).then((function(){var e;s(a,"code",(e=r,function(n){var t=n.lang;d(e||p)(n);var r={json5:"json"};r[t]&&(t=r[t]);var a=process&&process.env&&!!process.env.TWOSLASH_DISABLE;if(t&&l.includes(t)&&!a){var s=function(e,n,t){if(!t)return function(e,n){var t="";return t+='<pre class="shiki">',n.langId&&(t+='<div class="language-id">'+n.langId+"</div>"),t+="<div class='code-container'><code>",e.forEach((function(e){0===e.length?t+="\n":(e.forEach((function(e){t+='<span style="color: '+e.color+'">'+i(e.content)+"</span>"})),t+="\n")})),t=t.replace(/\n*$/,""),t+="</code></div></pre>"}(e,n);var r="";r+='<pre class="shiki twoslash">',n.langId&&(r+='<div class="language-id">'+n.langId+"</div>"),r+="<div class='code-container'><code>";var a,s=c(t.errors,(function(e){return e.line}))||new Map,l=c(t.staticQuickInfos,(function(e){return e.line}))||new Map,u=c(t.queries,(function(e){return e.line-1}))||new Map,p=0;return e.forEach((function(e,n){var t=s.get(n)||[],a=l.get(n)||[],c=u.get(n)||[];if(0===e.length&&0===n)p+=1;else if(0===e.length)p+=1,r+="\n";else{var d=0;e.forEach((function(e){var n="",s=function(n){return function(t){return n<=t.character&&n+e.content.length>=t.character+t.length}},i=t.filter(s(d)),l=a.filter(s(d)),u=c.filter(s(d)),f=[].concat(i,l,u).sort((function(e,n){return(e.start||0)-(n.start||0)}));n+=f.length?function(e,n){var t=[],r=!1;e.forEach((function(e){"lsp"===e.classes?(t.push({text:"⇍/data-lsp⇏",index:e.end}),t.push({text:"⇍data-lsp lsp=⇯"+(e.lsp||"")+"⇯⇏",index:e.begin})):"err"===e.classes?r=!0:"query"===e.classes&&(t.push({text:"⇍/data-highlight⇏",index:e.end}),t.push({text:"⇍data-highlight'⇏",index:e.begin}))}));var a=(" "+n).slice(1);return t.sort((function(e,n){return n.index-e.index})).forEach((function(e){var n,t,r;r=e.text,a=(n=a).slice(0,t=e.index)+r+n.slice(t+Math.abs(0))})),r&&(a="⇍data-err⇏"+a+"⇍/data-err⇏"),o(a).replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'")}(f.map((function(e){var n={begin:e.start-p,end:e.start+e.length-p};return"renderedMessage"in e&&(n.classes="err"),"kind"in e&&(n.classes=e.kind),"targetString"in e&&(n.classes="lsp",n.lsp=o(e.text)),n})),e.content):e.content.replace(/</g,"⇍").replace(/>/g,"⇏").replace(/'/g,"⇯"),r+='<span style="color: '+e.color+'">'+n+"</span>",d+=e.content.length,p+=e.content.length})),r+="\n",p+=1}if(t.length){var f=t.map((function(e){return i(e.renderedMessage)})).join("</br>"),g=t.map((function(e){return e.code})).join("<br/>");r+='<span class="error"><span>'+f+'</span><span class="code">'+g+"</span></span>",r+='<span class="error-behind">'+f+"</span>"}c.length&&(c.forEach((function(e){switch(e.kind){case"query":r+="<span class='query'>//"+"".padStart(e.offset-2)+"^ = "+e.text+"</span>";break;case"completions":if(e.completions){var n=e.completions.filter((function(n){return n.name.startsWith(e.completionsPrefix||"____")}));console.log("Prefix: ",e.completionsPrefix);var t=n.sort((function(e,n){return e.name.localeCompare(n.name)})).map((function(n){var t,r=n.name.substr((null===(t=e.completionsPrefix)||void 0===t?void 0:t.length)||0);return"<li><span><span class='result-found'>"+(e.completionsPrefix||"")+"</span>"+r+"<span></li>"})).join("");r+="".padStart(e.offset)+"<span class='inline-completions'><ul class='dropdown'>"+t+"</ul></span>"}else r+="<span class='query'>//"+"".padStart(e.offset-2)+"^ - No completions found</span>"}})),r+="\n")})),a=r.replace(/\n*$/,""),r=a.replace(/⇍/g,"<").replace(/⇏/g,">").replace(/⇯/g,"'"),r+="</code></div></pre>"}(u.codeToThemedTokens(n.value,t),{langId:t},n.twoslash);n.type="html",n.value=s,n.children=[]}}))}))}catch(e){return Promise.reject(e)}},exports.runTwoSlashAcrossDocument=function(e,n){return s(e.markdownAST,"code",d(n||p))},exports.runTwoSlashOnNode=d; | ||
//# sourceMappingURL=gatsby-remark-shiki-twoslash.cjs.production.min.js.map |
import { getTheme, loadTheme, getHighlighter } from 'shiki'; | ||
import { commonLangIds, commonLangAliases, otherLangIds } from 'shiki-languages'; | ||
import { twoslasher } from '@typescript/twoslash'; | ||
import { createDefaultMapFromNodeModules, addAllFilesFromFolder } from '@typescript/vfs'; | ||
import visit from 'unist-util-visit'; | ||
@@ -23,16 +24,16 @@ | ||
ranges.forEach(function (r) { | ||
if (r.classes === 'lsp') { | ||
if (r.classes === "lsp") { | ||
actions.push({ | ||
text: '⇍/data-lsp⇏', | ||
text: "⇍/data-lsp⇏", | ||
index: r.end | ||
}); | ||
actions.push({ | ||
text: "\u21CDdata-lsp lsp=\u21EF" + (r.lsp || '') + "\u21EF\u21CF", | ||
text: "\u21CDdata-lsp lsp=\u21EF" + (r.lsp || "") + "\u21EF\u21CF", | ||
index: r.begin | ||
}); | ||
} else if (r.classes === 'err') { | ||
} else if (r.classes === "err") { | ||
hasErrors = true; | ||
} else if (r.classes === 'query') { | ||
} else if (r.classes === "query") { | ||
actions.push({ | ||
text: '⇍/data-highlight⇏', | ||
text: "⇍/data-highlight⇏", | ||
index: r.end | ||
@@ -46,3 +47,3 @@ }); | ||
}); | ||
var html = (' ' + text).slice(1); // Apply all the edits | ||
var html = (" " + text).slice(1); // Apply all the edits | ||
@@ -57,18 +58,22 @@ actions.sort(function (l, r) { | ||
} | ||
var subTripleArrow = function subTripleArrow(str) { | ||
return str.replace(/</g, "⇍").replace(/>/g, "⇏").replace(/'/g, "⇯"); | ||
}; | ||
var replaceTripleArrow = function replaceTripleArrow(str) { | ||
return str.replace(/⇍/g, '<').replace(/⇏/g, '>').replace(/⇯/g, "'"); | ||
return str.replace(/⇍/g, "<").replace(/⇏/g, ">").replace(/⇯/g, "'"); | ||
}; | ||
var replaceTripleArrowEncoded = function replaceTripleArrowEncoded(str) { | ||
return str.replace(/⇍/g, "<").replace(/⇏/g, ">").replace(/⇯/g, "'"); | ||
}; | ||
function stripHTML(text) { | ||
var table = { | ||
'<': 'lt', | ||
'"': 'quot', | ||
"'": 'apos', | ||
'&': 'amp', | ||
'\r': '#10', | ||
'\n': '#13' | ||
"<": "lt", | ||
'"': "quot", | ||
"'": "apos", | ||
"&": "amp", | ||
"\r": "#10", | ||
"\n": "#13" | ||
}; | ||
return text.toString().replace(/[<"'\r\n&]/g, function (chr) { | ||
return '&' + table[chr] + ';'; | ||
return "&" + table[chr] + ";"; | ||
}); | ||
@@ -167,3 +172,3 @@ } | ||
} else { | ||
tokenContent += token.content; | ||
tokenContent += subTripleArrow(token.content); | ||
} | ||
@@ -194,3 +199,31 @@ | ||
queries.forEach(function (query) { | ||
html += "<span class='query'>" + ("//" + "".padStart(query.offset - 2) + "^ = " + query.text) + "</span>"; | ||
switch (query.kind) { | ||
case "query": | ||
{ | ||
html += "<span class='query'>" + ("//" + "".padStart(query.offset - 2) + "^ = " + query.text) + "</span>"; | ||
break; | ||
} | ||
case "completions": | ||
{ | ||
if (!query.completions) { | ||
html += "<span class='query'>" + ("//" + "".padStart(query.offset - 2) + "^ - No completions found") + "</span>"; | ||
} else { | ||
var prefixed = query.completions.filter(function (c) { | ||
return c.name.startsWith(query.completionsPrefix || "____"); | ||
}); | ||
console.log("Prefix: ", query.completionsPrefix); | ||
var lis = prefixed.sort(function (l, r) { | ||
return l.name.localeCompare(r.name); | ||
}).map(function (c) { | ||
var _query$completionsPre; | ||
var after = c.name.substr(((_query$completionsPre = query.completionsPrefix) === null || _query$completionsPre === void 0 ? void 0 : _query$completionsPre.length) || 0); | ||
var name = "<span><span class='result-found'>" + (query.completionsPrefix || "") + "</span>" + after + "<span>"; | ||
return "<li>" + name + "</li>"; | ||
}).join(""); | ||
html += "".padStart(query.offset) + ("<span class='inline-completions'><ul class='dropdown'>" + lis + "</ul></span>"); | ||
} | ||
} | ||
} | ||
}); | ||
@@ -200,3 +233,3 @@ html += "\n"; | ||
}); | ||
html = html.replace(/\n*$/, ""); // Get rid of final new lines | ||
html = replaceTripleArrowEncoded(html.replace(/\n*$/, "")); // Get rid of final new lines | ||
@@ -267,3 +300,3 @@ html += "</code></div></pre>"; | ||
var settings = options || {}; | ||
var theme = settings.theme || 'nord'; | ||
var theme = settings.theme || "nord"; | ||
var shikiTheme; | ||
@@ -277,3 +310,3 @@ | ||
} catch (error) { | ||
throw new Error('Unable to load theme: ' + theme + ' - ' + error.message); | ||
throw new Error("Unable to load theme: " + theme + " - " + error.message); | ||
} | ||
@@ -290,2 +323,4 @@ } | ||
}; | ||
var defaultSettings = {}; | ||
/** | ||
@@ -296,35 +331,43 @@ * The function doing the work of transforming any codeblock samples | ||
var visitor = function visitor(twoslashSettings) { | ||
return function (node) { | ||
var lang = node.lang; | ||
var settings = twoslashSettings || defaultSettings; // Run twoslash | ||
var visitor = function visitor(node) { | ||
var lang = node.lang; | ||
runTwoSlashOnNode(node); // Shiki doesn't respect json5 as an input, so switch it | ||
// to json, which can handle comments in the syntax highlight | ||
runTwoSlashOnNode(settings)(node); // 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' | ||
}; // @ts-ignore | ||
var replacer = { | ||
json5: "json" | ||
}; // @ts-ignore | ||
if (replacer[lang]) lang = replacer[lang]; // Check we can highlight and render | ||
if (replacer[lang]) lang = replacer[lang]; | ||
var shouldDisableTwoslash = process && process.env && !!process.env.TWOSLASH_DISABLE; // Check we can highlight and render | ||
var shouldHighlight = lang && languages.includes(lang); | ||
var shouldHighlight = lang && languages.includes(lang); | ||
if (shouldHighlight) { | ||
var tokens = highlighter.codeToThemedTokens(node.value, lang); | ||
var results = renderToHTML(tokens, { | ||
langId: lang | ||
}, node.twoslash); | ||
node.type = 'html'; | ||
node.value = results; | ||
node.children = []; | ||
} | ||
if (shouldHighlight && !shouldDisableTwoslash) { | ||
var tokens = highlighter.codeToThemedTokens(node.value, lang); | ||
var results = renderToHTML(tokens, { | ||
langId: lang | ||
}, node.twoslash); | ||
node.type = "html"; | ||
node.value = results; | ||
node.children = []; | ||
} | ||
}; | ||
}; | ||
/** The plugin API */ | ||
/** | ||
* The main interface for the remark shiki API, sets up the | ||
* highlighter then runs a visitor across all code tags in | ||
* the markdown running twoslash, then shiki. | ||
* */ | ||
var remarkShiki = function remarkShiki(_ref, settings) { | ||
var remarkShiki = function remarkShiki(_ref, shikiSettings, settings) { | ||
var markdownAST = _ref.markdownAST; | ||
try { | ||
return Promise.resolve(getHighlighterObj(settings)).then(function () { | ||
visit(markdownAST, 'code', visitor); | ||
return Promise.resolve(getHighlighterObj(shikiSettings)).then(function () { | ||
visit(markdownAST, "code", visitor(settings)); | ||
}); | ||
@@ -334,19 +377,36 @@ } catch (e) { | ||
} | ||
}; | ||
}; /////////////////// Mainly for internal use, but tests could use this, not considered public API, so could change | ||
var runTwoSlashOnNode = function runTwoSlashOnNode(node) { | ||
// Run twoslash and replace the main contents if | ||
// the ``` has 'twoslash' after it | ||
if (node.meta && node.meta.includes('twoslash')) { | ||
var results = twoslasher(node.value, node.lang); | ||
node.value = results.code; | ||
node.lang = results.extension; | ||
node.twoslash = results; | ||
} | ||
/** @internal */ | ||
var runTwoSlashOnNode = function runTwoSlashOnNode(settings) { | ||
return function (node) { | ||
// Run twoslash and replace the main contents if | ||
// the ``` has 'twoslash' after it | ||
if (node.meta && node.meta.includes("twoslash")) { | ||
var map = undefined; | ||
if (settings.useNodeModules) { | ||
var laterESVersion = 6; // we don't want a hard dep on TS, so that browsers can run this code) | ||
map = createDefaultMapFromNodeModules({ | ||
target: laterESVersion | ||
}); // Add @types to the fsmap | ||
addAllFilesFromFolder(map, settings.nodeModulesTypesPath || "node_modules/@types"); | ||
} | ||
var results = twoslasher(node.value, node.lang, undefined, undefined, undefined, map); | ||
node.value = results.code; | ||
node.lang = results.extension; | ||
node.twoslash = results; | ||
} | ||
}; | ||
}; | ||
/** Does a twoslash */ | ||
/** Sends the twoslash visitor over the existing MD AST and replaces the code samples inline, does not do highlighting */ | ||
var runTwoSlashAcrossDocument = function runTwoSlashAcrossDocument(_ref2) { | ||
var runTwoSlashAcrossDocument = function runTwoSlashAcrossDocument(_ref2, settings) { | ||
var markdownAST = _ref2.markdownAST; | ||
return visit(markdownAST, 'code', runTwoSlashOnNode); | ||
return visit(markdownAST, "code", runTwoSlashOnNode(settings || defaultSettings)); | ||
}; | ||
@@ -353,0 +413,0 @@ |
@@ -1,17 +0,25 @@ | ||
import { TLang } from 'shiki-languages'; | ||
import { Node } from 'unist'; | ||
import { TLang } from "shiki-languages"; | ||
import { Node } from "unist"; | ||
declare type RichNode = Node & { | ||
lang: TLang; | ||
type: string; | ||
restults: string; | ||
children: Node[]; | ||
value: string; | ||
meta?: string[]; | ||
twoslash?: import('@typescript/twoslash').TwoSlashReturn; | ||
twoslash?: import("@typescript/twoslash").TwoSlashReturn; | ||
}; | ||
/** The plugin API */ | ||
declare const remarkShiki: ({ markdownAST }: any, settings: any) => Promise<void>; | ||
export declare const runTwoSlashOnNode: (node: RichNode) => void; | ||
/** Does a twoslash */ | ||
export declare const runTwoSlashAcrossDocument: ({ markdownAST }: any) => any; | ||
declare type ShikiTwoslashSettings = { | ||
useNodeModules?: true; | ||
nodeModulesTypesPath?: string; | ||
}; | ||
/** | ||
* The main interface for the remark shiki API, sets up the | ||
* highlighter then runs a visitor across all code tags in | ||
* the markdown running twoslash, then shiki. | ||
* */ | ||
declare const remarkShiki: ({ markdownAST }: any, shikiSettings: import("shiki/dist/highlighter").HighlighterOptions, settings: ShikiTwoslashSettings) => Promise<void>; | ||
/** @internal */ | ||
export declare const runTwoSlashOnNode: (settings: ShikiTwoslashSettings) => (node: RichNode) => void; | ||
/** Sends the twoslash visitor over the existing MD AST and replaces the code samples inline, does not do highlighting */ | ||
export declare const runTwoSlashAcrossDocument: ({ markdownAST }: any, settings?: ShikiTwoslashSettings | undefined) => any; | ||
export default remarkShiki; |
@@ -15,3 +15,6 @@ declare type Range = { | ||
export declare function createHighlightedString2(ranges: Range[], text: string): string; | ||
export declare const subTripleArrow: (str: string) => string; | ||
export declare const replaceTripleArrow: (str: string) => string; | ||
export declare const replaceTripleArrowEncoded: (str: string) => string; | ||
export declare function stripHTML(text: string): string; | ||
export {}; |
{ | ||
"name": "gatsby-remark-shiki-twoslash", | ||
"version": "0.5.10", | ||
"version": "0.6.0", | ||
"license": "MIT", | ||
@@ -22,3 +22,4 @@ "homepage": "https://github.com/microsoft/TypeScript-Website/", | ||
"dependencies": { | ||
"@typescript/twoslash": "^0.2.0", | ||
"@typescript/twoslash": "0.4.0", | ||
"@typescript/vfs": "1.0.0", | ||
"typescript": "*", | ||
@@ -25,0 +26,0 @@ "shiki": "^0.1.6", |
@@ -154,3 +154,3 @@ ### gatsby-remark-shiki-twoslash | ||
border-radius: 2px; | ||
font-family: 'Jet Brains Mono', Menlo, Monaco, Consolas, Courier New, monospace; | ||
font-family: "JetBrains Mono", Menlo, Monaco, Consolas, Courier New, monospace; | ||
font-size: 14px; | ||
@@ -204,6 +204,6 @@ white-space: pre-wrap; | ||
function createLabel<T extends number | string>(idOrName: T): NameOrId<T> { | ||
throw 'unimplemented' | ||
throw "unimplemented" | ||
} | ||
let a = createLabel('typescript') | ||
let a = createLabel("typescript") | ||
``` | ||
@@ -210,0 +210,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
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
122444
880
0
6
8
+ Added@typescript/vfs@1.0.0
+ Added@typescript/twoslash@0.4.0(transitive)
+ Added@typescript/vfs@1.0.0(transitive)
- Removed@typescript/twoslash@0.2.0(transitive)
- Removed@typescript/vfs@1.6.1(transitive)
Updated@typescript/twoslash@0.4.0