@typescript/twoslash
Advanced tools
Comparing version 2.0.2 to 2.1.0
@@ -13,2 +13,9 @@ declare type LZ = typeof import("lz-string"); | ||
} | ||
export declare class TwoslashError extends Error { | ||
title: string; | ||
description: string; | ||
recommendation: string; | ||
code: string | undefined; | ||
constructor(title: string, description: string, recommendation: string, code?: string | undefined); | ||
} | ||
/** Available inline flags which are not compiler flags */ | ||
@@ -15,0 +22,0 @@ export interface ExampleOptions { |
@@ -25,2 +25,93 @@ 'use strict'; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_cache.set(Class, Wrapper); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
return _wrapNativeSuper(Class); | ||
} | ||
function _unsupportedIterableToArray(o, minLen) { | ||
@@ -80,3 +171,3 @@ if (!o) return; | ||
throw new Error("Unknown primitive type " + type + " with - " + value); | ||
throw new TwoslashError("Unknown primitive value in compiler flag", "The only recognized primitives are number, string and boolean. Got " + type + " with " + value + ".", "This is likely a typo."); | ||
} | ||
@@ -89,26 +180,14 @@ function cleanMarkdownEscaped(code) { | ||
function typesToExtension(types) { | ||
switch (types) { | ||
case "js": | ||
return "js"; | ||
case "javascript": | ||
return "js"; | ||
case "ts": | ||
return "ts"; | ||
case "typescript": | ||
return "ts"; | ||
case "tsx": | ||
return "tsx"; | ||
case "jsx": | ||
return "jsx"; | ||
case "jsn": | ||
return "json"; | ||
} | ||
throw new Error("Cannot handle the file extension:" + types); | ||
var map = { | ||
js: "js", | ||
javascript: "js", | ||
ts: "ts", | ||
typescript: "ts", | ||
tsx: "tsx", | ||
jsx: "jsx", | ||
json: "json", | ||
jsn: "json" | ||
}; | ||
if (map[types]) return map[types]; | ||
throw new TwoslashError("Unknown TypeScript extension given to Twoslash", "Received " + types + " but Twoslash only accepts: " + Object.keys(map) + " ", ""); | ||
} | ||
@@ -134,6 +213,2 @@ function getIdentifierTextSpans(ts, sourceFile) { | ||
} | ||
function stringAroundIndex(string, index) { | ||
var arr = [string[index - 3], string[index - 2], string[index - 1], ">", string[index], "<", string[index + 1], string[index + 2], string[index + 3]]; | ||
return arr.filter(Boolean).join(""); | ||
} | ||
/** Came from https://ourcodeworld.com/articles/read/223/how-to-retrieve-the-closest-word-in-a-string-with-a-given-index-in-javascript */ | ||
@@ -164,21 +239,50 @@ | ||
/** To ensure that errors are matched up right */ | ||
function validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode) { | ||
function validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode, vfsRoot) { | ||
var inErrsButNotFoundInTheHeader = relevantErrors.filter(function (e) { | ||
return !handbookOptions.errors.includes(e.code); | ||
}); | ||
var errorsFound = inErrsButNotFoundInTheHeader.map(function (e) { | ||
var errorsFound = Array.from(new Set(inErrsButNotFoundInTheHeader.map(function (e) { | ||
return e.code; | ||
}).join(' '); | ||
}))).join(" "); | ||
if (inErrsButNotFoundInTheHeader.length) { | ||
var codeToAdd = "// @errors: " + relevantErrors.map(function (e) { | ||
var errorsToShow = new Set(relevantErrors.map(function (e) { | ||
return e.code; | ||
}).join(' '); | ||
var postfix = handbookOptions.errors.length ? " - the annotation specified " + handbookOptions.errors : '\n\nExpected:\n' + codeToAdd; | ||
var afterMessage = inErrsButNotFoundInTheHeader.map(function (e) { | ||
var msg = typeof e.messageText === 'string' ? e.messageText : e.messageText.messageText; | ||
return "[" + e.code + "] - " + msg; | ||
}).join('\n '); | ||
var codeOutput = "\n\n## Code\n\n'''" + extension + "\n" + originalCode + "\n'''"; | ||
throw new Error("Errors were thrown in the sample, but not included in an errors tag: " + errorsFound + postfix + "\n\n " + afterMessage + codeOutput); | ||
})); | ||
var codeToAdd = "// @errors: " + Array.from(errorsToShow).join(" "); | ||
var missing = handbookOptions.errors.length ? "\nThe existing annotation specified " + handbookOptions.errors.join(" ") : "\nExpected: " + codeToAdd; // These get filled by below | ||
var filesToErrors = {}; | ||
var noFiles = []; | ||
inErrsButNotFoundInTheHeader.forEach(function (d) { | ||
var _d$file; | ||
var fileRef = ((_d$file = d.file) == null ? void 0 : _d$file.fileName) && d.file.fileName.replace(vfsRoot, ""); | ||
if (!fileRef) noFiles.push(d);else { | ||
var existing = filesToErrors[fileRef]; | ||
if (existing) existing.push(d);else filesToErrors[fileRef] = [d]; | ||
} | ||
}); | ||
var showDiagnostics = function showDiagnostics(title, diags) { | ||
return title + "\n " + diags.map(function (e) { | ||
var msg = typeof e.messageText === "string" ? e.messageText : e.messageText.messageText; | ||
return "[" + e.code + "] " + e.start + " - " + msg; | ||
}).join("\n "); | ||
}; | ||
var innerDiags = []; | ||
if (noFiles.length) { | ||
innerDiags.push(showDiagnostics("Ambient Errors", noFiles)); | ||
} | ||
Object.keys(filesToErrors).forEach(function (filepath) { | ||
innerDiags.push(showDiagnostics(filepath, filesToErrors[filepath])); | ||
}); | ||
var allMessages = innerDiags.join("\n\n"); | ||
var newErr = new TwoslashError("Errors were thrown in the sample, but not included in an errors tag", "These errors were not marked as being expected: " + errorsFound + ". " + missing, "Compiler Errors:\n\n" + allMessages); | ||
newErr.code = "## Code\n\n'''" + extension + "\n" + originalCode + "\n'''"; | ||
throw newErr; | ||
} | ||
@@ -189,8 +293,8 @@ } | ||
function validateInput(code) { | ||
if (code.includes('// @errors ')) { | ||
throw new Error("You have '@errors ' - you're missing the colon after errors"); | ||
if (code.includes("// @errors ")) { | ||
throw new TwoslashError("You have '// @errors ' (with a space)", "You want '// @errors: ' (with a colon)", "This is a pretty common typo"); | ||
} | ||
if (code.includes('// @filename ')) { | ||
throw new Error("You have '@filename ' - you're missing the colon after filename"); | ||
if (code.includes("// @filename ")) { | ||
throw new TwoslashError("You have '// @filename ' (with a space)", "You want '// @filename: ' (with a colon)", "This is a pretty common typo"); | ||
} | ||
@@ -210,3 +314,33 @@ } | ||
}; | ||
var TwoslashError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(TwoslashError, _Error); | ||
function TwoslashError(title, description, recommendation, code) { | ||
var _this; | ||
var message = "\n## " + title + "\n\n" + description + "\n"; | ||
if (recommendation) { | ||
message += "\n" + recommendation; | ||
} | ||
if (code) { | ||
message += "\n" + code; | ||
} | ||
_this = _Error.call(this, message) || this; | ||
_this.title = void 0; | ||
_this.description = void 0; | ||
_this.recommendation = void 0; | ||
_this.code = void 0; | ||
_this.title = title; | ||
_this.description = description; | ||
_this.recommendation = recommendation; | ||
_this.code = code; | ||
return _this; | ||
} | ||
return TwoslashError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
function filterHighlightLines(codeLines) { | ||
@@ -306,3 +440,3 @@ var highlights = []; | ||
var keys = Array.from(optMap.keys()); | ||
throw new Error("Invalid value " + key + " for " + name + ". Allowed values: " + keys.join(",")); | ||
throw new TwoslashError("Invalid inline compiler value", "Got " + key + " for " + name + " but it is not a supported value by the TS compiler.", "Allowed values: " + keys.join(",")); | ||
} | ||
@@ -362,3 +496,3 @@ | ||
throw new Error("No compiler setting named '" + name + "' exists!"); | ||
throw new TwoslashError("Invalid inline compiler flag", "There isn't a TypeScript compiler flag called '" + name + "'.", "This is likely a typo, you can check all the compiler flags in the TSConfig reference, or check the additional Twoslash flags in the npm page for @typescript/twoslash."); | ||
} | ||
@@ -539,4 +673,4 @@ | ||
var text = "Could not get LSP result: " + stringAroundIndex(env.getSourceFile(filename).text, position); | ||
var docs = undefined; | ||
var text; | ||
var docs; | ||
@@ -550,2 +684,4 @@ if (quickInfo && quickInfo.displayParts) { | ||
}).join("<br/>") : undefined; | ||
} else { | ||
throw new TwoslashError("Invalid QuickInfo query", "The request on line " + q.line + " in " + filename + " for quickinfo via ^? returned no from the compiler.", "This is likely that the x positioning is off."); | ||
} | ||
@@ -566,6 +702,6 @@ | ||
{ | ||
var _quickInfo = ls.getCompletionsAtPosition(filename, position - 1, {}); | ||
var completions = ls.getCompletionsAtPosition(filename, position - 1, {}); | ||
if (!_quickInfo && !handbookOptions.noErrorValidation) { | ||
throw new Error("Twoslash: The ^| query at line " + q.line + " in " + filename + " did not return any completions"); | ||
if (!completions && !handbookOptions.noErrorValidation) { | ||
throw new TwoslashError("Invalid completion query", "The request on line " + q.line + " in " + filename + " for completions via ^| returned no completions from the compiler.", "This is likely that the positioning is off."); | ||
} | ||
@@ -578,3 +714,3 @@ | ||
kind: "completions", | ||
completions: (_quickInfo == null ? void 0 : _quickInfo.entries) || [], | ||
completions: (completions == null ? void 0 : completions.entries) || [], | ||
completionPrefix: lastDot, | ||
@@ -636,4 +772,8 @@ line: q.line - i, | ||
var sourceFile = env.getSourceFile(file); | ||
if (!sourceFile) throw new Error("No sourcefile found for " + file + " in twoslash"); // Get all of the interesting quick info popover | ||
if (!sourceFile) { | ||
throw new TwoslashError("Could not find a TypeScript sourcefile for '" + file + "' in the Twoslash vfs", "It's a little hard to provide useful advice on this error. Maybe you imported something which the compiler doesn't think is a source file?", ""); | ||
} // Get all of the interesting quick info popover | ||
if (!handbookOptions.showEmit) { | ||
@@ -723,3 +863,3 @@ var fileContentStartIndexInModifiedFile = code.indexOf(source) == -1 ? 0 : code.indexOf(source); | ||
if (!handbookOptions.noErrorValidation && relevantErrors.length) { | ||
validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode); | ||
validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode, fsRoot); | ||
} | ||
@@ -764,3 +904,3 @@ | ||
throw new Error("Cannot find the corresponding **source** file for " + emitFilename + " (looking for: " + emitSourceFilename + " in the vfs) - in " + allFiles); | ||
throw new TwoslashError("Could not find source file to show the emit for", "Cannot find the corresponding **source** file " + emitFilename + " for completions via ^| returned no quickinfo from the compiler.", "Looked for: " + emitSourceFilename + " in the vfs - which contains: " + allFiles); | ||
} // Allow outfile, in which case you need any file. | ||
@@ -781,6 +921,5 @@ | ||
return o.name; | ||
}).join(", "); // prettier-ignore | ||
}).join(", "); | ||
throw new Error("Cannot find the file " + handbookOptions.showEmittedFile + " (looking for: " + (fsRoot + handbookOptions.showEmittedFile) + " in the vfs) - in " + _allFiles); | ||
throw new TwoslashError("Cannot find the output file in the Twoslash VFS", "Looking for " + handbookOptions.showEmittedFile + " in the Twoslash vfs after compiling", "Looked for\" " + (fsRoot + handbookOptions.showEmittedFile) + " in the vfs - which contains " + _allFiles + "."); | ||
} | ||
@@ -879,3 +1018,4 @@ | ||
exports.TwoslashError = TwoslashError; | ||
exports.twoslasher = twoslasher; | ||
//# sourceMappingURL=twoslash.cjs.development.js.map |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@typescript/vfs");function t(){return(t=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)}function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function r(e,t){var r;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return n(e,void 0);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,void 0):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=e[Symbol.iterator]()).next.bind(r)}function i(e,t){switch(t){case"number":return+e;case"string":return e;case"boolean":return"true"===e.toLowerCase()||0===e.length}throw new Error("Unknown primitive type "+t+" with - "+e)}var o=!1;try{o="undefined"!=typeof localStorage}catch(e){}var s="undefined"!=typeof process,a=o&&localStorage.getItem("DEBUG")||s&&process.env.DEBUG?console.log:function(e){return""};function l(e){for(var t=[],n=[],r=0,i=0,o=0,s=function(s){var c=e[s],u=function(){i=r,r+=c.length+1},f=function(t){a("Removing line "+s+" for "+t),o++,e.splice(s,1),s--};if(c.includes("//")){var p=/^\s*\/\/\s*\^+( .+)?$/.exec(c),d=/^\s*\/\/\s*\^\?\s*$/.exec(c),h=/^\s*\/\/ prettier-ignore$/.exec(c),g=/^\s*\/\/\s*\^\|$/.exec(c);if(null!==d){var v=c.indexOf("^");n.push({kind:"query",offset:v,text:void 0,docs:void 0,line:s+o-1}),f("having a query")}else if(null!==p){var m=c.indexOf("^"),x=c.lastIndexOf("^")-m+1,w=i+m,y=p[1]?p[1].trim():"";t.push({kind:"highlight",position:w,length:x,description:y,line:s}),f("having a highlight")}else if(null!==h)f("being a prettier ignore");else if(null!==g){var E=c.indexOf("^");n.push({kind:"completion",offset:E,text:void 0,docs:void 0,line:s+o-1}),f("having a completion query")}else u()}else u();l=s},l=0;l<e.length;l++)s(l);return{highlights:t,queries:n}}function c(e,t,n){var r=n.get(t.toLowerCase());if(a("Get "+e+" mapped option: "+t+" => "+r),void 0===r){var i=Array.from(n.keys());throw new Error("Invalid value "+t+" for "+e+". Allowed values: "+i.join(","))}return r}function u(e,t,n,o){a("Setting "+e+" to "+t);for(var s,l=function(){var r=s.value;if(r.name.toLowerCase()===e.toLowerCase()){switch(r.type){case"number":case"string":case"boolean":n[r.name]=i(t,r.type);break;case"list":var o=r.element.type,a=t.split(",");n[r.name]=a.map("string"==typeof o?function(e){return i(e,o)}:function(e){return c(r.name,e,o)});break;default:n[r.name]=c(r.name,t,r.type)}return{v:void 0}}},u=r(o.optionDeclarations);!(s=u()).done;){var f=l();if("object"==typeof f)return f.v}throw new Error("No compiler setting named '"+e+"' exists!")}var f=/^\/\/\s?@(\w+)$/,p=/^\/\/\s?@(\w+):\s?(.+)$/,d={errors:[],noErrors:!1,showEmit:!1,showEmittedFile:void 0,noStaticSemanticInfo:!1,emit:!1,noErrorValidation:!1};exports.twoslasher=function(n,i,o){var s,c,h;void 0===o&&(o={});var g=null!=(s=o.tsModule)?s:require("typescript"),v=null!=(c=o.lzstringModule)?c:require("lz-string"),m=n,x=function(e){switch(e){case"js":case"javascript":return"js";case"ts":case"typescript":return"ts";case"tsx":return"tsx";case"jsx":return"jsx";case"jsn":return"json"}throw new Error("Cannot handle the file extension:"+e)}(i),w="index."+x;a("\n\nLooking at code: \n```"+x+"\n"+n+"\n```\n");var y=t({strict:!0,target:g.ScriptTarget.ES2016,allowJs:!0},null!=(h=o.defaultCompilerOptions)?h:{});!function(e){if(e.includes("// @errors "))throw new Error("You have '@errors ' - you're missing the colon after errors");if(e.includes("// @filename "))throw new Error("You have '@filename ' - you're missing the colon after filename")}(n);var E=(n=function(e){return(e=e.replace(/¨D/g,"$")).replace(/¨T/g,"~")}(n)).split(/\r\n?|\n/g),j=t({},function(e){for(var n=t({},d),r=0;r<e.length;r++){var i=void 0;(i=f.exec(e[r]))?i[1]in n&&(n[i[1]]=!0,a("Setting options."+i[1]+" to true"),e.splice(r,1),r--):(i=p.exec(e[r]))&&i[1]in n&&(n[i[1]]=i[2],a("Setting options."+i[1]+" to "+i[2]),e.splice(r,1),r--)}return"errors"in n&&"string"==typeof n.errors&&(n.errors=n.errors.split(" ").map(Number),a("Setting options.error to ",n.errors)),n}(E),o.defaultOptions),S=function(e,n,r){for(var i=t({},n),o=0;o<e.length;){var s=void 0;if(s=f.exec(e[o]))i[s[1]]=!0,u(s[1],"true",i,r);else{if(!(s=p.exec(e[o]))){o++;continue}if("filename"===s[1]){o++;continue}u(s[1],s[2],i,r)}e.splice(o,1)}return i}(E,y,g);j.showEmittedFile||(j.showEmittedFile=S.jsx&&S.jsx===g.JsxEmit.Preserve?"index.jsx":"index.js");var b=function(){var e=require("path");return(o.vfsRoot||process.cwd()).split(e.sep).join(e.posix.sep)},F=!!o.fsMap,O=F&&o.fsMap?o.fsMap:new Map,k=F?e.createSystem(O):e.createFSBackedSystem(O,b(),g),P=F?"/":b()+"/",C=e.createVirtualTypeScriptEnvironment(k,[],g,S,o.customTransformers),T=C.languageService;n=E.join("\n");for(var q,A=[],I=[],L=[],M=function(e,t,n){for(var i,o=e.split(/\r\n?|\n/g),s=e.includes("@filename: "+t)?"global.ts":t,a=[],l=[],c=r(o);!(i=c()).done;){var u=i.value;u.includes("// @filename: ")?(l.push([n+s,a]),s=u.split("// @filename: ")[1].trim(),a=[]):a.push(u)}return l.push([n+s,a]),l.filter((function(e){return e[1].length>0&&(e[1].length>1||""!==e[1][0])}))}(n,w,P),$=["js","jsx","ts","tsx"],D=M.map((function(e){return e[0]})),N=function(){var e=q.value,t=e[0],n=e[1],r=t.split(".").pop()||"",i=S.resolveJsonModule&&"json"===r;if(!$.includes(r)&&!i)return"continue";var o=n.join("\n");C.createFile(t,o);var s=l(n);L=L.concat(s.highlights);var a=s.queries.map((function(e,n){var r,i,o=C.getSourceFile(t),s=g.getPositionOfLineAndCharacter(o,e.line,e.offset);switch(e.kind){case"query":var a=T.getQuickInfoAtPosition(t,s),l="Could not get LSP result: "+[(r=C.getSourceFile(t).text)[(i=s)-3],r[i-2],r[i-1],">",r[i],"<",r[i+1],r[i+2],r[i+3]].filter(Boolean).join(""),c=void 0;return a&&a.displayParts&&(l=a.displayParts.map((function(e){return e.text})).join(""),c=a.documentation?a.documentation.map((function(e){return e.text})).join("<br/>"):void 0),{kind:"query",text:l,docs:c,line:e.line-n,offset:e.offset,file:t};case"completion":var u=T.getCompletionsAtPosition(t,s-1,{});if(!u&&!j.noErrorValidation)throw new Error("Twoslash: The ^| query at line "+e.line+" in "+t+" did not return any completions");var f=function(e,t){e=String(e),t=Number(t)>>>0;var n=e.slice(0,t+1).search(/\S+$/),r=e.slice(t).search(/\s/);return r<0?{word:e.slice(n),startPos:n}:{word:e.slice(n,r+t),startPos:n}}(o.text,s-1),p=o.text.slice(f.startPos,s).split(".").pop()||"";return{kind:"completions",completions:(null==u?void 0:u.entries)||[],completionPrefix:p,line:e.line-n,offset:e.offset,file:t}}}));A=A.concat(a);var c=n.join("\n");C.updateFile(t,c)},U=r(M);!(q=U()).done;)N();var B=n.split(/\r\n?|\n/g);l(B),n=B.join("\n"),j.emit&&D.forEach((function(e){var t=e.split(".").pop()||"";$.includes(t)&&T.getEmitOutput(e).outputFiles.forEach((function(e){k.writeFile(e.name,e.text)}))}));var R=[],V=[];D.forEach((function(e){var t=e.split(".").pop()||"";if($.includes(t)){j.noErrors||(R=R.concat(T.getSemanticDiagnostics(e),T.getSyntacticDiagnostics(e)));var i=C.sys.readFile(e),o=C.getSourceFile(e);if(!o)throw new Error("No sourcefile found for "+e+" in twoslash");if(!j.showEmit){for(var s,a=-1==n.indexOf(i)?0:n.indexOf(i),l=n.slice(0,a).split("\n").length-1,c=r(j.noStaticSemanticInfo?[]:function(e,t){var n=[];return function r(i){e.forEachChild(i,(function(i){if(e.isIdentifier(i)){var o=i.getStart(t,!1);n.push({span:e.createTextSpan(o,i.end-o),text:i.getText(t)})}r(i)}))}(t),n}(g,o));!(s=c()).done;){var u=s.value,f=u.span,p=T.getQuickInfoAtPosition(e,f.start);if(p&&p.displayParts){var d=p.displayParts.map((function(e){return e.text})).join(""),h=u.text,v=p.documentation?p.documentation.map((function(e){return e.text})).join("\n"):void 0,m=f.start+a,x=g.createSourceFile("_.ts",n,g.ScriptTarget.ES2015),w=g.getLineAndCharacterOfPosition(x,m);V.push({text:d,docs:v,start:m,length:f.length,line:w.line,character:w.character,targetString:h})}}A.filter((function(t){return t.file===e})).forEach((function(e){var t=g.getPositionOfLineAndCharacter(o,e.line,e.offset)+a;switch(e.kind){case"query":I.push({docs:e.docs,kind:"query",start:t+a,length:e.text.length,text:e.text,offset:e.offset,line:e.line+l+1});break;case"completions":I.push({completions:e.completions,kind:"completions",start:t+a,completionsPrefix:e.completionPrefix,length:1,offset:e.offset,line:e.line+l+1})}}))}}}));var G=R.filter((function(e){return e.file&&D.includes(e.file.fileName)}));!j.noErrorValidation&&G.length&&function(e,t,n,r){var i=e.filter((function(e){return!t.errors.includes(e.code)})),o=i.map((function(e){return e.code})).join(" ");if(i.length){var s="// @errors: "+e.map((function(e){return e.code})).join(" "),a=t.errors.length?" - the annotation specified "+t.errors:"\n\nExpected:\n"+s,l=i.map((function(e){return"["+e.code+"] - "+("string"==typeof e.messageText?e.messageText:e.messageText.messageText)})).join("\n ");throw new Error("Errors were thrown in the sample, but not included in an errors tag: "+o+a+"\n\n "+l+"\n\n## Code\n\n'''"+n+"\n"+r+"\n'''")}}(G,j,i,m);for(var J,Q=[],_=r(G);!(J=_()).done;){var z=J.value,Y=C.sys.readFile(z.file.fileName),H=n.indexOf(Y),K=g.flattenDiagnosticMessageText(z.messageText,"\n"),W="err-"+z.code+"-"+z.start+"-"+z.length,X=g.getLineAndCharacterOfPosition(z.file,z.start);Q.push({category:z.category,code:z.code,length:z.length,start:z.start?z.start+H:void 0,line:X.line,character:X.character,renderedMessage:K,id:W})}if(j.showEmit){var Z=j.showEmittedFile||w,ee=P+Z.replace(".jsx","").replace(".js","").replace(".d.ts","").replace(".map",""),te=D.find((function(e){return e===ee+".ts"||e===ee+".tsx"}));if(!te&&!S.outFile){var ne=D.join(", ");throw new Error("Cannot find the corresponding **source** file for "+Z+" (looking for: "+ee+" in the vfs) - in "+ne)}S.outFile&&(te=D[0]);var re=T.getEmitOutput(te),ie=re.outputFiles.find((function(e){return e.name===P+j.showEmittedFile||e.name===j.showEmittedFile}));if(!ie){var oe=re.outputFiles.map((function(e){return e.name})).join(", ");throw new Error("Cannot find the file "+j.showEmittedFile+" (looking for: "+(P+j.showEmittedFile)+" in the vfs) - in "+oe)}n=ie.text,i=ie.name.split(".").pop(),L=[],A=[],V=[]}var se="https://www.typescriptlang.org/play/#code/"+v.compressToEncodedURIComponent(m),ae="// ---cut---\n";if(n.includes(ae)){var le=n.indexOf(ae)+ae.length,ce=n.substr(0,le).split("\n").length-1;n=n.split(ae).pop(),V.forEach((function(e){e.start-=le,e.line-=ce})),V=V.filter((function(e){return e.start>-1})),Q.forEach((function(e){e.start&&(e.start-=le),e.line&&(e.line-=ce)})),Q=Q.filter((function(e){return e.start&&e.start>-1})),L.forEach((function(e){e.position-=le,e.line-=ce})),L=L.filter((function(e){return e.position>-1})),I.forEach((function(e){return e.line-=ce})),I=I.filter((function(e){return e.line>-1}))}return{code:n,extension:i,highlights:L,queries:I,staticQuickInfos:V,errors:Q,playgroundURL:se}}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@typescript/vfs");function t(){return(t=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)}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function r(e,t){return(r=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function i(e,t,n){return(i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}()?Reflect.construct:function(e,t,n){var i=[null];i.push.apply(i,t);var o=new(Function.bind.apply(e,i));return n&&r(o,n.prototype),o}).apply(null,arguments)}function o(e){var t="function"==typeof Map?new Map:void 0;return(o=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,o)}function o(){return i(e,arguments,n(this).constructor)}return o.prototype=Object.create(e.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),r(o,e)})(e)}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function a(e,t){var n;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return s(e,void 0);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(e,void 0):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(n=e[Symbol.iterator]()).next.bind(n)}function c(e,t){switch(t){case"number":return+e;case"string":return e;case"boolean":return"true"===e.toLowerCase()||0===e.length}throw new p("Unknown primitive value in compiler flag","The only recognized primitives are number, string and boolean. Got "+t+" with "+e+".","This is likely a typo.")}var l=!1;try{l="undefined"!=typeof localStorage}catch(e){}var u="undefined"!=typeof process,f=l&&localStorage.getItem("DEBUG")||u&&process.env.DEBUG?console.log:function(e){return""},p=function(e){var t,n;function i(t,n,r,i){var o,s="\n## "+t+"\n\n"+n+"\n";return r&&(s+="\n"+r),i&&(s+="\n"+i),(o=e.call(this,s)||this).title=void 0,o.description=void 0,o.recommendation=void 0,o.code=void 0,o.title=t,o.description=n,o.recommendation=r,o.code=i,o}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,r(t,n),i}(o(Error));function h(e){for(var t=[],n=[],r=0,i=0,o=0,s=function(s){var c=e[s],l=function(){i=r,r+=c.length+1},u=function(t){f("Removing line "+s+" for "+t),o++,e.splice(s,1),s--};if(c.includes("//")){var p=/^\s*\/\/\s*\^+( .+)?$/.exec(c),h=/^\s*\/\/\s*\^\?\s*$/.exec(c),d=/^\s*\/\/ prettier-ignore$/.exec(c),v=/^\s*\/\/\s*\^\|$/.exec(c);if(null!==h){var m=c.indexOf("^");n.push({kind:"query",offset:m,text:void 0,docs:void 0,line:s+o-1}),u("having a query")}else if(null!==p){var g=c.indexOf("^"),y=c.lastIndexOf("^")-g+1,w=i+g,x=p[1]?p[1].trim():"";t.push({kind:"highlight",position:w,length:y,description:x,line:s}),u("having a highlight")}else if(null!==d)u("being a prettier ignore");else if(null!==v){var b=c.indexOf("^");n.push({kind:"completion",offset:b,text:void 0,docs:void 0,line:s+o-1}),u("having a completion query")}else l()}else l();a=s},a=0;a<e.length;a++)s(a);return{highlights:t,queries:n}}function d(e,t,n){var r=n.get(t.toLowerCase());if(f("Get "+e+" mapped option: "+t+" => "+r),void 0===r){var i=Array.from(n.keys());throw new p("Invalid inline compiler value","Got "+t+" for "+e+" but it is not a supported value by the TS compiler.","Allowed values: "+i.join(","))}return r}function v(e,t,n,r){f("Setting "+e+" to "+t);for(var i,o=function(){var r=i.value;if(r.name.toLowerCase()===e.toLowerCase()){switch(r.type){case"number":case"string":case"boolean":n[r.name]=c(t,r.type);break;case"list":var o=r.element.type,s=t.split(",");n[r.name]=s.map("string"==typeof o?function(e){return c(e,o)}:function(e){return d(r.name,e,o)});break;default:n[r.name]=d(r.name,t,r.type)}return{v:void 0}}},s=a(r.optionDeclarations);!(i=s()).done;){var l=o();if("object"==typeof l)return l.v}throw new p("Invalid inline compiler flag","There isn't a TypeScript compiler flag called '"+e+"'.","This is likely a typo, you can check all the compiler flags in the TSConfig reference, or check the additional Twoslash flags in the npm page for @typescript/twoslash.")}var m=/^\/\/\s?@(\w+)$/,g=/^\/\/\s?@(\w+):\s?(.+)$/,y={errors:[],noErrors:!1,showEmit:!1,showEmittedFile:void 0,noStaticSemanticInfo:!1,emit:!1,noErrorValidation:!1};exports.TwoslashError=p,exports.twoslasher=function(n,r,i){var o,s,c;void 0===i&&(i={});var l=null!=(o=i.tsModule)?o:require("typescript"),u=null!=(s=i.lzstringModule)?s:require("lz-string"),d=n,w=function(e){var t={js:"js",javascript:"js",ts:"ts",typescript:"ts",tsx:"tsx",jsx:"jsx",json:"json",jsn:"json"};if(t[e])return t[e];throw new p("Unknown TypeScript extension given to Twoslash","Received "+e+" but Twoslash only accepts: "+Object.keys(t)+" ","")}(r),x="index."+w;f("\n\nLooking at code: \n```"+w+"\n"+n+"\n```\n");var b=t({strict:!0,target:l.ScriptTarget.ES2016,allowJs:!0},null!=(c=i.defaultCompilerOptions)?c:{});!function(e){if(e.includes("// @errors "))throw new p("You have '// @errors ' (with a space)","You want '// @errors: ' (with a colon)","This is a pretty common typo");if(e.includes("// @filename "))throw new p("You have '// @filename ' (with a space)","You want '// @filename: ' (with a colon)","This is a pretty common typo")}(n);var j=(n=function(e){return(e=e.replace(/¨D/g,"$")).replace(/¨T/g,"~")}(n)).split(/\r\n?|\n/g),S=t({},function(e){for(var n=t({},y),r=0;r<e.length;r++){var i=void 0;(i=m.exec(e[r]))?i[1]in n&&(n[i[1]]=!0,f("Setting options."+i[1]+" to true"),e.splice(r,1),r--):(i=g.exec(e[r]))&&i[1]in n&&(n[i[1]]=i[2],f("Setting options."+i[1]+" to "+i[2]),e.splice(r,1),r--)}return"errors"in n&&"string"==typeof n.errors&&(n.errors=n.errors.split(" ").map(Number),f("Setting options.error to ",n.errors)),n}(j),i.defaultOptions),E=function(e,n,r){for(var i=t({},n),o=0;o<e.length;){var s=void 0;if(s=m.exec(e[o]))i[s[1]]=!0,v(s[1],"true",i,r);else{if(!(s=g.exec(e[o]))){o++;continue}if("filename"===s[1]){o++;continue}v(s[1],s[2],i,r)}e.splice(o,1)}return i}(j,b,l);S.showEmittedFile||(S.showEmittedFile=E.jsx&&E.jsx===l.JsxEmit.Preserve?"index.jsx":"index.js");var T=function(){var e=require("path");return(i.vfsRoot||process.cwd()).split(e.sep).join(e.posix.sep)},k=!!i.fsMap,O=k&&i.fsMap?i.fsMap:new Map,F=k?e.createSystem(O):e.createFSBackedSystem(O,T(),l),P=k?"/":T()+"/",q=e.createVirtualTypeScriptEnvironment(F,[],l,E,i.customTransformers),C=q.languageService;n=j.join("\n");for(var A,I=[],M=[],L=[],_=function(e,t,n){for(var r,i=e.split(/\r\n?|\n/g),o=e.includes("@filename: "+t)?"global.ts":t,s=[],c=[],l=a(i);!(r=l()).done;){var u=r.value;u.includes("// @filename: ")?(c.push([n+o,s]),o=u.split("// @filename: ")[1].trim(),s=[]):s.push(u)}return c.push([n+o,s]),c.filter((function(e){return e[1].length>0&&(e[1].length>1||""!==e[1][0])}))}(n,x,P),R=["js","jsx","ts","tsx"],$=_.map((function(e){return e[0]})),D=function(){var e=A.value,t=e[0],n=e[1],r=t.split(".").pop()||"",i=E.resolveJsonModule&&"json"===r;if(!R.includes(r)&&!i)return"continue";var o=n.join("\n");q.createFile(t,o);var s=h(n);L=L.concat(s.highlights);var a=s.queries.map((function(e,n){var r=q.getSourceFile(t),i=l.getPositionOfLineAndCharacter(r,e.line,e.offset);switch(e.kind){case"query":var o=C.getQuickInfoAtPosition(t,i);if(!o||!o.displayParts)throw new p("Invalid QuickInfo query","The request on line "+e.line+" in "+t+" for quickinfo via ^? returned no from the compiler.","This is likely that the x positioning is off.");return{kind:"query",text:o.displayParts.map((function(e){return e.text})).join(""),docs:o.documentation?o.documentation.map((function(e){return e.text})).join("<br/>"):void 0,line:e.line-n,offset:e.offset,file:t};case"completion":var s=C.getCompletionsAtPosition(t,i-1,{});if(!s&&!S.noErrorValidation)throw new p("Invalid completion query","The request on line "+e.line+" in "+t+" for completions via ^| returned no completions from the compiler.","This is likely that the positioning is off.");var a=function(e,t){e=String(e),t=Number(t)>>>0;var n=e.slice(0,t+1).search(/\S+$/),r=e.slice(t).search(/\s/);return r<0?{word:e.slice(n),startPos:n}:{word:e.slice(n,r+t),startPos:n}}(r.text,i-1),c=r.text.slice(a.startPos,i).split(".").pop()||"";return{kind:"completions",completions:(null==s?void 0:s.entries)||[],completionPrefix:c,line:e.line-n,offset:e.offset,file:t}}}));I=I.concat(a);var c=n.join("\n");q.updateFile(t,c)},U=a(_);!(A=U()).done;)D();var N=n.split(/\r\n?|\n/g);h(N),n=N.join("\n"),S.emit&&$.forEach((function(e){var t=e.split(".").pop()||"";R.includes(t)&&C.getEmitOutput(e).outputFiles.forEach((function(e){F.writeFile(e.name,e.text)}))}));var B=[],G=[];$.forEach((function(e){var t=e.split(".").pop()||"";if(R.includes(t)){S.noErrors||(B=B.concat(C.getSemanticDiagnostics(e),C.getSyntacticDiagnostics(e)));var r=q.sys.readFile(e),i=q.getSourceFile(e);if(!i)throw new p("Could not find a TypeScript sourcefile for '"+e+"' in the Twoslash vfs","It's a little hard to provide useful advice on this error. Maybe you imported something which the compiler doesn't think is a source file?","");if(!S.showEmit){for(var o,s=-1==n.indexOf(r)?0:n.indexOf(r),c=n.slice(0,s).split("\n").length-1,u=a(S.noStaticSemanticInfo?[]:function(e,t){var n=[];return function r(i){e.forEachChild(i,(function(i){if(e.isIdentifier(i)){var o=i.getStart(t,!1);n.push({span:e.createTextSpan(o,i.end-o),text:i.getText(t)})}r(i)}))}(t),n}(l,i));!(o=u()).done;){var f=o.value,h=f.span,d=C.getQuickInfoAtPosition(e,h.start);if(d&&d.displayParts){var v=d.displayParts.map((function(e){return e.text})).join(""),m=f.text,g=d.documentation?d.documentation.map((function(e){return e.text})).join("\n"):void 0,y=h.start+s,w=l.createSourceFile("_.ts",n,l.ScriptTarget.ES2015),x=l.getLineAndCharacterOfPosition(w,y);G.push({text:v,docs:g,start:y,length:h.length,line:x.line,character:x.character,targetString:m})}}I.filter((function(t){return t.file===e})).forEach((function(e){var t=l.getPositionOfLineAndCharacter(i,e.line,e.offset)+s;switch(e.kind){case"query":M.push({docs:e.docs,kind:"query",start:t+s,length:e.text.length,text:e.text,offset:e.offset,line:e.line+c+1});break;case"completions":M.push({completions:e.completions,kind:"completions",start:t+s,completionsPrefix:e.completionPrefix,length:1,offset:e.offset,line:e.line+c+1})}}))}}}));var V=B.filter((function(e){return e.file&&$.includes(e.file.fileName)}));!S.noErrorValidation&&V.length&&function(e,t,n,r,i){var o=e.filter((function(e){return!t.errors.includes(e.code)})),s=Array.from(new Set(o.map((function(e){return e.code})))).join(" ");if(o.length){var a=new Set(e.map((function(e){return e.code}))),c="// @errors: "+Array.from(a).join(" "),l=t.errors.length?"\nThe existing annotation specified "+t.errors.join(" "):"\nExpected: "+c,u={},f=[];o.forEach((function(e){var t,n=(null==(t=e.file)?void 0:t.fileName)&&e.file.fileName.replace(i,"");if(n){var r=u[n];r?r.push(e):u[n]=[e]}else f.push(e)}));var h=function(e,t){return e+"\n "+t.map((function(e){return"["+e.code+"] "+e.start+" - "+("string"==typeof e.messageText?e.messageText:e.messageText.messageText)})).join("\n ")},d=[];f.length&&d.push(h("Ambient Errors",f)),Object.keys(u).forEach((function(e){d.push(h(e,u[e]))}));var v=d.join("\n\n"),m=new p("Errors were thrown in the sample, but not included in an errors tag","These errors were not marked as being expected: "+s+". "+l,"Compiler Errors:\n\n"+v);throw m.code="## Code\n\n'''"+n+"\n"+r+"\n'''",m}}(V,S,r,d,P);for(var Q,Y=[],z=a(V);!(Q=z()).done;){var J=Q.value,H=q.sys.readFile(J.file.fileName),K=n.indexOf(H),W=l.flattenDiagnosticMessageText(J.messageText,"\n"),X="err-"+J.code+"-"+J.start+"-"+J.length,Z=l.getLineAndCharacterOfPosition(J.file,J.start);Y.push({category:J.category,code:J.code,length:J.length,start:J.start?J.start+K:void 0,line:Z.line,character:Z.character,renderedMessage:W,id:X})}if(S.showEmit){var ee=S.showEmittedFile||x,te=P+ee.replace(".jsx","").replace(".js","").replace(".d.ts","").replace(".map",""),ne=$.find((function(e){return e===te+".ts"||e===te+".tsx"}));if(!ne&&!E.outFile){var re=$.join(", ");throw new p("Could not find source file to show the emit for","Cannot find the corresponding **source** file "+ee+" for completions via ^| returned no quickinfo from the compiler.","Looked for: "+te+" in the vfs - which contains: "+re)}E.outFile&&(ne=$[0]);var ie=C.getEmitOutput(ne),oe=ie.outputFiles.find((function(e){return e.name===P+S.showEmittedFile||e.name===S.showEmittedFile}));if(!oe){var se=ie.outputFiles.map((function(e){return e.name})).join(", ");throw new p("Cannot find the output file in the Twoslash VFS","Looking for "+S.showEmittedFile+" in the Twoslash vfs after compiling",'Looked for" '+(P+S.showEmittedFile)+" in the vfs - which contains "+se+".")}n=oe.text,r=oe.name.split(".").pop(),L=[],I=[],G=[]}var ae="https://www.typescriptlang.org/play/#code/"+u.compressToEncodedURIComponent(d),ce="// ---cut---\n";if(n.includes(ce)){var le=n.indexOf(ce)+ce.length,ue=n.substr(0,le).split("\n").length-1;n=n.split(ce).pop(),G.forEach((function(e){e.start-=le,e.line-=ue})),G=G.filter((function(e){return e.start>-1})),Y.forEach((function(e){e.start&&(e.start-=le),e.line&&(e.line-=ue)})),Y=Y.filter((function(e){return e.start&&e.start>-1})),L.forEach((function(e){e.position-=le,e.line-=ue})),L=L.filter((function(e){return e.position>-1})),M.forEach((function(e){return e.line-=ue})),M=M.filter((function(e){return e.line>-1}))}return{code:n,extension:r,highlights:L,queries:M,staticQuickInfos:G,errors:Y,playgroundURL:ae}}; | ||
//# sourceMappingURL=twoslash.cjs.production.min.js.map |
@@ -21,2 +21,93 @@ import { createSystem, createFSBackedSystem, createVirtualTypeScriptEnvironment } from '@typescript/vfs'; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_cache.set(Class, Wrapper); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
return _wrapNativeSuper(Class); | ||
} | ||
function _unsupportedIterableToArray(o, minLen) { | ||
@@ -76,3 +167,3 @@ if (!o) return; | ||
throw new Error("Unknown primitive type " + type + " with - " + value); | ||
throw new TwoslashError("Unknown primitive value in compiler flag", "The only recognized primitives are number, string and boolean. Got " + type + " with " + value + ".", "This is likely a typo."); | ||
} | ||
@@ -85,26 +176,14 @@ function cleanMarkdownEscaped(code) { | ||
function typesToExtension(types) { | ||
switch (types) { | ||
case "js": | ||
return "js"; | ||
case "javascript": | ||
return "js"; | ||
case "ts": | ||
return "ts"; | ||
case "typescript": | ||
return "ts"; | ||
case "tsx": | ||
return "tsx"; | ||
case "jsx": | ||
return "jsx"; | ||
case "jsn": | ||
return "json"; | ||
} | ||
throw new Error("Cannot handle the file extension:" + types); | ||
var map = { | ||
js: "js", | ||
javascript: "js", | ||
ts: "ts", | ||
typescript: "ts", | ||
tsx: "tsx", | ||
jsx: "jsx", | ||
json: "json", | ||
jsn: "json" | ||
}; | ||
if (map[types]) return map[types]; | ||
throw new TwoslashError("Unknown TypeScript extension given to Twoslash", "Received " + types + " but Twoslash only accepts: " + Object.keys(map) + " ", ""); | ||
} | ||
@@ -130,6 +209,2 @@ function getIdentifierTextSpans(ts, sourceFile) { | ||
} | ||
function stringAroundIndex(string, index) { | ||
var arr = [string[index - 3], string[index - 2], string[index - 1], ">", string[index], "<", string[index + 1], string[index + 2], string[index + 3]]; | ||
return arr.filter(Boolean).join(""); | ||
} | ||
/** Came from https://ourcodeworld.com/articles/read/223/how-to-retrieve-the-closest-word-in-a-string-with-a-given-index-in-javascript */ | ||
@@ -160,21 +235,50 @@ | ||
/** To ensure that errors are matched up right */ | ||
function validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode) { | ||
function validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode, vfsRoot) { | ||
var inErrsButNotFoundInTheHeader = relevantErrors.filter(function (e) { | ||
return !handbookOptions.errors.includes(e.code); | ||
}); | ||
var errorsFound = inErrsButNotFoundInTheHeader.map(function (e) { | ||
var errorsFound = Array.from(new Set(inErrsButNotFoundInTheHeader.map(function (e) { | ||
return e.code; | ||
}).join(' '); | ||
}))).join(" "); | ||
if (inErrsButNotFoundInTheHeader.length) { | ||
var codeToAdd = "// @errors: " + relevantErrors.map(function (e) { | ||
var errorsToShow = new Set(relevantErrors.map(function (e) { | ||
return e.code; | ||
}).join(' '); | ||
var postfix = handbookOptions.errors.length ? " - the annotation specified " + handbookOptions.errors : '\n\nExpected:\n' + codeToAdd; | ||
var afterMessage = inErrsButNotFoundInTheHeader.map(function (e) { | ||
var msg = typeof e.messageText === 'string' ? e.messageText : e.messageText.messageText; | ||
return "[" + e.code + "] - " + msg; | ||
}).join('\n '); | ||
var codeOutput = "\n\n## Code\n\n'''" + extension + "\n" + originalCode + "\n'''"; | ||
throw new Error("Errors were thrown in the sample, but not included in an errors tag: " + errorsFound + postfix + "\n\n " + afterMessage + codeOutput); | ||
})); | ||
var codeToAdd = "// @errors: " + Array.from(errorsToShow).join(" "); | ||
var missing = handbookOptions.errors.length ? "\nThe existing annotation specified " + handbookOptions.errors.join(" ") : "\nExpected: " + codeToAdd; // These get filled by below | ||
var filesToErrors = {}; | ||
var noFiles = []; | ||
inErrsButNotFoundInTheHeader.forEach(function (d) { | ||
var _d$file; | ||
var fileRef = ((_d$file = d.file) == null ? void 0 : _d$file.fileName) && d.file.fileName.replace(vfsRoot, ""); | ||
if (!fileRef) noFiles.push(d);else { | ||
var existing = filesToErrors[fileRef]; | ||
if (existing) existing.push(d);else filesToErrors[fileRef] = [d]; | ||
} | ||
}); | ||
var showDiagnostics = function showDiagnostics(title, diags) { | ||
return title + "\n " + diags.map(function (e) { | ||
var msg = typeof e.messageText === "string" ? e.messageText : e.messageText.messageText; | ||
return "[" + e.code + "] " + e.start + " - " + msg; | ||
}).join("\n "); | ||
}; | ||
var innerDiags = []; | ||
if (noFiles.length) { | ||
innerDiags.push(showDiagnostics("Ambient Errors", noFiles)); | ||
} | ||
Object.keys(filesToErrors).forEach(function (filepath) { | ||
innerDiags.push(showDiagnostics(filepath, filesToErrors[filepath])); | ||
}); | ||
var allMessages = innerDiags.join("\n\n"); | ||
var newErr = new TwoslashError("Errors were thrown in the sample, but not included in an errors tag", "These errors were not marked as being expected: " + errorsFound + ". " + missing, "Compiler Errors:\n\n" + allMessages); | ||
newErr.code = "## Code\n\n'''" + extension + "\n" + originalCode + "\n'''"; | ||
throw newErr; | ||
} | ||
@@ -185,8 +289,8 @@ } | ||
function validateInput(code) { | ||
if (code.includes('// @errors ')) { | ||
throw new Error("You have '@errors ' - you're missing the colon after errors"); | ||
if (code.includes("// @errors ")) { | ||
throw new TwoslashError("You have '// @errors ' (with a space)", "You want '// @errors: ' (with a colon)", "This is a pretty common typo"); | ||
} | ||
if (code.includes('// @filename ')) { | ||
throw new Error("You have '@filename ' - you're missing the colon after filename"); | ||
if (code.includes("// @filename ")) { | ||
throw new TwoslashError("You have '// @filename ' (with a space)", "You want '// @filename: ' (with a colon)", "This is a pretty common typo"); | ||
} | ||
@@ -206,3 +310,33 @@ } | ||
}; | ||
var TwoslashError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(TwoslashError, _Error); | ||
function TwoslashError(title, description, recommendation, code) { | ||
var _this; | ||
var message = "\n## " + title + "\n\n" + description + "\n"; | ||
if (recommendation) { | ||
message += "\n" + recommendation; | ||
} | ||
if (code) { | ||
message += "\n" + code; | ||
} | ||
_this = _Error.call(this, message) || this; | ||
_this.title = void 0; | ||
_this.description = void 0; | ||
_this.recommendation = void 0; | ||
_this.code = void 0; | ||
_this.title = title; | ||
_this.description = description; | ||
_this.recommendation = recommendation; | ||
_this.code = code; | ||
return _this; | ||
} | ||
return TwoslashError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
function filterHighlightLines(codeLines) { | ||
@@ -302,3 +436,3 @@ var highlights = []; | ||
var keys = Array.from(optMap.keys()); | ||
throw new Error("Invalid value " + key + " for " + name + ". Allowed values: " + keys.join(",")); | ||
throw new TwoslashError("Invalid inline compiler value", "Got " + key + " for " + name + " but it is not a supported value by the TS compiler.", "Allowed values: " + keys.join(",")); | ||
} | ||
@@ -358,3 +492,3 @@ | ||
throw new Error("No compiler setting named '" + name + "' exists!"); | ||
throw new TwoslashError("Invalid inline compiler flag", "There isn't a TypeScript compiler flag called '" + name + "'.", "This is likely a typo, you can check all the compiler flags in the TSConfig reference, or check the additional Twoslash flags in the npm page for @typescript/twoslash."); | ||
} | ||
@@ -535,4 +669,4 @@ | ||
var text = "Could not get LSP result: " + stringAroundIndex(env.getSourceFile(filename).text, position); | ||
var docs = undefined; | ||
var text; | ||
var docs; | ||
@@ -546,2 +680,4 @@ if (quickInfo && quickInfo.displayParts) { | ||
}).join("<br/>") : undefined; | ||
} else { | ||
throw new TwoslashError("Invalid QuickInfo query", "The request on line " + q.line + " in " + filename + " for quickinfo via ^? returned no from the compiler.", "This is likely that the x positioning is off."); | ||
} | ||
@@ -562,6 +698,6 @@ | ||
{ | ||
var _quickInfo = ls.getCompletionsAtPosition(filename, position - 1, {}); | ||
var completions = ls.getCompletionsAtPosition(filename, position - 1, {}); | ||
if (!_quickInfo && !handbookOptions.noErrorValidation) { | ||
throw new Error("Twoslash: The ^| query at line " + q.line + " in " + filename + " did not return any completions"); | ||
if (!completions && !handbookOptions.noErrorValidation) { | ||
throw new TwoslashError("Invalid completion query", "The request on line " + q.line + " in " + filename + " for completions via ^| returned no completions from the compiler.", "This is likely that the positioning is off."); | ||
} | ||
@@ -574,3 +710,3 @@ | ||
kind: "completions", | ||
completions: (_quickInfo == null ? void 0 : _quickInfo.entries) || [], | ||
completions: (completions == null ? void 0 : completions.entries) || [], | ||
completionPrefix: lastDot, | ||
@@ -632,4 +768,8 @@ line: q.line - i, | ||
var sourceFile = env.getSourceFile(file); | ||
if (!sourceFile) throw new Error("No sourcefile found for " + file + " in twoslash"); // Get all of the interesting quick info popover | ||
if (!sourceFile) { | ||
throw new TwoslashError("Could not find a TypeScript sourcefile for '" + file + "' in the Twoslash vfs", "It's a little hard to provide useful advice on this error. Maybe you imported something which the compiler doesn't think is a source file?", ""); | ||
} // Get all of the interesting quick info popover | ||
if (!handbookOptions.showEmit) { | ||
@@ -719,3 +859,3 @@ var fileContentStartIndexInModifiedFile = code.indexOf(source) == -1 ? 0 : code.indexOf(source); | ||
if (!handbookOptions.noErrorValidation && relevantErrors.length) { | ||
validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode); | ||
validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode, fsRoot); | ||
} | ||
@@ -760,3 +900,3 @@ | ||
throw new Error("Cannot find the corresponding **source** file for " + emitFilename + " (looking for: " + emitSourceFilename + " in the vfs) - in " + allFiles); | ||
throw new TwoslashError("Could not find source file to show the emit for", "Cannot find the corresponding **source** file " + emitFilename + " for completions via ^| returned no quickinfo from the compiler.", "Looked for: " + emitSourceFilename + " in the vfs - which contains: " + allFiles); | ||
} // Allow outfile, in which case you need any file. | ||
@@ -777,6 +917,5 @@ | ||
return o.name; | ||
}).join(", "); // prettier-ignore | ||
}).join(", "); | ||
throw new Error("Cannot find the file " + handbookOptions.showEmittedFile + " (looking for: " + (fsRoot + handbookOptions.showEmittedFile) + " in the vfs) - in " + _allFiles); | ||
throw new TwoslashError("Cannot find the output file in the Twoslash VFS", "Looking for " + handbookOptions.showEmittedFile + " in the Twoslash vfs after compiling", "Looked for\" " + (fsRoot + handbookOptions.showEmittedFile) + " in the vfs - which contains " + _allFiles + "."); | ||
} | ||
@@ -875,3 +1014,3 @@ | ||
export { twoslasher }; | ||
export { TwoslashError, twoslasher }; | ||
//# sourceMappingURL=twoslash.esm.js.map |
@@ -31,2 +31,93 @@ | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_cache.set(Class, Wrapper); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
return _wrapNativeSuper(Class); | ||
} | ||
function _unsupportedIterableToArray(o, minLen) { | ||
@@ -86,3 +177,3 @@ if (!o) return; | ||
throw new Error("Unknown primitive type " + type + " with - " + value); | ||
throw new TwoslashError("Unknown primitive value in compiler flag", "The only recognized primitives are number, string and boolean. Got " + type + " with " + value + ".", "This is likely a typo."); | ||
} | ||
@@ -95,26 +186,14 @@ function cleanMarkdownEscaped(code) { | ||
function typesToExtension(types) { | ||
switch (types) { | ||
case "js": | ||
return "js"; | ||
case "javascript": | ||
return "js"; | ||
case "ts": | ||
return "ts"; | ||
case "typescript": | ||
return "ts"; | ||
case "tsx": | ||
return "tsx"; | ||
case "jsx": | ||
return "jsx"; | ||
case "jsn": | ||
return "json"; | ||
} | ||
throw new Error("Cannot handle the file extension:" + types); | ||
var map = { | ||
js: "js", | ||
javascript: "js", | ||
ts: "ts", | ||
typescript: "ts", | ||
tsx: "tsx", | ||
jsx: "jsx", | ||
json: "json", | ||
jsn: "json" | ||
}; | ||
if (map[types]) return map[types]; | ||
throw new TwoslashError("Unknown TypeScript extension given to Twoslash", "Received " + types + " but Twoslash only accepts: " + Object.keys(map) + " ", ""); | ||
} | ||
@@ -140,6 +219,2 @@ function getIdentifierTextSpans(ts, sourceFile) { | ||
} | ||
function stringAroundIndex(string, index) { | ||
var arr = [string[index - 3], string[index - 2], string[index - 1], ">", string[index], "<", string[index + 1], string[index + 2], string[index + 3]]; | ||
return arr.filter(Boolean).join(""); | ||
} | ||
/** Came from https://ourcodeworld.com/articles/read/223/how-to-retrieve-the-closest-word-in-a-string-with-a-given-index-in-javascript */ | ||
@@ -170,21 +245,50 @@ | ||
/** To ensure that errors are matched up right */ | ||
function validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode) { | ||
function validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode, vfsRoot) { | ||
var inErrsButNotFoundInTheHeader = relevantErrors.filter(function (e) { | ||
return !handbookOptions.errors.includes(e.code); | ||
}); | ||
var errorsFound = inErrsButNotFoundInTheHeader.map(function (e) { | ||
var errorsFound = Array.from(new Set(inErrsButNotFoundInTheHeader.map(function (e) { | ||
return e.code; | ||
}).join(' '); | ||
}))).join(" "); | ||
if (inErrsButNotFoundInTheHeader.length) { | ||
var codeToAdd = "// @errors: " + relevantErrors.map(function (e) { | ||
var errorsToShow = new Set(relevantErrors.map(function (e) { | ||
return e.code; | ||
}).join(' '); | ||
var postfix = handbookOptions.errors.length ? " - the annotation specified " + handbookOptions.errors : '\n\nExpected:\n' + codeToAdd; | ||
var afterMessage = inErrsButNotFoundInTheHeader.map(function (e) { | ||
var msg = typeof e.messageText === 'string' ? e.messageText : e.messageText.messageText; | ||
return "[" + e.code + "] - " + msg; | ||
}).join('\n '); | ||
var codeOutput = "\n\n## Code\n\n'''" + extension + "\n" + originalCode + "\n'''"; | ||
throw new Error("Errors were thrown in the sample, but not included in an errors tag: " + errorsFound + postfix + "\n\n " + afterMessage + codeOutput); | ||
})); | ||
var codeToAdd = "// @errors: " + Array.from(errorsToShow).join(" "); | ||
var missing = handbookOptions.errors.length ? "\nThe existing annotation specified " + handbookOptions.errors.join(" ") : "\nExpected: " + codeToAdd; // These get filled by below | ||
var filesToErrors = {}; | ||
var noFiles = []; | ||
inErrsButNotFoundInTheHeader.forEach(function (d) { | ||
var _d$file; | ||
var fileRef = ((_d$file = d.file) == null ? void 0 : _d$file.fileName) && d.file.fileName.replace(vfsRoot, ""); | ||
if (!fileRef) noFiles.push(d);else { | ||
var existing = filesToErrors[fileRef]; | ||
if (existing) existing.push(d);else filesToErrors[fileRef] = [d]; | ||
} | ||
}); | ||
var showDiagnostics = function showDiagnostics(title, diags) { | ||
return title + "\n " + diags.map(function (e) { | ||
var msg = typeof e.messageText === "string" ? e.messageText : e.messageText.messageText; | ||
return "[" + e.code + "] " + e.start + " - " + msg; | ||
}).join("\n "); | ||
}; | ||
var innerDiags = []; | ||
if (noFiles.length) { | ||
innerDiags.push(showDiagnostics("Ambient Errors", noFiles)); | ||
} | ||
Object.keys(filesToErrors).forEach(function (filepath) { | ||
innerDiags.push(showDiagnostics(filepath, filesToErrors[filepath])); | ||
}); | ||
var allMessages = innerDiags.join("\n\n"); | ||
var newErr = new TwoslashError("Errors were thrown in the sample, but not included in an errors tag", "These errors were not marked as being expected: " + errorsFound + ". " + missing, "Compiler Errors:\n\n" + allMessages); | ||
newErr.code = "## Code\n\n'''" + extension + "\n" + originalCode + "\n'''"; | ||
throw newErr; | ||
} | ||
@@ -195,8 +299,8 @@ } | ||
function validateInput(code) { | ||
if (code.includes('// @errors ')) { | ||
throw new Error("You have '@errors ' - you're missing the colon after errors"); | ||
if (code.includes("// @errors ")) { | ||
throw new TwoslashError("You have '// @errors ' (with a space)", "You want '// @errors: ' (with a colon)", "This is a pretty common typo"); | ||
} | ||
if (code.includes('// @filename ')) { | ||
throw new Error("You have '@filename ' - you're missing the colon after filename"); | ||
if (code.includes("// @filename ")) { | ||
throw new TwoslashError("You have '// @filename ' (with a space)", "You want '// @filename: ' (with a colon)", "This is a pretty common typo"); | ||
} | ||
@@ -216,3 +320,33 @@ } | ||
}; | ||
var TwoslashError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(TwoslashError, _Error); | ||
function TwoslashError(title, description, recommendation, code) { | ||
var _this; | ||
var message = "\n## " + title + "\n\n" + description + "\n"; | ||
if (recommendation) { | ||
message += "\n" + recommendation; | ||
} | ||
if (code) { | ||
message += "\n" + code; | ||
} | ||
_this = _Error.call(this, message) || this; | ||
_this.title = void 0; | ||
_this.description = void 0; | ||
_this.recommendation = void 0; | ||
_this.code = void 0; | ||
_this.title = title; | ||
_this.description = description; | ||
_this.recommendation = recommendation; | ||
_this.code = code; | ||
return _this; | ||
} | ||
return TwoslashError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
function filterHighlightLines(codeLines) { | ||
@@ -312,3 +446,3 @@ var highlights = []; | ||
var keys = Array.from(optMap.keys()); | ||
throw new Error("Invalid value " + key + " for " + name + ". Allowed values: " + keys.join(",")); | ||
throw new TwoslashError("Invalid inline compiler value", "Got " + key + " for " + name + " but it is not a supported value by the TS compiler.", "Allowed values: " + keys.join(",")); | ||
} | ||
@@ -368,3 +502,3 @@ | ||
throw new Error("No compiler setting named '" + name + "' exists!"); | ||
throw new TwoslashError("Invalid inline compiler flag", "There isn't a TypeScript compiler flag called '" + name + "'.", "This is likely a typo, you can check all the compiler flags in the TSConfig reference, or check the additional Twoslash flags in the npm page for @typescript/twoslash."); | ||
} | ||
@@ -545,4 +679,4 @@ | ||
var text = "Could not get LSP result: " + stringAroundIndex(env.getSourceFile(filename).text, position); | ||
var docs = undefined; | ||
var text; | ||
var docs; | ||
@@ -556,2 +690,4 @@ if (quickInfo && quickInfo.displayParts) { | ||
}).join("<br/>") : undefined; | ||
} else { | ||
throw new TwoslashError("Invalid QuickInfo query", "The request on line " + q.line + " in " + filename + " for quickinfo via ^? returned no from the compiler.", "This is likely that the x positioning is off."); | ||
} | ||
@@ -572,6 +708,6 @@ | ||
{ | ||
var _quickInfo = ls.getCompletionsAtPosition(filename, position - 1, {}); | ||
var completions = ls.getCompletionsAtPosition(filename, position - 1, {}); | ||
if (!_quickInfo && !handbookOptions.noErrorValidation) { | ||
throw new Error("Twoslash: The ^| query at line " + q.line + " in " + filename + " did not return any completions"); | ||
if (!completions && !handbookOptions.noErrorValidation) { | ||
throw new TwoslashError("Invalid completion query", "The request on line " + q.line + " in " + filename + " for completions via ^| returned no completions from the compiler.", "This is likely that the positioning is off."); | ||
} | ||
@@ -584,3 +720,3 @@ | ||
kind: "completions", | ||
completions: (_quickInfo == null ? void 0 : _quickInfo.entries) || [], | ||
completions: (completions == null ? void 0 : completions.entries) || [], | ||
completionPrefix: lastDot, | ||
@@ -642,4 +778,8 @@ line: q.line - i, | ||
var sourceFile = env.getSourceFile(file); | ||
if (!sourceFile) throw new Error("No sourcefile found for " + file + " in twoslash"); // Get all of the interesting quick info popover | ||
if (!sourceFile) { | ||
throw new TwoslashError("Could not find a TypeScript sourcefile for '" + file + "' in the Twoslash vfs", "It's a little hard to provide useful advice on this error. Maybe you imported something which the compiler doesn't think is a source file?", ""); | ||
} // Get all of the interesting quick info popover | ||
if (!handbookOptions.showEmit) { | ||
@@ -729,3 +869,3 @@ var fileContentStartIndexInModifiedFile = code.indexOf(source) == -1 ? 0 : code.indexOf(source); | ||
if (!handbookOptions.noErrorValidation && relevantErrors.length) { | ||
validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode); | ||
validateCodeForErrors(relevantErrors, handbookOptions, extension, originalCode, fsRoot); | ||
} | ||
@@ -770,3 +910,3 @@ | ||
throw new Error("Cannot find the corresponding **source** file for " + emitFilename + " (looking for: " + emitSourceFilename + " in the vfs) - in " + allFiles); | ||
throw new TwoslashError("Could not find source file to show the emit for", "Cannot find the corresponding **source** file " + emitFilename + " for completions via ^| returned no quickinfo from the compiler.", "Looked for: " + emitSourceFilename + " in the vfs - which contains: " + allFiles); | ||
} // Allow outfile, in which case you need any file. | ||
@@ -787,6 +927,5 @@ | ||
return o.name; | ||
}).join(", "); // prettier-ignore | ||
}).join(", "); | ||
throw new Error("Cannot find the file " + handbookOptions.showEmittedFile + " (looking for: " + (fsRoot + handbookOptions.showEmittedFile) + " in the vfs) - in " + _allFiles); | ||
throw new TwoslashError("Cannot find the output file in the Twoslash VFS", "Looking for " + handbookOptions.showEmittedFile + " in the Twoslash vfs after compiling", "Looked for\" " + (fsRoot + handbookOptions.showEmittedFile) + " in the vfs - which contains " + _allFiles + "."); | ||
} | ||
@@ -885,5 +1024,5 @@ | ||
const twoslash = { twoslasher }; | ||
const twoslash = { TwoslashError, twoslasher }; | ||
//# sourceMappingURL=twoslash.esm.js.map | ||
globals.twoslash = twoslash |
@@ -7,3 +7,3 @@ export declare function escapeHtml(text: string): string; | ||
export declare function cleanMarkdownEscaped(code: string): string; | ||
export declare function typesToExtension(types: string): "js" | "ts" | "tsx" | "jsx" | "json"; | ||
export declare function typesToExtension(types: string): string; | ||
export declare function getIdentifierTextSpans(ts: typeof import("typescript"), sourceFile: import("typescript").SourceFile): { | ||
@@ -10,0 +10,0 @@ span: import("typescript").TextSpan; |
/** To ensure that errors are matched up right */ | ||
export declare function validateCodeForErrors(relevantErrors: import('typescript').Diagnostic[], handbookOptions: { | ||
export declare function validateCodeForErrors(relevantErrors: import("typescript").Diagnostic[], handbookOptions: { | ||
errors: number[]; | ||
}, extension: string, originalCode: string): void; | ||
}, extension: string, originalCode: string, vfsRoot: string): void; | ||
/** Mainly to warn myself, I've lost a good few minutes to this before */ | ||
export declare function validateInput(code: string): void; |
{ | ||
"name": "@typescript/twoslash", | ||
"version": "2.0.2", | ||
"version": "2.1.0", | ||
"license": "MIT", | ||
@@ -5,0 +5,0 @@ "author": "TypeScript team", |
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
335362
2654