@frontmcp/uipack 1.12.0-rc.1 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/adapters/content-renderers.d.ts.map +1 -1
- package/adapters/index.js +15 -4
- package/adapters/markdown.d.ts.map +1 -1
- package/adapters/template-renderer.d.ts.map +1 -1
- package/bridge-runtime/iife-generator.d.ts.map +1 -1
- package/bridge-runtime/index.js +1 -0
- package/component/index.js +1 -0
- package/esm/adapters/index.mjs +15 -4
- package/esm/bridge-runtime/index.mjs +1 -0
- package/esm/component/index.mjs +1 -0
- package/esm/index.mjs +19 -8
- package/esm/package.json +2 -2
- package/esm/resolver/index.mjs +1 -1
- package/esm/shell/index.mjs +2 -1
- package/esm/typings/index.mjs +2 -2
- package/index.js +19 -8
- package/package.json +2 -2
- package/resolver/import-rewriter.d.ts.map +1 -1
- package/resolver/index.js +1 -1
- package/shell/index.js +2 -1
- package/shell/sanitize-css.d.ts.map +1 -1
- package/typings/dts-parser.d.ts.map +1 -1
- package/typings/index.js +2 -2
- package/typings/type-fetcher.d.ts +2 -1
- package/typings/type-fetcher.d.ts.map +1 -1
package/shell/index.js
CHANGED
|
@@ -388,6 +388,7 @@ var ExtAppsAdapter = {
|
|
|
388
388
|
});
|
|
389
389
|
},
|
|
390
390
|
handleMessage: function(context, event) {
|
|
391
|
+
if (event.source !== window.parent) return;
|
|
391
392
|
if (!this.isOriginTrusted(event.origin)) return;
|
|
392
393
|
var data = event.data;
|
|
393
394
|
if (!data || typeof data !== 'object' || data.jsonrpc !== '2.0') return;
|
|
@@ -1239,4 +1240,4 @@ ${sizingStyle}`:dataScript;let bridgeHtml="";if(ctx.includeBridge){const bridgeS
|
|
|
1239
1240
|
note.textContent = 'This widget loads from ' + widgetOrigin + ', which this host does not allow.';
|
|
1240
1241
|
frame.replaceWith(note);
|
|
1241
1242
|
});
|
|
1242
|
-
})();`}function escapeAttribute2(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function escapeText(value){return value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var import_entities=require("entities");var CSS_ESCAPE=/\\(?:([0-9a-fA-F]{1,6})[ \t\n\r\f]?|([^\n\r\f0-9a-fA-F]))/g;var CSS_COMMENT=/\/\*[\s\S]*?(?:\*\/|$)/g;function unescapeCss(text){return text.replace(CSS_ESCAPE,(_match,hex,character)=>{if(hex===void 0)return character??"";const codePoint=parseInt(hex,16);const valid=codePoint>0&&codePoint<=1114111&&(codePoint<55296||codePoint>57343);return valid?String.fromCodePoint(codePoint):"\uFFFD"})}function sanitizeStyleText(css){return removeImports(css.replace(/</g,"\\3c ").replace(/&(?=[#A-Za-z0-9])/g,"\\26 "))}function removeImports(css){const kept=[];let start=0;let index=css.indexOf("@");while(index!==-1){const nameEnd=identEnd(css,index+1);if(unescapeCss(css.slice(index+1,nameEnd)).toLowerCase()==="import"){kept.push(css.slice(start,index)," ");start=statementEnd(css,nameEnd);index=css.indexOf("@",start)}else{index=css.indexOf("@",index+1)}}kept.push(css.slice(start));return kept.join("")}function commentEnd(css,start){const end=css.indexOf("*/",start+2);return end===-1?css.length:end+2}function stringEnd(css,start){const quote=css[start];let index=start+1;while(index<css.length&&css[index]!==quote&&css[index]!=="\n"){index+=css[index]==="\\"?2:1}return Math.min(index+1,css.length)}function isIdentCharacter(character){return character==="-"||/\w/.test(character)||character.charCodeAt(0)>=128}function identEnd(css,start){let index=start;while(index<css.length){if(css[index]==="\\"&&css[index+1]!==void 0&&css[index+1]!=="\n"){index+=2}else if(isIdentCharacter(css[index])){index++}else{break}}return index}function statementEnd(css,start){let depth=0;let index=start;while(index<css.length){const character=css[index];if(character==="/"&&css[index+1]==="*"){index=commentEnd(css,index);continue}if(character==='"'||character==="'"){index=stringEnd(css,index);continue}if(character==="("||character==="["||character==="{")depth++;if(character===")"||character==="]")depth=Math.max(0,depth-1);if(character==="}"){if(depth===0)return index;depth--;if(depth===0)return index+1}if(character===";"&&depth===0)return index+1;index++}return css.length}function sanitizeStyleAttribute(style){const declarations=splitDeclarations(style);const kept=declarations.filter(declaration=>!isFixedPosition(declaration));return kept.length===declarations.length?style:kept.join(";")}function splitDeclarations(style){const declarations=[];let depth=0;let start=0;let index=0;while(index<style.length){const character=style[index];if(character==="/"&&style[index+1]==="*"){index=commentEnd(style,index);continue}if(character==='"'||character==="'"){index=stringEnd(style,index);continue}if(character==="(")depth++;if(character===")")depth=Math.max(0,depth-1);if(character===";"&&depth===0){declarations.push(style.slice(start,index));start=index+1}index++}declarations.push(style.slice(start));return declarations}function isFixedPosition(declaration){const text=declaration.replace(CSS_COMMENT,"");const colon=text.indexOf(":");if(colon===-1)return false;const property=unescapeCss(text.slice(0,colon)).trim().toLowerCase();const value=unescapeCss(text.slice(colon+1)).toLowerCase();return property==="position"&&/fixed|sticky|var\(/.test(value)}var DEFAULT_MAX_MARKUP_LENGTH=2*1024*1024;var POLICY_FLAGS=["allowUnsafeLinks","allowInlineScripts","allowToolCallAttributes","bypassSanitization"];var WHITESPACE=/[\t\n\f\r ]/;var TAG_NAME=/^[A-Za-z][A-Za-z0-9-]*$/;var ATTRIBUTE_NAME_BREAKERS=/[\s"'<>/=]/;var COMMENT_END=/--!?>/g;var RAW_TEXT_CONTENT={script:content=>content,style:sanitizeStyleText,textarea:content=>content.replace(/</g,"<"),title:content=>content.replace(/</g,"<"),xmp:content=>content.replace(/</g,"<"),iframe:()=>"",noembed:()=>"",noframes:()=>"",noscript:()=>""};var RAW_TEXT_END=Object.fromEntries(Object.keys(RAW_TEXT_CONTENT).map(name=>[name,new RegExp(`</${name}(?=[\\t\\n\\f\\r />])`,"gi")]));var DROPPED_TAGS=new Set(["base","meta","object","embed","applet","animate","animatecolor","animatemotion","animatetransform","set"]);var URL_ATTRIBUTES=new Set(["href","xlink:href","src","action","formaction","poster","background","cite","data","codebase","classid","archive","longdesc","lowsrc","dynsrc","manifest","icon","profile"]);var URL_LIST_ATTRIBUTES=new Set(["srcset","imagesrcset","ping"]);var SCRIPT_SOURCE_ATTRIBUTES=new Set(["src","href","xlink:href"]);var TOOL_CALL_ATTRIBUTES=new Set(["data-tool-call","data-tool-args"]);var NAVIGATION_ATTRIBUTES={a:new Set(["href","xlink:href"]),area:new Set(["href","xlink:href"]),form:new Set(["action"]),button:new Set(["formaction"]),input:new Set(["formaction"])};var SAFE_SCHEMES=new Set(["http","https","mailto"]);var RASTER_IMAGE_DATA_URL=/^data:image\/(png|gif|jpeg|webp|avif)[;,]/i;var URL_SCHEME=/^([A-Za-z][A-Za-z0-9+.-]*):/;function sanitizeHtml(markup,policy={}){const problems=describeContentSecurityProblems(policy);if(problems.length>0)throw new TypeError(problems.join(" "));if(policy.bypassSanitization)return markup;const maxLength=policy.maxMarkupLength??DEFAULT_MAX_MARKUP_LENGTH;if(markup.length>maxLength){throw new RangeError(`The markup is ${markup.length} characters, over the ${maxLength} that \`ui.contentSecurity\` sanitizes (\`maxMarkupLength\`), so it is not rendered.`)}const output=[];let index=0;while(index<markup.length){const open=markup.indexOf("<",index);if(open===-1){output.push(markup.slice(index));break}output.push(markup.slice(index,open));const next=markup[open+1]??"";if(next==="!"||next==="?"){index=skipDeclaration(markup,open)}else if(next==="/"){index=writeEndTag(markup,open,output)}else if(isAsciiLetter(next)){index=writeElement(markup,open,output,policy)}else{output.push("<");index=open+1}}return output.join("")}function describeContentSecurityProblems(policy){if(!isPlainObject(policy)){return[`\`ui.contentSecurity\` must be an object of flags, and it is ${describeValue(policy)}.`]}const problems=[];for(const[key,value]of Object.entries(policy)){if(value===void 0)continue;if(POLICY_FLAGS.includes(key)){if(typeof value!=="boolean"){problems.push(`\`ui.contentSecurity.${key}\` must be true or false, and it is ${describeValue(value)}.`)}}else if(key==="maxMarkupLength"){if(!Number.isSafeInteger(value)||value<=0){problems.push(`\`ui.contentSecurity.maxMarkupLength\` must be a positive integer, and it is ${describeValue(value)}.`)}}else{problems.push(`\`ui.contentSecurity\` has no \`${key}\` option; its options are \`${POLICY_FLAGS.join("`, `")}\` and \`maxMarkupLength\`.`)}}return problems}function isPlainObject(value){if(typeof value!=="object"||value===null)return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function describeValue(value){if(value===null||Array.isArray(value))return JSON.stringify(value);return typeof value==="object"||typeof value==="function"?`a ${typeof value}`:`${typeof value} ${JSON.stringify(value)}`}function isAsciiLetter(character){return/^[A-Za-z]$/.test(character)}function asciiLowerCase(text){return text.replace(/[A-Z]/g,letter=>letter.toLowerCase())}function skipDeclaration(markup,open){if(markup.startsWith("<!--",open)){COMMENT_END.lastIndex=open+2;const close2=COMMENT_END.exec(markup);return close2?close2.index+close2[0].length:markup.length}const close=markup.indexOf(">",open);return close===-1?markup.length:close+1}function writeEndTag(markup,open,output){if(!isAsciiLetter(markup[open+2]??"")){return markup.startsWith("</>",open)?open+3:skipDeclaration(markup,open)}const tag=parseTag(markup,open+2);if(!tag)return markup.length;if(TAG_NAME.test(tag.name)&&!DROPPED_TAGS.has(asciiLowerCase(tag.name)))output.push(`</${tag.name}>`);return tag.end}function writeElement(markup,open,output,policy){const tag=parseTag(markup,open+1);if(!tag)return markup.length;const name=asciiLowerCase(tag.name);if(name==="plaintext"){output.push(markup.slice(tag.end).replace(/</g,"<"));return markup.length}const keepContent=RAW_TEXT_CONTENT[name];if(keepContent){const{content,end}=readRawText(markup,tag.end,name);if(name==="script"&&!isAllowedScript(tag,policy))return end;output.push(`<${tag.name}${writeAttributes(name,tag.attributes,policy)}>${keepContent(content)}</${tag.name}>`);return end}if(TAG_NAME.test(tag.name)&&!DROPPED_TAGS.has(name)&&!isCrossOriginStylesheet(name,tag.attributes)){output.push(`<${tag.name}${writeAttributes(name,tag.attributes,policy)}${tag.selfClosing?" /":""}>`)}return tag.end}function isAllowedScript(tag,policy){return policy.allowInlineScripts===true&&!tag.attributes.some(({name})=>SCRIPT_SOURCE_ATTRIBUTES.has(asciiLowerCase(name)))}function isCrossOriginStylesheet(tagName,attributes){if(tagName!=="link")return false;const rel=attributeValue(attributes,"rel");const href=attributeValue(attributes,"href");if(rel===void 0||href===void 0||!/(^|[\t\n\f\r ])stylesheet($|[\t\n\f\r ])/i.test(rel))return false;const url=urlAsParsed(href);return URL_SCHEME.test(url)||/^[\\/]{2}/.test(url)}function attributeValue(attributes,name){const attribute=attributes.find(candidate=>asciiLowerCase(candidate.name)===name);return attribute?.value===void 0?void 0:decodeAttributeValue(attribute.value)}function readRawText(markup,start,name){const endTag=RAW_TEXT_END[name];endTag.lastIndex=start;const match=endTag.exec(markup);if(!match)return{content:markup.slice(start),end:markup.length};const tag=parseTag(markup,match.index+2);return{content:markup.slice(start,match.index),end:tag?tag.end:markup.length}}function parseTag(markup,start){let index=start;while(index<markup.length&&!/[\t\n\f\r />]/.test(markup[index]))index++;const tag={name:markup.slice(start,index),attributes:[],selfClosing:false,end:0};while(index<markup.length){const character=markup[index];if(WHITESPACE.test(character)){index++}else if(character===">"){tag.end=index+1;return tag}else if(character==="/"){index++;if(markup[index]===">"){tag.selfClosing=true;tag.end=index+1;return tag}}else{index=readAttribute(markup,index,tag.attributes)}}return void 0}function readAttribute(markup,start,attributes){let index=start+1;while(index<markup.length&&!/[\t\n\f\r />=]/.test(markup[index]))index++;const attribute={name:markup.slice(start,index),value:void 0};attributes.push(attribute);let afterName=index;while(afterName<markup.length&&WHITESPACE.test(markup[afterName]))afterName++;if(markup[afterName]!=="=")return afterName;index=afterName+1;while(index<markup.length&&WHITESPACE.test(markup[index]))index++;const quote=markup[index];if(quote==='"'||quote==="'"){const close=markup.indexOf(quote,index+1);if(close===-1)return markup.length;attribute.value=markup.slice(index+1,close);return close+1}if(quote===">"){attribute.value="";return index}const valueStart=index;while(index<markup.length&&!/[\t\n\f\r >]/.test(markup[index]))index++;attribute.value=markup.slice(valueStart,index);return index}function decodeAttributeValue(raw){return(0,import_entities.decodeHTMLAttribute)(raw).split("\0").join("\uFFFD")}function escapeAttributeValue(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function writeAttributes(tagName,attributes,policy){const seen=new Set;let written="";for(const attribute of attributes){const name=asciiLowerCase(attribute.name);if(seen.has(name))continue;seen.add(name);if(!isWritableAttributeName(attribute.name)||name==="srcdoc")continue;if(name.startsWith("on")&&!policy.allowInlineScripts)continue;if(TOOL_CALL_ATTRIBUTES.has(name)&&!policy.allowToolCallAttributes)continue;if(attribute.value===void 0){written+=` ${attribute.name}`;continue}const value=decodeAttributeValue(attribute.value);if(!isAllowedValue(tagName,name,value,policy))continue;written+=` ${attribute.name}="${escapeAttributeValue(name==="style"?sanitizeStyleAttribute(value):value)}"`}return written}function isWritableAttributeName(name){if(name.length===0||ATTRIBUTE_NAME_BREAKERS.test(name))return false;return[...name].every(character=>character.charCodeAt(0)>31&&character.charCodeAt(0)!==127)}function isAllowedValue(tagName,attributeName,value,policy){if(URL_ATTRIBUTES.has(attributeName)){return isAllowedUrl(value,{imageData:tagName==="img"&&attributeName==="src",navigation:policy.allowUnsafeLinks===true&&NAVIGATION_ATTRIBUTES[tagName]?.has(attributeName)===true})}if(URL_LIST_ATTRIBUTES.has(attributeName)){const separator=attributeName==="ping"?/\s+/:/,/;return value.split(separator).every(candidate=>isAllowedUrl(candidate.trim().split(/\s+/)[0]??"",{}))}return true}function urlAsParsed(value){const url=value.replace(/[\t\n\r]/g,"");let start=0;while(start<url.length&&(url.charCodeAt(start)<=32||/\s/.test(url[start])))start++;return url.slice(start)}function isAllowedUrl(value,allowed){const url=urlAsParsed(value);const scheme=URL_SCHEME.exec(url)?.[1].toLowerCase();if(scheme===void 0||SAFE_SCHEMES.has(scheme))return true;if(scheme==="data")return allowed.imageData===true&&RASTER_IMAGE_DATA_URL.test(url);return allowed.navigation===true}var DEFAULT_TIMEOUT_MS=1e4;var templateCache=new Map;async function resolveShellTemplate(source,options){if(isInlineShellSource(source)){return resolveInline(source.inline)}if(isUrlShellSource(source)){const cacheKey=`url:${source.url}`;if(!options?.noCache){const cached=templateCache.get(cacheKey);if(cached)return cached}const template=await fetchWithTimeout(source.url,source.timeout??DEFAULT_TIMEOUT_MS);const resolved=buildResolved(template,"url");if(!options?.noCache){templateCache.set(cacheKey,resolved)}return resolved}if(isNpmShellSource(source)){const specifier=source.version?`${source.npm}@${source.version}`:source.npm;const cacheKey=`npm:${specifier}`;if(!options?.noCache){const cached=templateCache.get(cacheKey);if(cached)return cached}const template=await resolveNpmTemplate(source,specifier,options?.resolver);const resolved=buildResolved(template,"npm");if(!options?.noCache){templateCache.set(cacheKey,resolved)}return resolved}throw new Error('Invalid custom shell source: must have "inline", "url", or "npm" property')}function clearShellTemplateCache(){templateCache.clear()}function resolveInline(template){return buildResolved(template,"inline")}function buildResolved(template,sourceType){const validation=validateShellTemplate(template);if(!validation.valid){throw new Error(`Custom shell template is missing required placeholder(s): ${validation.missingRequired.map(n=>`{{${n}}}`).join(", ")}`)}return{template,sourceType,validation}}async function fetchWithTimeout(url,timeoutMs){const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetch(url,{signal:controller.signal});if(!response.ok){throw new Error(`Failed to fetch shell template from ${url}: HTTP ${response.status}`)}return await response.text()}catch(err){if(err instanceof Error&&err.name==="AbortError"){throw new Error(`Shell template fetch timed out after ${timeoutMs}ms: ${url}`)}throw err}finally{clearTimeout(timer)}}async function resolveNpmTemplate(source,specifier,resolver){const cdnUrl=resolveNpmToCdnUrl(specifier,resolver);const moduleText=await fetchWithTimeout(cdnUrl,DEFAULT_TIMEOUT_MS);return extractTemplateFromModule(moduleText,source.exportName)}function resolveNpmToCdnUrl(specifier,resolver){if(resolver){const resolved=resolver.resolve(specifier);if(resolved){return resolved.value}}return`https://esm.sh/${specifier}`}function extractTemplateFromModule(moduleText,exportName){if(exportName&&exportName!=="default"){const namedPattern=new RegExp(`export\\s+(?:const|let|var)\\s+${escapeRegExp(exportName)}\\s*=\\s*\`([\\s\\S]*?)\``);const namedMatch=moduleText.match(namedPattern);if(namedMatch){return namedMatch[1]}throw new Error(`Could not extract named export "${exportName}" from npm shell package. The package must export a template literal string.`)}const defaultPattern=/export\s+default\s+`([\s\S]*?)`/;const defaultMatch=moduleText.match(defaultPattern);if(defaultMatch){return defaultMatch[1]}throw new Error("Could not extract default export from npm shell package. The package must export a template literal string (e.g., export default `<html>...</html>`).")}function escapeRegExp(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}0&&(module.exports={DEFAULT_CDN_DOMAINS,DEFAULT_CSP_DIRECTIVES,DEFAULT_MAX_MARKUP_LENGTH,OPTIONAL_PLACEHOLDERS,REQUIRED_PLACEHOLDERS,RESTRICTIVE_CSP_DIRECTIVES,SHELL_PLACEHOLDERS,SHELL_PLACEHOLDER_NAMES,applyShellTemplate,buildCSPDirectives,buildCSPMetaTag,buildCustomDataInjectionScript,buildDataInjectionScript,buildShell,buildSizingStyleTag,buildUrlWidgetShell,clearShellTemplateCache,createTemplateHelpers,describeContentSecurityProblems,hasSizing,html,isInlineShellSource,isNpmShellSource,isTrustedHtml,isUrlShellSource,resolveShellTemplate,sanitizeCSPDomains,sanitizeHtml,trustedHtml,validateCSPDomain,validateShellTemplate,widgetUrlOrigin});
|
|
1243
|
+
})();`}function escapeAttribute2(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function escapeText(value){return value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var import_entities=require("entities");var CSS_ESCAPE=/\\(?:([0-9a-fA-F]{1,6})(?:\r\n|[ \t\n\r\f])?|([^\n\r\f0-9a-fA-F]))/g;var CSS_ESCAPE_AT=new RegExp(CSS_ESCAPE.source,"y");var CSS_COMMENT=/\/\*[\s\S]*?(?:\*\/|$)/g;function unescapeCss(text){return text.replace(CSS_ESCAPE,(_match,hex,character)=>{if(hex===void 0)return character??"";const codePoint=parseInt(hex,16);const valid=codePoint>0&&codePoint<=1114111&&(codePoint<55296||codePoint>57343);return valid?String.fromCodePoint(codePoint):"\uFFFD"})}function sanitizeStyleText(css){return removeImports(css.replace(/</g,"\\3c ").replace(/&(?=[#A-Za-z0-9])/g,"\\26 "))}function removeImports(css){const kept=[];let start=0;let index=css.indexOf("@");while(index!==-1){const nameEnd=identEnd(css,index+1);if(unescapeCss(css.slice(index+1,nameEnd)).toLowerCase()==="import"){kept.push(css.slice(start,index)," ");start=statementEnd(css,nameEnd);index=css.indexOf("@",start)}else{index=css.indexOf("@",index+1)}}kept.push(css.slice(start));return kept.join("")}function commentEnd(css,start){const end=css.indexOf("*/",start+2);return end===-1?css.length:end+2}function stringEnd(css,start){const quote=css[start];let index=start+1;while(index<css.length&&css[index]!==quote&&css[index]!=="\n"){index+=css[index]==="\\"?2:1}return Math.min(index+1,css.length)}function isIdentCharacter(character){return character==="-"||/\w/.test(character)||character.charCodeAt(0)>=128}function identEnd(css,start){let index=start;while(index<css.length){CSS_ESCAPE_AT.lastIndex=index;if(CSS_ESCAPE_AT.test(css)){index=CSS_ESCAPE_AT.lastIndex}else if(isIdentCharacter(css[index])){index++}else{break}}return index}function statementEnd(css,start){let depth=0;let index=start;while(index<css.length){const character=css[index];if(character==="/"&&css[index+1]==="*"){index=commentEnd(css,index);continue}if(character==='"'||character==="'"){index=stringEnd(css,index);continue}if(character==="("||character==="["||character==="{")depth++;if(character===")"||character==="]")depth=Math.max(0,depth-1);if(character==="}"){if(depth===0)return index;depth--;if(depth===0)return index+1}if(character===";"&&depth===0)return index+1;index++}return css.length}function sanitizeStyleAttribute(style){const declarations=splitDeclarations(style);const kept=declarations.filter(declaration=>!isFixedPosition(declaration));return kept.length===declarations.length?style:kept.join(";")}function splitDeclarations(style){const declarations=[];let depth=0;let start=0;let index=0;while(index<style.length){const character=style[index];if(character==="/"&&style[index+1]==="*"){index=commentEnd(style,index);continue}if(character==='"'||character==="'"){index=stringEnd(style,index);continue}if(character==="(")depth++;if(character===")")depth=Math.max(0,depth-1);if(character===";"&&depth===0){declarations.push(style.slice(start,index));start=index+1}index++}declarations.push(style.slice(start));return declarations}function isFixedPosition(declaration){const text=declaration.replace(CSS_COMMENT,"");const colon=text.indexOf(":");if(colon===-1)return false;const property=unescapeCss(text.slice(0,colon)).trim().toLowerCase();const value=unescapeCss(text.slice(colon+1)).toLowerCase();return property==="position"&&/fixed|sticky|var\(/.test(value)}var DEFAULT_MAX_MARKUP_LENGTH=2*1024*1024;var POLICY_FLAGS=["allowUnsafeLinks","allowInlineScripts","allowToolCallAttributes","bypassSanitization"];var WHITESPACE=/[\t\n\f\r ]/;var TAG_NAME=/^[A-Za-z][A-Za-z0-9-]*$/;var ATTRIBUTE_NAME_BREAKERS=/[\s"'<>/=]/;var COMMENT_END=/--!?>/g;var RAW_TEXT_CONTENT={script:content=>content,style:sanitizeStyleText,textarea:content=>content.replace(/</g,"<"),title:content=>content.replace(/</g,"<"),xmp:content=>content.replace(/</g,"<"),iframe:()=>"",noembed:()=>"",noframes:()=>"",noscript:()=>""};var RAW_TEXT_END=Object.fromEntries(Object.keys(RAW_TEXT_CONTENT).map(name=>[name,new RegExp(`</${name}(?=[\\t\\n\\f\\r />])`,"gi")]));var DROPPED_TAGS=new Set(["base","meta","object","embed","applet","animate","animatecolor","animatemotion","animatetransform","set"]);var URL_ATTRIBUTES=new Set(["href","xlink:href","src","action","formaction","poster","background","cite","data","codebase","classid","archive","longdesc","lowsrc","dynsrc","manifest","icon","profile"]);var URL_LIST_ATTRIBUTES=new Set(["srcset","imagesrcset","ping"]);var SCRIPT_SOURCE_ATTRIBUTES=new Set(["src","href","xlink:href"]);var TOOL_CALL_ATTRIBUTES=new Set(["data-tool-call","data-tool-args"]);var NAVIGATION_ATTRIBUTES={a:new Set(["href","xlink:href"]),area:new Set(["href","xlink:href"]),form:new Set(["action"]),button:new Set(["formaction"]),input:new Set(["formaction"])};var SAFE_SCHEMES=new Set(["http","https","mailto"]);var RASTER_IMAGE_DATA_URL=/^data:image\/(png|gif|jpeg|webp|avif)[;,]/i;var URL_SCHEME=/^([A-Za-z][A-Za-z0-9+.-]*):/;function sanitizeHtml(markup,policy={}){const problems=describeContentSecurityProblems(policy);if(problems.length>0)throw new TypeError(problems.join(" "));if(policy.bypassSanitization)return markup;const maxLength=policy.maxMarkupLength??DEFAULT_MAX_MARKUP_LENGTH;if(markup.length>maxLength){throw new RangeError(`The markup is ${markup.length} characters, over the ${maxLength} that \`ui.contentSecurity\` sanitizes (\`maxMarkupLength\`), so it is not rendered.`)}const output=[];let index=0;while(index<markup.length){const open=markup.indexOf("<",index);if(open===-1){output.push(markup.slice(index));break}output.push(markup.slice(index,open));const next=markup[open+1]??"";if(next==="!"||next==="?"){index=skipDeclaration(markup,open)}else if(next==="/"){index=writeEndTag(markup,open,output)}else if(isAsciiLetter(next)){index=writeElement(markup,open,output,policy)}else{output.push("<");index=open+1}}return output.join("")}function describeContentSecurityProblems(policy){if(!isPlainObject(policy)){return[`\`ui.contentSecurity\` must be an object of flags, and it is ${describeValue(policy)}.`]}const problems=[];for(const[key,value]of Object.entries(policy)){if(value===void 0)continue;if(POLICY_FLAGS.includes(key)){if(typeof value!=="boolean"){problems.push(`\`ui.contentSecurity.${key}\` must be true or false, and it is ${describeValue(value)}.`)}}else if(key==="maxMarkupLength"){if(!Number.isSafeInteger(value)||value<=0){problems.push(`\`ui.contentSecurity.maxMarkupLength\` must be a positive integer, and it is ${describeValue(value)}.`)}}else{problems.push(`\`ui.contentSecurity\` has no \`${key}\` option; its options are \`${POLICY_FLAGS.join("`, `")}\` and \`maxMarkupLength\`.`)}}return problems}function isPlainObject(value){if(typeof value!=="object"||value===null)return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function describeValue(value){if(value===null||Array.isArray(value))return JSON.stringify(value);return typeof value==="object"||typeof value==="function"?`a ${typeof value}`:`${typeof value} ${JSON.stringify(value)}`}function isAsciiLetter(character){return/^[A-Za-z]$/.test(character)}function asciiLowerCase(text){return text.replace(/[A-Z]/g,letter=>letter.toLowerCase())}function skipDeclaration(markup,open){if(markup.startsWith("<!--",open)){COMMENT_END.lastIndex=open+2;const close2=COMMENT_END.exec(markup);return close2?close2.index+close2[0].length:markup.length}const close=markup.indexOf(">",open);return close===-1?markup.length:close+1}function writeEndTag(markup,open,output){if(!isAsciiLetter(markup[open+2]??"")){return markup.startsWith("</>",open)?open+3:skipDeclaration(markup,open)}const tag=parseTag(markup,open+2);if(!tag)return markup.length;if(TAG_NAME.test(tag.name)&&!DROPPED_TAGS.has(asciiLowerCase(tag.name)))output.push(`</${tag.name}>`);return tag.end}function writeElement(markup,open,output,policy){const tag=parseTag(markup,open+1);if(!tag)return markup.length;const name=asciiLowerCase(tag.name);if(name==="plaintext"){output.push(markup.slice(tag.end).replace(/</g,"<"));return markup.length}const keepContent=RAW_TEXT_CONTENT[name];if(keepContent){const{content,end}=readRawText(markup,tag.end,name);if(name==="script"&&!isAllowedScript(tag,policy))return end;output.push(`<${tag.name}${writeAttributes(name,tag.attributes,policy)}>${keepContent(content)}</${tag.name}>`);return end}if(TAG_NAME.test(tag.name)&&!DROPPED_TAGS.has(name)&&!isCrossOriginStylesheet(name,tag.attributes)){output.push(`<${tag.name}${writeAttributes(name,tag.attributes,policy)}${tag.selfClosing?" /":""}>`)}return tag.end}function isAllowedScript(tag,policy){return policy.allowInlineScripts===true&&!tag.attributes.some(({name})=>SCRIPT_SOURCE_ATTRIBUTES.has(asciiLowerCase(name)))}function isCrossOriginStylesheet(tagName,attributes){if(tagName!=="link")return false;const rel=attributeValue(attributes,"rel");const href=attributeValue(attributes,"href");if(rel===void 0||href===void 0||!/(^|[\t\n\f\r ])stylesheet($|[\t\n\f\r ])/i.test(rel))return false;const url=urlAsParsed(href);return URL_SCHEME.test(url)||/^[\\/]{2}/.test(url)}function attributeValue(attributes,name){const attribute=attributes.find(candidate=>asciiLowerCase(candidate.name)===name);return attribute?.value===void 0?void 0:decodeAttributeValue(attribute.value)}function readRawText(markup,start,name){const endTag=RAW_TEXT_END[name];endTag.lastIndex=start;const match=endTag.exec(markup);if(!match)return{content:markup.slice(start),end:markup.length};const tag=parseTag(markup,match.index+2);return{content:markup.slice(start,match.index),end:tag?tag.end:markup.length}}function parseTag(markup,start){let index=start;while(index<markup.length&&!/[\t\n\f\r />]/.test(markup[index]))index++;const tag={name:markup.slice(start,index),attributes:[],selfClosing:false,end:0};while(index<markup.length){const character=markup[index];if(WHITESPACE.test(character)){index++}else if(character===">"){tag.end=index+1;return tag}else if(character==="/"){index++;if(markup[index]===">"){tag.selfClosing=true;tag.end=index+1;return tag}}else{index=readAttribute(markup,index,tag.attributes)}}return void 0}function readAttribute(markup,start,attributes){let index=start+1;while(index<markup.length&&!/[\t\n\f\r />=]/.test(markup[index]))index++;const attribute={name:markup.slice(start,index),value:void 0};attributes.push(attribute);let afterName=index;while(afterName<markup.length&&WHITESPACE.test(markup[afterName]))afterName++;if(markup[afterName]!=="=")return afterName;index=afterName+1;while(index<markup.length&&WHITESPACE.test(markup[index]))index++;const quote=markup[index];if(quote==='"'||quote==="'"){const close=markup.indexOf(quote,index+1);if(close===-1)return markup.length;attribute.value=markup.slice(index+1,close);return close+1}if(quote===">"){attribute.value="";return index}const valueStart=index;while(index<markup.length&&!/[\t\n\f\r >]/.test(markup[index]))index++;attribute.value=markup.slice(valueStart,index);return index}function decodeAttributeValue(raw){return(0,import_entities.decodeHTMLAttribute)(raw).split("\0").join("\uFFFD")}function escapeAttributeValue(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function writeAttributes(tagName,attributes,policy){const seen=new Set;let written="";for(const attribute of attributes){const name=asciiLowerCase(attribute.name);if(seen.has(name))continue;seen.add(name);if(!isWritableAttributeName(attribute.name)||name==="srcdoc")continue;if(name.startsWith("on")&&!policy.allowInlineScripts)continue;if(TOOL_CALL_ATTRIBUTES.has(name)&&!policy.allowToolCallAttributes)continue;if(attribute.value===void 0){written+=` ${attribute.name}`;continue}const value=decodeAttributeValue(attribute.value);if(!isAllowedValue(tagName,name,value,policy))continue;written+=` ${attribute.name}="${escapeAttributeValue(name==="style"?sanitizeStyleAttribute(value):value)}"`}return written}function isWritableAttributeName(name){if(name.length===0||ATTRIBUTE_NAME_BREAKERS.test(name))return false;return[...name].every(character=>character.charCodeAt(0)>31&&character.charCodeAt(0)!==127)}function isAllowedValue(tagName,attributeName,value,policy){if(URL_ATTRIBUTES.has(attributeName)){return isAllowedUrl(value,{imageData:tagName==="img"&&attributeName==="src",navigation:policy.allowUnsafeLinks===true&&NAVIGATION_ATTRIBUTES[tagName]?.has(attributeName)===true})}if(URL_LIST_ATTRIBUTES.has(attributeName)){const separator=attributeName==="ping"?/\s+/:/,/;return value.split(separator).every(candidate=>isAllowedUrl(candidate.trim().split(/\s+/)[0]??"",{}))}return true}function urlAsParsed(value){const url=value.replace(/[\t\n\r]/g,"");let start=0;while(start<url.length&&(url.charCodeAt(start)<=32||/\s/.test(url[start])))start++;return url.slice(start)}function isAllowedUrl(value,allowed){const url=urlAsParsed(value);const scheme=URL_SCHEME.exec(url)?.[1].toLowerCase();if(scheme===void 0||SAFE_SCHEMES.has(scheme))return true;if(scheme==="data")return allowed.imageData===true&&RASTER_IMAGE_DATA_URL.test(url);return allowed.navigation===true}var DEFAULT_TIMEOUT_MS=1e4;var templateCache=new Map;async function resolveShellTemplate(source,options){if(isInlineShellSource(source)){return resolveInline(source.inline)}if(isUrlShellSource(source)){const cacheKey=`url:${source.url}`;if(!options?.noCache){const cached=templateCache.get(cacheKey);if(cached)return cached}const template=await fetchWithTimeout(source.url,source.timeout??DEFAULT_TIMEOUT_MS);const resolved=buildResolved(template,"url");if(!options?.noCache){templateCache.set(cacheKey,resolved)}return resolved}if(isNpmShellSource(source)){const specifier=source.version?`${source.npm}@${source.version}`:source.npm;const cacheKey=`npm:${specifier}`;if(!options?.noCache){const cached=templateCache.get(cacheKey);if(cached)return cached}const template=await resolveNpmTemplate(source,specifier,options?.resolver);const resolved=buildResolved(template,"npm");if(!options?.noCache){templateCache.set(cacheKey,resolved)}return resolved}throw new Error('Invalid custom shell source: must have "inline", "url", or "npm" property')}function clearShellTemplateCache(){templateCache.clear()}function resolveInline(template){return buildResolved(template,"inline")}function buildResolved(template,sourceType){const validation=validateShellTemplate(template);if(!validation.valid){throw new Error(`Custom shell template is missing required placeholder(s): ${validation.missingRequired.map(n=>`{{${n}}}`).join(", ")}`)}return{template,sourceType,validation}}async function fetchWithTimeout(url,timeoutMs){const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetch(url,{signal:controller.signal});if(!response.ok){throw new Error(`Failed to fetch shell template from ${url}: HTTP ${response.status}`)}return await response.text()}catch(err){if(err instanceof Error&&err.name==="AbortError"){throw new Error(`Shell template fetch timed out after ${timeoutMs}ms: ${url}`)}throw err}finally{clearTimeout(timer)}}async function resolveNpmTemplate(source,specifier,resolver){const cdnUrl=resolveNpmToCdnUrl(specifier,resolver);const moduleText=await fetchWithTimeout(cdnUrl,DEFAULT_TIMEOUT_MS);return extractTemplateFromModule(moduleText,source.exportName)}function resolveNpmToCdnUrl(specifier,resolver){if(resolver){const resolved=resolver.resolve(specifier);if(resolved){return resolved.value}}return`https://esm.sh/${specifier}`}function extractTemplateFromModule(moduleText,exportName){if(exportName&&exportName!=="default"){const namedPattern=new RegExp(`export\\s+(?:const|let|var)\\s+${escapeRegExp(exportName)}\\s*=\\s*\`([\\s\\S]*?)\``);const namedMatch=moduleText.match(namedPattern);if(namedMatch){return namedMatch[1]}throw new Error(`Could not extract named export "${exportName}" from npm shell package. The package must export a template literal string.`)}const defaultPattern=/export\s+default\s+`([\s\S]*?)`/;const defaultMatch=moduleText.match(defaultPattern);if(defaultMatch){return defaultMatch[1]}throw new Error("Could not extract default export from npm shell package. The package must export a template literal string (e.g., export default `<html>...</html>`).")}function escapeRegExp(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}0&&(module.exports={DEFAULT_CDN_DOMAINS,DEFAULT_CSP_DIRECTIVES,DEFAULT_MAX_MARKUP_LENGTH,OPTIONAL_PLACEHOLDERS,REQUIRED_PLACEHOLDERS,RESTRICTIVE_CSP_DIRECTIVES,SHELL_PLACEHOLDERS,SHELL_PLACEHOLDER_NAMES,applyShellTemplate,buildCSPDirectives,buildCSPMetaTag,buildCustomDataInjectionScript,buildDataInjectionScript,buildShell,buildSizingStyleTag,buildUrlWidgetShell,clearShellTemplateCache,createTemplateHelpers,describeContentSecurityProblems,hasSizing,html,isInlineShellSource,isNpmShellSource,isTrustedHtml,isUrlShellSource,resolveShellTemplate,sanitizeCSPDomains,sanitizeHtml,trustedHtml,validateCSPDomain,validateShellTemplate,widgetUrlOrigin});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sanitize-css.d.ts","sourceRoot":"","sources":["../../src/shell/sanitize-css.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;
|
|
1
|
+
{"version":3,"file":"sanitize-css.d.ts","sourceRoot":"","sources":["../../src/shell/sanitize-css.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAiBH;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAErD;AAuFD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAI5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dts-parser.d.ts","sourceRoot":"","sources":["../../src/typings/dts-parser.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAa,cAAc,EAAE,MAAM,SAAS,CAAC;AAwCzD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,CA2F/D;AAaD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAQ3D;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAiBjE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAM7E;AAQD;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAmBrE;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"dts-parser.d.ts","sourceRoot":"","sources":["../../src/typings/dts-parser.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAa,cAAc,EAAE,MAAM,SAAS,CAAC;AAwCzD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,CA2F/D;AAaD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAQ3D;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAiBjE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAM7E;AAQD;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAmBrE;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAmDxE"}
|
package/typings/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var typings_exports={};__export(typings_exports,{DEFAULT_ALLOWED_PACKAGES:()=>DEFAULT_ALLOWED_PACKAGES,DEFAULT_CACHE_OPTIONS:()=>DEFAULT_CACHE_OPTIONS,DEFAULT_TYPE_CACHE_TTL:()=>DEFAULT_TYPE_CACHE_TTL,DEFAULT_TYPE_FETCHER_OPTIONS:()=>DEFAULT_TYPE_FETCHER_OPTIONS,MemoryTypeCache:()=>MemoryTypeCache,TYPE_CACHE_PREFIX:()=>TYPE_CACHE_PREFIX,TypeFetcher:()=>TypeFetcher,buildTypeFiles:()=>buildTypeFiles,combineDtsContents:()=>combineDtsContents,createTypeFetcher:()=>createTypeFetcher,dtsImportSchema:()=>dtsImportSchema,dtsImportTypeSchema:()=>dtsImportTypeSchema,dtsParseResultSchema:()=>dtsParseResultSchema,getPackageFromSpecifier:()=>getPackageFromSpecifier,getRelativeImportPath:()=>getRelativeImportPath,getSubpathFromSpecifier:()=>getSubpathFromSpecifier,globalTypeCache:()=>globalTypeCache,isRelativeImport:()=>isRelativeImport,packageResolutionSchema:()=>packageResolutionSchema,parseDtsImports:()=>parseDtsImports,parseImportStatement:()=>parseImportStatement,safeParseBatchRequest:()=>safeParseBatchRequest,safeParseTypeFetcherOptions:()=>safeParseTypeFetcherOptions,typeCacheEntrySchema:()=>typeCacheEntrySchema,typeCacheStatsSchema:()=>typeCacheStatsSchema,typeFetchBatchRequestSchema:()=>typeFetchBatchRequestSchema,typeFetchBatchResultSchema:()=>typeFetchBatchResultSchema,typeFetchErrorCodeSchema:()=>typeFetchErrorCodeSchema,typeFetchErrorSchema:()=>typeFetchErrorSchema,typeFetchResultSchema:()=>typeFetchResultSchema,typeFetcherOptionsSchema:()=>typeFetcherOptionsSchema,typeFileSchema:()=>typeFileSchema,urlToVirtualPath:()=>urlToVirtualPath,validateBatchRequest:()=>validateBatchRequest,validateTypeFetcherOptions:()=>validateTypeFetcherOptions});module.exports=__toCommonJS(typings_exports);var DEFAULT_ALLOWED_PACKAGES=["react","react-dom","react/jsx-runtime","zod","@frontmcp/*"];var DEFAULT_TYPE_FETCHER_OPTIONS={allowedPackages:[...DEFAULT_ALLOWED_PACKAGES],maxDepth:4,timeout:1e4,maxConcurrency:5,cdnBaseUrl:"https://esm.sh"};var TYPE_CACHE_PREFIX="types:";var DEFAULT_TYPE_CACHE_TTL=60*60*1e3;var import_lazy_zod=require("@frontmcp/lazy-zod");var typeFetchErrorCodeSchema=import_lazy_zod.z.enum(["NETWORK_ERROR","TIMEOUT","NO_TYPES_HEADER","INVALID_SPECIFIER","PACKAGE_NOT_FOUND","PARSE_ERROR"]);var typeFileSchema=import_lazy_zod.z.object({path:import_lazy_zod.z.string().min(1),url:import_lazy_zod.z.string(),content:import_lazy_zod.z.string()}).strict();var typeFetchResultSchema=import_lazy_zod.z.object({specifier:import_lazy_zod.z.string().min(1),resolvedPackage:import_lazy_zod.z.string().min(1),subpath:import_lazy_zod.z.string().optional(),version:import_lazy_zod.z.string().min(1),content:import_lazy_zod.z.string(),files:import_lazy_zod.z.array(typeFileSchema),fetchedUrls:import_lazy_zod.z.array(import_lazy_zod.z.string().url()),fetchedAt:import_lazy_zod.z.string().datetime()}).strict();var typeFetchErrorSchema=import_lazy_zod.z.object({specifier:import_lazy_zod.z.string().min(1),code:typeFetchErrorCodeSchema,message:import_lazy_zod.z.string().min(1),url:import_lazy_zod.z.string().url().optional()}).strict();var typeFetchBatchRequestSchema=import_lazy_zod.z.object({imports:import_lazy_zod.z.array(import_lazy_zod.z.string().min(1)).min(1),maxDepth:import_lazy_zod.z.number().int().min(0).max(10).optional(),timeout:import_lazy_zod.z.number().int().min(1e3).max(6e4).optional(),maxConcurrency:import_lazy_zod.z.number().int().min(1).max(20).optional(),skipCache:import_lazy_zod.z.boolean().optional(),versionOverrides:import_lazy_zod.z.record(import_lazy_zod.z.string().min(1),import_lazy_zod.z.string().min(1)).optional()}).strict();var typeFetchBatchResultSchema=import_lazy_zod.z.object({results:import_lazy_zod.z.array(typeFetchResultSchema),errors:import_lazy_zod.z.array(typeFetchErrorSchema),totalTimeMs:import_lazy_zod.z.number().nonnegative(),cacheHits:import_lazy_zod.z.number().int().nonnegative(),networkRequests:import_lazy_zod.z.number().int().nonnegative()}).strict();var typeCacheEntrySchema=import_lazy_zod.z.object({result:typeFetchResultSchema,cachedAt:import_lazy_zod.z.number().int().positive(),size:import_lazy_zod.z.number().int().nonnegative(),accessCount:import_lazy_zod.z.number().int().nonnegative()}).strict();var typeCacheStatsSchema=import_lazy_zod.z.object({entries:import_lazy_zod.z.number().int().nonnegative(),totalSize:import_lazy_zod.z.number().nonnegative(),hits:import_lazy_zod.z.number().int().nonnegative(),misses:import_lazy_zod.z.number().int().nonnegative(),hitRate:import_lazy_zod.z.number().min(0).max(1)}).strict();var dtsImportTypeSchema=import_lazy_zod.z.enum(["import","export","reference","declare-module"]);var dtsImportSchema=import_lazy_zod.z.object({type:dtsImportTypeSchema,specifier:import_lazy_zod.z.string().min(1),statement:import_lazy_zod.z.string(),line:import_lazy_zod.z.number().int().positive()}).strict();var dtsParseResultSchema=import_lazy_zod.z.object({imports:import_lazy_zod.z.array(dtsImportSchema),externalPackages:import_lazy_zod.z.array(import_lazy_zod.z.string().min(1)),relativeImports:import_lazy_zod.z.array(import_lazy_zod.z.string())}).strict();var typeFetcherOptionsSchema=import_lazy_zod.z.object({maxDepth:import_lazy_zod.z.number().int().min(0).max(10).optional(),timeout:import_lazy_zod.z.number().int().min(1e3).max(6e4).optional(),maxConcurrency:import_lazy_zod.z.number().int().min(1).max(20).optional(),cdnBaseUrl:import_lazy_zod.z.string().url().optional()}).strict();var packageResolutionSchema=import_lazy_zod.z.object({packageName:import_lazy_zod.z.string().min(1),subpath:import_lazy_zod.z.string().optional(),version:import_lazy_zod.z.string().min(1),typesUrl:import_lazy_zod.z.string().url()}).strict();function validateBatchRequest(data){return typeFetchBatchRequestSchema.parse(data)}function safeParseBatchRequest(data){return typeFetchBatchRequestSchema.safeParse(data)}function validateTypeFetcherOptions(data){return typeFetcherOptionsSchema.parse(data)}function safeParseTypeFetcherOptions(data){return typeFetcherOptionsSchema.safeParse(data)}var DEFAULT_CACHE_OPTIONS={maxSize:500,defaultTtl:60*60*1e3,trackStats:true};var MemoryTypeCache=class{cache=new Map;maxSize;defaultTtl;trackStats;stats={hits:0,misses:0,evictions:0};constructor(options={}){const opts={...DEFAULT_CACHE_OPTIONS,...options};this.maxSize=opts.maxSize;this.defaultTtl=opts.defaultTtl;this.trackStats=opts.trackStats}async get(key){const internal=this.cache.get(key);if(!internal){if(this.trackStats)this.stats.misses++;return void 0}if(internal.expiresAt>0&&Date.now()>internal.expiresAt){this.cache.delete(key);if(this.trackStats)this.stats.misses++;return void 0}this.cache.delete(key);internal.entry.accessCount++;this.cache.set(key,internal);if(this.trackStats)this.stats.hits++;return internal.entry}async set(key,entry,ttl){if(this.cache.size>=this.maxSize&&!this.cache.has(key)){const oldestKey=this.cache.keys().next().value;if(oldestKey){this.cache.delete(oldestKey);if(this.trackStats)this.stats.evictions++}}const effectiveTtl=ttl??this.defaultTtl;const expiresAt=effectiveTtl>0?Date.now()+effectiveTtl:0;this.cache.set(key,{entry,expiresAt})}async has(key){const internal=this.cache.get(key);if(!internal)return false;if(internal.expiresAt>0&&Date.now()>internal.expiresAt){this.cache.delete(key);return false}return true}async delete(key){return this.cache.delete(key)}async clear(){this.cache.clear();this.stats={hits:0,misses:0,evictions:0}}async getStats(){let totalSize=0;for(const{entry}of this.cache.values()){totalSize+=entry.size}const total=this.stats.hits+this.stats.misses;return{entries:this.cache.size,totalSize,hits:this.stats.hits,misses:this.stats.misses,hitRate:total>0?this.stats.hits/total:0}}get size(){return this.cache.size}get evictions(){return this.stats.evictions}cleanup(){const now=Date.now();let cleaned=0;for(const[key,internal]of this.cache.entries()){if(internal.expiresAt>0&&now>internal.expiresAt){this.cache.delete(key);cleaned++}}return cleaned}};var globalTypeCache=new MemoryTypeCache({maxSize:500,defaultTtl:60*60*1e3});var IMPORT_PATTERN=/^import\s+(?:type\s+)?(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s+from\s+)?['"]([^'"]+)['"]/gm;var EXPORT_FROM_PATTERN=/^export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/gm;var REFERENCE_TYPES_PATTERN=/^\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/gm;var REFERENCE_PATH_PATTERN=/^\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/gm;var DECLARE_MODULE_PATTERN=/^declare\s+module\s+['"]([^'"]+)['"]/gm;function parseDtsImports(content){const imports=[];const externalPackages=new Set;const relativeImports=new Set;const lines=content.split("\n");for(let i=0;i<lines.length;i++){const line=lines[i];const lineNum=i+1;IMPORT_PATTERN.lastIndex=0;let match=IMPORT_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"import",specifier,statement:line.trim(),line:lineNum});categorizeSpecifier(specifier,externalPackages,relativeImports)}EXPORT_FROM_PATTERN.lastIndex=0;match=EXPORT_FROM_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"export",specifier,statement:line.trim(),line:lineNum});categorizeSpecifier(specifier,externalPackages,relativeImports)}REFERENCE_TYPES_PATTERN.lastIndex=0;match=REFERENCE_TYPES_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"reference",specifier,statement:line.trim(),line:lineNum});externalPackages.add(getPackageFromSpecifier(specifier))}REFERENCE_PATH_PATTERN.lastIndex=0;match=REFERENCE_PATH_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"reference",specifier,statement:line.trim(),line:lineNum});relativeImports.add(specifier)}DECLARE_MODULE_PATTERN.lastIndex=0;match=DECLARE_MODULE_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"declare-module",specifier,statement:line.trim(),line:lineNum})}}return{imports,externalPackages:Array.from(externalPackages),relativeImports:Array.from(relativeImports)}}function categorizeSpecifier(specifier,externalPackages,relativeImports){if(isRelativeImport(specifier)){relativeImports.add(specifier)}else{externalPackages.add(getPackageFromSpecifier(specifier))}}function isRelativeImport(specifier){return specifier.startsWith("./")||specifier.startsWith("../")||specifier.startsWith("/")||/^[A-Za-z]:/.test(specifier)}function getPackageFromSpecifier(specifier){if(specifier.startsWith("@")){const parts=specifier.split("/");if(parts.length>=2){return`${parts[0]}/${parts[1]}`}return specifier}const slashIndex=specifier.indexOf("/");if(slashIndex>0){return specifier.substring(0,slashIndex)}return specifier}function getSubpathFromSpecifier(specifier){const packageName=getPackageFromSpecifier(specifier);if(specifier.length>packageName.length+1){return specifier.substring(packageName.length+1)}return void 0}var MAX_IMPORT_STATEMENT_LENGTH=2e3;function parseImportStatement(statement){if(statement.length>MAX_IMPORT_STATEMENT_LENGTH){return null}const namedMatch=/import\s+(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s+from\s+['"]([^'"]+)['"]/.exec(statement);if(namedMatch){return namedMatch[1]}const sideEffectMatch=/import\s+['"]([^'"]+)['"]/.exec(statement);if(sideEffectMatch){return sideEffectMatch[1]}return null}function combineDtsContents(contents){const seenReferences=new Set;const references=[];const declarations=[];for(const[url,content]of contents.entries()){const lines=content.split("\n");let inReferences=true;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("///")){if(!seenReferences.has(trimmed)){seenReferences.add(trimmed);references.push(trimmed)}continue}if(inReferences&&trimmed===""){continue}inReferences=false;if(declarations.length===0||declarations[declarations.length-1]!==""){if(trimmed!==""){if(!declarations.some(d=>d.includes(`// Source: ${url}`))){declarations.push(`
|
|
2
|
-
// Source: ${url}`)}}}declarations.push(line)}}const parts=[];if(references.length>0){parts.push(references.join("\n"));parts.push("")}parts.push(declarations.join("\n").trim());return parts.join("\n")}var Semaphore=class{permits;waiting=[];constructor(permits){this.permits=permits}async acquire(){if(this.permits>0){this.permits--;return}return new Promise(resolve=>{this.waiting.push(resolve)})}release(){if(this.waiting.length>0){const next=this.waiting.shift();next?.()}else{this.permits++}}};var TypeFetcher=class{maxDepth;timeout;maxConcurrency;cdnBaseUrl;fetchFn;cache;allowedPatterns;allowlistEnabled;_initialized=false;constructor(options={},cache){this.maxDepth=options.maxDepth??2;this.timeout=options.timeout??1e4;this.maxConcurrency=options.maxConcurrency??5;this.cdnBaseUrl=options.cdnBaseUrl??"https://esm.sh";this.fetchFn=options.fetch??globalThis.fetch.bind(globalThis);this.cache=cache??globalTypeCache;if(options.allowedPackages===false){this.allowlistEnabled=false;this.allowedPatterns=[]}else{this.allowlistEnabled=true;this.allowedPatterns=[...DEFAULT_ALLOWED_PACKAGES,...options.allowedPackages??[]]}}isPackageAllowed(packageName){if(!this.allowlistEnabled){return true}return this.allowedPatterns.some(pattern=>{if(pattern.includes("*")){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");const regex=new RegExp(`^${escaped}$`);return regex.test(packageName)}return packageName===pattern||packageName.startsWith(pattern+"/")})}async initialize(options){if(this._initialized){const stats2=await this.cache.getStats();return{loaded:[],failed:[],cached:stats2.entries}}const loaded=[];const failed=[];const packagesToLoad=this.allowedPatterns.filter(p=>!p.includes("*"));for(const pkg of packagesToLoad){const result=await this.fetchBatch({imports:[`import * from "${pkg}"`],timeout:options?.timeout??this.timeout});if(result.results.length>0){loaded.push(pkg)}else if(result.errors.length>0){failed.push(pkg)}}this._initialized=true;const stats=await this.cache.getStats();return{loaded,failed,cached:stats.entries}}get initialized(){return this._initialized}get allowedPackagePatterns(){return this.allowedPatterns}async fetchBatch(request){const startTime=Date.now();const results=[];const errors=[];let cacheHits=0;let networkRequests=0;const maxDepth=request.maxDepth??this.maxDepth;const timeout=request.timeout??this.timeout;const maxConcurrency=request.maxConcurrency??this.maxConcurrency;const skipCache=request.skipCache??false;const versionOverrides=request.versionOverrides??{};const semaphore=new Semaphore(maxConcurrency);const promises=request.imports.map(async importStatement=>{await semaphore.acquire();try{const specifier=parseImportStatement(importStatement);if(!specifier){errors.push({specifier:importStatement,code:"INVALID_SPECIFIER",message:`Could not parse import statement: ${importStatement}`});return}const packageName=getPackageFromSpecifier(specifier);if(!this.isPackageAllowed(packageName)){errors.push({specifier,code:"PACKAGE_NOT_ALLOWED",message:`Package "${packageName}" is not in the allowlist`});return}const version=versionOverrides[packageName]??"latest";const cacheKey=`${TYPE_CACHE_PREFIX}${packageName}@${version}`;if(!skipCache){const cached=await this.cache.get(cacheKey);if(cached){cacheHits++;results.push(cached.result);return}}const result=await this.fetchTypesForSpecifier(specifier,{maxDepth,timeout,version});if(result.success){results.push(result.data);networkRequests+=result.fetchCount;const entry={result:result.data,cachedAt:Date.now(),size:result.data.content.length,accessCount:1};await this.cache.set(cacheKey,entry)}else{errors.push(result.error);networkRequests+=result.fetchCount}}finally{semaphore.release()}});await Promise.all(promises);return{results,errors,totalTimeMs:Date.now()-startTime,cacheHits,networkRequests}}async fetchTypesForSpecifier(specifier,options){let fetchCount=0;const fetchedUrls=[];const visitedUrls=new Set;const contents=new Map;try{const resolution=await this.resolvePackage(specifier,options.version,options.timeout);if(!resolution){return{success:false,error:{specifier,code:"PACKAGE_NOT_FOUND",message:`Could not resolve package: ${specifier}`},fetchCount}}fetchCount++;const fetchResult=await this.fetchRecursive(resolution.typesUrl,options.maxDepth,options.timeout,visitedUrls,contents);fetchCount+=fetchResult.fetchCount;fetchedUrls.push(...fetchResult.fetchedUrls);if(!fetchResult.success){return{success:false,error:{specifier,code:fetchResult.errorCode,message:fetchResult.errorMessage??"Unknown error",url:fetchResult.errorUrl},fetchCount}}const files=buildTypeFiles(contents,resolution.packageName,resolution.version,resolution.subpath);const combinedContent=combineDtsContents(contents);const result={specifier,resolvedPackage:resolution.packageName,subpath:resolution.subpath,version:resolution.version,content:combinedContent,files,fetchedUrls,fetchedAt:new Date().toISOString()};return{success:true,data:result,fetchCount}}catch(error){return{success:false,error:{specifier,code:"NETWORK_ERROR",message:error instanceof Error?error.message:String(error)},fetchCount}}}async resolvePackage(specifier,version,timeout){const packageName=getPackageFromSpecifier(specifier);const subpath=getSubpathFromSpecifier(specifier);const versionSuffix=version==="latest"?"":`@${version}`;const baseUrl=`${this.cdnBaseUrl}/${packageName}${versionSuffix}`;const urlsToTry=subpath?[`${baseUrl}/${subpath}`,baseUrl]:[baseUrl];for(const url of urlsToTry){try{const response=await this.fetchWithTimeout(url,timeout,"HEAD");if(response.ok){const typesHeader=response.headers.get("X-TypeScript-Types");if(typesHeader){const typesUrl=typesHeader.startsWith("/")?`${this.cdnBaseUrl}${typesHeader}`:typesHeader;const versionMatch=/@(\d+\.\d+\.\d+[^/]*)/.exec(typesUrl);const resolvedVersion=versionMatch?versionMatch[1]:version;return{packageName,subpath,version:resolvedVersion,typesUrl}}}}catch{continue}}return null}async fetchRecursive(url,depth,timeout,visited,contents){if(visited.has(url)){return{success:true,fetchCount:0,fetchedUrls:[]}}visited.add(url);let fetchCount=1;const fetchedUrls=[url];try{const response=await this.fetchWithTimeout(url,timeout,"GET");if(!response.ok){return{success:false,fetchCount,fetchedUrls,errorCode:"NETWORK_ERROR",errorMessage:`HTTP ${response.status}: ${response.statusText}`,errorUrl:url}}const content=await response.text();contents.set(url,content);if(depth<=0){return{success:true,fetchCount,fetchedUrls}}const parsed=parseDtsImports(content);for(const pkg of parsed.externalPackages){if(pkg.startsWith("@types/")||isBuiltinModule(pkg)){continue}const resolution=await this.resolvePackage(pkg,"latest",timeout);fetchCount++;if(resolution&&!visited.has(resolution.typesUrl)){const result=await this.fetchRecursive(resolution.typesUrl,depth-1,timeout,visited,contents);fetchCount+=result.fetchCount;fetchedUrls.push(...result.fetchedUrls)}}for(const relativePath of parsed.relativeImports){const resolvedUrl=resolveRelativeUrl(url,relativePath);if(resolvedUrl&&!visited.has(resolvedUrl)){const result=await this.fetchRecursive(resolvedUrl,depth-1,timeout,visited,contents);fetchCount+=result.fetchCount;fetchedUrls.push(...result.fetchedUrls)}}return{success:true,fetchCount,fetchedUrls}}catch(error){const isTimeout=error instanceof Error&&error.message.includes("timeout");return{success:false,fetchCount,fetchedUrls,errorCode:isTimeout?"TIMEOUT":"NETWORK_ERROR",errorMessage:error instanceof Error?error.message:String(error),errorUrl:url}}}async fetchWithTimeout(url,timeout,method){const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),timeout);try{const response=await this.fetchFn(url,{method,signal:controller.signal,headers:{Accept:"application/typescript, text/plain, */*"}});return response}finally{clearTimeout(timeoutId)}}};function isBuiltinModule(name){const builtins=new Set(["assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","fs","http","https","module","net","os","path","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","v8","vm","zlib","node:assert","node:buffer","node:child_process","node:cluster","node:console","node:constants","node:crypto","node:dgram","node:dns","node:domain","node:events","node:fs","node:http","node:https","node:module","node:net","node:os","node:path","node:punycode","node:querystring","node:readline","node:repl","node:stream","node:string_decoder","node:sys","node:timers","node:tls","node:tty","node:url","node:util","node:v8","node:vm","node:zlib"]);return builtins.has(name)}function resolveRelativeUrl(base,relative){try{let path=relative;if(!path.endsWith(".d.ts")&&!path.endsWith(".ts")){path=`${path}.d.ts`}const resolved=new URL(path,base);return resolved.toString()}catch{return null}}function buildTypeFiles(contents,packageName,version,subpath){const files=[];for(const[url,content]of contents.entries()){const virtualPath=urlToVirtualPath(url,packageName,version);files.push({path:virtualPath,url,content})}if(subpath){const aliasPath=`node_modules/${packageName}/${subpath}/index.d.ts`;const aliasExists=files.some(f=>f.path===aliasPath);if(!aliasExists){const aliasContent=`// Auto-generated alias for ${packageName}/${subpath}
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var typings_exports={};__export(typings_exports,{DEFAULT_ALLOWED_PACKAGES:()=>DEFAULT_ALLOWED_PACKAGES,DEFAULT_CACHE_OPTIONS:()=>DEFAULT_CACHE_OPTIONS,DEFAULT_TYPE_CACHE_TTL:()=>DEFAULT_TYPE_CACHE_TTL,DEFAULT_TYPE_FETCHER_OPTIONS:()=>DEFAULT_TYPE_FETCHER_OPTIONS,MemoryTypeCache:()=>MemoryTypeCache,TYPE_CACHE_PREFIX:()=>TYPE_CACHE_PREFIX,TypeFetcher:()=>TypeFetcher,buildTypeFiles:()=>buildTypeFiles,combineDtsContents:()=>combineDtsContents,createTypeFetcher:()=>createTypeFetcher,dtsImportSchema:()=>dtsImportSchema,dtsImportTypeSchema:()=>dtsImportTypeSchema,dtsParseResultSchema:()=>dtsParseResultSchema,getPackageFromSpecifier:()=>getPackageFromSpecifier,getRelativeImportPath:()=>getRelativeImportPath,getSubpathFromSpecifier:()=>getSubpathFromSpecifier,globalTypeCache:()=>globalTypeCache,isRelativeImport:()=>isRelativeImport,packageResolutionSchema:()=>packageResolutionSchema,parseDtsImports:()=>parseDtsImports,parseImportStatement:()=>parseImportStatement,safeParseBatchRequest:()=>safeParseBatchRequest,safeParseTypeFetcherOptions:()=>safeParseTypeFetcherOptions,typeCacheEntrySchema:()=>typeCacheEntrySchema,typeCacheStatsSchema:()=>typeCacheStatsSchema,typeFetchBatchRequestSchema:()=>typeFetchBatchRequestSchema,typeFetchBatchResultSchema:()=>typeFetchBatchResultSchema,typeFetchErrorCodeSchema:()=>typeFetchErrorCodeSchema,typeFetchErrorSchema:()=>typeFetchErrorSchema,typeFetchResultSchema:()=>typeFetchResultSchema,typeFetcherOptionsSchema:()=>typeFetcherOptionsSchema,typeFileSchema:()=>typeFileSchema,urlToVirtualPath:()=>urlToVirtualPath,validateBatchRequest:()=>validateBatchRequest,validateTypeFetcherOptions:()=>validateTypeFetcherOptions});module.exports=__toCommonJS(typings_exports);var DEFAULT_ALLOWED_PACKAGES=["react","react-dom","react/jsx-runtime","zod","@frontmcp/*"];var DEFAULT_TYPE_FETCHER_OPTIONS={allowedPackages:[...DEFAULT_ALLOWED_PACKAGES],maxDepth:4,timeout:1e4,maxConcurrency:5,cdnBaseUrl:"https://esm.sh"};var TYPE_CACHE_PREFIX="types:";var DEFAULT_TYPE_CACHE_TTL=60*60*1e3;var import_lazy_zod=require("@frontmcp/lazy-zod");var typeFetchErrorCodeSchema=import_lazy_zod.z.enum(["NETWORK_ERROR","TIMEOUT","NO_TYPES_HEADER","INVALID_SPECIFIER","PACKAGE_NOT_FOUND","PARSE_ERROR"]);var typeFileSchema=import_lazy_zod.z.object({path:import_lazy_zod.z.string().min(1),url:import_lazy_zod.z.string(),content:import_lazy_zod.z.string()}).strict();var typeFetchResultSchema=import_lazy_zod.z.object({specifier:import_lazy_zod.z.string().min(1),resolvedPackage:import_lazy_zod.z.string().min(1),subpath:import_lazy_zod.z.string().optional(),version:import_lazy_zod.z.string().min(1),content:import_lazy_zod.z.string(),files:import_lazy_zod.z.array(typeFileSchema),fetchedUrls:import_lazy_zod.z.array(import_lazy_zod.z.string().url()),fetchedAt:import_lazy_zod.z.string().datetime()}).strict();var typeFetchErrorSchema=import_lazy_zod.z.object({specifier:import_lazy_zod.z.string().min(1),code:typeFetchErrorCodeSchema,message:import_lazy_zod.z.string().min(1),url:import_lazy_zod.z.string().url().optional()}).strict();var typeFetchBatchRequestSchema=import_lazy_zod.z.object({imports:import_lazy_zod.z.array(import_lazy_zod.z.string().min(1)).min(1),maxDepth:import_lazy_zod.z.number().int().min(0).max(10).optional(),timeout:import_lazy_zod.z.number().int().min(1e3).max(6e4).optional(),maxConcurrency:import_lazy_zod.z.number().int().min(1).max(20).optional(),skipCache:import_lazy_zod.z.boolean().optional(),versionOverrides:import_lazy_zod.z.record(import_lazy_zod.z.string().min(1),import_lazy_zod.z.string().min(1)).optional()}).strict();var typeFetchBatchResultSchema=import_lazy_zod.z.object({results:import_lazy_zod.z.array(typeFetchResultSchema),errors:import_lazy_zod.z.array(typeFetchErrorSchema),totalTimeMs:import_lazy_zod.z.number().nonnegative(),cacheHits:import_lazy_zod.z.number().int().nonnegative(),networkRequests:import_lazy_zod.z.number().int().nonnegative()}).strict();var typeCacheEntrySchema=import_lazy_zod.z.object({result:typeFetchResultSchema,cachedAt:import_lazy_zod.z.number().int().positive(),size:import_lazy_zod.z.number().int().nonnegative(),accessCount:import_lazy_zod.z.number().int().nonnegative()}).strict();var typeCacheStatsSchema=import_lazy_zod.z.object({entries:import_lazy_zod.z.number().int().nonnegative(),totalSize:import_lazy_zod.z.number().nonnegative(),hits:import_lazy_zod.z.number().int().nonnegative(),misses:import_lazy_zod.z.number().int().nonnegative(),hitRate:import_lazy_zod.z.number().min(0).max(1)}).strict();var dtsImportTypeSchema=import_lazy_zod.z.enum(["import","export","reference","declare-module"]);var dtsImportSchema=import_lazy_zod.z.object({type:dtsImportTypeSchema,specifier:import_lazy_zod.z.string().min(1),statement:import_lazy_zod.z.string(),line:import_lazy_zod.z.number().int().positive()}).strict();var dtsParseResultSchema=import_lazy_zod.z.object({imports:import_lazy_zod.z.array(dtsImportSchema),externalPackages:import_lazy_zod.z.array(import_lazy_zod.z.string().min(1)),relativeImports:import_lazy_zod.z.array(import_lazy_zod.z.string())}).strict();var typeFetcherOptionsSchema=import_lazy_zod.z.object({maxDepth:import_lazy_zod.z.number().int().min(0).max(10).optional(),timeout:import_lazy_zod.z.number().int().min(1e3).max(6e4).optional(),maxConcurrency:import_lazy_zod.z.number().int().min(1).max(20).optional(),cdnBaseUrl:import_lazy_zod.z.string().url().optional()}).strict();var packageResolutionSchema=import_lazy_zod.z.object({packageName:import_lazy_zod.z.string().min(1),subpath:import_lazy_zod.z.string().optional(),version:import_lazy_zod.z.string().min(1),typesUrl:import_lazy_zod.z.string().url()}).strict();function validateBatchRequest(data){return typeFetchBatchRequestSchema.parse(data)}function safeParseBatchRequest(data){return typeFetchBatchRequestSchema.safeParse(data)}function validateTypeFetcherOptions(data){return typeFetcherOptionsSchema.parse(data)}function safeParseTypeFetcherOptions(data){return typeFetcherOptionsSchema.safeParse(data)}var DEFAULT_CACHE_OPTIONS={maxSize:500,defaultTtl:60*60*1e3,trackStats:true};var MemoryTypeCache=class{cache=new Map;maxSize;defaultTtl;trackStats;stats={hits:0,misses:0,evictions:0};constructor(options={}){const opts={...DEFAULT_CACHE_OPTIONS,...options};this.maxSize=opts.maxSize;this.defaultTtl=opts.defaultTtl;this.trackStats=opts.trackStats}async get(key){const internal=this.cache.get(key);if(!internal){if(this.trackStats)this.stats.misses++;return void 0}if(internal.expiresAt>0&&Date.now()>internal.expiresAt){this.cache.delete(key);if(this.trackStats)this.stats.misses++;return void 0}this.cache.delete(key);internal.entry.accessCount++;this.cache.set(key,internal);if(this.trackStats)this.stats.hits++;return internal.entry}async set(key,entry,ttl){if(this.cache.size>=this.maxSize&&!this.cache.has(key)){const oldestKey=this.cache.keys().next().value;if(oldestKey){this.cache.delete(oldestKey);if(this.trackStats)this.stats.evictions++}}const effectiveTtl=ttl??this.defaultTtl;const expiresAt=effectiveTtl>0?Date.now()+effectiveTtl:0;this.cache.set(key,{entry,expiresAt})}async has(key){const internal=this.cache.get(key);if(!internal)return false;if(internal.expiresAt>0&&Date.now()>internal.expiresAt){this.cache.delete(key);return false}return true}async delete(key){return this.cache.delete(key)}async clear(){this.cache.clear();this.stats={hits:0,misses:0,evictions:0}}async getStats(){let totalSize=0;for(const{entry}of this.cache.values()){totalSize+=entry.size}const total=this.stats.hits+this.stats.misses;return{entries:this.cache.size,totalSize,hits:this.stats.hits,misses:this.stats.misses,hitRate:total>0?this.stats.hits/total:0}}get size(){return this.cache.size}get evictions(){return this.stats.evictions}cleanup(){const now=Date.now();let cleaned=0;for(const[key,internal]of this.cache.entries()){if(internal.expiresAt>0&&now>internal.expiresAt){this.cache.delete(key);cleaned++}}return cleaned}};var globalTypeCache=new MemoryTypeCache({maxSize:500,defaultTtl:60*60*1e3});var IMPORT_PATTERN=/^import\s+(?:type\s+)?(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s+from\s+)?['"]([^'"]+)['"]/gm;var EXPORT_FROM_PATTERN=/^export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/gm;var REFERENCE_TYPES_PATTERN=/^\/\/\/\s*<reference\s+types\s*=\s*['"]([^'"]+)['"]\s*\/>/gm;var REFERENCE_PATH_PATTERN=/^\/\/\/\s*<reference\s+path\s*=\s*['"]([^'"]+)['"]\s*\/>/gm;var DECLARE_MODULE_PATTERN=/^declare\s+module\s+['"]([^'"]+)['"]/gm;function parseDtsImports(content){const imports=[];const externalPackages=new Set;const relativeImports=new Set;const lines=content.split("\n");for(let i=0;i<lines.length;i++){const line=lines[i];const lineNum=i+1;IMPORT_PATTERN.lastIndex=0;let match=IMPORT_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"import",specifier,statement:line.trim(),line:lineNum});categorizeSpecifier(specifier,externalPackages,relativeImports)}EXPORT_FROM_PATTERN.lastIndex=0;match=EXPORT_FROM_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"export",specifier,statement:line.trim(),line:lineNum});categorizeSpecifier(specifier,externalPackages,relativeImports)}REFERENCE_TYPES_PATTERN.lastIndex=0;match=REFERENCE_TYPES_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"reference",specifier,statement:line.trim(),line:lineNum});externalPackages.add(getPackageFromSpecifier(specifier))}REFERENCE_PATH_PATTERN.lastIndex=0;match=REFERENCE_PATH_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"reference",specifier,statement:line.trim(),line:lineNum});relativeImports.add(specifier)}DECLARE_MODULE_PATTERN.lastIndex=0;match=DECLARE_MODULE_PATTERN.exec(line);if(match){const specifier=match[1];imports.push({type:"declare-module",specifier,statement:line.trim(),line:lineNum})}}return{imports,externalPackages:Array.from(externalPackages),relativeImports:Array.from(relativeImports)}}function categorizeSpecifier(specifier,externalPackages,relativeImports){if(isRelativeImport(specifier)){relativeImports.add(specifier)}else{externalPackages.add(getPackageFromSpecifier(specifier))}}function isRelativeImport(specifier){return specifier.startsWith("./")||specifier.startsWith("../")||specifier.startsWith("/")||/^[A-Za-z]:/.test(specifier)}function getPackageFromSpecifier(specifier){if(specifier.startsWith("@")){const parts=specifier.split("/");if(parts.length>=2){return`${parts[0]}/${parts[1]}`}return specifier}const slashIndex=specifier.indexOf("/");if(slashIndex>0){return specifier.substring(0,slashIndex)}return specifier}function getSubpathFromSpecifier(specifier){const packageName=getPackageFromSpecifier(specifier);if(specifier.length>packageName.length+1){return specifier.substring(packageName.length+1)}return void 0}var MAX_IMPORT_STATEMENT_LENGTH=2e3;function parseImportStatement(statement){if(statement.length>MAX_IMPORT_STATEMENT_LENGTH){return null}const namedMatch=/import\s+(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s+from\s+['"]([^'"]+)['"]/.exec(statement);if(namedMatch){return namedMatch[1]}const sideEffectMatch=/import\s+['"]([^'"]+)['"]/.exec(statement);if(sideEffectMatch){return sideEffectMatch[1]}return null}function combineDtsContents(contents){const seenReferences=new Set;const references=[];const declarations=[];for(const[url,content]of contents.entries()){const lines=content.split("\n");let inReferences=true;let markerAdded=false;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("///")){if(!seenReferences.has(trimmed)){seenReferences.add(trimmed);references.push(trimmed)}continue}if(inReferences&&trimmed===""){continue}inReferences=false;if(declarations.length===0||declarations[declarations.length-1]!==""){if(trimmed!==""&&!markerAdded){declarations.push(`
|
|
2
|
+
// Source: ${url}`);markerAdded=true}}declarations.push(line)}}const parts=[];if(references.length>0){parts.push(references.join("\n"));parts.push("")}parts.push(declarations.join("\n").trim());return parts.join("\n")}var Semaphore=class{permits;waiting=[];constructor(permits){this.permits=permits}async acquire(){if(this.permits>0){this.permits--;return}return new Promise(resolve=>{this.waiting.push(resolve)})}release(){if(this.waiting.length>0){const next=this.waiting.shift();next?.()}else{this.permits++}}};var TypeFetcher=class{maxDepth;timeout;maxConcurrency;cdnBaseUrl;fetchFn;cache;allowedPatterns;allowlistEnabled;_initialized=false;constructor(options={},cache){this.maxDepth=options.maxDepth??2;this.timeout=options.timeout??1e4;this.maxConcurrency=options.maxConcurrency??5;this.cdnBaseUrl=options.cdnBaseUrl??"https://esm.sh";this.fetchFn=options.fetch??globalThis.fetch.bind(globalThis);this.cache=cache??globalTypeCache;if(options.allowedPackages===false){this.allowlistEnabled=false;this.allowedPatterns=[]}else{this.allowlistEnabled=true;this.allowedPatterns=[...DEFAULT_ALLOWED_PACKAGES,...options.allowedPackages??[]]}}isPackageAllowed(packageName){if(!this.allowlistEnabled){return true}return this.allowedPatterns.some(pattern=>{if(pattern.includes("*")){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");const regex=new RegExp(`^${escaped}$`);return regex.test(packageName)}return packageName===pattern||packageName.startsWith(pattern+"/")})}async initialize(options){if(this._initialized){const stats2=await this.cache.getStats();return{loaded:[],failed:[],cached:stats2.entries}}const loaded=[];const failed=[];const packagesToLoad=this.allowedPatterns.filter(p=>!p.includes("*"));for(const pkg of packagesToLoad){const result=await this.fetchBatch({imports:[`import * from "${pkg}"`],timeout:options?.timeout??this.timeout});if(result.results.length>0){loaded.push(pkg)}else if(result.errors.length>0){failed.push(pkg)}}this._initialized=true;const stats=await this.cache.getStats();return{loaded,failed,cached:stats.entries}}get initialized(){return this._initialized}get allowedPackagePatterns(){return this.allowedPatterns}async fetchBatch(request){const startTime=Date.now();const results=[];const errors=[];let cacheHits=0;let networkRequests=0;const maxDepth=request.maxDepth??this.maxDepth;const timeout=request.timeout??this.timeout;const maxConcurrency=request.maxConcurrency??this.maxConcurrency;const skipCache=request.skipCache??false;const versionOverrides=request.versionOverrides??{};const semaphore=new Semaphore(maxConcurrency);const promises=request.imports.map(async importStatement=>{await semaphore.acquire();try{const specifier=parseImportStatement(importStatement);if(!specifier){errors.push({specifier:importStatement,code:"INVALID_SPECIFIER",message:`Could not parse import statement: ${importStatement}`});return}const packageName=getPackageFromSpecifier(specifier);if(!this.isPackageAllowed(packageName)){errors.push({specifier,code:"PACKAGE_NOT_ALLOWED",message:`Package "${packageName}" is not in the allowlist`});return}const version=versionOverrides[packageName]??"latest";if(!isRequestablePackage(packageName,getSubpathFromSpecifier(specifier),version)){errors.push({specifier,code:"INVALID_SPECIFIER",message:`"${specifier}" at version "${version}" is not an npm package name, subpath and version that name the same package in a CDN URL. Use a subpath without "." or ".." segments and a version, range or tag.`});return}const cacheKey=`${TYPE_CACHE_PREFIX}${packageName}@${version}`;if(!skipCache){const cached=await this.cache.get(cacheKey);if(cached){cacheHits++;results.push(cached.result);return}}const result=await this.fetchTypesForSpecifier(specifier,{maxDepth,timeout,version});if(result.success){results.push(result.data);networkRequests+=result.fetchCount;const entry={result:result.data,cachedAt:Date.now(),size:result.data.content.length,accessCount:1};await this.cache.set(cacheKey,entry)}else{errors.push(result.error);networkRequests+=result.fetchCount}}finally{semaphore.release()}});await Promise.all(promises);return{results,errors,totalTimeMs:Date.now()-startTime,cacheHits,networkRequests}}async fetchTypesForSpecifier(specifier,options){let fetchCount=0;const fetchedUrls=[];const visitedUrls=new Set;const contents=new Map;try{const resolution=await this.resolvePackage(specifier,options.version,options.timeout);if(!resolution){return{success:false,error:{specifier,code:"PACKAGE_NOT_FOUND",message:`Could not resolve package: ${specifier}`},fetchCount}}fetchCount++;const fetchResult=await this.fetchRecursive(resolution.typesUrl,options.maxDepth,options.timeout,visitedUrls,contents);fetchCount+=fetchResult.fetchCount;fetchedUrls.push(...fetchResult.fetchedUrls);if(!fetchResult.success){return{success:false,error:{specifier,code:fetchResult.errorCode,message:fetchResult.errorMessage??"Unknown error",url:fetchResult.errorUrl},fetchCount}}const files=buildTypeFiles(contents,resolution.packageName,resolution.version,resolution.subpath);const combinedContent=combineDtsContents(contents);const result={specifier,resolvedPackage:resolution.packageName,subpath:resolution.subpath,version:resolution.version,content:combinedContent,files,fetchedUrls,fetchedAt:new Date().toISOString()};return{success:true,data:result,fetchCount}}catch(error){return{success:false,error:{specifier,code:"NETWORK_ERROR",message:error instanceof Error?error.message:String(error)},fetchCount}}}async resolvePackage(specifier,version,timeout){const packageName=getPackageFromSpecifier(specifier);const subpath=getSubpathFromSpecifier(specifier);if(!isRequestablePackage(packageName,subpath,version))return null;const versionSuffix=version==="latest"?"":`@${version}`;const baseUrl=`${this.cdnBaseUrl}/${packageName}${versionSuffix}`;const urlsToTry=subpath?[`${baseUrl}/${subpath}`,baseUrl]:[baseUrl];for(const url of urlsToTry){try{const response=await this.fetchWithTimeout(url,timeout,"HEAD");if(response.ok){const typesHeader=response.headers.get("X-TypeScript-Types");if(typesHeader){const typesUrl=typesHeader.startsWith("/")?`${this.cdnBaseUrl}${typesHeader}`:typesHeader;const versionMatch=/@(\d+\.\d+\.\d+[^/]*)/.exec(typesUrl);const resolvedVersion=versionMatch?versionMatch[1]:version;return{packageName,subpath,version:resolvedVersion,typesUrl}}}}catch{continue}}return null}async fetchRecursive(url,depth,timeout,visited,contents){if(visited.has(url)){return{success:true,fetchCount:0,fetchedUrls:[]}}visited.add(url);let fetchCount=1;const fetchedUrls=[url];try{const response=await this.fetchWithTimeout(url,timeout,"GET");if(!response.ok){return{success:false,fetchCount,fetchedUrls,errorCode:"NETWORK_ERROR",errorMessage:`HTTP ${response.status}: ${response.statusText}`,errorUrl:url}}const content=await response.text();contents.set(url,content);if(depth<=0){return{success:true,fetchCount,fetchedUrls}}const parsed=parseDtsImports(content);for(const pkg of parsed.externalPackages){if(pkg.startsWith("@types/")||isBuiltinModule(pkg)){continue}const resolution=await this.resolvePackage(pkg,"latest",timeout);fetchCount++;if(resolution&&!visited.has(resolution.typesUrl)){const result=await this.fetchRecursive(resolution.typesUrl,depth-1,timeout,visited,contents);fetchCount+=result.fetchCount;fetchedUrls.push(...result.fetchedUrls)}}for(const relativePath of parsed.relativeImports){const resolvedUrl=resolveRelativeUrl(url,relativePath);if(resolvedUrl&&!visited.has(resolvedUrl)){const result=await this.fetchRecursive(resolvedUrl,depth-1,timeout,visited,contents);fetchCount+=result.fetchCount;fetchedUrls.push(...result.fetchedUrls)}}return{success:true,fetchCount,fetchedUrls}}catch(error){const isTimeout=error instanceof Error&&error.message.includes("timeout");return{success:false,fetchCount,fetchedUrls,errorCode:isTimeout?"TIMEOUT":"NETWORK_ERROR",errorMessage:error instanceof Error?error.message:String(error),errorUrl:url}}}async fetchWithTimeout(url,timeout,method){const cdnOrigin=new URL(this.cdnBaseUrl).origin;assertSameOrigin(url,cdnOrigin);const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),timeout);try{const response=await this.fetchFn(url,{method,signal:controller.signal,headers:{Accept:"application/typescript, text/plain, */*"}});if(response.url)assertSameOrigin(response.url,cdnOrigin);return response}finally{clearTimeout(timeoutId)}}};function isBuiltinModule(name){const builtins=new Set(["assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","fs","http","https","module","net","os","path","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","v8","vm","zlib","node:assert","node:buffer","node:child_process","node:cluster","node:console","node:constants","node:crypto","node:dgram","node:dns","node:domain","node:events","node:fs","node:http","node:https","node:module","node:net","node:os","node:path","node:punycode","node:querystring","node:readline","node:repl","node:stream","node:string_decoder","node:sys","node:timers","node:tls","node:tty","node:url","node:util","node:v8","node:vm","node:zlib"]);return builtins.has(name)}var PACKAGE_NAME=/^(?:@[a-z0-9-][\w.-]*\/)?[a-z0-9-][\w.-]*$/i;var SUBPATH_SEGMENT=/^[\w-][\w.-]*$/;var VERSION=/^[\w.^~*<>=+-]+$/;function isRequestablePackage(packageName,subpath,version){return PACKAGE_NAME.test(packageName)&&(subpath===void 0||subpath.split("/").every(segment=>SUBPATH_SEGMENT.test(segment)))&&VERSION.test(version)}function assertSameOrigin(url,origin){if(new URL(url).origin!==origin){throw new Error(`${url} is outside ${origin}, the origin of cdnBaseUrl, so it is not fetched.`)}}function resolveRelativeUrl(base,relative){try{let path=relative;if(!path.endsWith(".d.ts")&&!path.endsWith(".ts")){path=`${path}.d.ts`}const resolved=new URL(path,base);return resolved.toString()}catch{return null}}function buildTypeFiles(contents,packageName,version,subpath){const files=[];for(const[url,content]of contents.entries()){const virtualPath=urlToVirtualPath(url,packageName,version);files.push({path:virtualPath,url,content})}if(subpath){const aliasPath=`node_modules/${packageName}/${subpath}/index.d.ts`;const aliasExists=files.some(f=>f.path===aliasPath);if(!aliasExists){const aliasContent=`// Auto-generated alias for ${packageName}/${subpath}
|
|
3
3
|
export * from '${getRelativeImportPath(subpath)}';
|
|
4
4
|
`;files.push({path:aliasPath,url:"",content:aliasContent})}}return files}function getRelativeImportPath(subpath){const depth=subpath.split("/").length;const prefix="../".repeat(depth);return`${prefix}index`}function urlToVirtualPath(url,packageName,version){try{const urlObj=new URL(url);const pathname=urlObj.pathname;const cleanPath=pathname.replace(/^\/v\d+\//,"/");const versionedPackage=`${packageName}@${version}`;const packageIndex=cleanPath.indexOf(versionedPackage);if(packageIndex!==-1){const afterPackageVersion=cleanPath.substring(packageIndex+versionedPackage.length);const relativePath=afterPackageVersion.startsWith("/")?afterPackageVersion.substring(1):afterPackageVersion;return`node_modules/${packageName}/${relativePath||"index.d.ts"}`}const packagePattern=new RegExp(`/${escapeRegExp(packageName)}@[^/]+(/.*)?$`);const match=pathname.match(packagePattern);if(match){const filePath=match[1]?match[1].substring(1):"index.d.ts";return`node_modules/${packageName}/${filePath}`}return`node_modules/${packageName}/${pathname.split("/").pop()||"index.d.ts"}`}catch{return`node_modules/${packageName}/index.d.ts`}}function escapeRegExp(string){return string.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function createTypeFetcher(options,cache){return new TypeFetcher(options,cache)}0&&(module.exports={DEFAULT_ALLOWED_PACKAGES,DEFAULT_CACHE_OPTIONS,DEFAULT_TYPE_CACHE_TTL,DEFAULT_TYPE_FETCHER_OPTIONS,MemoryTypeCache,TYPE_CACHE_PREFIX,TypeFetcher,buildTypeFiles,combineDtsContents,createTypeFetcher,dtsImportSchema,dtsImportTypeSchema,dtsParseResultSchema,getPackageFromSpecifier,getRelativeImportPath,getSubpathFromSpecifier,globalTypeCache,isRelativeImport,packageResolutionSchema,parseDtsImports,parseImportStatement,safeParseBatchRequest,safeParseTypeFetcherOptions,typeCacheEntrySchema,typeCacheStatsSchema,typeFetchBatchRequestSchema,typeFetchBatchResultSchema,typeFetchErrorCodeSchema,typeFetchErrorSchema,typeFetchResultSchema,typeFetcherOptionsSchema,typeFileSchema,urlToVirtualPath,validateBatchRequest,validateTypeFetcherOptions});
|
|
@@ -98,7 +98,8 @@ export declare class TypeFetcher {
|
|
|
98
98
|
*/
|
|
99
99
|
private fetchRecursive;
|
|
100
100
|
/**
|
|
101
|
-
* Fetch with timeout support
|
|
101
|
+
* Fetch with timeout support, from the origin of `cdnBaseUrl` only: a URL that a declaration file
|
|
102
|
+
* or a redirect points elsewhere is refused.
|
|
102
103
|
*/
|
|
103
104
|
private fetchWithTimeout;
|
|
104
105
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type-fetcher.d.ts","sourceRoot":"","sources":["../../src/typings/type-fetcher.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAmB,KAAK,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAQjE,OAAO,EAKL,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EAIvB,KAAK,QAAQ,EACd,MAAM,SAAS,CAAC;AA0CjB;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;IAClD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAmB;IACzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAW;IAC3C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAU;IAC3C,OAAO,CAAC,YAAY,CAAS;gBAEjB,OAAO,GAAE,kBAAuB,EAAE,KAAK,CAAC,EAAE,gBAAgB;IAkBtE;;;;;;OAMG;IACH,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO;IAkB9C;;;;;;OAMG;IACG,UAAU,CAAC,OAAO,CAAC,EAAE;QACzB,qCAAqC;QACrC,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC;QACV,6CAA6C;QAC7C,MAAM,EAAE,MAAM,EAAE,CAAC;QACjB,mCAAmC;QACnC,MAAM,EAAE,MAAM,EAAE,CAAC;QACjB,sDAAsD;QACtD,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;IAgCF;;OAEG;IACH,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED;;OAEG;IACH,IAAI,sBAAsB,IAAI,SAAS,MAAM,EAAE,CAE9C;IAED;;;;;OAKG;IACG,UAAU,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"type-fetcher.d.ts","sourceRoot":"","sources":["../../src/typings/type-fetcher.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAmB,KAAK,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAQjE,OAAO,EAKL,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EAIvB,KAAK,QAAQ,EACd,MAAM,SAAS,CAAC;AA0CjB;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;IAClD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAmB;IACzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAW;IAC3C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAU;IAC3C,OAAO,CAAC,YAAY,CAAS;gBAEjB,OAAO,GAAE,kBAAuB,EAAE,KAAK,CAAC,EAAE,gBAAgB;IAkBtE;;;;;;OAMG;IACH,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO;IAkB9C;;;;;;OAMG;IACG,UAAU,CAAC,OAAO,CAAC,EAAE;QACzB,qCAAqC;QACrC,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC;QACV,6CAA6C;QAC7C,MAAM,EAAE,MAAM,EAAE,CAAC;QACjB,mCAAmC;QACnC,MAAM,EAAE,MAAM,EAAE,CAAC;QACjB,sDAAsD;QACtD,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;IAgCF;;OAEG;IACH,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED;;OAEG;IACH,IAAI,sBAAsB,IAAI,SAAS,MAAM,EAAE,CAE9C;IAED;;;;;OAKG;IACG,UAAU,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAwG/E;;OAEG;YACW,sBAAsB;IAqFpC;;;OAGG;YACW,cAAc;IA4C5B;;OAEG;YACW,cAAc;IA4F5B;;;OAGG;YACW,gBAAgB;CAoB/B;AA4HD;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAC7B,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,MAAM,GACf,QAAQ,EAAE,CAiCZ;AAED;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAI7D;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAoC1F;AAaD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,CAAC,EAAE,kBAAkB,EAAE,KAAK,CAAC,EAAE,gBAAgB,GAAG,WAAW,CAErG"}
|