svelte-typecheck 0.1.3 → 0.1.5
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/README.md +1 -0
- package/cli.js +2 -2
- package/index.js +1 -1
- package/package.json +1 -1
- package/{shared-x0bdkz02.js → shared-0bqrrt0s.js} +19 -12
- package/shared-hmmvdprg.js +1 -0
- package/shared-zgnhwdjy.js +2 -0
- package/shims/shims.d.ts +33 -5
- package/shared-9x993ww1.js +0 -1
- package/shared-a6ge4681.js +0 -2
package/README.md
CHANGED
|
@@ -132,6 +132,7 @@ What svelte-typecheck does that svelte-check doesn't:
|
|
|
132
132
|
- **A syntax error in a TS or JS file** stops `tsc` and the other CLI checkers from type-checking at all, so only syntax errors are reported until it's fixed; svelte-check's language service reports the type errors in other files too. A component's syntax errors don't do this.
|
|
133
133
|
- **Svelte 3 and 4 with `lang="ts"` and no preprocessors**: svelte-check strips the types with a fallback preprocessor and reports the compiler's warnings; here the compiler can't read the script, so there are none.
|
|
134
134
|
- **`--out-dir` outside the project** can't find its packages from the generated code; the default is inside `node_modules`.
|
|
135
|
+
- **`<svelte:element this={tag}>` whose tag may be any element**, such as a component's generic `Tag extends keyof HTMLElementTagNameMap`: svelte-check reports TypeScript's "union type too complex" and checks none of the element's attributes; here its attributes are checked as an element's. An attribute error on it names the attributes' type with the tag widened: `keyof HTMLElementTagNameMap extends Tag ? string : Tag`.
|
|
135
136
|
|
|
136
137
|
### API
|
|
137
138
|
|
package/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import"./shared-
|
|
2
|
+
import"./shared-zgnhwdjy.js";import{EmitError,typecheck2,watch2,createBaseline2,applyBaseline2}from"./shared-0bqrrt0s.js";import{readFileSync as readFileSync2,writeFileSync}from"node:fs";import{resolve}from"node:path";import{parseArgs}from"node:util";import{readFileSync}from"node:fs";import{relative,sep}from"node:path";var OUTPUT_FORMATS=["human","human-verbose","machine","machine-verbose"];function colors(force){let env=process.env,enabled=force??(env.FORCE_COLOR!==void 0?env.FORCE_COLOR!=="0":env.NO_COLOR===void 0&&Boolean(process.stdout.isTTY)&&env.TERM!=="dumb"),paint=(open,close)=>(text)=>enabled?`\x1B[${open}m${text}\x1B[${close}m`:text;return{red:paint(31,39),yellow:paint(33,39),green:paint(32,39),cyan:paint(36,39),magenta:paint(35,39)}}function lineOf(text,line){return text.split(`
|
|
3
3
|
`)[line-1]??""}function codeFrame(d,c){let text;try{text=readFileSync(d.file,"utf-8")}catch{return""}let endLine=d.endLine??d.line,endColumn=d.endColumn??d.column,first=lineOf(text,d.line),last=lineOf(text,endLine),middle=d.line===endLine?first.slice(0,d.column-1)+c.magenta(first.slice(d.column-1,endColumn-1))+first.slice(endColumn-1):first.slice(0,d.column-1)+c.magenta([first.slice(d.column-1),...text.split(`
|
|
4
4
|
`).slice(d.line,endLine-1),last.slice(0,endColumn-1)].join(`
|
|
5
5
|
`))+last.slice(endColumn-1),before=d.line>1?`${lineOf(text,d.line-1)}
|
|
@@ -70,6 +70,6 @@ svelte-typecheck's own:
|
|
|
70
70
|
|
|
71
71
|
Exits 1 on an error, or a warning with --fail-on-warnings.`;async function main(argv){let values;try{values=parse(argv).values}catch(error){return console.error(`${error.message}
|
|
72
72
|
|
|
73
|
-
${HELP}`),1}if(values.help)return console.log(HELP),0;if(values.version){let{version}=await import("./shared-
|
|
73
|
+
${HELP}`),1}if(values.help)return console.log(HELP),0;if(values.version){let{version}=await import("./shared-hmmvdprg.js");return console.log(version),0}let format=formatOf(values.output),out=writer(format,(text)=>process.stdout.write(text),colors(colorFlag(values.color,values["no-color"]))),options={workspace:values.workspace??".",tsconfig:values["no-tsconfig"]?!1:values.tsconfig,ignore:values.ignore?.split(","),config:values.config,checker:values.checker??(values.tsgo||values["tsgo-experimental-api"]?"tsgo":void 0),components:values.components,outDir:values["out-dir"],declarations:!values["no-declarations"],svelte:values.svelte,diagnosticSources:values["diagnostic-sources"]?.split(",").map((source)=>source.trim()),compilerWarnings:parseCompilerWarnings(values["compiler-warnings"]),incremental:!values["no-incremental"]};if(values.changed||values.since)try{options.only=changedFiles(process.cwd(),values.since)}catch(error){return out.failure(error),1}let baselinePath=values.baseline&&resolve(values.baseline);if(values["update-baseline"]&&!baselinePath)return out.failure(Error("--update-baseline needs --baseline <file>")),1;let strict=values["strict-baseline"];if(strict&&!baselinePath)return out.failure(Error("--strict-baseline needs --baseline <file>")),1;for(let flag of["update-baseline","strict-baseline"])if(values[flag]&&(values.changed||values.since))return out.failure(Error(`--${flag} takes every file's: drop --changed`)),1;let baseline;if(baselinePath&&!values["update-baseline"])try{baseline=JSON.parse(readFileSync2(baselinePath,"utf-8"))}catch{return out.failure(Error(`No baseline at ${baselinePath}: write one with --update-baseline`)),1}let errorsOnly=values.threshold==="error",failOnWarnings=values["fail-on-warnings"],report=(result,watching)=>{if(result instanceof Error)return out.failure(result instanceof EmitError?Error(`${result.message}
|
|
74
74
|
This is a svelte-typecheck bug; please report it.`):result),1;if(baselinePath&&values["update-baseline"]){let written=createBaseline2(result.diagnostics,result.workspace);return writeFileSync(baselinePath,`${JSON.stringify(written,null,2)}
|
|
75
75
|
`),out.note(`Wrote ${result.diagnostics.length} diagnostics to ${baselinePath}`),0}let known=baseline?applyBaseline2(result.diagnostics,baseline,result.workspace):void 0,shown=known?known.diagnostics:result.diagnostics;out.start(result.workspace,watching&&!values.preserveWatchOutput);for(let d of shown)if(!errorsOnly||d.severity==="error")out.diagnostic(d,result.workspace);for(let f of result.failed)out.failure(Error(`${f.file}: failed to parse: ${f.message}`));let summary=summarize(shown,result.components);if(known?.known)out.note(`${known.known} more in the baseline, not shown`);if(known?.fixed)out.note(`${known.fixed} in the baseline are fixed: --update-baseline drops them`);if(result.skipped>0)out.note(`${result.skipped} more in files the changes don't reach, not shown`);return out.completion(summary,watching),summary.errors>0||result.failed.length>0||failOnWarnings&&summary.warnings>0||strict&&(known?.fixed??0)>0?1:0};if(values.watch)return watch2(options,(result)=>report(result,!0)),new Promise(()=>{});try{return report(await typecheck2(options),!1)}catch(error){return report(error,!1)}}function formatOf(output){if(output&&OUTPUT_FORMATS.includes(output))return output;return process.env.CLAUDECODE==="1"?"machine":"human-verbose"}function parse(argv){return parseArgs({args:argv,options:{workspace:{type:"string"},output:{type:"string"},tsconfig:{type:"string"},"no-tsconfig":{type:"boolean",default:!1},ignore:{type:"string"},config:{type:"string"},"diagnostic-sources":{type:"string"},threshold:{type:"string"},"compiler-warnings":{type:"string"},"fail-on-warnings":{type:"boolean",default:!1},color:{type:"boolean",default:!1},"no-color":{type:"boolean",default:!1},tsgo:{type:"boolean",default:!1},incremental:{type:"boolean",default:!1},"no-incremental":{type:"boolean",default:!1},watch:{type:"boolean",default:!1},preserveWatchOutput:{type:"boolean",default:!1},"tsgo-experimental-api":{type:"boolean",default:!1},checker:{type:"string"},components:{type:"string",multiple:!0},"out-dir":{type:"string"},"no-declarations":{type:"boolean",default:!1},svelte:{type:"string"},changed:{type:"boolean",default:!1},baseline:{type:"string"},"update-baseline":{type:"boolean",default:!1},"strict-baseline":{type:"boolean",default:!1},since:{type:"string"},help:{type:"boolean",short:"h",default:!1},version:{type:"boolean",short:"v",default:!1}}})}function parseCompilerWarnings(list){if(!list)return;let levels={};for(let entry of list.split(",")){let[code,level]=entry.trim().split(":");if(code&&(level==="ignore"||level==="error"))levels[code]=level}return levels}function colorFlag(on,off){if(on)return!0;if(off)return!1;return}process.exitCode=await main(process.argv.slice(2));
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./shared-
|
|
1
|
+
import"./shared-zgnhwdjy.js";import{compilerDiagnostics2,typecheck2,watch2,createBaseline2,applyBaseline2}from"./shared-0bqrrt0s.js";export{applyBaseline2 as applyBaseline,compilerDiagnostics2 as compilerDiagnostics,createBaseline2 as createBaseline,typecheck2 as typecheck,watch2 as watch};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "svelte-typecheck",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "A drop-in svelte-check replacement that checks with tsc, tsgo, tsrs or bun check. Up to 11x faster, zero dependencies.",
|
|
6
6
|
"author": "Eric Liu (https://github.com/metonym)",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{version2}from"./shared-a6ge4681.js";import{spawn}from"node:child_process";import{createHash}from"node:crypto";import{existsSync as existsSync4,readFileSync as readFileSync4,statSync}from"node:fs";import{mkdir,readFile,rm,writeFile}from"node:fs/promises";import{createRequire as createRequire4}from"node:module";import{basename as basename3,dirname as dirname5,join as join6,relative as relative2,resolve as resolve3,sep as sep2}from"node:path";import{fileURLToPath}from"node:url";var REGEX_LANG_ATTRIBUTE=/<!--[\s\S]*?-->|<script\s+(?:[^>]*|(?:[^=>'"/]+=(?:"[^"]*"|'[^']*'|[^>\s]+)\s+)*)lang=(["'])?([^"' >]+)\1[^>]*>/y;function withoutByteOrderMark(source){return source.charCodeAt(0)===65279?source.slice(1):source}function isDigit(code){return code>=48&&code<=57}function isWhitespace(code){if(code===32||code<=13&&code>=9)return!0;if(code<160)return!1;return code===160||code===5760||code>=8192&&code<=8202||code===8232||code===8233||code===8239||code===8287||code===12288||code===65279}function skipWhitespace(source,from){let index=from;while(index<source.length&&isWhitespace(source.charCodeAt(index)))index++;return index}function isTypeScript(source){let index=source.indexOf("<");while(index!==-1){let next=source.charCodeAt(index+1);if(next===33||next===115){REGEX_LANG_ATTRIBUTE.lastIndex=index;let match=REGEX_LANG_ATTRIBUTE.exec(source);if(match){if(next===115)return match[2]==="ts";index=source.indexOf("<",REGEX_LANG_ATTRIBUTE.lastIndex);continue}}index=source.indexOf("<",index+1)}return!1}function closingScriptTag(source,from){let close=source.indexOf("</script",from);while(close!==-1){if(source.charCodeAt(skipWhitespace(source,close+8))===GT)return close;close=source.indexOf("</script",close+8)}return-1}function closingScriptTagEnd(source,close){return skipWhitespace(source,close+8)+1}var VOID_ELEMENTS=new Set("area base br col command embed hr img input keygen link meta param source track wbr".split(" "));function isVoid(name){return VOID_ELEMENTS.has(name)||name.charCodeAt(0)===33&&name.toLowerCase()==="!doctype"}function styleContentEnd(source,from){let index=from;while(index<source.length){let code=source.charCodeAt(index);if(code===47&&source.charCodeAt(index+1)===42){let end=source.indexOf("*/",index+2);index=end===-1?source.length:end+2}else if(code===34||code===39){index++;while(index<source.length){let next=source.charCodeAt(index);if(next===code||next===10)break;index+=next===92?2:1}index++}else if(code===60&&source.startsWith("</style",index))break;else index++}return Math.min(index,source.length)}var DOUBLE_QUOTE=34,SINGLE_QUOTE=39,SLASH=47,EQUALS=61,GT=62,isQuote=(code)=>code===DOUBLE_QUOTE||code===SINGLE_QUOTE;function nameEnd(source,from,isAttribute){let i=from;for(;i<source.length;i++){let code=source.charCodeAt(i);if(isWhitespace(code)||code===SLASH||code===GT)break;if(isAttribute&&(isQuote(code)||code===EQUALS))break}return i}function endsUnquotedValue(source,i){let code=source.charCodeAt(i);return isWhitespace(code)||isQuote(code)||code===EQUALS||code===60||code===GT||code===96||code===SLASH&&source.charCodeAt(i+1)===GT}var STATEMENT_START=0,OPERATOR=1,BLOCK_OPENER=2,VALUE=3,PAREN=0,HEAD_PAREN=1,BLOCK=2,OBJECT=3,TEMPLATE=4,HEAD=4,IMPORT=5,EXPORT=6,REQUIRE=7,KEYWORDS={await:OPERATOR,case:OPERATOR,default:OPERATOR,delete:OPERATOR,extends:OPERATOR,in:OPERATOR,instanceof:OPERATOR,new:OPERATOR,of:OPERATOR,return:OPERATOR,throw:OPERATOR,typeof:OPERATOR,void:OPERATOR,yield:OPERATOR,do:BLOCK_OPENER,else:BLOCK_OPENER,finally:BLOCK_OPENER,try:BLOCK_OPENER,for:HEAD,if:HEAD,while:HEAD,with:HEAD,import:IMPORT,export:EXPORT,require:REQUIRE},LONGEST_KEYWORD=10,KEYWORDS_BY_KEY=Array(keywordKey(128,0)).fill(null);for(let entry of Object.entries(KEYWORDS)){let key=keywordKey(entry[0].charCodeAt(0),entry[0].length),entries=KEYWORDS_BY_KEY[key]??[];entries.push(entry),KEYWORDS_BY_KEY[key]=entries}function keywordKey(first,length){return first*(LONGEST_KEYWORD+1)+length}function wordKind(source,start,end){let first=source.charCodeAt(start);if(first>=128||end-start>LONGEST_KEYWORD)return VALUE;let key=keywordKey(first,end-start),entries=KEYWORDS_BY_KEY[key];if(entries===null)return VALUE;for(let i=0;i<entries.length;i++)if(source.startsWith(entries[i][0],start))return entries[i][1];return VALUE}var ASCII_WORD=new Uint8Array(128);for(let range of["az","AZ","09","__","$$","\\\\"])for(let code=range.charCodeAt(0);code<=range.charCodeAt(1);code++)ASCII_WORD[code]=1;function isWordCode(code){return code>=128?!isWhitespace(code):ASCII_WORD[code]===1}function scan(source,localExports,parseAt,exportLists=!1){tokenize(source,lastStatementKeyword(source,localExports,exportLists),localExports,exportLists,parseAt,void 0,void 0)}function tokenize(source,last,localExports,exportLists,parseAt,literal,call){let stack=[],pos=source.startsWith("#!")?lineEnd(source,2):0,prev=STATEMENT_START,afterDot=!1,head=!1,decorators=-1,statementEnd=()=>{if(prev=STATEMENT_START,stack.length===0)decorators=-1};while(pos<=last){let code=source.charCodeAt(pos);if(code===32||code===10||isWhitespace(code)){pos++;continue}if(code===47){let end=commentEnd(source,pos);if(end!==-1){pos=end;continue}}let wasAfterDot=afterDot,wasHead=head;if(afterDot=!1,head=!1,isWordCode(code)||code===35){let start=pos;pos=wordEnd(source,pos+1);let kind=wasAfterDot?VALUE:wordKind(source,start,pos);if(call!==void 0&&(kind===IMPORT||kind===REQUIRE))call(start,prev===STATEMENT_START||prev===VALUE);if(parseAt!==void 0&&stack.length===0&&(kind===EXPORT?localExports||isReexport(source,pos,exportLists):kind===IMPORT&&isImportDeclaration(source,pos)))pos=Math.max(pos,parseAt(decorators!==-1&&kind===EXPORT?decorators:start,start)),statementEnd();else if(kind===EXPORT)prev=BLOCK_OPENER;else if(kind===HEAD)head=!0,prev=VALUE;else prev=kind===OPERATOR||kind===BLOCK_OPENER?kind:VALUE;continue}switch(pos++,code){case 34:case 39:{let start=pos-1;pos=stringEnd(source,pos,code),literal?.(start,pos,!1),prev=VALUE;break}case 96:{let start=pos;pos=templateEnd(source,pos,stack),literal?.(start,quasiEnd(source,pos),!0),prev=source.charCodeAt(pos-1)===123?OPERATOR:VALUE;break}case 47:{let end=prev===VALUE?-1:regexEnd(source,pos);if(end===-1)prev=OPERATOR;else pos=wordCodesEnd(source,end),prev=VALUE;break}case 40:stack.push(wasHead?HEAD_PAREN:PAREN),prev=OPERATOR;break;case 41:prev=stack.pop()===HEAD_PAREN?BLOCK_OPENER:VALUE;break;case 123:stack.push(prev===OPERATOR?OBJECT:BLOCK),prev=STATEMENT_START;break;case 125:{let open=stack.pop();if(open===TEMPLATE){let start=pos;pos=templateEnd(source,pos,stack),literal?.(start,quasiEnd(source,pos),!0),prev=source.charCodeAt(pos-1)===123?OPERATOR:VALUE}else if(open===OBJECT)prev=VALUE;else statementEnd();break}case 59:statementEnd();break;case 44:prev=stack[stack.length-1]===OBJECT?STATEMENT_START:OPERATOR;break;case 93:prev=VALUE;break;case 46:if(isDigit(source.charCodeAt(pos)))pos=wordCodesEnd(source,pos),prev=VALUE;else if(source.startsWith("..",pos))pos+=2,prev=OPERATOR;else afterDot=!0,prev=OPERATOR;break;case 63:if(source.charCodeAt(pos)===46&&!isDigit(source.charCodeAt(pos+1)))pos++,afterDot=!0;prev=OPERATOR;break;case 33:prev=prev===VALUE&&!isWhitespace(source.charCodeAt(pos-2))?VALUE:OPERATOR;break;case 43:case 45:if(source.charCodeAt(pos)===code&&prev===VALUE)pos++;else prev=OPERATOR;break;case 61:if(prev=source.charCodeAt(pos)===62?BLOCK_OPENER:OPERATOR,prev===BLOCK_OPENER)pos++;break;case 64:if(stack.length===0&&decorators===-1)decorators=pos-1;prev=OPERATOR;break;default:prev=OPERATOR}}}function closingBracket(source,from,word){let length=source.length,stack=[],pos=from,prev=OPERATOR,afterDot=!1;while(pos<length){let code=source.charCodeAt(pos);if(code===32||code===10||isWhitespace(code)){pos++;continue}if(code===47){let end=commentEnd(source,pos);if(end!==-1){pos=end;continue}}let wasAfterDot=afterDot;if(afterDot=!1,isWordCode(code)||code===35){let start=pos;if(pos=wordEnd(source,pos+1),!wasAfterDot&&word?.(start,pos))return-1;let kind=wasAfterDot?VALUE:wordKind(source,start,pos);prev=kind===OPERATOR||kind===BLOCK_OPENER||kind===HEAD?OPERATOR:VALUE;continue}switch(pos++,code){case 34:case 39:pos=stringEnd(source,pos,code),prev=VALUE;break;case 96:pos=templateEnd(source,pos,stack),prev=source.charCodeAt(pos-1)===123?OPERATOR:VALUE;break;case 47:{let end=prev===VALUE?-1:regexEnd(source,pos);if(end===-1)prev=OPERATOR;else pos=wordCodesEnd(source,end),prev=VALUE;break}case 40:stack.push(PAREN),prev=OPERATOR;break;case 41:if(stack.length===0)return pos-1;stack.pop(),prev=VALUE;break;case 123:stack.push(prev===OPERATOR?OBJECT:BLOCK),prev=STATEMENT_START;break;case 125:{if(stack.length===0)return pos-1;let open=stack.pop();if(open===TEMPLATE)pos=templateEnd(source,pos,stack),prev=source.charCodeAt(pos-1)===123?OPERATOR:VALUE;else prev=open===OBJECT?VALUE:STATEMENT_START;break}case 93:prev=VALUE;break;case 46:if(isDigit(source.charCodeAt(pos)))pos=wordCodesEnd(source,pos),prev=VALUE;else if(source.startsWith("..",pos))pos+=2,prev=OPERATOR;else afterDot=!0,prev=OPERATOR;break;case 63:if(source.charCodeAt(pos)===46&&!isDigit(source.charCodeAt(pos+1)))pos++,afterDot=!0;prev=OPERATOR;break;case 33:prev=prev===VALUE&&!isWhitespace(source.charCodeAt(pos-2))?VALUE:OPERATOR;break;case 43:case 45:if(source.charCodeAt(pos)===code&&prev===VALUE)pos++;else prev=OPERATOR;break;case 61:if(source.charCodeAt(pos)===62)pos++;prev=OPERATOR;break;default:prev=OPERATOR}}return length}function isLineBreak(code){return code===10||code===13||code===8232||code===8233}function lineEnd(source,pos){for(let i=pos;i<source.length;i++)if(isLineBreak(source.charCodeAt(i)))return i;return source.length}function commentEnd(source,slash){let next=source.charCodeAt(slash+1);if(next===47)return lineEnd(source,slash+2);if(next!==42)return-1;let end=source.indexOf("*/",slash+2);return end===-1?source.length:end+2}function wordEnd(source,pos){let i=pos;while(i<source.length){let code=source.charCodeAt(i);if(code===92)i+=2;else if(isWordCode(code))i++;else break}return i}function wordCodesEnd(source,pos){let i=pos;while(i<source.length&&isWordCode(source.charCodeAt(i)))i++;return i}function stringEnd(source,pos,quote){for(let i=pos;i<source.length;i++){let code=source.charCodeAt(i);if(code===quote)return i+1;if(code===92)i+=source.startsWith(`\r
|
|
1
|
+
import{version2}from"./shared-zgnhwdjy.js";import{spawn}from"node:child_process";import{createHash}from"node:crypto";import{existsSync as existsSync4,readFileSync as readFileSync4,statSync}from"node:fs";import{mkdir,readFile,rm,writeFile}from"node:fs/promises";import{createRequire as createRequire4}from"node:module";import{basename as basename3,dirname as dirname5,join as join6,relative as relative2,resolve as resolve3,sep as sep2}from"node:path";import{fileURLToPath}from"node:url";var REGEX_LANG_ATTRIBUTE=/<!--[\s\S]*?-->|<script\s+(?:[^>]*|(?:[^=>'"/]+=(?:"[^"]*"|'[^']*'|[^>\s]+)\s+)*)lang=(["'])?([^"' >]+)\1[^>]*>/y;function withoutByteOrderMark(source){return source.charCodeAt(0)===65279?source.slice(1):source}function isDigit(code){return code>=48&&code<=57}function isWhitespace(code){if(code===32||code<=13&&code>=9)return!0;if(code<160)return!1;return code===160||code===5760||code>=8192&&code<=8202||code===8232||code===8233||code===8239||code===8287||code===12288||code===65279}function skipWhitespace(source,from){let index=from;while(index<source.length&&isWhitespace(source.charCodeAt(index)))index++;return index}function isTypeScript(source){let index=source.indexOf("<");while(index!==-1){let next=source.charCodeAt(index+1);if(next===33||next===115){REGEX_LANG_ATTRIBUTE.lastIndex=index;let match=REGEX_LANG_ATTRIBUTE.exec(source);if(match){if(next===115)return match[2]==="ts";index=source.indexOf("<",REGEX_LANG_ATTRIBUTE.lastIndex);continue}}index=source.indexOf("<",index+1)}return!1}function closingScriptTag(source,from){let close=source.indexOf("</script",from);while(close!==-1){if(source.charCodeAt(skipWhitespace(source,close+8))===GT)return close;close=source.indexOf("</script",close+8)}return-1}function closingScriptTagEnd(source,close){return skipWhitespace(source,close+8)+1}var VOID_ELEMENTS=new Set("area base br col command embed hr img input keygen link meta param source track wbr".split(" "));function isVoid(name){return VOID_ELEMENTS.has(name)||name.charCodeAt(0)===33&&name.toLowerCase()==="!doctype"}function styleContentEnd(source,from){let index=from;while(index<source.length){let code=source.charCodeAt(index);if(code===47&&source.charCodeAt(index+1)===42){let end=source.indexOf("*/",index+2);index=end===-1?source.length:end+2}else if(code===34||code===39){index++;while(index<source.length){let next=source.charCodeAt(index);if(next===code||next===10)break;index+=next===92?2:1}index++}else if(code===60&&source.startsWith("</style",index))break;else index++}return Math.min(index,source.length)}var DOUBLE_QUOTE=34,SINGLE_QUOTE=39,SLASH=47,EQUALS=61,GT=62,isQuote=(code)=>code===DOUBLE_QUOTE||code===SINGLE_QUOTE;function nameEnd(source,from,isAttribute){let i=from;for(;i<source.length;i++){let code=source.charCodeAt(i);if(isWhitespace(code)||code===SLASH||code===GT)break;if(isAttribute&&(isQuote(code)||code===EQUALS))break}return i}function endsUnquotedValue(source,i){let code=source.charCodeAt(i);return isWhitespace(code)||isQuote(code)||code===EQUALS||code===60||code===GT||code===96||code===SLASH&&source.charCodeAt(i+1)===GT}var STATEMENT_START=0,OPERATOR=1,BLOCK_OPENER=2,VALUE=3,PAREN=0,HEAD_PAREN=1,BLOCK=2,OBJECT=3,TEMPLATE=4,HEAD=4,IMPORT=5,EXPORT=6,REQUIRE=7,KEYWORDS={await:OPERATOR,case:OPERATOR,default:OPERATOR,delete:OPERATOR,extends:OPERATOR,in:OPERATOR,instanceof:OPERATOR,new:OPERATOR,of:OPERATOR,return:OPERATOR,throw:OPERATOR,typeof:OPERATOR,void:OPERATOR,yield:OPERATOR,do:BLOCK_OPENER,else:BLOCK_OPENER,finally:BLOCK_OPENER,try:BLOCK_OPENER,for:HEAD,if:HEAD,while:HEAD,with:HEAD,import:IMPORT,export:EXPORT,require:REQUIRE},LONGEST_KEYWORD=10,KEYWORDS_BY_KEY=Array(keywordKey(128,0)).fill(null);for(let entry of Object.entries(KEYWORDS)){let key=keywordKey(entry[0].charCodeAt(0),entry[0].length),entries=KEYWORDS_BY_KEY[key]??[];entries.push(entry),KEYWORDS_BY_KEY[key]=entries}function keywordKey(first,length){return first*(LONGEST_KEYWORD+1)+length}function wordKind(source,start,end){let first=source.charCodeAt(start);if(first>=128||end-start>LONGEST_KEYWORD)return VALUE;let key=keywordKey(first,end-start),entries=KEYWORDS_BY_KEY[key];if(entries===null)return VALUE;for(let i=0;i<entries.length;i++)if(source.startsWith(entries[i][0],start))return entries[i][1];return VALUE}var ASCII_WORD=new Uint8Array(128);for(let range of["az","AZ","09","__","$$","\\\\"])for(let code=range.charCodeAt(0);code<=range.charCodeAt(1);code++)ASCII_WORD[code]=1;function isWordCode(code){return code>=128?!isWhitespace(code):ASCII_WORD[code]===1}function scan(source,localExports,parseAt,exportLists=!1){tokenize(source,lastStatementKeyword(source,localExports,exportLists),localExports,exportLists,parseAt,void 0,void 0)}function tokenize(source,last,localExports,exportLists,parseAt,literal,call){let stack=[],pos=source.startsWith("#!")?lineEnd(source,2):0,prev=STATEMENT_START,afterDot=!1,head=!1,decorators=-1,statementEnd=()=>{if(prev=STATEMENT_START,stack.length===0)decorators=-1};while(pos<=last){let code=source.charCodeAt(pos);if(code===32||code===10||isWhitespace(code)){pos++;continue}if(code===47){let end=commentEnd(source,pos);if(end!==-1){pos=end;continue}}let wasAfterDot=afterDot,wasHead=head;if(afterDot=!1,head=!1,isWordCode(code)||code===35){let start=pos;pos=wordEnd(source,pos+1);let kind=wasAfterDot?VALUE:wordKind(source,start,pos);if(call!==void 0&&(kind===IMPORT||kind===REQUIRE))call(start,prev===STATEMENT_START||prev===VALUE);if(parseAt!==void 0&&stack.length===0&&(kind===EXPORT?localExports||isReexport(source,pos,exportLists):kind===IMPORT&&isImportDeclaration(source,pos)))pos=Math.max(pos,parseAt(decorators!==-1&&kind===EXPORT?decorators:start,start)),statementEnd();else if(kind===EXPORT)prev=BLOCK_OPENER;else if(kind===HEAD)head=!0,prev=VALUE;else prev=kind===OPERATOR||kind===BLOCK_OPENER?kind:VALUE;continue}switch(pos++,code){case 34:case 39:{let start=pos-1;pos=stringEnd(source,pos,code),literal?.(start,pos,!1),prev=VALUE;break}case 96:{let start=pos;pos=templateEnd(source,pos,stack),literal?.(start,quasiEnd(source,pos),!0),prev=source.charCodeAt(pos-1)===123?OPERATOR:VALUE;break}case 47:{let end=prev===VALUE?-1:regexEnd(source,pos);if(end===-1)prev=OPERATOR;else pos=wordCodesEnd(source,end),prev=VALUE;break}case 40:stack.push(wasHead?HEAD_PAREN:PAREN),prev=OPERATOR;break;case 41:prev=stack.pop()===HEAD_PAREN?BLOCK_OPENER:VALUE;break;case 123:stack.push(prev===OPERATOR?OBJECT:BLOCK),prev=STATEMENT_START;break;case 125:{let open=stack.pop();if(open===TEMPLATE){let start=pos;pos=templateEnd(source,pos,stack),literal?.(start,quasiEnd(source,pos),!0),prev=source.charCodeAt(pos-1)===123?OPERATOR:VALUE}else if(open===OBJECT)prev=VALUE;else statementEnd();break}case 59:statementEnd();break;case 44:prev=stack[stack.length-1]===OBJECT?STATEMENT_START:OPERATOR;break;case 93:prev=VALUE;break;case 46:if(isDigit(source.charCodeAt(pos)))pos=wordCodesEnd(source,pos),prev=VALUE;else if(source.startsWith("..",pos))pos+=2,prev=OPERATOR;else afterDot=!0,prev=OPERATOR;break;case 63:if(source.charCodeAt(pos)===46&&!isDigit(source.charCodeAt(pos+1)))pos++,afterDot=!0;prev=OPERATOR;break;case 33:prev=prev===VALUE&&!isWhitespace(source.charCodeAt(pos-2))?VALUE:OPERATOR;break;case 43:case 45:if(source.charCodeAt(pos)===code&&prev===VALUE)pos++;else prev=OPERATOR;break;case 61:if(prev=source.charCodeAt(pos)===62?BLOCK_OPENER:OPERATOR,prev===BLOCK_OPENER)pos++;break;case 64:if(stack.length===0&&decorators===-1)decorators=pos-1;prev=OPERATOR;break;default:prev=OPERATOR}}}function closingBracket(source,from,word){let length=source.length,stack=[],pos=from,prev=OPERATOR,afterDot=!1;while(pos<length){let code=source.charCodeAt(pos);if(code===32||code===10||isWhitespace(code)){pos++;continue}if(code===47){let end=commentEnd(source,pos);if(end!==-1){pos=end;continue}}let wasAfterDot=afterDot;if(afterDot=!1,isWordCode(code)||code===35){let start=pos;if(pos=wordEnd(source,pos+1),!wasAfterDot&&word?.(start,pos))return-1;let kind=wasAfterDot?VALUE:wordKind(source,start,pos);prev=kind===OPERATOR||kind===BLOCK_OPENER||kind===HEAD?OPERATOR:VALUE;continue}switch(pos++,code){case 34:case 39:pos=stringEnd(source,pos,code),prev=VALUE;break;case 96:pos=templateEnd(source,pos,stack),prev=source.charCodeAt(pos-1)===123?OPERATOR:VALUE;break;case 47:{let end=prev===VALUE?-1:regexEnd(source,pos);if(end===-1)prev=OPERATOR;else pos=wordCodesEnd(source,end),prev=VALUE;break}case 40:stack.push(PAREN),prev=OPERATOR;break;case 41:if(stack.length===0)return pos-1;stack.pop(),prev=VALUE;break;case 123:stack.push(prev===OPERATOR?OBJECT:BLOCK),prev=STATEMENT_START;break;case 125:{if(stack.length===0)return pos-1;let open=stack.pop();if(open===TEMPLATE)pos=templateEnd(source,pos,stack),prev=source.charCodeAt(pos-1)===123?OPERATOR:VALUE;else prev=open===OBJECT?VALUE:STATEMENT_START;break}case 93:prev=VALUE;break;case 46:if(isDigit(source.charCodeAt(pos)))pos=wordCodesEnd(source,pos),prev=VALUE;else if(source.startsWith("..",pos))pos+=2,prev=OPERATOR;else afterDot=!0,prev=OPERATOR;break;case 63:if(source.charCodeAt(pos)===46&&!isDigit(source.charCodeAt(pos+1)))pos++,afterDot=!0;prev=OPERATOR;break;case 33:prev=prev===VALUE&&!isWhitespace(source.charCodeAt(pos-2))?VALUE:OPERATOR;break;case 43:case 45:if(source.charCodeAt(pos)===code&&prev===VALUE)pos++;else prev=OPERATOR;break;case 61:if(source.charCodeAt(pos)===62)pos++;prev=OPERATOR;break;default:prev=OPERATOR}}return length}function isLineBreak(code){return code===10||code===13||code===8232||code===8233}function lineEnd(source,pos){for(let i=pos;i<source.length;i++)if(isLineBreak(source.charCodeAt(i)))return i;return source.length}function commentEnd(source,slash){let next=source.charCodeAt(slash+1);if(next===47)return lineEnd(source,slash+2);if(next!==42)return-1;let end=source.indexOf("*/",slash+2);return end===-1?source.length:end+2}function wordEnd(source,pos){let i=pos;while(i<source.length){let code=source.charCodeAt(i);if(code===92)i+=2;else if(isWordCode(code))i++;else break}return i}function wordCodesEnd(source,pos){let i=pos;while(i<source.length&&isWordCode(source.charCodeAt(i)))i++;return i}function stringEnd(source,pos,quote){for(let i=pos;i<source.length;i++){let code=source.charCodeAt(i);if(code===quote)return i+1;if(code===92)i+=source.startsWith(`\r
|
|
2
2
|
`,i+1)?2:1;else if(code===10||code===13)return i}return source.length}function templateEnd(source,pos,stack){for(let i=pos;i<source.length;i++){let code=source.charCodeAt(i);if(code===96)return i+1;if(code===92)i++;else if(code===36&&source.charCodeAt(i+1)===123)return stack.push(TEMPLATE),i+2}return source.length}function quasiEnd(source,pos){let code=source.charCodeAt(pos-1);if(code===96)return pos-1;if(code===123&&source.charCodeAt(pos-2)===36)return pos-2;return pos}function regexEnd(source,pos){let inClass=!1;for(let i=pos;i<source.length;i++){let code=source.charCodeAt(i);if(isLineBreak(code))return-1;if(code===92)i++;else if(code===91)inClass=!0;else if(code===93)inClass=!1;else if(code===47&&!inClass)return i+1}return-1}function skipTrivia(source,pos){let i=pos;while(i<source.length){let code=source.charCodeAt(i);if(isWhitespace(code)){i++;continue}let end=code===47?commentEnd(source,i):-1;if(end===-1)return i;i=end}return source.length}function isWordAt(source,pos,word){return source.charCodeAt(pos)===word.charCodeAt(0)&&source.startsWith(word,pos)&&!isWordCode(source.charCodeAt(pos+word.length))}function isImportDeclaration(source,pos){let code=source.charCodeAt(skipTrivia(source,pos));return code!==40&&code!==46}function isReexport(source,pos,lists){let i=skipTrivia(source,pos);if(isWordAt(source,i,"import"))return!0;if(isWordAt(source,i,"type"))i=skipTrivia(source,i+4);let code=source.charCodeAt(i);if(code===42)return!0;if(code!==123)return!1;if(lists)return!0;for(i++;i<source.length;i++){let inner=source.charCodeAt(i);if(inner===125)break;if(inner===34||inner===39)i=stringEnd(source,i+1,inner)-1;else if(inner===47)i=Math.max(i,skipTrivia(source,i)-1)}return isWordAt(source,skipTrivia(source,i+1),"from")}var STATEMENT_KEYWORD=/import|export/g;function lastStatementKeyword(source,localExports,exportLists){let last=-1;STATEMENT_KEYWORD.lastIndex=0;for(let match=STATEMENT_KEYWORD.exec(source);match!==null;match=STATEMENT_KEYWORD.exec(source)){let start=match.index,end=start+6;if(!isWordCode(source.charCodeAt(start-1))&&!isWordCode(source.charCodeAt(end))&&(source.charCodeAt(start)===105?isImportDeclaration(source,end):localExports||isReexport(source,end,exportLists)))last=start}return last}var AUTOCLOSING_CHILDREN={li:["li"],dt:["dt","dd"],dd:["dt","dd"],p:"address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul".split(" "),rt:["rt","rp"],rp:["rt","rp"],optgroup:["optgroup"],option:["option","optgroup"],thead:["tbody","tfoot"],tbody:["tbody","tfoot"],tfoot:["tbody"],tr:["tr","tbody"],td:["td","th","tr"],th:["td","th","tr"]};function closingTagOmitted(current,next){return Object.hasOwn(AUTOCLOSING_CHILDREN,current)&&AUTOCLOSING_CHILDREN[current].includes(next)}var BLOCK2="{",LT=60,GT2=62,SLASH2=47,EQUALS2=61,BRACE=123,REGEX_CLOSING_STYLE_TAG_END=/\s*>/y,REGEX_CLOSING_TEXTAREA=/<\/textarea(\s[^>]*)?>/iy,SECTION_TAG_NAMES=["cript","tyle","velte:options"],CLOSING_OPTIONS_TAG="</svelte:options";function lexComponent2(input){let source=withoutByteOrderMark(input).trimEnd();return lex(source,isTypeScript(source),null)}function topLevelTags(source){let found={tags:[],comments:[]};return lex(source,!1,found),found}function lex(source,typescript,found){let component={typescript,instance:null,module:null,css:null,options:null},last=lastSectionTag(source),stack=[],i=0;while(i<=last){let code=source.charCodeAt(i);if(code===LT)i=readTag(source,i,stack,component,found);else if(code===BRACE)i=readMustache(source,i,stack);else i++}return component}function lastSectionTag(source){let last=-1,i=source.indexOf("<s");while(i!==-1){let end=sectionTagNameEnd(source,i+2);if(end!==-1){let code=source.charCodeAt(end);if(end===source.length||isWhitespace(code)||code===SLASH2||code===GT2)last=i}i=source.indexOf("<s",i+2)}return last}function sectionTagNameEnd(source,from){for(let name of SECTION_TAG_NAMES)if(source.startsWith(name,from))return from+name.length;return-1}function expressionEnd(source,from){return Math.min(closingBracket(source,from)+1,source.length)}function readMustache(source,start,stack){let i=skipWhitespace(source,start+1),code=source.charCodeAt(i),next=source.charCodeAt(i+1);if(code===35||code===58||code===64||code===SLASH2&&next!==SLASH2&&next!==42){i++;while(i<source.length){let letter=source.charCodeAt(i);if(letter<97||letter>122)break;i++}if(code===35)stack.push(BLOCK2);else if(code===SLASH2){let open=stack.lastIndexOf(BLOCK2);if(open!==-1)stack.length=open}}return expressionEnd(source,i)}function readTag(source,start,stack,component,found){if(source.startsWith("!--",start+1)){let close=source.indexOf("-->",start+4),end=close===-1?source.length:close+3;if(found&&stack.length===0)found.comments.push(start,end);return end}if(source.charCodeAt(start+1)===SLASH2){let nameStart=start+2,name=source.slice(nameStart,nameEnd(source,nameStart,!1)),open=stack.lastIndexOf(name);if(open!==-1)stack.length=open;return eatGreaterThan(source,skipWhitespace(source,nameStart+name.length))}let name=source.slice(start+1,nameEnd(source,start+1,!1)),i=skipWhitespace(source,start+1+name.length),parent=stack[stack.length-1];if(parent!==void 0&&closingTagOmitted(parent,name))stack.pop();let topLevel=stack.length===0;if(found&&topLevel&&(name==="script"||name==="style"||name==="svelte:options"))found.tags.push(start);if(topLevel&&(name==="script"||name==="style")){let attributes=[];if(i=eatGreaterThan(source,readStaticAttributes(source,i,attributes)),name==="script"){let script=readScript(source,start,i,attributes);if(script.context==="module")component.module??=script;else component.instance??=script;return script.end}let css=readStyle(source,start,i,attributes);return component.css??=css,css.end}let attributes=topLevel&&name==="svelte:options"?[]:null;if(i=readAttributes(source,i,attributes),source.charCodeAt(i)===SLASH2||isVoid(name)){if(source.charCodeAt(i)===SLASH2)i++;i=eatGreaterThan(source,i)}else{if(i=eatGreaterThan(source,i),name==="textarea")return textareaEnd(source,i);if(name==="script"||name==="style"){let closer=`</${name}>`,close=source.indexOf(closer,i);return close===-1?source.length:close+closer.length}if(attributes&&source.startsWith(CLOSING_OPTIONS_TAG,i))i=eatGreaterThan(source,skipWhitespace(source,i+CLOSING_OPTIONS_TAG.length));else return stack.push(name),i}if(attributes)component.options??={start,end:i,attributes};return i}function eatGreaterThan(source,i){return source.charCodeAt(i)===GT2?i+1:i}function readScript(source,start,contentStart,attributes){let close=closingScriptTag(source,contentStart),contentEnd=close===-1?source.length:close,module=attributes.some((attribute)=>attribute.name==="module"||attribute.name==="context");return{start,end:close===-1?source.length:closingScriptTagEnd(source,close),context:module?"module":"default",attributes,content:{start:contentStart,end:contentEnd}}}function readStyle(source,start,contentStart,attributes){let contentEnd=styleContentEnd(source,contentStart),end=contentEnd;if(source.startsWith("</style",end)){end+=7,REGEX_CLOSING_STYLE_TAG_END.lastIndex=end;let close=REGEX_CLOSING_STYLE_TAG_END.exec(source);if(close)end+=close[0].length}return{start,end,attributes,content:{start:contentStart,end:contentEnd}}}function readStaticAttributes(source,from,into){let i=from;for(;;){let start=i,end=nameEnd(source,i,!0);if(end===start)return i;i=end;let value=!0;if(source.charCodeAt(i)===EQUALS2){let at=skipWhitespace(source,i+1),quote=source.charCodeAt(at),valueEnd=-1;if(isQuote(quote)){let close=source.indexOf(source[at],at+1);if(close!==-1)valueEnd=close+1}if(valueEnd===-1){valueEnd=at;while(valueEnd<source.length&&source.charCodeAt(valueEnd)!==GT2&&!isWhitespace(source.charCodeAt(valueEnd)))valueEnd++}let quotes=isQuote(quote)?1:0;value=source.slice(at+quotes,valueEnd-quotes),i=valueEnd}into.push({name:source.slice(start,end),value,start,end:i}),i=skipWhitespace(source,i)}}function readAttributes(source,from,into){let i=from;for(;;){for(;;){if(source.startsWith("/*",i)){let end=source.indexOf("*/",i+2);i=end===-1?source.length:end+2}else if(source.startsWith("//",i)){let end=source.indexOf(`
|
|
3
3
|
`,i+2);i=end===-1?source.length:end}else break;i=skipWhitespace(source,i)}let start=i;if(source.charCodeAt(i)===BRACE){i=skipWhitespace(source,expressionEnd(source,i+1));continue}let nameEndAt=nameEnd(source,i,!0);if(nameEndAt===start)return i;let end=nameEndAt,value=!0;if(i=skipWhitespace(source,nameEndAt),source.charCodeAt(i)===EQUALS2){let at=skipWhitespace(source,i+1);end=source.startsWith("/>",at)?at+1:attributeValueEnd(source,at),value=isQuote(source.charCodeAt(at))?source.slice(at+1,Math.max(at+1,end-1)):source.slice(at,end),i=skipWhitespace(source,end)}into?.push({name:source.slice(start,nameEndAt),value,start,end})}}function attributeValueEnd(source,from){let quote=source.charCodeAt(from);if(isQuote(quote)){let i=from+1;while(i<source.length){let code=source.charCodeAt(i);if(code===quote)return i+1;i=code===BRACE?expressionEnd(source,i+1):i+1}return source.length}let i=from;while(i<source.length&&!endsUnquotedValue(source,i))i=source.charCodeAt(i)===BRACE?expressionEnd(source,i+1):i+1;return i}function textareaEnd(source,from){let i=from;while(i<source.length){let code=source.charCodeAt(i);if(code===LT){if(REGEX_CLOSING_TEXTAREA.lastIndex=i,REGEX_CLOSING_TEXTAREA.test(source))return REGEX_CLOSING_TEXTAREA.lastIndex}i=code===BRACE?expressionEnd(source,i+1):i+1}return source.length}function lexImportsExports(source,options={}){let lexer=new Lexer(source);lexer.exportLists=options.exportLists??!1;let statements=[];return scan(source,!1,(_start,keyword)=>{let statement=lexer.statement(keyword);return statements.push(statement),statement.end},lexer.exportLists),statements}class Lexer{source;pos=0;end=0;escapeEnd=0;exportLists=!1;constructor(source){this.source=source}statement(keyword){this.pos=this.end=keyword+6;let statement={kind:this.source.charCodeAt(keyword)===105?"import":"export",start:keyword,end:0,source:null,typeOnly:!1,specifiers:[]};if(!(statement.kind==="import"?this.import(statement):this.export(statement)))statement.source=null,statement.specifiers=[];return statement.end=this.end,statement}import(statement){let module=this.string();if(module!==null)return statement.source=module,this.finish();if(this.isWord("type")){let next=this.peekAfter(4);if(next===123||next===42||isIdentifierStart(next)&&!this.isWordAfter(4,"from"))statement.typeOnly=!0,this.advance(4)}let{specifiers,typeOnly}=statement,next=this.at();if(next!==123&&next!==42){let start=this.pos,local=this.name();if(local===null)return!1;if(this.at()===61)return this.importEquals();if(specifiers.push({kind:"default",imported:"default",local,typeOnly,start,end:this.end}),!this.eat(44))return this.from(statement);next=this.at()}if(next===42){let start=this.pos;if(this.advance(1),!this.eatWord("as"))return!1;let local=this.name();if(local===null)return!1;return specifiers.push({kind:"namespace",imported:"*",local,typeOnly,start,end:this.end}),this.from(statement)}if(!this.eat(123))return!1;while(!this.eat(125)){let start=this.skip(),named=this.typeModifier()||typeOnly,name=this.name(),imported=name??this.string()?.value;if(imported===void 0)return!1;let local=name;if(this.eatWord("as"))local=this.name();if(local===null)return!1;if(specifiers.push({kind:"named",imported,local,typeOnly:named,start,end:this.end}),!this.eat(44)&&this.at()!==125)return!1}return this.from(statement)}export(statement){if(this.eatWord("import")){if(this.isWord("type")&&isIdentifierStart(this.peekAfter(4))&&!this.isWordAfter(4,"from"))statement.typeOnly=!0,this.advance(4);return this.name()!==null&&this.at()===61&&this.importEquals()}if(this.isWord("type")){let next=this.peekAfter(4);if(next===123||next===42)statement.typeOnly=!0,this.advance(4)}let{specifiers,typeOnly}=statement;if(this.at()===42){let start=this.pos;this.advance(1);let exported=null;if(this.eatWord("as")){if(exported=this.moduleExportName(),exported===null)return!1}return specifiers.push({kind:exported===null?"all":"namespace",local:"*",exported,typeOnly,start,end:this.end}),this.from(statement)}if(!this.eat(123))return!1;while(!this.eat(125)){let start=this.skip(),named=this.typeModifier()||typeOnly,local=this.moduleExportName();if(local===null)return!1;let exported=local;if(this.eatWord("as"))exported=this.moduleExportName();if(exported===null)return!1;if(specifiers.push({kind:"named",local,exported,typeOnly:named,start,end:this.end}),!this.eat(44)&&this.at()!==125)return!1}if(this.exportLists&&!this.isWord("from")){for(let specifier of specifiers)specifier.kind="local";return this.eat(59),!0}return this.from(statement)}dynamicImport(start,member){let isImport=this.source.charCodeAt(start)===105;this.pos=this.end=start+(isImport?6:7);let kind=isImport?"import":"require";if(isImport&&this.eat(46)){if(!this.eatWord("meta")||!this.eat(46)||!this.eatWord("glob")||!this.typeArguments())return null;kind="glob"}if(!this.eat(40))return null;let argument=this.skip(),source=this.string()??this.template(),close=this.at()===41?this.pos:-1;if(close===-1){if(this.at()!==44)source=null;close=closingBracket(this.source,argument)}if(member&&kind!=="glob"){let after=this.source.charCodeAt(skipTrivia(this.source,close+1));if(after===123||after===58)return null}return{kind,source,start,end:Math.min(close+1,this.source.length)}}typeArguments(){if(this.at()!==60)return!0;let source=this.source,depth=0;for(let i=this.pos;i<source.length;i=skipTrivia(source,i+1)){let code=source.charCodeAt(i);if(code===34||code===39||code===96){let end=source.indexOf(source[i],i+1);if(end===-1)return!1;i=end}else if(code===60)depth++;else if(code===62&&source.charCodeAt(i-1)!==61){if(--depth===0)return this.advance(i+1-this.pos),!0}}return!1}template(){let source=this.source,start=this.skip();if(source.charCodeAt(start)!==96)return null;for(let i=start+1;i<source.length;i++){let code=source.charCodeAt(i);if(code===96){let value=this.cooked(start+1,i,!0);if(value===null)return null;return this.advance(i+1-start),{value,start,end:i+1}}if(code===92)i++;else if(code===36&&source.charCodeAt(i+1)===123)return null}return null}typeModifier(){if(!this.isWord("type"))return!1;let next=this.peekAfter(4);if(next===34||next===39||isIdentifierStart(next)&&!this.isWordAfter(4,"as"))return this.advance(4),!0;return!1}importEquals(){if(this.advance(1),this.isWord("require")&&this.peekAfter(7)===40){if(this.advance(7),this.eat(40),this.string()===null||!this.eat(41))return!1}else do if(this.name()===null)return!1;while(this.eat(46));return this.eat(59),!0}from(statement){if(!this.eatWord("from"))return!1;return statement.source=this.string(),statement.source!==null&&this.finish()}finish(){let keyword=this.isWord("with")?4:0;if(this.isWord("assert")&&lineEnd(this.source,this.end)>=this.pos)keyword=6;if(keyword!==0&&this.peekAfter(keyword)===123){this.advance(keyword),this.eat(123);while(!this.eat(125))if(this.string()===null&&this.name()===null&&!this.eat(58)&&!this.eat(44))return!1}return this.eat(59),!0}skip(){return this.pos=skipTrivia(this.source,this.pos),this.pos}at(){return this.source.charCodeAt(this.skip())}advance(length){this.pos+=length,this.end=this.pos}peekAfter(length){return this.source.charCodeAt(skipTrivia(this.source,this.pos+length))}isWordAfter(length,word){return isWordAt(this.source,skipTrivia(this.source,this.pos+length),word)}eat(code){if(this.at()!==code)return!1;return this.advance(1),!0}isWord(word){return isWordAt(this.source,this.skip(),word)}eatWord(word){if(!this.isWord(word))return!1;return this.advance(word.length),!0}moduleExportName(){return this.name()??this.string()?.value??null}name(){let source=this.source,start=this.skip();if(!isWordCode(source.charCodeAt(start))||isDigit(source.charCodeAt(start)))return null;let value="",chunk=start,i=start;while(i<source.length){let code=source.charCodeAt(i);if(code===92){if(source.charCodeAt(i+1)!==117)return null;let escaped=this.unicodeEscape(i+2);if(escaped===null)return null;value+=source.slice(chunk,i)+escaped,i=chunk=this.escapeEnd}else if(isWordCode(code))i++;else break}return this.advance(i-start),value+source.slice(chunk,i)}string(){let source=this.source,start=this.skip(),quote=source.charCodeAt(start);if(quote!==34&"e!==39)return null;let value="",chunk=start+1;for(let i=chunk;i<source.length;){let code=source.charCodeAt(i);if(code===quote)return this.advance(i+1-start),{value:value+source.slice(chunk,i),start,end:i+1};if(code===10||code===13)return null;if(code===92){let escaped=this.escape(i+1);if(escaped===null)return null;value+=source.slice(chunk,i)+escaped,i=chunk=this.escapeEnd}else i++}return null}cooked(from,to,template){let source=this.source,value="",chunk=from;for(let i=from;i<to;){let code=source.charCodeAt(i);if(code===92){let escaped=this.escape(i+1);if(escaped===null)return null;value+=source.slice(chunk,i)+escaped,i=chunk=this.escapeEnd}else if(code===13&&template)value+=`${source.slice(chunk,i)}
|
|
4
4
|
`,i+=source.charCodeAt(i+1)===10?2:1,chunk=i;else i++}return value+source.slice(chunk,to)}escape(pos){let code=this.source.charCodeAt(pos);switch(this.escapeEnd=pos+1,code){case 110:return`
|
|
@@ -24,31 +24,31 @@ ${" ".repeat(digits+2+tabsToSpaces(text.slice(0,column)).length)}^`}).join(`
|
|
|
24
24
|
`);i!==-1;i=text.indexOf(`
|
|
25
25
|
`,i+1))starts.push(i+1);return{position(offset){let lo=0,hi=starts.length-1;while(lo<hi){let mid=lo+hi+1>>1;if(starts[mid]<=offset)lo=mid;else hi=mid-1}return{line:lo+1,column:offset-starts[lo]+1}},offset(line,column){return(starts[line-1]??text.length)+column-1}}}var DIGITS=new Map([..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].map((char,i)=>[char,i]));function decode(mappings){let lines=[],line=0,originalColumn=0;for(let encoded of mappings.split(";")){let segments=[],column=0;for(let segment of encoded.split(",")){if(!segment)continue;let fields=[],value=0,shift=0;for(let char of segment){let digit=DIGITS.get(char)??0;if(value+=(digit&31)<<shift,digit&32)shift+=5;else fields.push(value&1?-(value>>>1):value>>>1),value=0,shift=0}if(column+=fields[0]??0,fields.length<4)continue;line+=fields[2]??0,originalColumn+=fields[3]??0,segments.push([column,line,originalColumn])}lines.push(segments)}return lines}function originalPosition(map){if(!map)return(line,column)=>({line,column});let lines=decode(map.mappings);return(line,column)=>{let segments=lines[line-1]??[],found;for(let segment of segments){if(segment[0]>column-1)break;found=segment}if(!found)return{line,column};return{line:found[1]+1,column:found[2]+(column-1-found[0])+1}}}function svelteDirOf(cwd,svelte){return svelte?resolve(cwd,svelte):dirname2(createRequire(join2(cwd,"package.json")).resolve("svelte/package.json"))}var compilers=new Map;function compilerOf(svelteDir){let compiler=compilers.get(svelteDir);if(!compiler)compiler=createRequire(join2(svelteDir,"package.json"))("svelte/compiler"),compilers.set(svelteDir,compiler);return compiler}function diagnosticsOf(compiler,source,filename,compilerOptions={}){try{let{warnings}=compiler.compile(source,{...compilerOptions,filename,generate:!1});return warnings.map((w)=>({severity:"warning",code:w.code,message:w.message,...positionsOf(w)}))}catch(error){let e=error;return[{severity:"error",code:e.code??"compile_error",message:e.message,...positionsOf(e)}]}}function positionsOf(w){let line=w.start?.line??1,column=(w.start?.column??0)+1;return{line,column,endLine:w.end?.line??line,endColumn:w.end?w.end.column+1:column}}function compilerDiagnostics2(source,filename,options={}){let compiler=compilerOf(svelteDirOf(resolve(options.cwd??process.cwd()),options.svelte));return diagnosticsOf(compiler,source,filename)}async function preprocessedDiagnostics(source,filename,svelteDir,config){let compiler=compilerOf(svelteDir),{preprocess,compilerOptions}=config,diagnostics,processed=preprocess?await compiler.preprocess(source,preprocess,{filename}):void 0;if(!processed||processed.code===source)diagnostics=diagnosticsOf(compiler,source,filename,compilerOptions);else{let map=typeof processed.map==="string"?JSON.parse(processed.map):processed.map,toOriginal=originalPosition(map);diagnostics=diagnosticsOf(compiler,processed.code,filename,compilerOptions).map((d)=>{let start=toOriginal(d.line,d.column),end=toOriginal(d.endLine??d.line,d.endColumn??d.column);return{...d,...start,endLine:end.line,endColumn:end.column}})}return asSvelteCheck(diagnostics,source,Boolean(preprocess))}var TEXT_TYPE=/^text\//,EXPORTED_TYPE=(name)=>new RegExp(`\\bexport\\s+?(enum|namespace)\\s+?${name}\\b`);function asSvelteCheck(diagnostics,source,preprocessed){let lexed=lexComponent2(source),script=lexed.instance??lexed.module,langOf=(attributes=[])=>{let lang=attributes.find((a)=>a.name==="lang")??attributes.find((a)=>a.name==="type");return typeof lang?.value==="string"?lang.value.replace(TEXT_TYPE,""):""},scriptLang=langOf(script?.attributes),styleLang=langOf(lexed.css?.attributes),ignoreScript=!preprocessed&&scriptLang!==""&&scriptLang!=="ts",ignoreStyle=!preprocessed&&styleLang!=="",offsetOf=createLocator(source).offset,inside=(d,tag)=>{if(!tag)return!1;let at=offsetOf(d.line,d.column);return tag.content.start<=at&&at<=tag.content.end},kept=[];for(let d of diagnostics){if(d.severity==="error"){if(d.message.includes("expected")){if(!preprocessed&&(scriptLang||styleLang))continue;let inScript=inside(d,script);if(inScript||inside(d,lexed.css))d.message+=`
|
|
26
26
|
|
|
27
|
-
If you expect this syntax to work, here are some suggestions: `+(inScript?'\nIf you use typescript with `svelte-preprocess`, did you add `lang="ts"` to your `script` tag? ':'\nIf you use less/SCSS with `svelte-preprocess`, did you add `lang="scss"`/`lang="less"` to your `style` tag? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. ')+"\nDid you setup a `svelte.config.js` or `vite.config.js`? \nSee https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info."}kept.push(d);continue}if(ignoreScript&&!d.code.startsWith("a11y"))continue;if(ignoreStyle&&(d.code==="css_unused_selector"||d.code==="css-unused-selector"))continue;if(d.code==="export_let_unused"||d.code==="unused-export-let"){let name=d.message.slice(d.message.indexOf("'")+1,d.message.lastIndexOf("'"));if(EXPORTED_TYPE(name).test(source))continue}kept.push(d)}return kept}import{existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";import{createRequire as createRequire2}from"node:module";import{basename,dirname as dirname3,join as join3}from"node:path";import{pathToFileURL}from"node:url";var VITE_CONFIGS=["js","mjs","ts","cjs","mts","cts"].map((ext)=>`vite.config.${ext}`),SVELTE_CONFIGS=["js","cjs","mjs",...process.versions.bun||process.features.typescript?["ts","mts"]:[]].map((ext)=>`svelte.config.${ext}`),SVELTE_CONFIG=/^svelte\.config\./;async function svelteConfigOf(dir,explicit){let config=(explicit?await fromFile(explicit):await fromDir(dir))??{},{preprocess}=config;return{preprocess:preprocess&&(Array.isArray(preprocess)?preprocess:[preprocess]),compilerOptions:{dev:!0,...config.compilerOptions}}}function configFingerprint(dir,explicit){let parts=[],add=(path)=>{try{parts.push(path,readFileSync2(path,"utf-8"))}catch{}};if(explicit)add(explicit);else for(let at=dir;;at=dirname3(at)){for(let name of[...VITE_CONFIGS,...SVELTE_CONFIGS]){let path=join3(at,name);if(existsSync2(path))add(path)}if(dirname3(at)===at)break}return JSON.stringify(parts)}var firstIn=(dir,names)=>names.map((name)=>join3(dir,name)).find((path)=>existsSync2(path));async function fromFile(path){if(SVELTE_CONFIG.test(basename(path)))return fromSvelteConfig(path);let result=await fromVite(dirname3(path),path);return result==="error"?void 0:result??fromSvelteConfig(path)}async function fromDir(dir){for(let at=dir;;at=dirname3(at)){let vite=firstIn(at,VITE_CONFIGS),result=vite?await fromVite(at,vite):void 0;if(result&&result!=="error")return result;let svelte=firstIn(at,SVELTE_CONFIGS);if(svelte)return fromSvelteConfig(svelte);if(result==="error"||dirname3(at)===at)return}}async function fromSvelteConfig(path){try{return(await import(pathToFileURL(path).href)).default}catch{return}}var resolving=Promise.resolve();async function fromVite(root,configFile){let vite=await importVite(root);if(!vite)return;let previous=resolving,done=()=>{};resolving=new Promise((resolve)=>{done=resolve}),await previous;let cwd=process.cwd();try{process.chdir(root)}catch{}try{let{plugins}=await vite.resolveConfig({root,configFile,logLevel:"error"},"serve"),options=(name)=>plugins.find((p)=>p.name===name)?.api?.options;return options("vite-plugin-sveltekit-setup")??options("vite-plugin-svelte:config")}catch{return"error"}finally{try{process.chdir(cwd)}catch{}done()}}async function importVite(root){try{let pkgPath=createRequire2(join3(root,"package.json")).resolve("vite/package.json"),pkg=JSON.parse(readFileSync2(pkgPath,"utf-8")),entry=importEntry(pkg.exports?.["."])??pkg.module??pkg.main;if(!entry)return;return await import(pathToFileURL(join3(dirname3(pkgPath),entry)).href)}catch{return}}function importEntry(entry){if(typeof entry==="string")return entry;if(!entry||typeof entry!=="object")return;let{import:imported,default:fallback}=entry;if(typeof imported==="string")return imported;if(imported&&typeof imported==="object"){let nested=imported.default;if(typeof nested==="string")return nested}return typeof fallback==="string"?fallback:void 0}class ScopeNode{node;parent;porous;index;declarations=new Map;constructor(node,parent,porous,index){this.node=node,this.parent=parent,this.porous=porous,this.index=index}get(name){for(let scope=this;scope;scope=scope.parent){let binding=scope.declarations.get(name);if(binding!==void 0)return binding}return null}}class BindingNode{name;kind;node;declaration;initial;scope;references=[];rune=null;prop=null;constructor(name,kind,node,declaration,initial,scope){this.name=name,this.kind=kind,this.node=node,this.declaration=declaration,this.initial=initial,this.scope=scope}}class ReferenceNode{node;parent;scope;binding=null;reads;writes;mutates;store=!1;constructor(node,parent,scope,reads,writes,mutates){this.node=node,this.parent=parent,this.scope=scope,this.reads=reads,this.writes=writes,this.mutates=mutates}}var keysByType2=Object.assign(Object.create(null),valueVisitorKeys2),ELEMENTS=new Set(["SvelteElement","RegularElement","SvelteFragment","Component","SvelteComponent","SvelteSelf","SlotElement"]),NO_BINDINGS=new Map;function analyzeScopes2(ast){return new Analysis(ast,!1)}class Analysis{module;instance;instanceProgram=null;component;ast;scopes=[];scopeIn;synthetic=new Map;recorded;made=new Map;declared=new Map;references=new Map;pending=[];declarators=[];implicit=[];stores=new Map;constructor(ast,record){if(this.ast=ast,this.scopeIn=record?new Map:null,ast.type==="Program")this.component=!1,this.module=this.scope(ast,null,!1),this.instance=this.module,this.made.set(ast,this.module),this.visit(ast,null,this.module);else{this.component=!0;let module=ast.module?.content??null,instance=ast.instance?.content??null;this.module=this.scope(module,null,!1),this.instance=this.scope(instance,this.module,!1),this.instanceProgram=instance,this.scopeIn?.set(ast,this.module);for(let[script,scope]of[[ast.module,this.module],[ast.instance,this.instance]]){if(script===void 0)continue;this.scopeIn?.set(script,scope),this.made.set(script.content,scope);for(let attribute of script.attributes)this.visit(attribute,script,scope);this.visit(script.content,script,scope)}this.visit(ast.fragment,ast,this.instance)}this.declareImplicit(),this.resolve(),this.findRunesAndProps()}scopeOf(node){let synthetic=this.synthetic.get(node);if(synthetic!==void 0)return synthetic;if(this.scopeIn!==null)return this.scopeIn.get(node)??null;this.recorded??=new Analysis(this.ast,!0);let recorded=this.recorded.scopeIn?.get(node);return recorded===void 0?null:this.scopes[recorded.index]}scope(node,parent,porous){let scope=new ScopeNode(node,parent,porous,this.scopes.length);return this.scopes.push(scope),scope}bindingOf(node){return this.declared.get(node)??this.references.get(node)?.binding??null}referenceOf(node){return this.references.get(node)??null}declaredIn(node){return this.made.get(node)?.declarations??NO_BINDINGS}child(scope,node,porous){let made=this.scope(node,scope,porous);return this.made.set(node,made),made}declare(scope,node,name,kind,declaration,initial){let target=scope;if(kind==="var")while(target.porous&&target.parent!==null)target=target.parent;let existing=target.declarations.get(name);if(existing!==void 0&&existing.declaration.type!=="TSDeclareFunction"){if(node!==null)this.declared.set(node,existing);return}let binding=new BindingNode(name,kind,node,declaration,initial,target);if(target.declarations.set(name,binding),node!==null)this.declared.set(node,binding)}reference(node,parent,scope,reads,writes,mutates){this.pending.push(new ReferenceNode(node,parent,scope,reads,writes,mutates))}referenceName(name,start,parent,scope){let root=name.split(".")[0],node={type:"Identifier",name:root,start,end:start+root.length};this.synthetic.set(node,scope),this.reference(node,parent,scope,!0,!1,!1)}visit(node,parent,scope){switch(this.scopeIn?.set(node,scope),node.type){case"Identifier":if(parent!==null&&isReference2(node,parent))this.reference(node,parent,scope,!0,!1,!1);this.visitFields(node,scope);return;case"ImportDeclaration":for(let specifier of node.specifiers){if(this.scopeIn?.set(specifier,scope),this.scopeIn?.set(specifier.local,scope),specifier.type==="ImportSpecifier")this.scopeIn?.set(specifier.imported,scope);this.declare(scope,specifier.local,specifier.local.name,"import",specifier,node)}this.visit(node.source,node,scope);for(let attribute of node.attributes??[])this.visit(attribute,node,scope);return;case"ExportNamedDeclaration":if(node.declaration)this.visit(node.declaration,node,scope);for(let specifier of node.specifiers)if(this.scopeIn?.set(specifier,scope),this.scopeIn?.set(specifier.local,scope),this.scopeIn?.set(specifier.exported,scope),!node.source&&specifier.local.type==="Identifier")this.reference(specifier.local,specifier,scope,!0,!1,!1);if(node.source)this.visit(node.source,node,scope);for(let attribute of node.attributes??[])this.visit(attribute,node,scope);return;case"VariableDeclaration":this.visitDeclaration(node,parent,scope);return;case"FunctionDeclaration":if(node.id)this.scopeIn?.set(node.id,scope),this.declare(scope,node.id,node.id.name,"function",node,node);this.visitFunction(node,this.child(scope,node,!0));return;case"FunctionExpression":{let inner=this.child(scope,node,!0);if(node.id)this.scopeIn?.set(node.id,inner),this.declare(inner,node.id,node.id.name,"function",node,node);this.visitFunction(node,inner);return}case"ArrowFunctionExpression":this.visitFunction(node,this.child(scope,node,!0));return;case"ClassDeclaration":case"ClassExpression":{let inner=scope;if(node.id){if(node.type==="ClassExpression")inner=this.child(scope,node,!1);this.scopeIn?.set(node.id,inner),this.declare(inner,node.id,node.id.name,"class",node,node)}for(let decorator of node.decorators??[])this.visit(decorator,node,scope);if(node.superClass)this.visit(node.superClass,node,inner);this.visit(node.body,node,inner);return}case"BlockStatement":this.visitFields(node,this.child(scope,node,!(parent!==null&&isFunction2(parent)&&parent.body===node)));return;case"StaticBlock":this.visitFields(node,this.child(scope,node,!1));return;case"ForStatement":case"SwitchStatement":this.visitFields(node,this.child(scope,node,!0));return;case"ForInStatement":case"ForOfStatement":{let inner=this.child(scope,node,!0);if(node.left.type==="VariableDeclaration")this.visit(node.left,node,inner);else this.visitTarget(node.left,node,inner,!1);this.visit(node.right,node,inner),this.visit(node.body,node,inner);return}case"CatchClause":{if(!node.param)break;let inner=this.child(scope,node,!0);this.declarePattern(node.param,node,inner,"catch",node,null),this.visit(node.body,node,inner);return}case"AssignmentExpression":this.visitTarget(node.left,node,scope,node.operator!=="="),this.visit(node.right,node,scope);return;case"UpdateExpression":this.visitTarget(node.argument,node,scope,!0);return;case"LabeledStatement":if(parent===this.instanceProgram&&node.label.name==="$"){this.visitReactive(node,scope);return}break;case"TSEnumDeclaration":{this.scopeIn?.set(node.id,scope),this.declare(scope,node.id,node.id.name,"enum",node,node);let inner=this.child(scope,node,!1);for(let member of node.members)if(this.scopeIn?.set(member,inner),this.scopeIn?.set(member.id,inner),member.id.type==="Identifier")this.declare(inner,member.id,member.id.name,"enum-member",member,member.initializer??null);for(let member of node.members)if(member.initializer)this.visit(member.initializer,member,inner);return}case"TSModuleDeclaration":if(this.scopeIn?.set(node.id,scope),node.id.type==="Identifier"&&!node.global)this.declare(scope,node.id,node.id.name,"namespace",node,node);if(node.body)this.visit(node.body,node,this.child(scope,node,!1));return;case"TSImportEqualsDeclaration":{this.scopeIn?.set(node.id,scope),this.declare(scope,node.id,node.id.name,"import",node,node.moduleReference);let name=node.moduleReference;while(name.type==="TSQualifiedName")this.scopeIn?.set(name,scope),this.scopeIn?.set(name.right,scope),name=name.left;if(name.type==="Identifier")this.scopeIn?.set(name,scope),this.reference(name,node,scope,!0,!1,!1);else this.visit(name,node,scope);return}case"TSDeclareFunction":if(node.id){if(this.scopeIn?.set(node.id,scope),!scope.declarations.has(node.id.name))this.declare(scope,node.id,node.id.name,"function",node,node)}return;case"Fragment":this.visitFields(node,this.child(scope,node,!1));return;case"RegularElement":case"SvelteElement":case"SlotElement":case"SvelteFragment":this.visitFields(node,this.child(scope,node,!1));return;case"Component":case"SvelteComponent":case"SvelteSelf":this.visitComponent(node,scope);return;case"LetDirective":this.visitLet(node,scope);return;case"EachBlock":this.visitEach(node,scope);return;case"AwaitBlock":this.visitAwait(node,scope);return;case"SnippetBlock":{this.scopeIn?.set(node.expression,scope);let{name}=node.expression;this.declare(scope,node.expression,name,"snippet",node,node);let inner=this.child(scope,node,!1);for(let parameter of node.parameters??[])this.declarePattern(parameter,node,inner,"snippet-param",node,null);this.visit(node.body,node,inner);return}case"BindDirective":if(node.expression.type==="SequenceExpression")break;this.visitTarget(node.expression,node,scope,!0);return;case"TransitionDirective":case"AnimateDirective":case"UseDirective":{this.referenceName(node.name,node.start+prefixLength(node),node,scope);break}case"StyleDirective":if(node.value===!0)this.referenceName(node.name,node.start+6,node,scope);break}this.visitFields(node,scope)}visitFields(node,scope){let keys=keysByType2[node.type];if(keys===void 0)throw Error(`unknown node type: ${node.type}`);let fields=fieldsOf(node);for(let k=0;k<keys.length;k++){let value=fields[keys[k]];if(Array.isArray(value))for(let i=0;i<value.length;i++){let child=value[i];if(isNode(child))this.visit(child,node,scope)}else if(isNode(value))this.visit(value,node,scope)}}visitDeclaration(node,parent,scope){let kind=node.kind==="await using"?"using":node.kind;if(parent?.type==="ConstTag")kind="const-tag";for(let declarator of node.declarations)if(this.scopeIn?.set(declarator,scope),this.declarePattern(declarator.id,declarator,scope,kind,declarator,declarator.init??null),this.declarators.push([declarator,scope]),declarator.init)this.visit(declarator.init,declarator,scope)}visitFunction(node,scope){for(let param of node.params){if(param.type==="Identifier"&¶m.name==="this"){this.scopeIn?.set(param,scope);continue}this.declarePattern(param,node,scope,"param",node,null)}this.visit(node.body,node,scope)}declarePattern(pattern,parent,scope,kind,declaration,initial){switch(this.scopeIn?.set(pattern,scope),pattern.type){case"Identifier":this.declare(scope,pattern,pattern.name,kind,declaration,initial);break;case"ObjectPattern":for(let property of pattern.properties){if(this.scopeIn?.set(property,scope),property.type==="RestElement"){this.declarePattern(property,pattern,scope,kind,declaration,initial);continue}if(property.computed)this.visit(property.key,property,scope);else this.scopeIn?.set(property.key,scope);this.declarePattern(property.value,property,scope,kind,declaration,initial)}break;case"ArrayPattern":for(let element of pattern.elements)if(element)this.declarePattern(element,pattern,scope,kind,declaration,initial);break;case"RestElement":this.declarePattern(pattern.argument,pattern,scope,kind,declaration,initial);break;case"AssignmentPattern":this.declarePattern(pattern.left,pattern,scope,kind,declaration,initial),this.visit(pattern.right,pattern,scope);break;case"TSParameterProperty":this.declarePattern(pattern.parameter,pattern,scope,kind,declaration,initial);break;default:this.visit(pattern,parent,scope);return}if("decorators"in pattern&&pattern.decorators)for(let decorator of pattern.decorators)this.visit(decorator,pattern,scope)}visitTarget(target,parent,scope,reads){switch(this.scopeIn?.set(target,scope),target.type){case"Identifier":this.reference(target,parent,scope,reads,!0,!1);return;case"MemberExpression":{let object=target,holder=parent;while(object.type==="MemberExpression"){if(this.scopeIn?.set(object,scope),object.computed)this.visit(object.property,object,scope);else this.scopeIn?.set(object.property,scope);holder=object,object=object.object}if(object.type==="Identifier")this.scopeIn?.set(object,scope),this.reference(object,holder,scope,!0,!1,!0);else this.visit(object,holder,scope);return}case"ObjectPattern":for(let property of target.properties){if(this.scopeIn?.set(property,scope),property.type==="RestElement"){this.visitTarget(property,target,scope,!1);continue}if(property.computed)this.visit(property.key,property,scope);else this.scopeIn?.set(property.key,scope);this.visitTarget(property.value,property,scope,!1)}return;case"ArrayPattern":for(let element of target.elements)if(element)this.visitTarget(element,target,scope,!1);return;case"RestElement":this.visitTarget(target.argument,target,scope,!1);return;case"AssignmentPattern":this.visitTarget(target.left,target,scope,!1),this.visit(target.right,target,scope);return}if(target.type==="TSAsExpression"||target.type==="TSSatisfiesExpression"||target.type==="TSNonNullExpression"||target.type==="TSTypeAssertion"){this.visitTarget(target.expression,target,scope,reads);return}this.visit(target,parent,scope)}visitReactive(node,scope){let inner=this.child(scope,node,!1);this.scopeIn?.set(node.label,scope);let{body}=node;if(body.type==="ExpressionStatement"&&body.expression.type==="AssignmentExpression"){let{left,right}=body.expression;for(let id of extractIdentifiers2(left))if(!id.name.startsWith("$"))this.implicit.push([id,node,right])}this.visit(body,node,inner)}visitComponent(node,scope){if(node.type==="Component")this.referenceName(node.name,node.start+1,node,scope);let slotted=slotOf(node)!==null,defaults=this.scope(node,scope,!1),lets=slotted?scope:defaults;if(this.made.set(node,lets),node.type==="SvelteComponent")this.visit(node.expression,node,scope);for(let attribute of node.attributes)this.visit(attribute,node,attribute.type==="LetDirective"?lets:scope);this.scopeIn?.set(node.fragment,defaults);for(let child of node.fragment.nodes){let slot=slotOf(child);this.visit(child,node.fragment,slot===null?defaults:this.child(scope,child,!1))}}visitLet(node,scope){if(node.expression===null){this.declare(scope,null,node.name,"let-directive",node,null);return}let declare=(expression)=>{switch(this.scopeIn?.set(expression,scope),expression.type){case"Identifier":this.declare(scope,expression,expression.name,"let-directive",node,null);return;case"ObjectExpression":for(let property of expression.properties)if(this.scopeIn?.set(property,scope),property.type==="SpreadElement")declare(property.argument);else this.scopeIn?.set(property.key,scope),declare(property.value);return;case"ArrayExpression":for(let element of expression.elements){if(element===null)continue;if(element.type==="SpreadElement")this.scopeIn?.set(element,scope),declare(element.argument);else declare(element)}}};declare(node.expression)}visitEach(node,scope){if(this.visit(node.expression,node,scope),node.fallback)this.visit(node.fallback,node,scope);let inner=this.child(scope,node,!1);if(node.context)this.declarePattern(node.context,node,inner,"each",node,null);if(node.index!==void 0)this.declare(inner,null,node.index,"each-index",node,node);if(node.key)this.visit(node.key,node,inner);this.scopeIn?.set(node.body,inner);for(let child of node.body.nodes)this.visit(child,node.body,inner)}visitAwait(node,scope){if(this.visit(node.expression,node,scope),node.pending)this.visit(node.pending,node,scope);for(let[fragment,pattern,kind]of[[node.then,node.value,"await-value"],[node.catch,node.error,"await-error"]]){if(fragment===null)continue;this.visit(fragment,node,scope);let inner=this.made.get(fragment);if(pattern!==null&&inner!==void 0)this.declarePattern(pattern,node,inner,kind,node,null)}}declareImplicit(){for(let[id,label,right]of this.implicit)if(this.instance.get(id.name)===null)this.declare(this.instance,id,id.name,"reactive",label,right)}resolve(){let unordered=new Set;for(let reference of this.pending){let{node}=reference,declared=this.declared.get(node);if(declared!==void 0&&declared.kind!=="reactive")continue;this.references.set(node,reference);let binding=reference.scope.get(node.name);if(binding===null&&this.component){let store=this.storeOf(node.name);if(store!==!1)reference.store=!0,reference.mutates||=reference.writes,reference.reads=!0,reference.writes=!1,binding=store}if(binding!==null){reference.binding=binding;let last=binding.references.at(-1);if(last!==void 0&&last.node.start>node.start)unordered.add(binding);binding.references.push(reference)}}for(let binding of unordered)binding.references.sort((a,b)=>a.node.start-b.node.start)}storeOf(name){let cached=this.stores.get(name);if(cached!==void 0)return cached;let store=!1;if(name.length>1&&name.startsWith("$")&&!name.startsWith("$$")){let declaration=this.instance.get(name.slice(1));if(!RUNE_NAMES.has(name))store=declaration;else if(declaration!==null){let initial=declaration.initial,rune=runeOf2(initial,this.instance,null);if((rune===null||name!=="$props"&&rune==="$props")&&!(name==="$derived"&&initial?.type==="ImportDeclaration"&&initial.source.value==="svelte/store"))store=declaration}}return this.stores.set(name,store),store}findRunesAndProps(){for(let[declarator,scope]of this.declarators){let rune=runeOf2(declarator.init??null,scope,this.references);if(rune===null)continue;for(let id of extractIdentifiers2(declarator.id)){let binding=this.declared.get(id);if(binding?.declaration===declarator)binding.rune=rune}if(rune!=="$props")continue;if(declarator.id.type==="Identifier"){let binding=this.declared.get(declarator.id);if(binding)binding.initial=null;continue}if(declarator.id.type!=="ObjectPattern")continue;for(let property of declarator.id.properties){if(property.type==="RestElement"){for(let id of extractIdentifiers2(property)){let binding=this.declared.get(id);if(binding)binding.initial=null}continue}let value=property.value.type==="AssignmentPattern"?property.value.left:property.value,binding=value.type==="Identifier"?this.declared.get(value):void 0;if(binding===void 0||property.computed)continue;binding.prop=keyName(property.key),binding.initial=property.value.type==="AssignmentPattern"?unwrapBindable(property.value.right):null}}this.findLegacyProps()}findLegacyProps(){if(this.instanceProgram===null)return;for(let statement of this.instanceProgram.body){if(statement.type!=="ExportNamedDeclaration")continue;let{declaration}=statement;if(declaration?.type==="VariableDeclaration"){if(declaration.kind!=="let"&&declaration.kind!=="var")continue;for(let declarator of declaration.declarations)for(let id of extractIdentifiers2(declarator.id)){let binding=this.declared.get(id);if(binding)binding.prop=id.name}continue}if(statement.source)continue;for(let specifier of statement.specifiers){if(specifier.local.type!=="Identifier")continue;let binding=this.instance.declarations.get(specifier.local.name);if(binding?.kind!=="let"&&binding?.kind!=="var")continue;binding.prop=specifier.exported.type==="Identifier"?specifier.exported.name:String(specifier.exported.value)}}}}function isFunction2(node){return node.type==="ArrowFunctionExpression"||node.type==="FunctionExpression"||node.type==="FunctionDeclaration"}function slotOf(node){if(!ELEMENTS.has(node.type)||!("attributes"in node))return null;for(let attribute of node.attributes??[])if(attribute.type==="Attribute"&&attribute.name==="slot"&&Array.isArray(attribute.value)&&attribute.value.length===1&&attribute.value[0].type==="Text")return attribute.value[0].data;return null}function runeOf2(initial,scope,references){if(initial?.type!=="CallExpression")return null;let node=initial.callee,keypath="";while(node.type==="MemberExpression"){if(node.computed||node.property.type!=="Identifier")return null;keypath=`.${node.property.name}${keypath}`,node=node.object}if(node.type==="CallExpression"&&node.callee.type==="Identifier")keypath=`()${keypath}`,node=node.callee;if(node.type!=="Identifier")return null;if(references!==null){let reference=references.get(node);if(reference?.binding!==null||reference.store)return null}else if(scope.get(node.name)!==null)return null;return keypath=node.name+keypath,RUNES.has(keypath)?keypath:null}function unwrapBindable(node){if(node.type==="CallExpression"&&node.callee.type==="Identifier"&&node.callee.name==="$bindable"){let[argument]=node.arguments;return argument===void 0||argument.type==="SpreadElement"?null:argument}return node}function prefixLength(node){if(node.type==="UseDirective")return 4;if(node.type==="AnimateDirective")return 8;if(node.intro&&node.outro)return 11;return node.intro?3:4}function keyName(key){if(key.type==="Identifier")return key.name;return key.type==="Literal"?String(key.value):null}var ROUTE_FILES=new Set(["+page","+layout","+page.server","+layout.server","+server"]),EXTENSION=/\.[^./]+$/,SCRIPT=/\.[cm]?[jt]s$/,TS_FILE=/\.[cm]?ts$/,JSDOC_BLOCK=/\/\*\*[\s\S]*?\*\//g,JSDOC_FUNCTION=/@(type|param)\b/,JSDOC_VARIABLE=/@(type|satisfies)\b/,API_METHODS=["GET","PUT","POST","PATCH","DELETE","OPTIONS","HEAD","fallback"],PAGE_OPTIONS=[["prerender","boolean | 'auto'"],["trailingSlash","'never' | 'always' | 'ignore'"],["ssr","boolean"],["csr","boolean"]];function isKitRouteFile(basename){let name=basename.includes("@")?basename.split("@")[0]:basename.replace(EXTENSION,"");return ROUTE_FILES.has(name??"")}function isKitErrorFile(basename){return basename.replace(EXTENSION,"")==="+error"}function isHooksFile(path,basename,hooks){return(basename==="index.ts"||basename==="index.js")&&path.slice(0,-basename.length-1).endsWith(hooks)||path.replace(EXTENSION,"").endsWith(hooks)}function isParamsFile(path,basename){return path.slice(0,-basename.length-1).endsWith("src/params")&&!basename.includes(".test")&&!basename.includes(".spec")}function isKitFile(path){let posix=path.replaceAll("\\","/"),basename=posix.slice(posix.lastIndexOf("/")+1);if(!SCRIPT.test(basename))return!1;return isKitRouteFile(basename)||["src/hooks.server","src/hooks.client","src/hooks"].some((hooks)=>isHooksFile(posix,basename,hooks))||isParamsFile(posix,basename)}function kitFile(path,source,hooksModule){let posix=path.replaceAll("\\","/"),basename=posix.slice(posix.lastIndexOf("/")+1);if(!isKitFile(posix))return;let isTs=TS_FILE.test(basename),inserts=[],insert=(at,text)=>inserts.push([at,text]),exports=exportsOf(source,isTs),paramEnd=(fn)=>fn.params[0].end,returnAt=(fn)=>fn.type==="ArrowFunctionExpression"?source.lastIndexOf("=>",fn.body.start):fn.body.start,jsdocAt=(e)=>e.node.type==="FunctionDeclaration"?e.statement.start:e.node.start,jsdocParam=(e,type)=>{let p=e.node.params[0],name=p?.type==="Identifier"?p.name:"arg0";insert(jsdocAt(e),`/** @param {${type}} ${name} */ `)},wrap=(init,before,after)=>{insert(init.start,before),insert(init.end,after)},typeFunction=(name,type,returnType,asyncReturnType)=>{let fn=exports.get(name);if(fn?.type!=="function"||fn.node.params.length!==1||fn.typed)return;if(!isTs){insert(jsdocAt(fn),`/** @type {${returnType===void 0?type:`(arg0: ${type}) => ${returnType}`}} */ `);return}if(insert(paramEnd(fn.node),returnType===void 0?`: Parameters<${type}>[0]`:`: ${type}`),fn.node.returnType||!fn.node.body)return;let effective=fn.node.async&&asyncReturnType?asyncReturnType:returnType;insert(returnAt(fn.node),effective===void 0?`: ReturnType<${type}> `:`: ${effective} `)},typeVariable=(name,type)=>{let v=exports.get(name);if(v?.type!=="var"||v.typed||!v.node.init)return;if(isTs)insert(v.node.id.end,` : ${type}`);else wrap(v.node.init,`/** @type {${type}} */ (`,")")};if(isKitRouteFile(basename)){let kind=basename.includes("layout")?"Layout":"Page",loadType=`import('./$types.js').${kind}${basename.includes("server")?"Server":""}Load`,load=exports.get("load");if(load?.type==="function"&&load.node.params.length===1){if(!load.typed)if(isTs)insert(paramEnd(load.node),`: ${loadType}Event`);else jsdocParam(load,`${loadType}Event`)}else if(load?.type==="var"&&!load.typed&&load.node.init)if(isTs)wrap(load.node.init,"(",`) satisfies ${loadType}`);else wrap(load.node.init,`/** @satisfies {${loadType}} */ (`,")");let entries=exports.get("entries");if(entries?.type==="function"&&entries.node.params.length===0&&!entries.typed&&kind==="Page"){if(isTs&&!entries.node.returnType&&entries.node.body)insert(returnAt(entries.node),": ReturnType<import('./$types.js').EntryGenerator> ");else if(!isTs)insert(jsdocAt(entries),"/** @type {import('./$types.js').EntryGenerator} */ ")}let actions=exports.get("actions");if(actions?.type==="var"&&!actions.typed&&actions.node.init)if(isTs)insert(actions.node.init.end," satisfies import('./$types.js').Actions");else wrap(actions.node.init,"/** @satisfies {import('./$types.js').Actions} */ (",")");for(let[name,type]of PAGE_OPTIONS)typeVariable(name,type);for(let method of API_METHODS)typeFunction(method,"import('./$types.js').RequestEvent","Response | Promise<Response>","Promise<Response>")}else if(isHooksFile(posix,basename,"src/hooks.server"))typeFunction("handleError",`import('${hooksModule}').HandleServerError`),typeFunction("handle",`import('${hooksModule}').Handle`),typeFunction("handleFetch",`import('${hooksModule}').HandleFetch`);else if(isHooksFile(posix,basename,"src/hooks.client"))typeFunction("handleError",`import('${hooksModule}').HandleClientError`);else if(isHooksFile(posix,basename,"src/hooks"))typeFunction("reroute",`import('${hooksModule}').Reroute`);else typeFunction("match","string","boolean");inserts.sort((a,b)=>a[0]-b[0]);let out=new Output(source),at=0;for(let[pos,text]of inserts)out.copy(at,pos).raw(text),at=pos;return out.copy(at,source.length)}function exportsOf(source,isTs){let exports=new Map,previous=0;for(let statement of parseModule(source,{typescript:isTs}).body){let before=previous;if(previous=statement.end,statement.type!=="ExportNamedDeclaration")continue;let d=statement.declaration,jsdoc=(to,tags)=>!isTs&&[...source.slice(before,to).matchAll(JSDOC_BLOCK)].some((m)=>tags.test(m[0])),typedParameter=(fn)=>Boolean(paramType(fn.params[0]))||jsdoc(fn.start,JSDOC_FUNCTION);if(d?.type==="FunctionDeclaration"&&d.id)exports.set(d.id.name,{type:"function",node:d,statement,typed:typedParameter(d)});if(d?.type!=="VariableDeclaration"||d.declarations.length!==1)continue;let declarator=d.declarations[0],init=declarator.init,typed=Boolean(declarator.id.typeAnnotation)||jsdoc(declarator.id.start,JSDOC_VARIABLE)||init?.type==="TSSatisfiesExpression",fn=init?.type==="TSSatisfiesExpression"?init.expression:init;if(fn?.type==="FunctionExpression"||fn?.type==="ArrowFunctionExpression")exports.set(source.slice(declarator.id.start,declarator.id.end),{type:"function",node:fn,statement,typed:typed||typedParameter(fn)});else if(declarator.id.type==="Identifier")exports.set(declarator.id.name,{type:"var",node:declarator,statement,typed})}return exports}function paramType(p){if(!p)return;return p.type==="AssignmentPattern"?p.left.typeAnnotation:p.typeAnnotation}function kitPropType(basename,name){if(!isKitRouteFile(basename))return;let layout=basename.includes("layout");if(name==="data")return`import('./$types.js').${layout?"LayoutData":"PageData"}`;if(name==="form")return"import('./$types.js').ActionData";if(name==="snapshot")return"import('./$types.js').Snapshot";return}function kitRuneProp(basename,name){if(isKitErrorFile(basename))return name==="error"?"App.Error":void 0;if(!isKitRouteFile(basename))return;let layout=basename.includes("layout");if(name==="params")return`import('./$types.js').${layout?"LayoutProps":"PageProps"}['params']`;if(name==="data"||name==="form"&&!layout)return kitPropType(basename,name);return}var GENERIC_PARAM=/^(\w+)(?:\s+extends\s+([\s\S]+?))?(?:\s*=\s*([\s\S]+))?$/,TS_LANG=/^(ts|typescript)$/,OWNS_TEMPLATE=/@(typedef|callback)\b/,JSDOC_BLOCK2=/\/\*\*[\s\S]*?\*\//g,CALL_PARENS=/\s*\(\s*\)$/,JSDOC_LINE_START=/^\s*\/?\*+\s?/,JSDOC_END=/\s*\*\/\s*$/,USES_ALL_PROPS=/\$\$(restProps|props)\b/,TYPING_INTERFACES=new Set(["$$Props","$$Events","$$Slots"]),NUMBER_ATTRIBUTES=new Set("aria-colcount aria-colindex aria-colspan aria-level aria-posinset aria-rowcount aria-rowindex aria-rowspan aria-setsize aria-valuemax aria-valuemin aria-valuenow results span marginheight marginwidth maxlength minlength currenttime defaultplaybackrate volume high low optimum start size border cols rows colspan rowspan tabindex".split(" "));function genericParams(generics){let params=[],depth=0,current="";for(let c of generics){if("<([{".includes(c))depth++;if(">)]}".includes(c))depth--;if(c===","&&depth===0)params.push(current),current="";else current+=c}return params.push(current),params.map((p)=>p.trim()).filter(Boolean)}function jsdocTemplates(generics){return genericParams(generics).map((p)=>{let m=p.match(GENERIC_PARAM);if(!m)return` * @template ${p}`;let[,name,constraint,fallback]=m;return` * @template ${constraint?`{${constraint}} `:""}${fallback?`[${name}=${fallback}]`:name}`})}var JSDOC_TYPE=/@type\b/,TS_WRAPPER=/^TS(As|Satisfies|NonNull)Expression$/,FUNCTION=/^(FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|MethodDefinition|PropertyDefinition)$/;function typeOfDefault(init,source){if(init.type==="TSAsExpression")return source.slice(init.typeAnnotation.start,init.typeAnnotation.end);if(init.type==="Literal"){if(typeof init.value==="string")return"string";if(typeof init.value==="number")return"number";if(typeof init.value==="boolean")return"boolean";return"any"}if(init.type==="Identifier"&&init.name!=="undefined")return`typeof ${init.name}`;if(init.type==="ArrowFunctionExpression")return"Function";if(init.type==="ObjectExpression")return"Record<string, any>";if(init.type==="ArrayExpression")return"any[]";return"any"}function propsDeclaratorOf(s){if(s.type!=="VariableDeclaration")return;return s.declarations.find((d)=>d.init?.type==="CallExpression"&&d.init.callee.type==="Identifier"&&d.init.callee.name==="$props")}function parseComponent2(source){try{return{ast:parse2(source,{css:!1}),tsInJs:[]}}catch(error){if(!error.start)throw error;let ast=parse2(source,{css:!1,script:!1}),tsInJs=[];for(let script of[ast.instance,ast.module]){if(!script)continue;let{start,end}=script.content,program;try{program=parseModule(" ".repeat(start)+source.slice(start,end),{typescript:!0})}catch{throw error}program.start=start,program.end=end,script.content=program,tsInJs.push(...typescriptOnly(program))}return{ast,tsInJs}}}var TS_ONLY={TSTypeAnnotation:["TS8010","Type annotations can only be used in TypeScript files."],TSAsExpression:["TS8016","Type assertion expressions can only be used in TypeScript files."],TSSatisfiesExpression:["TS8037","Type satisfaction expressions can only be used in TypeScript files."],TSNonNullExpression:["TS8013","Non-null assertions can only be used in TypeScript files."],TSInterfaceDeclaration:["TS8006","'interface' declarations can only be used in TypeScript files."],TSEnumDeclaration:["TS8006","'enum' declarations can only be used in TypeScript files."],TSTypeAliasDeclaration:["TS8008","Type aliases can only be used in TypeScript files."],TSTypeParameterDeclaration:["TS8004","Type parameter declarations can only be used in TypeScript files."],TSTypeParameterInstantiation:["TS8011","Type arguments can only be used in TypeScript files."]};function typescriptOnly(program){let found=[];return walk2(program,{enter(node){if((node.type==="ImportDeclaration"||node.type==="ExportNamedDeclaration")&&(node.importKind==="type"||node.exportKind==="type")){let keyword=node.type==="ImportDeclaration"?"import":"export";return found.push({at:node.start,code:"TS8006",message:`'${keyword} type' declarations can only be used in TypeScript files.`}),SKIP2}let ts=TS_ONLY[node.type];if(!ts)return;let at=node.id?.start??node.typeAnnotation?.start??node.params?.[0]?.start??node.start;return found.push({at,code:ts[0],message:ts[1]}),node.type==="TSNonNullExpression"||node.type==="TSAsExpression"||node.type==="TSSatisfiesExpression"?void 0:SKIP2}}),found}function emit(source,{rewriteImport,svelte=5,basename="",checkJs=!0}={}){let{ast,tsInJs}=parseComponent2(source),scopes=analyzeScopes2(ast),out=new Output(source),{instance,module}=ast,lang=[instance,module].some((script)=>script?.attributes?.some((a)=>a.name==="lang"&&TS_LANG.test(textOf(a))))?"ts":"js",isTs=lang==="ts"||tsInJs.length>0;if(tsInJs.length>0&&!checkJs)out.raw(`// @ts-nocheck
|
|
27
|
+
If you expect this syntax to work, here are some suggestions: `+(inScript?'\nIf you use typescript with `svelte-preprocess`, did you add `lang="ts"` to your `script` tag? ':'\nIf you use less/SCSS with `svelte-preprocess`, did you add `lang="scss"`/`lang="less"` to your `style` tag? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. ')+"\nDid you setup a `svelte.config.js` or `vite.config.js`? \nSee https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info."}kept.push(d);continue}if(ignoreScript&&!d.code.startsWith("a11y"))continue;if(ignoreStyle&&(d.code==="css_unused_selector"||d.code==="css-unused-selector"))continue;if(d.code==="export_let_unused"||d.code==="unused-export-let"){let name=d.message.slice(d.message.indexOf("'")+1,d.message.lastIndexOf("'"));if(EXPORTED_TYPE(name).test(source))continue}kept.push(d)}return kept}import{existsSync as existsSync2,readFileSync as readFileSync2}from"node:fs";import{createRequire as createRequire2}from"node:module";import{basename,dirname as dirname3,join as join3}from"node:path";import{pathToFileURL}from"node:url";var VITE_CONFIGS=["js","mjs","ts","cjs","mts","cts"].map((ext)=>`vite.config.${ext}`),SVELTE_CONFIGS=["js","cjs","mjs",...process.versions.bun||process.features.typescript?["ts","mts"]:[]].map((ext)=>`svelte.config.${ext}`),SVELTE_CONFIG=/^svelte\.config\./;async function svelteConfigOf(dir,explicit){let config=(explicit?await fromFile(explicit):await fromDir(dir))??{},{preprocess}=config;return{preprocess:preprocess&&(Array.isArray(preprocess)?preprocess:[preprocess]),compilerOptions:{dev:!0,...config.compilerOptions}}}function configFingerprint(dir,explicit){let parts=[],add=(path)=>{try{parts.push(path,readFileSync2(path,"utf-8"))}catch{}};if(explicit)add(explicit);else for(let at=dir;;at=dirname3(at)){for(let name of[...VITE_CONFIGS,...SVELTE_CONFIGS]){let path=join3(at,name);if(existsSync2(path))add(path)}if(dirname3(at)===at)break}return JSON.stringify(parts)}var firstIn=(dir,names)=>names.map((name)=>join3(dir,name)).find((path)=>existsSync2(path));async function fromFile(path){if(SVELTE_CONFIG.test(basename(path)))return fromSvelteConfig(path);let result=await fromVite(dirname3(path),path);return result==="error"?void 0:result??fromSvelteConfig(path)}async function fromDir(dir){for(let at=dir;;at=dirname3(at)){let vite=firstIn(at,VITE_CONFIGS),result=vite?await fromVite(at,vite):void 0;if(result&&result!=="error")return result;let svelte=firstIn(at,SVELTE_CONFIGS);if(svelte)return fromSvelteConfig(svelte);if(result==="error"||dirname3(at)===at)return}}async function fromSvelteConfig(path){try{return(await import(pathToFileURL(path).href)).default}catch{return}}var resolving=Promise.resolve();async function fromVite(root,configFile){let vite=await importVite(root);if(!vite)return;let previous=resolving,done=()=>{};resolving=new Promise((resolve)=>{done=resolve}),await previous;let cwd=process.cwd();try{process.chdir(root)}catch{}try{let{plugins}=await vite.resolveConfig({root,configFile,logLevel:"error"},"serve"),options=(name)=>plugins.find((p)=>p.name===name)?.api?.options;return options("vite-plugin-sveltekit-setup")??options("vite-plugin-svelte:config")}catch{return"error"}finally{try{process.chdir(cwd)}catch{}done()}}async function importVite(root){try{let pkgPath=createRequire2(join3(root,"package.json")).resolve("vite/package.json"),pkg=JSON.parse(readFileSync2(pkgPath,"utf-8")),entry=importEntry(pkg.exports?.["."])??pkg.module??pkg.main;if(!entry)return;return await import(pathToFileURL(join3(dirname3(pkgPath),entry)).href)}catch{return}}function importEntry(entry){if(typeof entry==="string")return entry;if(!entry||typeof entry!=="object")return;let{import:imported,default:fallback}=entry;if(typeof imported==="string")return imported;if(imported&&typeof imported==="object"){let nested=imported.default;if(typeof nested==="string")return nested}return typeof fallback==="string"?fallback:void 0}class ScopeNode{node;parent;porous;index;declarations=new Map;constructor(node,parent,porous,index){this.node=node,this.parent=parent,this.porous=porous,this.index=index}get(name){for(let scope=this;scope;scope=scope.parent){let binding=scope.declarations.get(name);if(binding!==void 0)return binding}return null}}class BindingNode{name;kind;node;declaration;initial;scope;references=[];rune=null;prop=null;constructor(name,kind,node,declaration,initial,scope){this.name=name,this.kind=kind,this.node=node,this.declaration=declaration,this.initial=initial,this.scope=scope}}class ReferenceNode{node;parent;scope;binding=null;reads;writes;mutates;store=!1;constructor(node,parent,scope,reads,writes,mutates){this.node=node,this.parent=parent,this.scope=scope,this.reads=reads,this.writes=writes,this.mutates=mutates}}var keysByType2=Object.assign(Object.create(null),valueVisitorKeys2),ELEMENTS=new Set(["SvelteElement","RegularElement","SvelteFragment","Component","SvelteComponent","SvelteSelf","SlotElement"]),NO_BINDINGS=new Map;function analyzeScopes2(ast){return new Analysis(ast,!1)}class Analysis{module;instance;instanceProgram=null;component;ast;scopes=[];scopeIn;synthetic=new Map;recorded;made=new Map;declared=new Map;references=new Map;pending=[];declarators=[];implicit=[];stores=new Map;constructor(ast,record){if(this.ast=ast,this.scopeIn=record?new Map:null,ast.type==="Program")this.component=!1,this.module=this.scope(ast,null,!1),this.instance=this.module,this.made.set(ast,this.module),this.visit(ast,null,this.module);else{this.component=!0;let module=ast.module?.content??null,instance=ast.instance?.content??null;this.module=this.scope(module,null,!1),this.instance=this.scope(instance,this.module,!1),this.instanceProgram=instance,this.scopeIn?.set(ast,this.module);for(let[script,scope]of[[ast.module,this.module],[ast.instance,this.instance]]){if(script===void 0)continue;this.scopeIn?.set(script,scope),this.made.set(script.content,scope);for(let attribute of script.attributes)this.visit(attribute,script,scope);this.visit(script.content,script,scope)}this.visit(ast.fragment,ast,this.instance)}this.declareImplicit(),this.resolve(),this.findRunesAndProps()}scopeOf(node){let synthetic=this.synthetic.get(node);if(synthetic!==void 0)return synthetic;if(this.scopeIn!==null)return this.scopeIn.get(node)??null;this.recorded??=new Analysis(this.ast,!0);let recorded=this.recorded.scopeIn?.get(node);return recorded===void 0?null:this.scopes[recorded.index]}scope(node,parent,porous){let scope=new ScopeNode(node,parent,porous,this.scopes.length);return this.scopes.push(scope),scope}bindingOf(node){return this.declared.get(node)??this.references.get(node)?.binding??null}referenceOf(node){return this.references.get(node)??null}declaredIn(node){return this.made.get(node)?.declarations??NO_BINDINGS}child(scope,node,porous){let made=this.scope(node,scope,porous);return this.made.set(node,made),made}declare(scope,node,name,kind,declaration,initial){let target=scope;if(kind==="var")while(target.porous&&target.parent!==null)target=target.parent;let existing=target.declarations.get(name);if(existing!==void 0&&existing.declaration.type!=="TSDeclareFunction"){if(node!==null)this.declared.set(node,existing);return}let binding=new BindingNode(name,kind,node,declaration,initial,target);if(target.declarations.set(name,binding),node!==null)this.declared.set(node,binding)}reference(node,parent,scope,reads,writes,mutates){this.pending.push(new ReferenceNode(node,parent,scope,reads,writes,mutates))}referenceName(name,start,parent,scope){let root=name.split(".")[0],node={type:"Identifier",name:root,start,end:start+root.length};this.synthetic.set(node,scope),this.reference(node,parent,scope,!0,!1,!1)}visit(node,parent,scope){switch(this.scopeIn?.set(node,scope),node.type){case"Identifier":if(parent!==null&&isReference2(node,parent))this.reference(node,parent,scope,!0,!1,!1);this.visitFields(node,scope);return;case"ImportDeclaration":for(let specifier of node.specifiers){if(this.scopeIn?.set(specifier,scope),this.scopeIn?.set(specifier.local,scope),specifier.type==="ImportSpecifier")this.scopeIn?.set(specifier.imported,scope);this.declare(scope,specifier.local,specifier.local.name,"import",specifier,node)}this.visit(node.source,node,scope);for(let attribute of node.attributes??[])this.visit(attribute,node,scope);return;case"ExportNamedDeclaration":if(node.declaration)this.visit(node.declaration,node,scope);for(let specifier of node.specifiers)if(this.scopeIn?.set(specifier,scope),this.scopeIn?.set(specifier.local,scope),this.scopeIn?.set(specifier.exported,scope),!node.source&&specifier.local.type==="Identifier")this.reference(specifier.local,specifier,scope,!0,!1,!1);if(node.source)this.visit(node.source,node,scope);for(let attribute of node.attributes??[])this.visit(attribute,node,scope);return;case"VariableDeclaration":this.visitDeclaration(node,parent,scope);return;case"FunctionDeclaration":if(node.id)this.scopeIn?.set(node.id,scope),this.declare(scope,node.id,node.id.name,"function",node,node);this.visitFunction(node,this.child(scope,node,!0));return;case"FunctionExpression":{let inner=this.child(scope,node,!0);if(node.id)this.scopeIn?.set(node.id,inner),this.declare(inner,node.id,node.id.name,"function",node,node);this.visitFunction(node,inner);return}case"ArrowFunctionExpression":this.visitFunction(node,this.child(scope,node,!0));return;case"ClassDeclaration":case"ClassExpression":{let inner=scope;if(node.id){if(node.type==="ClassExpression")inner=this.child(scope,node,!1);this.scopeIn?.set(node.id,inner),this.declare(inner,node.id,node.id.name,"class",node,node)}for(let decorator of node.decorators??[])this.visit(decorator,node,scope);if(node.superClass)this.visit(node.superClass,node,inner);this.visit(node.body,node,inner);return}case"BlockStatement":this.visitFields(node,this.child(scope,node,!(parent!==null&&isFunction2(parent)&&parent.body===node)));return;case"StaticBlock":this.visitFields(node,this.child(scope,node,!1));return;case"ForStatement":case"SwitchStatement":this.visitFields(node,this.child(scope,node,!0));return;case"ForInStatement":case"ForOfStatement":{let inner=this.child(scope,node,!0);if(node.left.type==="VariableDeclaration")this.visit(node.left,node,inner);else this.visitTarget(node.left,node,inner,!1);this.visit(node.right,node,inner),this.visit(node.body,node,inner);return}case"CatchClause":{if(!node.param)break;let inner=this.child(scope,node,!0);this.declarePattern(node.param,node,inner,"catch",node,null),this.visit(node.body,node,inner);return}case"AssignmentExpression":this.visitTarget(node.left,node,scope,node.operator!=="="),this.visit(node.right,node,scope);return;case"UpdateExpression":this.visitTarget(node.argument,node,scope,!0);return;case"LabeledStatement":if(parent===this.instanceProgram&&node.label.name==="$"){this.visitReactive(node,scope);return}break;case"TSEnumDeclaration":{this.scopeIn?.set(node.id,scope),this.declare(scope,node.id,node.id.name,"enum",node,node);let inner=this.child(scope,node,!1);for(let member of node.members)if(this.scopeIn?.set(member,inner),this.scopeIn?.set(member.id,inner),member.id.type==="Identifier")this.declare(inner,member.id,member.id.name,"enum-member",member,member.initializer??null);for(let member of node.members)if(member.initializer)this.visit(member.initializer,member,inner);return}case"TSModuleDeclaration":if(this.scopeIn?.set(node.id,scope),node.id.type==="Identifier"&&!node.global)this.declare(scope,node.id,node.id.name,"namespace",node,node);if(node.body)this.visit(node.body,node,this.child(scope,node,!1));return;case"TSImportEqualsDeclaration":{this.scopeIn?.set(node.id,scope),this.declare(scope,node.id,node.id.name,"import",node,node.moduleReference);let name=node.moduleReference;while(name.type==="TSQualifiedName")this.scopeIn?.set(name,scope),this.scopeIn?.set(name.right,scope),name=name.left;if(name.type==="Identifier")this.scopeIn?.set(name,scope),this.reference(name,node,scope,!0,!1,!1);else this.visit(name,node,scope);return}case"TSDeclareFunction":if(node.id){if(this.scopeIn?.set(node.id,scope),!scope.declarations.has(node.id.name))this.declare(scope,node.id,node.id.name,"function",node,node)}return;case"Fragment":this.visitFields(node,this.child(scope,node,!1));return;case"RegularElement":case"SvelteElement":case"SlotElement":case"SvelteFragment":this.visitFields(node,this.child(scope,node,!1));return;case"Component":case"SvelteComponent":case"SvelteSelf":this.visitComponent(node,scope);return;case"LetDirective":this.visitLet(node,scope);return;case"EachBlock":this.visitEach(node,scope);return;case"AwaitBlock":this.visitAwait(node,scope);return;case"SnippetBlock":{this.scopeIn?.set(node.expression,scope);let{name}=node.expression;this.declare(scope,node.expression,name,"snippet",node,node);let inner=this.child(scope,node,!1);for(let parameter of node.parameters??[])this.declarePattern(parameter,node,inner,"snippet-param",node,null);this.visit(node.body,node,inner);return}case"BindDirective":if(node.expression.type==="SequenceExpression")break;this.visitTarget(node.expression,node,scope,!0);return;case"TransitionDirective":case"AnimateDirective":case"UseDirective":{this.referenceName(node.name,node.start+prefixLength(node),node,scope);break}case"StyleDirective":if(node.value===!0)this.referenceName(node.name,node.start+6,node,scope);break}this.visitFields(node,scope)}visitFields(node,scope){let keys=keysByType2[node.type];if(keys===void 0)throw Error(`unknown node type: ${node.type}`);let fields=fieldsOf(node);for(let k=0;k<keys.length;k++){let value=fields[keys[k]];if(Array.isArray(value))for(let i=0;i<value.length;i++){let child=value[i];if(isNode(child))this.visit(child,node,scope)}else if(isNode(value))this.visit(value,node,scope)}}visitDeclaration(node,parent,scope){let kind=node.kind==="await using"?"using":node.kind;if(parent?.type==="ConstTag")kind="const-tag";for(let declarator of node.declarations)if(this.scopeIn?.set(declarator,scope),this.declarePattern(declarator.id,declarator,scope,kind,declarator,declarator.init??null),this.declarators.push([declarator,scope]),declarator.init)this.visit(declarator.init,declarator,scope)}visitFunction(node,scope){for(let param of node.params){if(param.type==="Identifier"&¶m.name==="this"){this.scopeIn?.set(param,scope);continue}this.declarePattern(param,node,scope,"param",node,null)}this.visit(node.body,node,scope)}declarePattern(pattern,parent,scope,kind,declaration,initial){switch(this.scopeIn?.set(pattern,scope),pattern.type){case"Identifier":this.declare(scope,pattern,pattern.name,kind,declaration,initial);break;case"ObjectPattern":for(let property of pattern.properties){if(this.scopeIn?.set(property,scope),property.type==="RestElement"){this.declarePattern(property,pattern,scope,kind,declaration,initial);continue}if(property.computed)this.visit(property.key,property,scope);else this.scopeIn?.set(property.key,scope);this.declarePattern(property.value,property,scope,kind,declaration,initial)}break;case"ArrayPattern":for(let element of pattern.elements)if(element)this.declarePattern(element,pattern,scope,kind,declaration,initial);break;case"RestElement":this.declarePattern(pattern.argument,pattern,scope,kind,declaration,initial);break;case"AssignmentPattern":this.declarePattern(pattern.left,pattern,scope,kind,declaration,initial),this.visit(pattern.right,pattern,scope);break;case"TSParameterProperty":this.declarePattern(pattern.parameter,pattern,scope,kind,declaration,initial);break;default:this.visit(pattern,parent,scope);return}if("decorators"in pattern&&pattern.decorators)for(let decorator of pattern.decorators)this.visit(decorator,pattern,scope)}visitTarget(target,parent,scope,reads){switch(this.scopeIn?.set(target,scope),target.type){case"Identifier":this.reference(target,parent,scope,reads,!0,!1);return;case"MemberExpression":{let object=target,holder=parent;while(object.type==="MemberExpression"){if(this.scopeIn?.set(object,scope),object.computed)this.visit(object.property,object,scope);else this.scopeIn?.set(object.property,scope);holder=object,object=object.object}if(object.type==="Identifier")this.scopeIn?.set(object,scope),this.reference(object,holder,scope,!0,!1,!0);else this.visit(object,holder,scope);return}case"ObjectPattern":for(let property of target.properties){if(this.scopeIn?.set(property,scope),property.type==="RestElement"){this.visitTarget(property,target,scope,!1);continue}if(property.computed)this.visit(property.key,property,scope);else this.scopeIn?.set(property.key,scope);this.visitTarget(property.value,property,scope,!1)}return;case"ArrayPattern":for(let element of target.elements)if(element)this.visitTarget(element,target,scope,!1);return;case"RestElement":this.visitTarget(target.argument,target,scope,!1);return;case"AssignmentPattern":this.visitTarget(target.left,target,scope,!1),this.visit(target.right,target,scope);return}if(target.type==="TSAsExpression"||target.type==="TSSatisfiesExpression"||target.type==="TSNonNullExpression"||target.type==="TSTypeAssertion"){this.visitTarget(target.expression,target,scope,reads);return}this.visit(target,parent,scope)}visitReactive(node,scope){let inner=this.child(scope,node,!1);this.scopeIn?.set(node.label,scope);let{body}=node;if(body.type==="ExpressionStatement"&&body.expression.type==="AssignmentExpression"){let{left,right}=body.expression;for(let id of extractIdentifiers2(left))if(!id.name.startsWith("$"))this.implicit.push([id,node,right])}this.visit(body,node,inner)}visitComponent(node,scope){if(node.type==="Component")this.referenceName(node.name,node.start+1,node,scope);let slotted=slotOf(node)!==null,defaults=this.scope(node,scope,!1),lets=slotted?scope:defaults;if(this.made.set(node,lets),node.type==="SvelteComponent")this.visit(node.expression,node,scope);for(let attribute of node.attributes)this.visit(attribute,node,attribute.type==="LetDirective"?lets:scope);this.scopeIn?.set(node.fragment,defaults);for(let child of node.fragment.nodes){let slot=slotOf(child);this.visit(child,node.fragment,slot===null?defaults:this.child(scope,child,!1))}}visitLet(node,scope){if(node.expression===null){this.declare(scope,null,node.name,"let-directive",node,null);return}let declare=(expression)=>{switch(this.scopeIn?.set(expression,scope),expression.type){case"Identifier":this.declare(scope,expression,expression.name,"let-directive",node,null);return;case"ObjectExpression":for(let property of expression.properties)if(this.scopeIn?.set(property,scope),property.type==="SpreadElement")declare(property.argument);else this.scopeIn?.set(property.key,scope),declare(property.value);return;case"ArrayExpression":for(let element of expression.elements){if(element===null)continue;if(element.type==="SpreadElement")this.scopeIn?.set(element,scope),declare(element.argument);else declare(element)}}};declare(node.expression)}visitEach(node,scope){if(this.visit(node.expression,node,scope),node.fallback)this.visit(node.fallback,node,scope);let inner=this.child(scope,node,!1);if(node.context)this.declarePattern(node.context,node,inner,"each",node,null);if(node.index!==void 0)this.declare(inner,null,node.index,"each-index",node,node);if(node.key)this.visit(node.key,node,inner);this.scopeIn?.set(node.body,inner);for(let child of node.body.nodes)this.visit(child,node.body,inner)}visitAwait(node,scope){if(this.visit(node.expression,node,scope),node.pending)this.visit(node.pending,node,scope);for(let[fragment,pattern,kind]of[[node.then,node.value,"await-value"],[node.catch,node.error,"await-error"]]){if(fragment===null)continue;this.visit(fragment,node,scope);let inner=this.made.get(fragment);if(pattern!==null&&inner!==void 0)this.declarePattern(pattern,node,inner,kind,node,null)}}declareImplicit(){for(let[id,label,right]of this.implicit)if(this.instance.get(id.name)===null)this.declare(this.instance,id,id.name,"reactive",label,right)}resolve(){let unordered=new Set;for(let reference of this.pending){let{node}=reference,declared=this.declared.get(node);if(declared!==void 0&&declared.kind!=="reactive")continue;this.references.set(node,reference);let binding=reference.scope.get(node.name);if(binding===null&&this.component){let store=this.storeOf(node.name);if(store!==!1)reference.store=!0,reference.mutates||=reference.writes,reference.reads=!0,reference.writes=!1,binding=store}if(binding!==null){reference.binding=binding;let last=binding.references.at(-1);if(last!==void 0&&last.node.start>node.start)unordered.add(binding);binding.references.push(reference)}}for(let binding of unordered)binding.references.sort((a,b)=>a.node.start-b.node.start)}storeOf(name){let cached=this.stores.get(name);if(cached!==void 0)return cached;let store=!1;if(name.length>1&&name.startsWith("$")&&!name.startsWith("$$")){let declaration=this.instance.get(name.slice(1));if(!RUNE_NAMES.has(name))store=declaration;else if(declaration!==null){let initial=declaration.initial,rune=runeOf2(initial,this.instance,null);if((rune===null||name!=="$props"&&rune==="$props")&&!(name==="$derived"&&initial?.type==="ImportDeclaration"&&initial.source.value==="svelte/store"))store=declaration}}return this.stores.set(name,store),store}findRunesAndProps(){for(let[declarator,scope]of this.declarators){let rune=runeOf2(declarator.init??null,scope,this.references);if(rune===null)continue;for(let id of extractIdentifiers2(declarator.id)){let binding=this.declared.get(id);if(binding?.declaration===declarator)binding.rune=rune}if(rune!=="$props")continue;if(declarator.id.type==="Identifier"){let binding=this.declared.get(declarator.id);if(binding)binding.initial=null;continue}if(declarator.id.type!=="ObjectPattern")continue;for(let property of declarator.id.properties){if(property.type==="RestElement"){for(let id of extractIdentifiers2(property)){let binding=this.declared.get(id);if(binding)binding.initial=null}continue}let value=property.value.type==="AssignmentPattern"?property.value.left:property.value,binding=value.type==="Identifier"?this.declared.get(value):void 0;if(binding===void 0||property.computed)continue;binding.prop=keyName(property.key),binding.initial=property.value.type==="AssignmentPattern"?unwrapBindable(property.value.right):null}}this.findLegacyProps()}findLegacyProps(){if(this.instanceProgram===null)return;for(let statement of this.instanceProgram.body){if(statement.type!=="ExportNamedDeclaration")continue;let{declaration}=statement;if(declaration?.type==="VariableDeclaration"){if(declaration.kind!=="let"&&declaration.kind!=="var")continue;for(let declarator of declaration.declarations)for(let id of extractIdentifiers2(declarator.id)){let binding=this.declared.get(id);if(binding)binding.prop=id.name}continue}if(statement.source)continue;for(let specifier of statement.specifiers){if(specifier.local.type!=="Identifier")continue;let binding=this.instance.declarations.get(specifier.local.name);if(binding?.kind!=="let"&&binding?.kind!=="var")continue;binding.prop=specifier.exported.type==="Identifier"?specifier.exported.name:String(specifier.exported.value)}}}}function isFunction2(node){return node.type==="ArrowFunctionExpression"||node.type==="FunctionExpression"||node.type==="FunctionDeclaration"}function slotOf(node){if(!ELEMENTS.has(node.type)||!("attributes"in node))return null;for(let attribute of node.attributes??[])if(attribute.type==="Attribute"&&attribute.name==="slot"&&Array.isArray(attribute.value)&&attribute.value.length===1&&attribute.value[0].type==="Text")return attribute.value[0].data;return null}function runeOf2(initial,scope,references){if(initial?.type!=="CallExpression")return null;let node=initial.callee,keypath="";while(node.type==="MemberExpression"){if(node.computed||node.property.type!=="Identifier")return null;keypath=`.${node.property.name}${keypath}`,node=node.object}if(node.type==="CallExpression"&&node.callee.type==="Identifier")keypath=`()${keypath}`,node=node.callee;if(node.type!=="Identifier")return null;if(references!==null){let reference=references.get(node);if(reference?.binding!==null||reference.store)return null}else if(scope.get(node.name)!==null)return null;return keypath=node.name+keypath,RUNES.has(keypath)?keypath:null}function unwrapBindable(node){if(node.type==="CallExpression"&&node.callee.type==="Identifier"&&node.callee.name==="$bindable"){let[argument]=node.arguments;return argument===void 0||argument.type==="SpreadElement"?null:argument}return node}function prefixLength(node){if(node.type==="UseDirective")return 4;if(node.type==="AnimateDirective")return 8;if(node.intro&&node.outro)return 11;return node.intro?3:4}function keyName(key){if(key.type==="Identifier")return key.name;return key.type==="Literal"?String(key.value):null}var ROUTE_FILES=new Set(["+page","+layout","+page.server","+layout.server","+server"]),EXTENSION=/\.[^./]+$/,SCRIPT=/\.[cm]?[jt]s$/,TS_FILE=/\.[cm]?ts$/,JSDOC_BLOCK=/\/\*\*[\s\S]*?\*\//g,JSDOC_FUNCTION=/@(type|param)\b/,JSDOC_VARIABLE=/@(type|satisfies)\b/,API_METHODS=["GET","PUT","POST","PATCH","DELETE","OPTIONS","HEAD","fallback"],PAGE_OPTIONS=[["prerender","boolean | 'auto'"],["trailingSlash","'never' | 'always' | 'ignore'"],["ssr","boolean"],["csr","boolean"]];function isKitRouteFile(basename){let name=basename.includes("@")?basename.split("@")[0]:basename.replace(EXTENSION,"");return ROUTE_FILES.has(name??"")}function isKitErrorFile(basename){return basename.replace(EXTENSION,"")==="+error"}function isHooksFile(path,basename,hooks){return(basename==="index.ts"||basename==="index.js")&&path.slice(0,-basename.length-1).endsWith(hooks)||path.replace(EXTENSION,"").endsWith(hooks)}function isParamsFile(path,basename){return path.slice(0,-basename.length-1).endsWith("src/params")&&!basename.includes(".test")&&!basename.includes(".spec")}function isKitFile(path){let posix=path.replaceAll("\\","/"),basename=posix.slice(posix.lastIndexOf("/")+1);if(!SCRIPT.test(basename))return!1;return isKitRouteFile(basename)||["src/hooks.server","src/hooks.client","src/hooks"].some((hooks)=>isHooksFile(posix,basename,hooks))||isParamsFile(posix,basename)}function kitFile(path,source,hooksModule){let posix=path.replaceAll("\\","/"),basename=posix.slice(posix.lastIndexOf("/")+1);if(!isKitFile(posix))return;let isTs=TS_FILE.test(basename),inserts=[],insert=(at,text)=>inserts.push([at,text]),exports=exportsOf(source,isTs),paramEnd=(fn)=>fn.params[0].end,returnAt=(fn)=>fn.type==="ArrowFunctionExpression"?source.lastIndexOf("=>",fn.body.start):fn.body.start,jsdocAt=(e)=>e.node.type==="FunctionDeclaration"?e.statement.start:e.node.start,jsdocParam=(e,type)=>{let p=e.node.params[0],name=p?.type==="Identifier"?p.name:"arg0";insert(jsdocAt(e),`/** @param {${type}} ${name} */ `)},wrap=(init,before,after)=>{insert(init.start,before),insert(init.end,after)},typeFunction=(name,type,returnType,asyncReturnType)=>{let fn=exports.get(name);if(fn?.type!=="function"||fn.node.params.length!==1||fn.typed)return;if(!isTs){insert(jsdocAt(fn),`/** @type {${returnType===void 0?type:`(arg0: ${type}) => ${returnType}`}} */ `);return}if(insert(paramEnd(fn.node),returnType===void 0?`: Parameters<${type}>[0]`:`: ${type}`),fn.node.returnType||!fn.node.body)return;let effective=fn.node.async&&asyncReturnType?asyncReturnType:returnType;insert(returnAt(fn.node),effective===void 0?`: ReturnType<${type}> `:`: ${effective} `)},typeVariable=(name,type)=>{let v=exports.get(name);if(v?.type!=="var"||v.typed||!v.node.init)return;if(isTs)insert(v.node.id.end,` : ${type}`);else wrap(v.node.init,`/** @type {${type}} */ (`,")")};if(isKitRouteFile(basename)){let kind=basename.includes("layout")?"Layout":"Page",loadType=`import('./$types.js').${kind}${basename.includes("server")?"Server":""}Load`,load=exports.get("load");if(load?.type==="function"&&load.node.params.length===1){if(!load.typed)if(isTs)insert(paramEnd(load.node),`: ${loadType}Event`);else jsdocParam(load,`${loadType}Event`)}else if(load?.type==="var"&&!load.typed&&load.node.init)if(isTs)wrap(load.node.init,"(",`) satisfies ${loadType}`);else wrap(load.node.init,`/** @satisfies {${loadType}} */ (`,")");let entries=exports.get("entries");if(entries?.type==="function"&&entries.node.params.length===0&&!entries.typed&&kind==="Page"){if(isTs&&!entries.node.returnType&&entries.node.body)insert(returnAt(entries.node),": ReturnType<import('./$types.js').EntryGenerator> ");else if(!isTs)insert(jsdocAt(entries),"/** @type {import('./$types.js').EntryGenerator} */ ")}let actions=exports.get("actions");if(actions?.type==="var"&&!actions.typed&&actions.node.init)if(isTs)insert(actions.node.init.end," satisfies import('./$types.js').Actions");else wrap(actions.node.init,"/** @satisfies {import('./$types.js').Actions} */ (",")");for(let[name,type]of PAGE_OPTIONS)typeVariable(name,type);for(let method of API_METHODS)typeFunction(method,"import('./$types.js').RequestEvent","Response | Promise<Response>","Promise<Response>")}else if(isHooksFile(posix,basename,"src/hooks.server"))typeFunction("handleError",`import('${hooksModule}').HandleServerError`),typeFunction("handle",`import('${hooksModule}').Handle`),typeFunction("handleFetch",`import('${hooksModule}').HandleFetch`);else if(isHooksFile(posix,basename,"src/hooks.client"))typeFunction("handleError",`import('${hooksModule}').HandleClientError`);else if(isHooksFile(posix,basename,"src/hooks"))typeFunction("reroute",`import('${hooksModule}').Reroute`);else typeFunction("match","string","boolean");inserts.sort((a,b)=>a[0]-b[0]);let out=new Output(source),at=0;for(let[pos,text]of inserts)out.copy(at,pos).raw(text),at=pos;return out.copy(at,source.length)}function exportsOf(source,isTs){let exports=new Map,previous=0;for(let statement of parseModule(source,{typescript:isTs}).body){let before=previous;if(previous=statement.end,statement.type!=="ExportNamedDeclaration")continue;let d=statement.declaration,jsdoc=(to,tags)=>!isTs&&[...source.slice(before,to).matchAll(JSDOC_BLOCK)].some((m)=>tags.test(m[0])),typedParameter=(fn)=>Boolean(paramType(fn.params[0]))||jsdoc(fn.start,JSDOC_FUNCTION);if(d?.type==="FunctionDeclaration"&&d.id)exports.set(d.id.name,{type:"function",node:d,statement,typed:typedParameter(d)});if(d?.type!=="VariableDeclaration"||d.declarations.length!==1)continue;let declarator=d.declarations[0],init=declarator.init,typed=Boolean(declarator.id.typeAnnotation)||jsdoc(declarator.id.start,JSDOC_VARIABLE)||init?.type==="TSSatisfiesExpression",fn=init?.type==="TSSatisfiesExpression"?init.expression:init;if(fn?.type==="FunctionExpression"||fn?.type==="ArrowFunctionExpression")exports.set(source.slice(declarator.id.start,declarator.id.end),{type:"function",node:fn,statement,typed:typed||typedParameter(fn)});else if(declarator.id.type==="Identifier")exports.set(declarator.id.name,{type:"var",node:declarator,statement,typed})}return exports}function paramType(p){if(!p)return;return p.type==="AssignmentPattern"?p.left.typeAnnotation:p.typeAnnotation}function kitPropType(basename,name){if(!isKitRouteFile(basename))return;let layout=basename.includes("layout");if(name==="data")return`import('./$types.js').${layout?"LayoutData":"PageData"}`;if(name==="form")return"import('./$types.js').ActionData";if(name==="snapshot")return"import('./$types.js').Snapshot";return}function kitRuneProp(basename,name){if(isKitErrorFile(basename))return name==="error"?"App.Error":void 0;if(!isKitRouteFile(basename))return;let layout=basename.includes("layout");if(name==="params")return`import('./$types.js').${layout?"LayoutProps":"PageProps"}['params']`;if(name==="data"||name==="form"&&!layout)return kitPropType(basename,name);return}var GENERIC_PARAM=/^(\w+)(?:\s+extends\s+([\s\S]+?))?(?:\s*=\s*([\s\S]+))?$/,TS_LANG=/^(ts|typescript)$/,IDENTIFIER=/^[A-Za-z_$][\w$]*$/,OWNS_TEMPLATE=/@(typedef|callback)\b/,JSDOC_BLOCK2=/\/\*\*[\s\S]*?\*\//g,CALL_PARENS=/\s*\(\s*\)$/,JSDOC_LINE_START=/^\s*\/?\*+\s?/,JSDOC_END=/\s*\*\/\s*$/,USES_ALL_PROPS=/\$\$(restProps|props)\b/,WHITESPACE=/\s/,TYPING_INTERFACES=new Set(["$$Props","$$Events","$$Slots"]),NUMBER_ATTRIBUTES=new Set("aria-colcount aria-colindex aria-colspan aria-level aria-posinset aria-rowcount aria-rowindex aria-rowspan aria-setsize aria-valuemax aria-valuemin aria-valuenow results span marginheight marginwidth maxlength minlength currenttime defaultplaybackrate volume high low optimum start size border cols rows colspan rowspan tabindex".split(" ")),keyOf=(name)=>IDENTIFIER.test(name)?name:JSON.stringify(name);function genericParams(generics){let params=[],depth=0,current="";for(let c of generics){if("<([{".includes(c))depth++;if(">)]}".includes(c))depth--;if(c===","&&depth===0)params.push(current),current="";else current+=c}return params.push(current),params.map((p)=>p.trim()).filter(Boolean)}function jsdocTemplates(generics){return genericParams(generics).map((p)=>{let m=p.match(GENERIC_PARAM);if(!m)return` * @template ${p}`;let[,name,constraint,fallback]=m;return` * @template ${constraint?`{${constraint}} `:""}${fallback?`[${name}=${fallback}]`:name}`})}var JSDOC_TYPE=/@type\b/,TS_WRAPPER=/^TS(As|Satisfies|NonNull)Expression$/,FUNCTION=/^(FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|MethodDefinition|PropertyDefinition)$/;function typeOfDefault(init,source){if(init.type==="TSAsExpression")return source.slice(init.typeAnnotation.start,init.typeAnnotation.end);if(init.type==="Literal"){if(typeof init.value==="string")return"string";if(typeof init.value==="number")return"number";if(typeof init.value==="boolean")return"boolean";return"any"}if(init.type==="Identifier"&&init.name!=="undefined")return`typeof ${init.name}`;if(init.type==="ArrowFunctionExpression")return"Function";if(init.type==="ObjectExpression")return"Record<string, any>";if(init.type==="ArrayExpression")return"any[]";return"any"}function propsDeclaratorOf(s){if(s.type!=="VariableDeclaration")return;return s.declarations.find((d)=>d.init?.type==="CallExpression"&&d.init.callee.type==="Identifier"&&d.init.callee.name==="$props")}function parseComponent2(source){let parsed=parseComponentSource(source);return includeLeadingCasts(parsed.ast.fragment,source),parsed}var LEADING_CAST=/\/\*\*(?:(?!\*\/)[\s\S])*@(?:type|satisfies)\b(?:(?!\*\/)[\s\S])*\*\/\s*$/,TEMPLATE_EXPRESSIONS=["expression","test"];function includeLeadingCasts(node,source){if(!node||typeof node!=="object")return;if(Array.isArray(node)){for(let child of node)includeLeadingCasts(child,source);return}for(let[key,value]of Object.entries(node)){if(!value||typeof value!=="object"||key==="parent")continue;if(TEMPLATE_EXPRESSIONS.includes(key)){let expression=value;if(typeof expression.start==="number"&&source[expression.start]==="("){let cast=LEADING_CAST.exec(source.slice(Math.max(0,expression.start-1000),expression.start));if(cast)expression.start-=cast[0].length}continue}includeLeadingCasts(value,source)}}function parseComponentSource(source){try{return{ast:parse2(source,{css:!1}),tsInJs:[]}}catch(error){if(!error.start)throw error;let ast=parse2(source,{css:!1,script:!1}),tsInJs=[];for(let script of[ast.instance,ast.module]){if(!script)continue;let{start,end}=script.content,program;try{program=parseModule(" ".repeat(start)+source.slice(start,end),{typescript:!0})}catch{throw error}program.start=start,program.end=end,script.content=program,tsInJs.push(...typescriptOnly(program))}return{ast,tsInJs}}}var TS_ONLY={TSTypeAnnotation:["TS8010","Type annotations can only be used in TypeScript files."],TSAsExpression:["TS8016","Type assertion expressions can only be used in TypeScript files."],TSSatisfiesExpression:["TS8037","Type satisfaction expressions can only be used in TypeScript files."],TSNonNullExpression:["TS8013","Non-null assertions can only be used in TypeScript files."],TSInterfaceDeclaration:["TS8006","'interface' declarations can only be used in TypeScript files."],TSEnumDeclaration:["TS8006","'enum' declarations can only be used in TypeScript files."],TSTypeAliasDeclaration:["TS8008","Type aliases can only be used in TypeScript files."],TSTypeParameterDeclaration:["TS8004","Type parameter declarations can only be used in TypeScript files."],TSTypeParameterInstantiation:["TS8011","Type arguments can only be used in TypeScript files."]};function typescriptOnly(program){let found=[];return walk2(program,{enter(node){if((node.type==="ImportDeclaration"||node.type==="ExportNamedDeclaration")&&(node.importKind==="type"||node.exportKind==="type")){let keyword=node.type==="ImportDeclaration"?"import":"export";return found.push({at:node.start,code:"TS8006",message:`'${keyword} type' declarations can only be used in TypeScript files.`}),SKIP2}let ts=TS_ONLY[node.type];if(!ts)return;let at=node.id?.start??node.typeAnnotation?.start??node.params?.[0]?.start??node.start;return found.push({at,code:ts[0],message:ts[1]}),node.type==="TSNonNullExpression"||node.type==="TSAsExpression"||node.type==="TSSatisfiesExpression"?void 0:SKIP2}}),found}function emit(source,{rewriteImport,svelte=5,basename="",checkJs=!0}={}){let{ast,tsInJs}=parseComponent2(source),scopes=analyzeScopes2(ast),out=new Output(source),{instance,module}=ast,lang=[instance,module].some((script)=>script?.attributes?.some((a)=>a.name==="lang"&&TS_LANG.test(textOf(a))))?"ts":"js",isTs=lang==="ts"||tsInJs.length>0;if(tsInJs.length>0&&!checkJs)out.raw(`// @ts-nocheck
|
|
28
28
|
`);let uid=0,reactive=[],transitions=[],slots=new Map,forwarded=new Map,runes=svelte>=5&&isRunesMode(source),bindingChecks=[];function textOf(attribute){return(Array.isArray(attribute.value)?attribute.value[0]:attribute.value)?.data??""}let idsOf=(pattern,ids=[])=>{if(!pattern)return ids;if(pattern.type==="Identifier")ids.push(pattern.name);else if(pattern.type==="ObjectPattern")for(let p of pattern.properties)idsOf(p.type==="RestElement"?p.argument:p.value,ids);else if(pattern.type==="ArrayPattern")for(let e of pattern.elements)idsOf(e,ids);else if(pattern.type==="AssignmentPattern")idsOf(pattern.left,ids);else if(pattern.type==="RestElement")idsOf(pattern.argument,ids);return ids},copyStatement=(s)=>{let spec=s.source?.value,next=typeof spec==="string"?rewriteImport?.(spec):void 0;if(next===void 0)return out.copy(s.start,s.end);return out.copy(s.start,s.source.start),out.from(s.source.start,()=>out.raw(JSON.stringify(next))),out.copy(s.source.end,s.end)};if(module){let at=module.content.start;for(let s of module.content.body)out.copy(at,s.start),copyStatement(s),at=s.end;out.copy(at,module.content.end).raw(`
|
|
29
29
|
`)}let body=instance?.content.body??[],topLevelAwait=!1;if(svelte>=5)for(let s of body)walk2(s,{enter(node){if(node.type==="AwaitExpression")topLevelAwait=!0;return FUNCTION.test(node.type)?SKIP2:void 0}});for(let s of body)if(s.type==="ImportDeclaration")copyStatement(s).raw(`
|
|
30
|
-
`);let typed=new Set;for(let s of body){let d=s.type==="ExportNamedDeclaration"?s.declaration:s;if((d?.type==="TSInterfaceDeclaration"||d?.type==="TSTypeAliasDeclaration")&&TYPING_INTERFACES.has(d.id?.name))typed.add(d.id.name)}let strictEvents=typed.has("$$Events")||instance?.attributes?.some((a)=>a.name==="strictEvents"),templateBlocks=[],typeParams=[],genericAliases=new Set;if(instance&&isTs)for(let s of body){let ref=s.type==="TSTypeAliasDeclaration"?s.typeAnnotation:null;if(ref?.type!=="TSTypeReference"||ref.typeName?.name!=="$$Generic")continue;genericAliases.add(s);let arg=(ref.typeArguments??ref.typeParameters)?.params?.[0];typeParams.push(arg?`${s.id.name} extends ${source.slice(arg.start,arg.end)}`:s.id.name)}let generics="",templateDoc="";if(instance){let tags=[],attr=instance.attributes.find((a)=>a.name==="generics");if(attr&&isTs)typeParams.unshift(...genericParams(textOf(attr)));else if(attr)tags.push(...jsdocTemplates(textOf(attr)));let text=source.slice(instance.content.start,instance.content.end);for(let m of text.matchAll(JSDOC_BLOCK2)){let start=instance.content.start+(m.index??0);if(OWNS_TEMPLATE.test(m[0])){templateBlocks.push([start,start+m[0].length]),out.copy(start,start+m[0].length).raw(`
|
|
30
|
+
`);let typed=new Set,propsDeclaredAt=0;for(let s of body){let d=s.type==="ExportNamedDeclaration"?s.declaration:s;if((d?.type==="TSInterfaceDeclaration"||d?.type==="TSTypeAliasDeclaration")&&TYPING_INTERFACES.has(d.id?.name)){if(typed.add(d.id.name),d.id.name==="$$Props")propsDeclaredAt=d.id.start}}let strictEvents=typed.has("$$Events")||instance?.attributes?.some((a)=>a.name==="strictEvents"),templateBlocks=[],typeParams=[],genericAliases=new Set;if(instance&&isTs)for(let s of body){let ref=s.type==="TSTypeAliasDeclaration"?s.typeAnnotation:null;if(ref?.type!=="TSTypeReference"||ref.typeName?.name!=="$$Generic")continue;genericAliases.add(s);let arg=(ref.typeArguments??ref.typeParameters)?.params?.[0];typeParams.push(arg?`${s.id.name} extends ${source.slice(arg.start,arg.end)}`:s.id.name)}let generics="",templateDoc="";if(instance){let tags=[],attr=instance.attributes.find((a)=>a.name==="generics");if(attr&&isTs)typeParams.unshift(...genericParams(textOf(attr)));else if(attr)tags.push(...jsdocTemplates(textOf(attr)));let text=source.slice(instance.content.start,instance.content.end);for(let m of text.matchAll(JSDOC_BLOCK2)){let start=instance.content.start+(m.index??0);if(OWNS_TEMPLATE.test(m[0])){templateBlocks.push([start,start+m[0].length]),out.copy(start,start+m[0].length).raw(`
|
|
31
31
|
;
|
|
32
32
|
`);continue}if(!m[0].includes("@template"))continue;templateBlocks.push([start,start+m[0].length]);for(let line of m[0].split(`
|
|
33
33
|
`))if(line.includes("@template"))tags.push(` * ${line.replace(JSDOC_LINE_START,"").replace(JSDOC_END,"")}`)}if(tags.length>0&&!isTs)templateDoc=`/**
|
|
34
34
|
${tags.join(`
|
|
35
35
|
`)}
|
|
36
36
|
*/
|
|
37
|
-
`}if(typeParams.length>0)generics=`<${typeParams.join(", ")}>`;let storeAfter=new Map,storeAtStart=[],seenStores=new Set,storeUses=new Map;for(let scope of[scopes.instance,scopes.module])for(let b of scope?.declarations?.values()??[])for(let r of b.references){if(!r.store)continue;if(storeUses.set(b.name,[...storeUses.get(b.name)??[],r.node.start]),seenStores.has(b.name))continue;seenStores.add(b.name);let decl=b.declaration,top=scope===scopes.instance&&b.kind!=="import"?body.find((s)=>decl&&s.start<=decl.start&&decl.end<=s.end):void 0;if(top)storeAfter.set(top.end,[...storeAfter.get(top.end)??[],b.name]);else storeAtStart.push(b.name)}let storeDeclarations=[],declareStore=(name)=>{let start=out.code.length;out.raw(`let $${name} = __sveltets_2_store_get(${name});`),storeDeclarations.push({start,end:out.code.length,name,uses:storeUses.get(name)??[]})},attrValue=(value)=>{if(value===!0)return out.raw("true");let parts=Array.isArray(value)?value:[value];if(parts.length===1&&parts[0].type==="ExpressionTag")return out.raw("(").copy(parts[0].expression.start,parts[0].expression.end).raw(")");if(parts.every((p)=>p.type==="Text"))return out.from(parts[0]?.start??0,()=>out.raw(JSON.stringify(parts.map((p)=>p.data).join(""))));out.raw("`");for(let p of parts)if(p.type==="Text")out.raw(p.data.replace(/[`\\]|\$\{/g,(c)=>`\\${c}`));else out.raw("${").copy(p.expression.start,p.expression.end).raw("}");return out.raw("`")},key=(attribute,name)=>out.from(attribute.start,()=>out.raw(JSON.stringify(name))).raw(":"),nameAt=(attribute)=>source.indexOf(":",attribute.start)+1,expression=(node)=>out.raw("(").copy(node.start,node.end).raw(")"),directives=(node,elementId,tag)=>{for(let a of node.attributes??[])if(a.type==="BindDirective"){if(a.name==="this")out.copy(a.expression.start,a.expression.end).raw(` = ${elementId};`);else if(!isGetSet(a.expression))widen(a.expression)}else if(a.type==="ClassDirective")expression(a.expression).raw(";");else if(a.type==="StyleDirective")if(a.value===!0){let at=nameAt(a);out.copy(at,at+a.name.length).raw(";")}else attrValue(a.value).raw(";");else if(a.type==="AnimateDirective")
|
|
38
|
-
`)},slotOf=(slotted)=>(slotted.attributes??[]).find((a)=>a.type==="Attribute"&&a.name==="slot"),lets=(node)=>(node.attributes??[]).filter((a)=>a.type==="LetDirective"),destructureLets=(letDirectives,from)=>{if(letDirectives.length===0)return;out.raw("const {");for(let d of letDirectives){let at=nameAt(d);if(d.expression)out.raw(`${d.name}:`).copy(d.expression.start,d.expression.end);else out.copy(at,at+d.name.length);out.raw(",")}out.raw(
|
|
39
|
-
`)},child=(node,inComponent=!1)=>{switch(node.type){case"Text":case"Comment":case"DebugTag":case"ConstTag":return;case"ExpressionTag":case"HtmlTag":return expression(node.expression).raw(";");case"RenderTag":return out.raw(";__sveltets_2_ensureSnippet(").copy(node.expression.start,node.expression.end).raw(");");case"RegularElement":return element(node,()=>out.raw(JSON.stringify(node.name)),JSON.stringify(node.name),inComponent);case"SvelteElement":return element(node,()=>expression(node.tag),"__sveltets_2_any(0)",inComponent);case"SvelteWindow":case"SvelteBody":case"SvelteDocument":return element(node,()=>out.raw(JSON.stringify(node.name)),"__sveltets_2_any(0)",!1);case"SvelteBoundary":return element(node,()=>out.raw('"svelte:boundary"'),"__sveltets_2_any(0)",!1);case"SvelteHead":case"SvelteFragment":case"TitleElement":return fragment(node.fragment);case"SvelteOptions":return;case"Component":return component(node,()=>{let at=node.start+1;out.copy(at,at+node.name.length)},inComponent);case"SvelteComponent":return component(node,()=>expression(node.expression),inComponent);case"SvelteSelf":return component(node,()=>out.raw("__sveltets_2_any(0)"));case"SlotElement":{let nameAttr=(node.attributes??[]).find((a)=>a.type==="Attribute"&&a.name==="name");slots.set(nameAttr?textOf(nameAttr):"default",node.attributes??[]),
|
|
37
|
+
`}if(typeParams.length>0)generics=`<${typeParams.join(", ")}>`;let storeAfter=new Map,storeAtStart=[],seenStores=new Set,storeUses=new Map;for(let scope of[scopes.instance,scopes.module])for(let b of scope?.declarations?.values()??[])for(let r of b.references){if(!r.store)continue;if(storeUses.set(b.name,[...storeUses.get(b.name)??[],r.node.start]),seenStores.has(b.name))continue;seenStores.add(b.name);let decl=b.declaration,top=scope===scopes.instance&&b.kind!=="import"?body.find((s)=>decl&&s.start<=decl.start&&decl.end<=s.end):void 0;if(top)storeAfter.set(top.end,[...storeAfter.get(top.end)??[],b.name]);else storeAtStart.push(b.name)}let storeDeclarations=[],declareStore=(name)=>{let start=out.code.length;out.raw(`let $${name} = __sveltets_2_store_get(${name});`),storeDeclarations.push({start,end:out.code.length,name,uses:storeUses.get(name)??[]})},attrValue=(value)=>{if(value===!0)return out.raw("true");let parts=Array.isArray(value)?value:[value];if(parts.length===1&&parts[0].type==="ExpressionTag")return out.raw("(").copy(parts[0].expression.start,parts[0].expression.end).raw(")");if(parts.every((p)=>p.type==="Text"))return out.from(parts[0]?.start??0,()=>out.raw(JSON.stringify(parts.map((p)=>p.data).join(""))));out.raw("`");for(let p of parts)if(p.type==="Text")out.raw(p.data.replace(/[`\\]|\$\{/g,(c)=>`\\${c}`));else out.raw("${").copy(p.expression.start,p.expression.end).raw("}");return out.raw("`")},key=(attribute,name)=>out.from(attribute.start,()=>out.raw(JSON.stringify(name))).raw(":"),nameAt=(attribute)=>source.indexOf(":",attribute.start)+1,expression=(node)=>out.raw("(").copy(node.start,node.end).raw(")"),directiveCall=(a,tag,extra="")=>{let at=nameAt(a);out.copy(at,at+a.name.length);let equals=a.expression?source.lastIndexOf("=",a.expression.start):at+a.name.length-1;if(out.from(equals,()=>out.raw(`(svelteHTML.mapElementTag(${tag})${extra}`)),a.expression)out.raw(",").copy(a.expression.start,a.expression.end);out.raw(")")},directives=(node,elementId,tag)=>{for(let a of node.attributes??[])if(a.type==="BindDirective"){if(a.name==="this")out.copy(a.expression.start,a.expression.end).raw(` = ${elementId};`);else if(!isGetSet(a.expression))widen(a.expression)}else if(a.type==="ClassDirective")expression(a.expression).raw(";");else if(a.type==="StyleDirective")if(a.value===!0){let at=nameAt(a);out.copy(at,at+a.name.length).raw(";")}else attrValue(a.value).raw(";");else if(a.type==="AnimateDirective")out.raw("__sveltets_2_ensureAnimation("),directiveCall(a,tag,",__sveltets_2_AnimationMove"),out.raw(");");else if(a.type==="TransitionDirective")transitions.push([a.start,a.end]),out.raw("__sveltets_2_ensureTransition("),directiveCall(a,tag),out.raw(");")},shorthandOf=(a)=>{let value=Array.isArray(a.value)?a.value[0]:a.value;return source[a.start]==="{"&&value?.type==="ExpressionTag"&&value.expression.type==="Identifier"?value.expression:void 0},elementAttribute=(a,inComponent)=>{if(a.type==="Attribute"){if(inComponent&&a.name==="slot")return;let shorthand=shorthandOf(a);if(shorthand){out.copy(shorthand.start,shorthand.end).raw(",");return}if(a.name.startsWith("data-")){out.raw("...__sveltets_2_empty({"),key(a,a.name),attrValue(a.value).raw("}),");return}key(a,a.name);let only=Array.isArray(a.value)&&a.value.length===1?a.value[0]:null;if(a.value===!0&&a.name==="popover")out.raw('""');else if(only?.type==="Text"&&NUMBER_ATTRIBUTES.has(a.name.toLowerCase())&&only.data.trim()!==""&&!Number.isNaN(Number(only.data)))out.copy(only.start,only.end);else attrValue(a.value);out.raw(",")}else if(a.type==="SpreadAttribute")out.raw("...").copy(a.expression.start,a.expression.end).raw(",");else if(a.type==="OnDirective"){if(key(a,`on:${a.name}`),a.expression)expression(a.expression);else out.raw("undefined"),forwarded.set(a.name,`__sveltets_2_mapElementEvent(${JSON.stringify(a.name)})`);out.raw(",")}else if(a.type==="BindDirective"&&a.name!=="this")key(a,`bind:${a.name}`),bound(a.expression).raw(",");else if(a.type==="AttachTag")attach(a)},widen=(e)=>{let target=e;while(TS_WRAPPER.test(target.type))target=target.expression;out.raw("() => ").copy(target.start,target.end).raw(" = __sveltets_2_any(null);")},isGetSet=(e)=>e.type==="SequenceExpression"&&e.expressions.length===2,bound=(e)=>{if(!isGetSet(e))return expression(e);let[get,set]=e.expressions;return out.raw("__sveltets_2_get_set_binding(").copy(get.start,get.end).raw(","),out.copy(set.start,set.end).raw(")")},attach=(a)=>out.raw('[Symbol("@attach")]:').copy(a.expression.start,a.expression.end).raw(","),attributeKey=(a)=>{if(a.type==="Attribute")return a.name;if(a.type==="OnDirective")return`on:${a.name}`;if(a.type==="BindDirective")return`bind:${a.name}`;return null},element=(node,tag,tagText,inComponent)=>{let id=`$$_el${uid++}`,boundary=node.type==="SvelteBoundary",objectAt=node.type==="RegularElement"?node.start+node.name.length:node.tag?.end??node.start+1,seen=new Set,repeats=[];out.raw("{");let actions=[];for(let a of node.attributes??[]){if(a.type!=="UseDirective")continue;let action=`$$_action${uid++}`;actions.push(action),out.raw(`const ${action} = __sveltets_2_ensureAction(`),directiveCall(a,tagText),out.raw(");")}out.raw(`const ${id} = `),out.from(node.type==="SvelteElement"?node.start:node.start+1,()=>{if(out.raw("svelteHTML.createElement("),tag(),out.raw(", "),actions.length>0)out.raw(`__sveltets_2_union(${actions.join(",")}), `);out.from(objectAt,()=>out.raw("{"));for(let a of node.attributes??[]){let k=attributeKey(a);if(k!==null&&seen.has(k))repeats.push(a);else{if(k!==null)seen.add(k);elementAttribute(a,inComponent)}}if(boundary){for(let c of node.fragment.nodes)if(c.type==="SnippetBlock")snippetProp(c)}out.raw("})")}),out.raw(";");for(let a of repeats)out.from(objectAt,()=>{out.raw("svelteHTML.createElement("),tag(),out.raw(", {"),elementAttribute(a,inComponent),out.raw("});")});directives(node,id,tagText),fragment(node.fragment,!boundary),out.raw(`}
|
|
38
|
+
`)},slotOf=(slotted)=>(slotted.attributes??[]).find((a)=>a.type==="Attribute"&&a.name==="slot"),lets=(node)=>(node.attributes??[]).filter((a)=>a.type==="LetDirective"),destructureLets=(letDirectives,from,slotted)=>{let slotEnd=slotted?slotOf(slotted).end-1:1/0;if(letDirectives.length===0){if(!slotted)return;let binds=(slotted.attributes??[]).some((a)=>a.type==="BindDirective");out.from(binds?slotEnd:slotted.start,()=>out.raw(from)).raw(";");return}out.raw("const {");for(let d of letDirectives){let at=nameAt(d);if(d.expression)out.raw(`${d.name}:`).copy(d.expression.start,d.expression.end);else out.copy(at,at+d.name.length);out.raw(",")}out.raw("} = ");let last=letDirectives.at(-1).end,after=WHITESPACE.test(source[last]??"")?last:last-1;out.from(Math.min(after,slotEnd),()=>out.raw(from)),out.raw(";")},component=(node,ctor,inComponent=!1)=>{let id=`$$_c${uid++}`,children=node.fragment?.nodes??[],snippets=children.filter((c)=>c.type==="SnippetBlock"),named=children.filter((c)=>c.type!=="SnippetBlock"&&slotOf(c)),rest=children.filter((c)=>c.type!=="SnippetBlock"&&!slotOf(c)),hasDefault=rest.some((c)=>c.type!=="Text"||c.data.trim())&&!snippets.some((s)=>s.expression.name==="children");out.raw(`{ const ${id}C = __sveltets_2_ensureComponent(`),ctor(),out.raw("); "),out.from(node.start+1,()=>{if(out.raw(`const ${id} = new ${id}C({ target: __sveltets_2_any(), props: {`),hasDefault&&svelte>=5)out.raw("children:() => { return __sveltets_2_any(0); },");for(let a of node.attributes??[])if(a.type==="Attribute"){if(inComponent&&a.name==="slot")continue;let shorthand=shorthandOf(a);if(shorthand)out.copy(shorthand.start,shorthand.end).raw(",");else key(a,a.name),attrValue(a.value).raw(",")}else if(a.type==="SpreadAttribute")out.raw("...").copy(a.expression.start,a.expression.end).raw(",");else if(a.type==="BindDirective"&&a.name!=="this")if(out.from(nameAt(a),()=>out.raw(JSON.stringify(a.name))).raw(":"),isGetSet(a.expression))bound(a.expression).raw(",");else out.copy(a.expression.start,a.expression.end).raw(",");else if(a.type==="AttachTag")attach(a);for(let s of snippets)snippetProp(s);out.raw("} });")});for(let a of node.attributes??[])if(a.type==="BindDirective")if(a.name==="this")out.copy(a.expression.start,a.expression.end).raw(` = ${id};`);else{if(!isGetSet(a.expression))widen(a.expression);if(svelte>=5){let start=out.code.length;out.raw(`${id}.$$bindings`),bindingChecks.push({start,end:out.code.length,from:a.start,to:a.end}),out.raw(` = ${JSON.stringify(a.name)};`)}}else if(a.type==="OnDirective"&&!a.expression){if(!forwarded.has(a.name))forwarded.set(a.name,"__sveltets_2_any(0)")}else if(a.type==="OnDirective"&&a.expression)out.from(nameAt(a),()=>out.raw(`${id}.$on(${JSON.stringify(a.name)}, `)),out.copy(a.expression.start,a.expression.end).raw(");");out.raw("{"),destructureLets(lets(node),`${id}.$$slot_def.default`),consts(rest);for(let c of rest)child(c,!0);out.raw("}");for(let c of named){if(out.raw("{"),destructureLets(lets(c),`${id}.$$slot_def[${JSON.stringify(textOf(slotOf(c)))}]`,c),c.type==="SvelteFragment")fragment(c.fragment);else child(c,!0);out.raw("}")}out.raw(`}
|
|
39
|
+
`)},child=(node,inComponent=!1)=>{switch(node.type){case"Text":case"Comment":case"DebugTag":case"ConstTag":return;case"ExpressionTag":case"HtmlTag":return expression(node.expression).raw(";");case"RenderTag":return out.raw(";__sveltets_2_ensureSnippet(").copy(node.expression.start,node.expression.end).raw(");");case"RegularElement":return element(node,()=>out.raw(JSON.stringify(node.name)),JSON.stringify(node.name),inComponent);case"SvelteElement":return element(node,()=>{out.raw("__sveltets_2_elementTag("),expression(node.tag),out.raw(")")},"__sveltets_2_any(0)",inComponent);case"SvelteWindow":case"SvelteBody":case"SvelteDocument":return element(node,()=>out.raw(JSON.stringify(node.name)),"__sveltets_2_any(0)",!1);case"SvelteBoundary":return element(node,()=>out.raw('"svelte:boundary"'),"__sveltets_2_any(0)",!1);case"SvelteHead":case"SvelteFragment":case"TitleElement":return fragment(node.fragment);case"SvelteOptions":return;case"Component":return component(node,()=>{let at=node.start+1;out.copy(at,at+node.name.length)},inComponent);case"SvelteComponent":return component(node,()=>expression(node.expression),inComponent);case"SvelteSelf":return component(node,()=>out.raw("__sveltets_2_any(0)"));case"SlotElement":{let nameAttr=(node.attributes??[]).find((a)=>a.type==="Attribute"&&a.name==="name");if(slots.set(nameAttr?textOf(nameAttr):"default",node.attributes??[]),typed.has("$$Slots")){let name=JSON.stringify(nameAttr?textOf(nameAttr):"default");if(out.raw("__sveltets_createSlot("),nameAttr?.value?.[0])out.from(nameAttr.value[0].start,()=>out.raw(name));else out.raw(name);out.raw(", {")}else out.raw("({");for(let a of node.attributes??[])if(a.type==="Attribute"&&a.name!=="name")key(a,a.name),attrValue(a.value).raw(",");else if(a.type==="SpreadAttribute")out.raw("...").copy(a.expression.start,a.expression.end).raw(",");return out.raw("});{"),fragment(node.fragment),out.raw(`}
|
|
40
40
|
`)}case"IfBlock":if(out.raw("if ("),expression(node.test).raw(") {"),fragment(node.consequent),out.raw("}"),node.alternate)out.raw(" else {"),fragment(node.alternate),out.raw("}");return out.raw(`
|
|
41
41
|
`);case"EachBlock":if(out.raw("for (let "),node.context)out.copy(node.context.start,node.context.end);else out.raw("$$_item");if(out.raw(" of __sveltets_2_ensureArray("),out.copy(node.expression.start,node.expression.end).raw(")) {"),node.index)out.raw(`let ${node.index} = 1;`);if(node.key)expression(node.key).raw(";");if(fragment(node.body),out.raw("}"),node.fallback)out.raw("{"),fragment(node.fallback),out.raw("}");return out.raw(`
|
|
42
42
|
`);case"AwaitBlock":{let p=`$$_p${uid++}`;if(out.raw(`{ const ${p} = `),expression(node.expression).raw(";{"),fragment(node.pending),out.raw("}{ const "),node.value)out.copy(node.value.start,node.value.end);else out.raw("$$_v");if(out.raw(` = await ${p};`),fragment(node.then),out.raw("}{ const "),node.error)out.copy(node.error.start,node.error.end);else out.raw("$$_e");return out.raw(" = __sveltets_2_any(0);"),fragment(node.catch),out.raw(`}}
|
|
43
43
|
`)}case"KeyBlock":return expression(node.expression).raw(";"),fragment(node.fragment);default:if(node.fragment)fragment(node.fragment)}};function hoistable(snippets){let names=new Set(snippets.map((s)=>s.expression.name)),reads=new Map;for(let s of snippets){let read={instance:!1,snippets:new Set};walk2(s,{enter(node,parent){if(node===s.expression)return;let name;if(node.type==="Component")name=node.name.split(".")[0];else if(node.type==="Identifier"&&isReference2(node,parent))name=node.name;if(!name)return;let b=node.type==="Identifier"?scopes.bindingOf(node):void 0;if(b&&b.scope!==scopes.instance&&b.scope!==scopes.module)return;if(b?.scope===scopes.instance||scopes.instance?.get(name))read.instance=!0;else if(names.has(name))read.snippets.add(name)}}),reads.set(s,read)}let kept=new Set(snippets.filter((s)=>!reads.get(s)?.instance));for(let changed=!0;changed;){changed=!1;let keptNames=new Set([...kept].map((s)=>s.expression.name));for(let s of kept)if([...reads.get(s)?.snippets??[]].some((n)=>!keptNames.has(n)))kept.delete(s),changed=!0}return kept}function parameters(node){for(let[i,p]of node.parameters.entries()){if(i)out.raw(",");out.copy(p.start,p.end)}}function snippetProp(node){out.from(node.expression.start,()=>out.raw(JSON.stringify(node.expression.name))),out.raw(":("),parameters(node),out.raw(") => { async () => {"),fragment(node.body),out.raw("}; return __sveltets_2_any(0); },")}function snippet(node){if(out.raw("const ").copy(node.expression.start,node.expression.end),isTs){if(out.raw(" = "),node.typeParams){let at=source.indexOf("<",node.expression.end);out.from(at,()=>out.raw(`<${node.typeParams}>`))}out.raw("(")}else out.raw(" = /** @returns {ReturnType<import('svelte').Snippet>} */ (");parameters(node),out.raw(`)${isTs?": ReturnType<import('svelte').Snippet>":""} => { async () => {`),fragment(node.body),out.raw(`}; return __sveltets_2_any(0); };
|
|
44
44
|
`)}function fragment(f,hoist=f!==ast.fragment){if(!f)return;if(hoist){for(let n of f.nodes)if(n.type==="SnippetBlock")snippet(n)}consts(f.nodes);for(let n of f.nodes)if(n.type!=="SnippetBlock")child(n)}function consts(nodes){for(let n of nodes)if(n.type==="ConstTag"){let d=n.declaration;out.raw("const ").copy(d.declarations[0].start,d.declarations[0].end).raw(";")}}let rootSnippets=ast.fragment.nodes.filter((n)=>n.type==="SnippetBlock"),moduleSnippets=module?hoistable(rootSnippets):new Set;for(let n of rootSnippets)if(moduleSnippets.has(n))snippet(n);out.raw(templateDoc);let async=topLevelAwait?"async ":"";out.raw(runes?`${async}function $$render${generics}() { `:`${async}function $$render${generics}() { let $$props = __sveltets_2_allPropsType(); let $$restProps = __sveltets_2_restPropsType(); let $$slots = __sveltets_2_any(0); ${typed.has("$$Slots")?"const __sveltets_createSlot = __sveltets_2_createCreateSlot<$$Slots>(); ":""}`);for(let name of storeAtStart)declareStore(name);out.raw(`
|
|
45
|
-
`);for(let n of rootSnippets)if(!moduleSnippets.has(n))snippet(n);let props=[],exportsOf=[],runesProps,bindings=[],kitRoute=isKitRouteFile(basename),kitLayout=kitRoute&&basename.includes("layout"),kitError=isKitErrorFile(basename),propsRune=(s,d,gapStart)=>{let pattern=d.id,locals=[],inferred=[],withUnknown=pattern.type!=="ObjectPattern";for(let p of pattern.type==="ObjectPattern"?pattern.properties:[]){let value=p.value?.type==="AssignmentPattern"?p.value.left:p.value;if(p.type==="RestElement"||p.computed||p.key.type!=="Identifier"||value.type!=="Identifier"){withUnknown=!0;continue}let name=p.key.name,init=p.value.type==="AssignmentPattern"?p.value.right:void 0,call=init?.type==="TSAsExpression"?init.expression:init,bindable=call?.type==="CallExpression"&&call.callee.name==="$bindable";if(bindable)bindings.push(name),locals.push(value.name),init=call.arguments[0];if(kitRoute||kitError){let type=kitRuneProp(basename,name);if(type)inferred.push(`${name}: ${type}`)}else if(bindable&&!init)inferred.push(`${name}?: any`);else inferred.push(init?`${name}?: ${typeOfDefault(init,source)}`:`${name}: any`)}if(kitLayout)inferred.push("children: import('svelte').Snippet");let propsStr=inferred.length>0?`{ ${inferred.join(", ")} }${withUnknown?" & Record<string, any>":""}`:"Record<string, any>",declared=inferred.length>0||withUnknown&&pattern.type==="ObjectPattern",annotation=pattern.typeAnnotation?.typeAnnotation;if(isTs&&annotation)if(annotation.type==="TSTypeReference")runesProps=`{} as any as ${source.slice(annotation.start,annotation.end)}`,out.copy(s.start,s.end);else out.raw(";type $$ComponentProps = ").copy(annotation.start,annotation.end),out.raw(";").copy(s.start,annotation.start).raw("$$ComponentProps"),out.copy(annotation.end,s.end),runesProps="{} as any as $$ComponentProps";else if(isTs){if(declared)out.raw(`;type $$ComponentProps = ${propsStr};`),out.copy(s.start,pattern.end).raw(": $$ComponentProps"),out.copy(pattern.end,s.end);else out.copy(s.start,s.end);runesProps=declared?"{} as any as $$ComponentProps":"{} as any"}else{let comment=[...source.slice(gapStart,pattern.start).matchAll(JSDOC_BLOCK2)].map((m)=>m[0]).findLast((c)=>JSDOC_TYPE.test(c));if(comment||!declared)out.copy(s.start,s.end);else out.copy(s.start,pattern.start),out.raw(`/** @typedef {${propsStr}} $$ComponentProps *//** @type {$$ComponentProps} */`),out.copy(pattern.start,s.end);runesProps=`${comment??`/** @type {${declared?"$$ComponentProps":"any"}} */`}({})`}if(locals.length>0)out.raw(`;${locals.map((l)=>`${l};`).join("")}`)},copyGap=(from,to)=>{let at=from;for(let[s,e]of templateBlocks){if(e<=at||s>=to)continue;out.copy(at,s),at=e}out.copy(at,to)};if(instance){let cursor=instance.content.start;for(let s of body){let gapStart=cursor;if(copyGap(cursor,s.start),cursor=s.end,s.type==="ImportDeclaration"||genericAliases.has(s))continue;if(s.type==="ExportNamedDeclaration"){let d=s.declaration;if(d){let at=d.start;if(d.type==="VariableDeclaration")for(let decl of d.declarations){let type=decl.id.type==="Identifier"&&!decl.id.typeAnnotation&&(d.kind==="let"||decl.id.name==="snapshot")?kitPropType(basename,decl.id.name):void 0,jsdoc=!isTs&&[...source.slice(gapStart,decl.id.start).matchAll(JSDOC_BLOCK2)].some((m)=>JSDOC_TYPE.test(m[0]));if(!type||jsdoc)continue;if(isTs)out.copy(at,decl.id.end).raw(`: ${type}`),at=decl.id.end;else out.copy(at,decl.id.start).raw(`/** @type {${type}} */ `),at=decl.id.start}if(out.copy(at,d.end),d.type==="VariableDeclaration"&&d.kind==="let")for(let decl of d.declarations){let widens=decl.id.type==="Identifier"&&(!decl.init||decl.id.typeAnnotation||[...source.slice(gapStart,decl.id.start).matchAll(JSDOC_BLOCK2)].some((m)=>JSDOC_TYPE.test(m[0]))||decl.init.type==="Literal"&&typeof decl.init.value==="boolean");for(let name of idsOf(decl.id))if(props.push({name,local:name,optional:decl.init!=null,type:decl.id.type==="Identifier"&&decl.id.typeAnnotation?.typeAnnotation?source.slice(decl.id.typeAnnotation.typeAnnotation.start,decl.id.typeAnnotation.typeAnnotation.end):void 0}),widens)out.raw(`;${name} = __sveltets_2_any(${decl.init?name:0});`)}else for(let name of d.declarations?d.declarations.flatMap((x)=>idsOf(x.id)):[d.id?.name])if(name)exportsOf.push([name,name])}else for(let spec of s.specifiers){let binding=scopes.instance.get(spec.local.name);if(runes)exportsOf.push([spec.exported.name,spec.local.name]);else if(binding?.kind==="let"||binding?.kind==="prop")props.push({name:spec.exported.name,local:spec.local.name,optional:!0})}}else if(s.type==="LabeledStatement"&&s.label.name==="$"){reactive.push([s.start,s.end]);let e=s.body.type==="ExpressionStatement"?s.body.expression:null;if(e?.type==="AssignmentExpression"&&e.operator==="="&&idsOf(e.left).some((n)=>
|
|
45
|
+
`);for(let n of rootSnippets)if(!moduleSnippets.has(n))snippet(n);let props=[],exportsOf=[],runesProps,bindings=[],kitRoute=isKitRouteFile(basename),kitLayout=kitRoute&&basename.includes("layout"),kitError=isKitErrorFile(basename),propsRune=(s,d,gapStart)=>{let pattern=d.id,locals=[],inferred=[],withUnknown=pattern.type!=="ObjectPattern";for(let p of pattern.type==="ObjectPattern"?pattern.properties:[]){let value=p.value?.type==="AssignmentPattern"?p.value.left:p.value;if(p.type==="RestElement"||p.computed||p.key.type!=="Identifier"||value.type!=="Identifier"){withUnknown=!0;continue}let name=p.key.name,init=p.value.type==="AssignmentPattern"?p.value.right:void 0,call=init?.type==="TSAsExpression"?init.expression:init,bindable=call?.type==="CallExpression"&&call.callee.name==="$bindable";if(bindable)bindings.push(name),locals.push(value.name),init=call.arguments[0];if(kitRoute||kitError){let type=kitRuneProp(basename,name);if(type)inferred.push(`${name}: ${type}`)}else if(bindable&&!init)inferred.push(`${name}?: any`);else inferred.push(init?`${name}?: ${typeOfDefault(init,source)}`:`${name}: any`)}if(kitLayout)inferred.push("children: import('svelte').Snippet");let propsStr=inferred.length>0?`{ ${inferred.join(", ")} }${withUnknown?" & Record<string, any>":""}`:"Record<string, any>",declared=inferred.length>0||withUnknown&&pattern.type==="ObjectPattern",annotation=pattern.typeAnnotation?.typeAnnotation;if(isTs&&annotation)if(annotation.type==="TSTypeReference")runesProps=`{} as any as ${source.slice(annotation.start,annotation.end)}`,out.copy(s.start,s.end);else out.raw(";type $$ComponentProps = ").copy(annotation.start,annotation.end),out.raw(";").copy(s.start,annotation.start).raw("$$ComponentProps"),out.copy(annotation.end,s.end),runesProps="{} as any as $$ComponentProps";else if(isTs){if(declared)out.raw(`;type $$ComponentProps = ${propsStr};`),out.copy(s.start,pattern.end).raw(": $$ComponentProps"),out.copy(pattern.end,s.end);else out.copy(s.start,s.end);runesProps=declared?"{} as any as $$ComponentProps":"{} as any"}else{let comment=[...source.slice(gapStart,pattern.start).matchAll(JSDOC_BLOCK2)].map((m)=>m[0]).findLast((c)=>JSDOC_TYPE.test(c));if(comment||!declared)out.copy(s.start,s.end);else out.copy(s.start,pattern.start),out.raw(`/** @typedef {${propsStr}} $$ComponentProps *//** @type {$$ComponentProps} */`),out.copy(pattern.start,s.end);runesProps=`${comment??`/** @type {${declared?"$$ComponentProps":"any"}} */`}({})`}if(locals.length>0)out.raw(`;${locals.map((l)=>`${l};`).join("")}`)},annotationOf=(name)=>{for(let s of body){let d=s.type==="ExportNamedDeclaration"?s.declaration:s;if(d?.type!=="VariableDeclaration")continue;for(let decl of d.declarations){let annotation=decl.id.type==="Identifier"&&decl.id.name===name?decl.id.typeAnnotation?.typeAnnotation:void 0;if(annotation)return source.slice(annotation.start,annotation.end)}}return},copyGap=(from,to)=>{let at=from;for(let[s,e]of templateBlocks){if(e<=at||s>=to)continue;out.copy(at,s),at=e}out.copy(at,to)};if(instance){let cursor=instance.content.start;for(let s of body){let gapStart=cursor;if(copyGap(cursor,s.start),cursor=s.end,s.type==="ImportDeclaration"||genericAliases.has(s))continue;if(s.type==="ExportNamedDeclaration"){let d=s.declaration;if(d){let at=d.start;if(d.type==="VariableDeclaration")for(let decl of d.declarations){let type=decl.id.type==="Identifier"&&!decl.id.typeAnnotation&&(d.kind==="let"||decl.id.name==="snapshot")?kitPropType(basename,decl.id.name):void 0,jsdoc=!isTs&&[...source.slice(gapStart,decl.id.start).matchAll(JSDOC_BLOCK2)].some((m)=>JSDOC_TYPE.test(m[0]));if(!type||jsdoc)continue;if(isTs)out.copy(at,decl.id.end).raw(`: ${type}`),at=decl.id.end;else out.copy(at,decl.id.start).raw(`/** @type {${type}} */ `),at=decl.id.start}if(out.copy(at,d.end),d.type==="VariableDeclaration"&&d.kind==="let")for(let decl of d.declarations){let widens=decl.id.type==="Identifier"&&(!decl.init||decl.id.typeAnnotation||[...source.slice(gapStart,decl.id.start).matchAll(JSDOC_BLOCK2)].some((m)=>JSDOC_TYPE.test(m[0]))||decl.init.type==="Literal"&&typeof decl.init.value==="boolean");for(let name of idsOf(decl.id))if(props.push({name,local:name,optional:decl.init!=null,type:decl.id.type==="Identifier"&&decl.id.typeAnnotation?.typeAnnotation?source.slice(decl.id.typeAnnotation.typeAnnotation.start,decl.id.typeAnnotation.typeAnnotation.end):void 0}),widens)out.raw(`;${name} = __sveltets_2_any(${decl.init?name:0});`)}else for(let name of d.declarations?d.declarations.flatMap((x)=>idsOf(x.id)):[d.id?.name])if(name){if(exportsOf.push([name,name]),!runes)props.push({name,local:name,optional:!0})}}else for(let spec of s.specifiers){let binding=scopes.instance.get(spec.local.name);if(runes)exportsOf.push([spec.exported.name,spec.local.name]);else if(binding?.kind==="let"||binding?.kind==="prop")props.push({name:spec.exported.name,local:spec.local.name,optional:!0,type:annotationOf(spec.local.name)})}}else if(s.type==="LabeledStatement"&&s.label.name==="$"){reactive.push([s.start,s.end]);let e=s.body.type==="ExpressionStatement"?s.body.expression:null;if(e?.type==="AssignmentExpression"&&e.operator==="="&&idsOf(e.left).some((n)=>scopes.instance.get(n)?.kind==="reactive"))out.raw("let ").copy(e.left.start,e.left.end),out.raw(" = __sveltets_2_invalidate(() => (").copy(e.right.start,e.right.end).raw("));");else out.raw(";() => {").copy(s.start,s.end).raw("}")}else if(runes&&propsDeclaratorOf(s))propsRune(s,propsDeclaratorOf(s),gapStart);else{let call=typed.has("$$Events")&&s.type==="VariableDeclaration"?s.declarations.map((d)=>d.init).find((init)=>init?.type==="CallExpression"&&init.callee?.name==="createEventDispatcher"&&!init.typeArguments&&!init.typeParameters):void 0;if(call)out.copy(s.start,call.callee.end).raw("<__sveltets_2_CustomEvents<$$Events>>").copy(call.callee.end,s.end);else out.copy(s.start,s.end)}for(let name of storeAfter.get(s.end)??[])declareStore(name)}copyGap(cursor,instance.content.end)}out.raw(`
|
|
46
46
|
async () => {
|
|
47
47
|
`),fragment(ast.fragment),out.raw(`};
|
|
48
|
-
`);let accessors=ast.options?.attributes?.some((a)=>a.name==="accessors"&&a.value!==!1),markupScoped=(value)=>{let scoped=!1;for(let part of Array.isArray(value)?value:[value])if(part?.type==="ExpressionTag")walk2(part.expression,{enter(node,parent){if(node.type!=="Identifier"||!isReference2(node,parent))return;let b=scopes.bindingOf(node);if(b&&b.scope!==scopes.instance&&b.scope!==scopes.module)scoped=!0}});return scoped},eachItemOf=(value)=>{let parts=Array.isArray(value)?value:[value],only=parts.length===1?parts[0]:void 0;if(only?.type!=="ExpressionTag"||only.expression.type!=="Identifier")return;let b=scopes.bindingOf(only.expression);if(b?.kind==="each-index")return"0";let block=b?.declaration;if(b?.kind!=="each"||block?.context?.type!=="Identifier"||markupScoped({type:"ExpressionTag",expression:block.expression}))return;return`__sveltets_2_unwrapArr(${source.slice(block.expression.start,block.expression.end)})`},entries=(pairs)=>pairs.map(([k,v])=>`${
|
|
48
|
+
`);let accessors=ast.options?.attributes?.some((a)=>a.name==="accessors"&&a.value!==!1),markupScoped=(value)=>{let scoped=!1;for(let part of Array.isArray(value)?value:[value])if(part?.type==="ExpressionTag")walk2(part.expression,{enter(node,parent){if(node.type!=="Identifier"||!isReference2(node,parent))return;let b=scopes.bindingOf(node);if(b&&b.scope!==scopes.instance&&b.scope!==scopes.module)scoped=!0}});return scoped},eachItemOf=(value)=>{let parts=Array.isArray(value)?value:[value],only=parts.length===1?parts[0]:void 0;if(only?.type!=="ExpressionTag"||only.expression.type!=="Identifier")return;let b=scopes.bindingOf(only.expression);if(b?.kind==="each-index")return"0";let block=b?.declaration;if(b?.kind!=="each"||block?.context?.type!=="Identifier"||markupScoped({type:"ExpressionTag",expression:block.expression}))return;return`__sveltets_2_unwrapArr(${source.slice(block.expression.start,block.expression.end)})`},entries=(pairs)=>pairs.map(([k,v])=>`${keyOf(k)}: ${v}`).join(", ");if(runes)return runesExport(),{out,isTs,lang,tsInJs,reactive,transitions,storeDeclarations,bindingChecks};let declaredProps=`{${props.map((p)=>`${keyOf(p.name)}${p.optional?"?":""}: ${p.type??`typeof ${p.local}`}`).join(", ")}}`;if(out.raw("return { props: "),typed.has("$$Props"))out.raw(`{ ...__sveltets_2_ensureRightProps<${declaredProps}>(`),out.from(propsDeclaredAt,()=>out.raw('__sveltets_2_any("") as $$Props')),out.raw(") } as $$Props");else if(out.raw(`{${entries(props.map((p)=>[p.name,p.local]))}}`),isTs)out.raw(` as ${declaredProps}`);let exposed=[...accessors?props.map((p)=>[p.name,p.type??`typeof ${p.local}`]):[],...exportsOf.map(([k,v])=>[k,`typeof ${v}`])],exposedType=`{${exposed.map(([k,type])=>`${keyOf(k)}: ${type}`).join(", ")}}`,exportsValue="{}";if(exposed.length>0)exportsValue=isTs?`{} as any as ${exposedType}`:`/** @type {${exposedType}} */ ({})`;out.raw(`, exports: ${exportsValue}, bindings: "", slots: ${typed.has("$$Slots")?"{} as unknown as $$Slots, __slots: {":"{"}`);for(let[name,attributes]of slots){out.raw(`${JSON.stringify(name)}: {`);for(let a of attributes)if(a.type==="Attribute"&&a.name!=="name"){out.raw(`${JSON.stringify(a.name)}: `);let each=eachItemOf(a.value);if(each)out.raw(each);else if(markupScoped(a.value))out.raw("__sveltets_2_any(0)");else attrValue(a.value);out.raw(", ")}else if(a.type==="SpreadAttribute"&&!markupScoped({type:"ExpressionTag",expression:a.expression}))out.raw("...").copy(a.expression.start,a.expression.end).raw(", ");out.raw("}, ")}let dispatcher=body.flatMap((s)=>s.type==="VariableDeclaration"?s.declarations:[]).map((d)=>d.init).find((init)=>init?.type==="CallExpression"&&init.callee?.name==="createEventDispatcher"),typings=dispatcher?source.slice(dispatcher.callee.end,dispatcher.end).replace(CALL_PARENS,""):"",eventsType=typed.has("$$Events")?"{} as unknown as $$Events":`{${typings.startsWith("<")?`...__sveltets_2_toEventTypings${typings}(), `:""}${entries([...forwarded])}}`;out.raw(`}, events: ${eventsType} };
|
|
49
49
|
}
|
|
50
50
|
`);let optional=props.filter((p)=>p.optional).map((p)=>JSON.stringify(p.name)),anyProp=USES_ALL_PROPS.test(source),renderCall=topLevelAwait?"$$$render":"$$render()";if(topLevelAwait)out.raw(`const $$$render = await $$render();
|
|
51
|
-
`);let rendered=strictEvents?renderCall:`__sveltets_2_with_any_event(${renderCall})`,withProps=typed.has("$$Props")
|
|
51
|
+
`);let rendered=strictEvents?renderCall:`__sveltets_2_with_any_event(${renderCall})`,withProps=rendered;if(isTs){if(anyProp&&!typed.has("$$Props"))withProps=`__sveltets_2_with_any(${rendered})`}else if(!typed.has("$$Props"))withProps=`__sveltets_2_partial${anyProp?"_with_any":""}(${optional.length>0?`[${optional.join(",")}], `:""}${rendered})`;let hasSlots=slots.size>0||typed.has("$$Slots");if(isTs&&typeParams.length>0&&svelte>=4){let names=typeParams.map((p)=>p.match(GENERIC_PARAM)?.[1]??p),args=`<${names.join(", ")}>`,wrapped=withProps.replaceAll(renderCall,()=>topLevelAwait?`(await $$render${args}())`:`$$render${args}()`),part=(name)=>`ReturnType<__sveltets_Render${args}["${name}"]>`,children=hasSlots?" & { children?: any }":"";out.raw(`class __sveltets_Render${generics} { props() { return ${wrapped}.props; } events() { return ${wrapped}.events; } slots() { return ${wrapped}.slots; } bindings() { return ""; } exports() { return $$render${args}().exports; } }
|
|
52
52
|
interface $$IsomorphicComponent { new ${generics}(options: import("svelte").ComponentConstructorOptions<${part("props")}${children}>): import("svelte").SvelteComponent<${part("props")}, ${part("events")}, ${part("slots")}> & { $$bindings?: ${part("bindings")} } & ${part("exports")}; ${generics}(internal: unknown, props: ${part("props")} & { $$events?: ${part("events")}; $$slots?: ${part("slots")}${hasSlots?"; children?: any":""} }): ${part("exports")}; z_$$bindings?: ReturnType<__sveltets_Render<${names.map(()=>"any").join(", ")}>["bindings"]>; }
|
|
53
53
|
const $$Component: $$IsomorphicComponent = null as any;
|
|
54
54
|
type $$Component${generics} = InstanceType<typeof $$Component${args}>;
|
|
@@ -70,14 +70,21 @@ const $$Component = __sveltets_2_fn_component($$$render);
|
|
|
70
70
|
`);out.raw(`export default $$Component;
|
|
71
71
|
`)}}import{readdirSync}from"node:fs";import{join as join4}from"node:path";var GLOB_LITERAL=/[.+^$()|[\]\\]/g,LEADING_DOT_SLASH=/^\.\//;function globToRegExp(pattern){let source="";for(let i=0;i<pattern.length;i++){let char=pattern[i]??"";if(char==="*"&&pattern[i+1]==="*"){let slash=pattern[i+2]==="/";source+=slash?"(?:.*/)?":".*",i+=slash?2:1}else if(char==="*")source+="[^/]*";else if(char==="?")source+="[^/]";else if(char==="{")source+="(?:";else if(char==="}")source+=")";else if(char===",")source+="|";else source+=char.replace(GLOB_LITERAL,String.raw`\$&`)}return new RegExp(`^${source}$`)}function matcher(globs){if(globs.length===0)return()=>!1;let res=globs.map((pattern)=>globToRegExp(pattern.replace(LEADING_DOT_SLASH,"")));return(path)=>res.some((re)=>re.test(path))}function glob(root,globs){let matches=matcher(globs),dotFolders=globs.some((g)=>g.startsWith(".")||g.includes("/.")),found=[],walk=(dir,prefix)=>{for(let entry of readdirSync(dir,{withFileTypes:!0})){let rel=prefix+entry.name;if(entry.isDirectory()){if(entry.name==="node_modules")continue;if(entry.name.startsWith(".")&&!dotFolders)continue;walk(join4(dir,entry.name),`${rel}/`)}else if(matches(rel))found.push(rel)}};return walk(root,""),found.sort()}import{existsSync as existsSync3,readFileSync as readFileSync3}from"node:fs";import{createRequire as createRequire3}from"node:module";import{basename as basename2,dirname as dirname4,isAbsolute,join as join5,relative,resolve as resolve2,sep}from"node:path";var LINE_COMMENT=/\/\/[^\n]*/g,BLOCK_COMMENT=/\/\*[\s\S]*?\*\//g,TRAILING_COMMA=/,(\s*[}\]])/g,STRING=/"(?:[^"\\]|\\.)*"/g,PLACEHOLDER=/"\0(\d+)"/g,WILDCARD=/[*?{]/,HAS_EXTENSION=/\.[^/\\]+$/,NODE_MODULES_JS=/\/node_modules\/.+\.[cm]?js$/,DEFAULT_EXCLUDE=["node_modules","bower_components","jspm_packages"],CONFIG_DIR="${configDir}";function parseJsonc(text){let strings=[],stripped=text.replace(STRING,(s)=>`"\x00${strings.push(s)-1}"`).replace(LINE_COMMENT,"").replace(BLOCK_COMMENT,"").replace(TRAILING_COMMA,"$1").replaceAll(PLACEHOLDER,(_,i)=>strings[Number(i)]??"");return JSON.parse(stripped)}function readInputs(path,read=[]){read.push(path);let config=parseJsonc(readFileSync3(path,"utf-8")),dir=dirname4(path),absolute=(list)=>list?.map((p)=>resolve2(dir,p)),inputs={},bases=typeof config.extends==="string"?[config.extends]:config.extends;for(let base of bases??[]){let basePath=base.startsWith(".")?resolve2(dir,base):createRequire3(path).resolve(base),baseInputs=readInputs(basePath,read),difference=toPosix(relative(dir,dirname4(basePath))),rebase=(specs)=>specs?.map((spec)=>difference&&!isAbsolute(spec)&&!spec.startsWith(CONFIG_DIR)?`${difference}/${spec}`:spec);inputs={...inputs,...defined({...baseInputs,includeSpecs:rebase(baseInputs.includeSpecs),excludeSpecs:rebase(baseInputs.excludeSpecs)})}}let options=config.compilerOptions,baseUrl=options?.baseUrl?resolve2(dir,options.baseUrl):void 0,pathsBase=baseUrl??inputs.baseUrl??dir;return{...inputs,...defined({include:absolute(config.include),exclude:absolute(config.exclude),files:absolute(config.files),rootDirs:absolute(options?.rootDirs),checkJs:options?.checkJs,allowJs:options?.allowJs,includeSpecs:config.include,excludeSpecs:config.exclude,outDir:options?.outDir&&resolve2(dir,options.outDir),declarationDir:options?.declarationDir&&resolve2(dir,options.declarationDir),baseUrl,paths:options?.paths&&Object.fromEntries(Object.entries(options.paths).map(([key,targets])=>[key,targets.map((t)=>resolve2(pathsBase,t))]))})}}function defined(inputs){return Object.fromEntries(Object.entries(inputs).filter(([,value])=>value!==void 0))}function findUp(from,name){for(let dir=from;;dir=dirname4(dir)){let path=join5(dir,name);if(existsSync3(path))return path;if(dirname4(dir)===dir)return}}function findTsconfig(dir){let ts=findUp(dir,"tsconfig.json"),js=findUp(dir,"jsconfig.json");return ts&&(!js||ts.length>=js.length)?ts:js}var toPosix=(path)=>path.split(sep).join("/"),asTypeScriptPath=(path)=>toPosix(path).replace(/^[A-Z]:/,(drive)=>drive.toLowerCase());function splitGlob(pattern){let parts=toPosix(pattern).split("/"),at=parts.findIndex((part)=>WILDCARD.test(part));if(at===-1)return[pattern,""];return[parts.slice(0,at).join("/")||"/",parts.slice(at).join("/")]}function svelteGlobOf(pattern){if(pattern.endsWith(".svelte"))return pattern;if(WILDCARD.test(pattern))return pattern.endsWith("*")?`${pattern.slice(0,-1)}*.svelte`:void 0;return HAS_EXTENSION.test(pattern)?void 0:`${pattern}/**/*.svelte`}function absoluteMatcher(patterns){let globs=patterns.flatMap((p)=>{let posix=toPosix(p);return WILDCARD.test(posix)?[posix]:[posix,`${posix}/**`]}),matches=matcher(globs.map((g)=>g.replace(/^\//,"")));return(path)=>matches(toPosix(path).replace(/^\//,""))}function projectOf(options){let{workspace}=options,tsconfig=tsconfigOf(workspace,options.tsconfig);if(options.tsconfig&&tsconfig&&!existsSync3(tsconfig))throw Error(`Could not find tsconfig/jsconfig file at ${tsconfig}`);if(!tsconfig){let isIgnored=ignoreMatcher(options.ignore??[]);return{components:glob(workspace,options.components??["**/*.svelte"]).filter((rel)=>!isIgnored(rel)).map((rel)=>join5(workspace,rel)),files:[],include:[],exclude:[],rootDirs:[],configFiles:[],paths:{},checkJs:!0,allowJs:!0,raw:{},reports:()=>!1}}let configFiles=[],inputs=readInputs(tsconfig,configFiles),raw=parseJsonc(readFileSync3(tsconfig,"utf-8")),include=inputs.include??(inputs.files?[]:[join5(dirname4(tsconfig),"**/*")]),exclude=inputs.exclude??DEFAULT_EXCLUDE.map((p)=>join5(dirname4(tsconfig),p)),files=new Set(inputs.files??[]),isExcluded=absoluteMatcher(exclude),components;if(options.components)components=glob(workspace,options.components).map((rel)=>join5(workspace,rel));else{let found=new Set([...files].filter((f)=>f.endsWith(".svelte")));for(let pattern of include){let svelteGlob=svelteGlobOf(pattern);if(!svelteGlob)continue;let[base,rest]=splitGlob(svelteGlob);if(!rest){if(existsSync3(base))found.add(base);continue}if(!existsSync3(base))continue;for(let rel of glob(base,[rest]))found.add(join5(base,rel))}components=[...found].sort()}return components=components.filter((path)=>!isExcluded(path)),{tsconfig,components,files:inputs.files??[],include,exclude,rootDirs:inputs.rootDirs??[],configFiles,paths:{...importsOf(dirname4(tsconfig)),...inputs.paths},checkJs:inputs.checkJs??!1,allowJs:inputs.allowJs??basename2(tsconfig)==="jsconfig.json",raw,inputSpecs:inputs.files||raw.references?void 0:{include:inputs.includeSpecs??["**/*"],exclude:inputs.excludeSpecs??[inputs.outDir,inputs.declarationDir].flatMap((dir)=>dir?[asTypeScriptPath(dir)]:[])},reports:(path)=>!NODE_MODULES_JS.test(toPosix(path))}}function importsOf(dir){let path=findUp(dir,"package.json");if(!path)return{};let imports;try{({imports}=JSON.parse(readFileSync3(path,"utf-8")))}catch{return{}}let paths={};for(let[key,value]of Object.entries(imports??{})){let target=importTarget(value);if(key.startsWith("#")&&target?.startsWith("./"))paths[key]=[resolve2(dirname4(path),target)]}return paths}function importTarget(value){if(typeof value==="string")return value;if(Array.isArray(value))return importTarget(value[0]);if(!value||typeof value!=="object")return;let conditions=value;for(let condition of["types","import","default"])if(condition in conditions)return importTarget(conditions[condition]);return importTarget(Object.values(conditions)[0])}var PROGRAM_FILE=/\.(svelte|[cm]?[jt]sx?)$/,JS_FILE=/\.[cm]?jsx?$/;function byFolder(a,b){let pa=a.split(sep),pb=b.split(sep);for(let i=0;i<Math.min(pa.length,pb.length);i++){if(pa[i]===pb[i])continue;let aFile=i===pa.length-1,bFile=i===pb.length-1;if(aFile!==bFile)return aFile?-1:1;return(pa[i]??"")<(pb[i]??"")?-1:1}return pa.length-pb.length}function programFiles(project){let isExcluded=absoluteMatcher(project.exclude),found=new Set(project.files);for(let pattern of project.include){let fileGlob=WILDCARD.test(pattern)||HAS_EXTENSION.test(pattern)?pattern:`${pattern}/**/*`,[base,rest]=splitGlob(fileGlob);if(!rest){if(existsSync3(base)&&PROGRAM_FILE.test(base)&&(project.allowJs||!JS_FILE.test(base)))found.add(base);continue}if(!existsSync3(base))continue;let matched=glob(base,[rest]).map((rel)=>join5(base,rel)).filter((path)=>PROGRAM_FILE.test(path)&&(project.allowJs||!JS_FILE.test(path))&&!isExcluded(path)).sort(byFolder);for(let path of matched)found.add(path)}return[...found]}function scriptsOf(project,test){let isExcluded=absoluteMatcher(project.exclude),found=new Set;for(let pattern of project.include){let scriptGlob=WILDCARD.test(pattern)||HAS_EXTENSION.test(pattern)?pattern:`${pattern}/**/*`,[base,rest]=splitGlob(scriptGlob);if(!rest){if(existsSync3(base)&&test(base))found.add(base);continue}if(!existsSync3(base))continue;for(let rel of glob(base,[rest])){let path=join5(base,rel);if(test(path)&&!isExcluded(path))found.add(path)}}return[...found].sort()}function relativeTo(from,path){let rel=toPosix(relative(from,path));return rel.startsWith(".")||isAbsolute(rel)?rel:`./${rel}`}function ignoreMatcher(patterns){let tests=patterns.map((raw)=>{let pattern=raw.trim();if(pattern.endsWith("**"))pattern=pattern.slice(0,-2);if(pattern.startsWith("**")){let rest=pattern.slice(2);if(rest.includes("*"))throw Error(INVALID_IGNORE);return(path)=>path.includes(rest)}if(pattern.includes("*"))throw Error(INVALID_IGNORE);return(path)=>path.startsWith(pattern)});return(path)=>tests.some((test)=>test(path))}var INVALID_IGNORE="Invalid --ignore pattern: only ** at the start or end is supported";function tsconfigOf(workspace,option){if(option===!1)return;if(option)return resolve2(workspace,option);return findTsconfig(workspace)}var DIAGNOSTIC=/^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/,CONTINUATION=/^\s+\S/,GLOBAL_DIAGNOSTIC=/^error (TS\d+): (.*)$/,TS_MODULE=/\.[cm]?tsx?$/,LINE_BREAK2=/\r?\n/,JS_FILE2=/\.[cm]?jsx?$/,SYNTAX_CODE=/^TS[18]\d{3}$/,STOPPED=/Stopped before type checking/,TS_SCRIPT=/<script\b[^>]*\blang=["']?(ts|typescript)\b/,GENERATED_NAME=/(?:\+\+)?([^/\\]+?)(?:\.d\.svelte(?:\.ts)?|\.svelte\.[jt]s)$/,DRIVE_PATH=/\b[A-Z]:\//g,toPosix2=(path)=>path.split(sep2).join("/"),escapeRegExp=(text)=>text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),TYPE_CODE=/^TS[2-7]\d{3}$/,TOKEN=/^(?:[\w$]+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`[^`]*`)/,STORE_ERROR=/^TS(2769|2345)$/,REACTIVE_NOISE=/^TS(7028|2695)$/,SHIMS=fileURLToPath(new URL("./shims/",import.meta.url)),CACHE_FORMAT=1,RESULT_CACHE="result.json",EMIT_CACHE="emit-cache.json",COMPILE_CACHE="compile-cache.json",hash=(text)=>createHash("sha1").update(text).digest("hex"),MANIFEST="manifest.json",DEFAULT_COMPILER_OPTIONS={allowJs:!0,noEmit:!0,declaration:!1,skipLibCheck:!0,maxNodeModuleJsDepth:2,allowSyntheticDefaultImports:!0,target:"esnext",module:"esnext",moduleResolution:"bundler"};class EmitError extends Error{}var SHELL_SPECIAL=/[\s"&|<>^()%!]/,quote=(arg)=>SHELL_SPECIAL.test(arg)?`"${arg.replaceAll('"','""')}"`:arg;function run2(command,args,cwd,shell=!1){return new Promise((done,fail)=>{let child=shell?spawn(quote(command),args.map(quote),{cwd,shell:!0}):spawn(command,args,{cwd}),output="";child.stdout.on("data",(chunk)=>{output+=chunk}),child.stderr.on("data",(chunk)=>{output+=chunk}),child.on("error",fail),child.on("close",()=>done(output))})}function parseDiagnostics(text){let found=[],continues=!1;for(let line of text.split(LINE_BREAK2)){let m=DIAGNOSTIC.exec(line),global=m?null:GLOBAL_DIAGNOSTIC.exec(line);if(m)found.push({file:m[1]??"",line:Number(m[2]),column:Number(m[3]),code:m[4]??"",message:m[5]??""});else if(global)found.push({file:"",line:1,column:1,code:global[1]??"",message:global[2]??""});else if(continues&&CONTINUATION.test(line)){let last=found.at(-1);if(last)last.message+=`
|
|
72
72
|
${line}`}continues=m!==null||global!==null||continues&&line.trim()!==""}return found}var STATIC_IMPORT=/(?:\bfrom\s*|^\s*import\s*)["']([^"']+)["']/gm,DYNAMIC_IMPORT=/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,JS_EXTENSION=/\.([cm]?)js(x?)$/;function programOrder(roots,specifiersOf,resolveImport,imports=new Map){let order=new Map,next=0,visit=(path)=>{if(order.has(path))return;order.set(path,Number.POSITIVE_INFINITY);for(let specifier of specifiersOf(path)){let target=resolveImport(path,specifier);if(!target)continue;imports.set(path,(imports.get(path)??new Set).add(target)),visit(target)}order.set(path,next++)};for(let root of roots)visit(root);return order}function importResolver(rootDirs,paths){let exists=new Map,isFile=(path)=>{let found=exists.get(path);if(found===void 0)found=statSync(path,{throwIfNoEntry:!1})?.isFile()??!1,exists.set(path,found);return found},fileAt=(target)=>[target,`${target}.ts`,`${target}.d.ts`,`${target}.js`,target.replace(JS_EXTENSION,".$1ts$2"),target.replace(JS_EXTENSION,".d.$1ts"),join6(target,"index.ts"),join6(target,"index.js")].find((path)=>!path.includes(`${sep2}node_modules${sep2}`)&&isFile(path)),throughRootDirs=(target)=>{let from=rootDirs.filter((dir)=>target.startsWith(`${dir}${sep2}`)).sort((a,b)=>b.length-a.length)[0];if(!from)return;let suffix=relative2(from,target);for(let dir of rootDirs){if(dir===from)continue;let found=fileAt(join6(dir,suffix));if(found)return found}return},patterns=Object.entries(paths).map(([key,targets])=>{let star=key.indexOf("*");return{key,star,targets}});return(from,specifier)=>{if(specifier.startsWith(".")){let target=resolve3(dirname5(from),specifier);return fileAt(target)??throughRootDirs(target)}for(let{key,star,targets}of patterns){let rest;if(star===-1){if(specifier!==key)continue;rest=""}else{let prefix=key.slice(0,star),suffix=key.slice(star+1);if(!specifier.startsWith(prefix)||!specifier.endsWith(suffix)||specifier.length<prefix.length+suffix.length)continue;rest=specifier.slice(prefix.length,specifier.length-suffix.length)}for(let target of targets){let found=fileAt(target.replace("*",rest));if(found)return found}}return}}var NON_BINDABLE=`Cannot use 'bind:' with this property. It is declared as non-bindable inside the component.
|
|
73
|
-
`;function
|
|
73
|
+
`;function withHint(d,svelteMajor){if(d.code==="TS2345"&&d.message.includes("ConstructorOfATypedSvelteComponent"))return{...d,message:`${d.message}
|
|
74
|
+
|
|
75
|
+
Possible causes:
|
|
76
|
+
- You use the instance type of a component where you should use the constructor type
|
|
77
|
+
- Type definitions are missing for this Svelte Component. ${svelteMajor>=5?"":`If you are using Svelte 3.31+, use SvelteComponentTyped to add a definition:
|
|
78
|
+
import type { SvelteComponentTyped } from "svelte";
|
|
79
|
+
class ComponentName extends SvelteComponentTyped<{propertyName: string;}> {}`}`};if(d.code==="TS1184")return{...d,message:`${d.message}
|
|
80
|
+
If this is a declare statement, move it into <script context="module">..</script>`};return d}function nonBindableMessage(message){if(message.startsWith("Type '")&&message.includes("is not assignable to type '")){let at=message.indexOf(`Type '"`)+7,prop=message.slice(at,message.indexOf('"',at));return`${NON_BINDABLE}To mark a property as bindable: 'let { ${prop} = $bindable() } = $props()'`}return`${NON_BINDABLE}To mark a property as bindable: 'let { prop = $bindable() } = $props()'
|
|
74
81
|
|
|
75
82
|
${message}`}var NOTHING_EMITTED={reactive:[],transitions:[],storeDeclarations:[],bindingChecks:[]};function kitMajor(root){try{let path=createRequire4(join6(root,"package.json")).resolve("@sveltejs/kit/package.json"),{version}=JSON.parse(readFileSync4(path,"utf-8"));return Number.parseInt(version,10)}catch{return 0}}function commonDir(paths){let common=paths[0]??sep2;for(let path of paths)while(!`${path}${sep2}`.startsWith(`${common}${sep2}`)&&common!==sep2)common=dirname5(common);return common}async function typecheck2(options={}){let cwd=resolve3(options.cwd??process.cwd()),workspace=resolve3(cwd,options.workspace??"."),project=projectOf({workspace,tsconfig:options.tsconfig,ignore:options.ignore,components:options.components}),outDir=resolve3(cwd,options.outDir??join6("node_modules/.cache/svelte-typecheck",relative2(cwd,workspace))),genDir=join6(outDir,"svelte"),declarations=options.declarations??!0,svelteDir=svelteDirOf(cwd,options.svelte),sources=new Set(options.diagnosticSources??["js","svelte"]),errorsOnly=options.threshold==="error",{version}=JSON.parse(readFileSync4(join6(svelteDir,"package.json"),"utf-8")),svelteMajor=Number(version.split(".")[0]),svelteHtml=svelteMajor===3?join6(SHIMS,"svelte3-elements.d.ts"):join6(svelteDir,"svelte-html.d.ts"),checker=options.checker??CHECKERS.find((c)=>checkerCommand(c,workspace)!==void 0),command=checker&&checkerCommand(checker,workspace);if(!(checker&&command))throw Error(`No type checker found: install \`typescript\` (or one of ${CHECKERS.slice(1).join(", ")}), or name one with \`checker\`.`);let started=performance.now(),incremental=options.incremental??!0,previous=incremental?await readFile(join6(outDir,MANIFEST),"utf-8").then((text)=>new Set(JSON.parse(text))).catch(()=>new Set):new Set;if(!incremental)await rm(outDir,{recursive:!0,force:!0});let files=project.components,listedFiles=project.tsconfig?programFiles(project):[...files].sort(byFolder),configDir=options.config?dirname5(resolve3(workspace,options.config)):workspace,configFile=options.config?resolve3(workspace,options.config):void 0,resultPath=join6(outDir,RESULT_CACHE),projectDir=project.tsconfig?dirname5(project.tsconfig):workspace,last=incremental?await readFile(resultPath,"utf-8").then((text)=>JSON.parse(text)).catch(()=>{return}):void 0,runKey=incremental?hash(JSON.stringify([version2,CACHE_FORMAT,version,checker,command.version,cwd,options,configFingerprint(configDir,configFile),statsOf([...files,...listedFiles,...project.configFiles,...project.rootDirs.flatMap((dir)=>`${projectDir}${sep2}`.startsWith(`${dir}${sep2}`)||outDir.startsWith(`${dir}${sep2}`)||!existsSync4(dir)?[]:glob(dir,["**/*"]).map((rel)=>join6(dir,rel))),...packageFilesOf(projectDir)])])):"";if(last?.key===runKey&&Array.isArray(last.inputs)&&hash(JSON.stringify(statsOf(last.inputs)))===last.inputsKey)return{...last.result,timings:{emit:0,check:0,compile:0}};let texts=await Promise.all(files.map((path)=>readFile(path,"utf-8"))),root=commonDir([project.tsconfig?dirname5(project.tsconfig):workspace,...files.map((file)=>dirname5(file))]),outputs=new Map,writes=[],written=new Set,write=(path,content)=>{written.add(path),writes.push((incremental?readFile(path,"utf-8").catch(()=>{return}):Promise.resolve(void 0)).then(async(old)=>{if(old===content)return;await mkdir(dirname5(path),{recursive:!0}),await writeFile(path,content)}))},failed=[],parseErrors=[],under=(path,dir)=>path.startsWith(`${dir}${sep2}`),tsconfig=join6(outDir,"tsconfig.json");if(sources.has("js")){let emitCachePath=join6(outDir,EMIT_CACHE),emitFingerprint=hash(JSON.stringify([version2,CACHE_FORMAT,svelteMajor,project.checkJs,project.allowJs,declarations,root,genDir])),emitCache=(incremental?await readFile(emitCachePath,"utf-8").then((text)=>JSON.parse(text)).then((c)=>c.fingerprint===emitFingerprint?c:void 0).catch(()=>{return}):void 0)??{fingerprint:emitFingerprint,entries:{}},nextEmitCache={fingerprint:emitFingerprint,entries:{}},emitFor=(i)=>{let path=files[i]??"",genFrom=join6(genDir,relative2(root,dirname5(path)));return emit(texts[i]??"",{svelte:svelteMajor,basename:basename3(path),checkJs:project.checkJs,rewriteImport(specifier){if(!specifier.startsWith("."))return;let target=resolve3(dirname5(path),specifier);if(target.startsWith(`${root}${sep2}`))return;return relativeTo(genFrom,target)}})},lazyOutput=(i,lang)=>{let result,get=()=>(result??=emitFor(i),result);return{source:texts[i]??"",svelte:files[i]??"",isTs:lang==="ts",get output(){return get().out},get emitted(){return get()}}};for(let[i,path]of files.entries()){let genFrom=join6(genDir,relative2(root,dirname5(path))),name=path.slice(path.lastIndexOf(sep2)+1,-7),typed=declarations&&!existsSync4(`${path}.d.ts`),key=hash(`${path}\x00${typed}\x00${texts[i]??""}`),cached=emitCache.entries[key];if(cached&&(!cached.genPath||existsSync4(cached.genPath))){for(let file of cached.files)written.add(file);if(parseErrors.push(...cached.diagnostics),cached.genPath&&cached.lang)outputs.set(cached.genPath,lazyOutput(i,cached.lang));nextEmitCache.entries[key]=cached;continue}let effects={files:[],diagnostics:[]};nextEmitCache.entries[key]=effects;let put=(file,content)=>{effects.files.push(file),write(file,content)},result;try{result=emitFor(i)}catch(error){let e=error;if(!e.start){failed.push({file:path,message:e.message}),delete nextEmitCache.entries[key];continue}let isTs=TS_SCRIPT.test(texts[i]??"");effects.diagnostics.push({file:path,line:e.start.line,column:e.start.column+1,endLine:e.start.line,endColumn:e.start.column+1,severity:"error",source:isTs?"ts":"js",code:"-1",message:e.message});let lexed=lexComponent2(texts[i]??""),stub=[lexed.instance,lexed.module].some((script)=>script&&lexImportsExports((texts[i]??"").slice(script.content.start,script.content.end)).length>0)?`export {};
|
|
76
83
|
`:"";if(put(join6(genFrom,`++${name}.svelte.${isTs?"ts":"js"}`),stub),declarations)put(join6(genFrom,`${name}.d.svelte.ts`),stub);parseErrors.push(...effects.diagnostics);continue}let locate=createLocator(texts[i]??"");for(let t of result.tsInJs){let at=locate.position(t.at);effects.diagnostics.push({file:path,line:at.line,column:at.column,severity:"error",source:"js",code:t.code,message:t.message})}if(parseErrors.push(...effects.diagnostics),result.lang==="js"&&!project.allowJs){if(typed)put(join6(genFrom,`${name}.svelte.js`),result.out.code);continue}let genPath=join6(genFrom,`++${name}.svelte.${result.isTs?"ts":"js"}`);if(effects.genPath=genPath,effects.lang=result.lang==="ts"?"ts":"js",outputs.set(genPath,{output:result.out,source:texts[i]??"",svelte:path,isTs:result.lang==="ts",emitted:result}),put(genPath,result.out.code),typed)put(join6(genFrom,`${name}.d.svelte.ts`),`export { default } from "./++${name}.svelte.js";
|
|
77
84
|
export * from "./++${name}.svelte.js";
|
|
78
85
|
`)}if(incremental)write(emitCachePath,JSON.stringify(nextEmitCache));let mirror=(path)=>join6(genDir,relative2(root,path)),kitProject=project.tsconfig!==void 0&&(project.rootDirs.some((dir)=>dir.includes(".svelte-kit"))||files.some((path)=>isKitRouteFile(basename3(path)))),replaced=[];if(kitProject){let hooksModule=kitMajor(root)>=3?"@sveltejs/kit/hooks":"@sveltejs/kit";for(let path of scriptsOf(project,isKitFile)){if(!under(path,root))continue;let source=readFileSync4(path,"utf-8"),output=kitFile(path,source,hooksModule);if(!output)continue;replaced.push(path),outputs.set(mirror(path),{output,source,svelte:path,isTs:!JS_FILE2.test(path),emitted:NOTHING_EMITTED,kit:!0}),write(mirror(path),output.code)}}let rootDirs=[];for(let dir of project.rootDirs){if(dir===root||under(dir,outDir))continue;if(!(kitProject&&under(dir,root)&&existsSync4(dir))){rootDirs.push(dir);continue}replaced.push(dir),rootDirs.push(mirror(dir));for(let file of glob(dir,["**/*.{ts,js}"]))write(mirror(join6(dir,file)),readFileSync4(join6(dir,file),"utf-8"))}let paths=Object.fromEntries(Object.entries(project.paths).map(([key,targets])=>[key,targets.flatMap((t)=>under(t,root)?[mirror(t),t]:[t])])),shims=join6(outDir,"shims.d.ts");write(shims,readFileSync4(join6(SHIMS,"shims.d.ts"),"utf-8"));let rel=(path)=>relativeTo(outDir,path),generatedFor=new Map([...outputs].map(([genPath,gen])=>[gen.svelte,genPath])),replacedSet=new Set(replaced),rootFiles=[...new Set([...listedFiles.filter((path)=>path.endsWith(".svelte")).map((path)=>generatedFor.get(path)).filter((path)=>path!==void 0),...[...outputs].filter(([,gen])=>!gen.kit).map(([genPath])=>genPath),...listedFiles.filter((path)=>!path.endsWith(".svelte")).map((path)=>{if(replacedSet.has(path))return generatedFor.get(path);return replaced.find((d)=>under(path,d))?mirror(path):path}).filter((path)=>path!==void 0)])];write(tsconfig,JSON.stringify({...project.tsconfig?{extends:rel(project.tsconfig)}:{},compilerOptions:{...project.tsconfig?{}:DEFAULT_COMPILER_OPTIONS,rootDirs:[rel(root),"svelte",...rootDirs.map(rel)],...Object.keys(paths).length>0?{paths:Object.fromEntries(Object.entries(paths).map(([key,targets])=>[key,targets.map(rel)]))}:{},allowArbitraryExtensions:!0,noEmit:!0,composite:!1,incremental,...incremental?{tsBuildInfoFile:"./tsbuildinfo"}:{}},files:[...rootFiles,shims,svelteHtml,...svelteMajor>=5?[join6(svelteDir,"types/index.d.ts")]:[]].map(rel),include:[]},null,2)),write(join6(outDir,MANIFEST),JSON.stringify([...written].sort()));for(let path of previous)if(!written.has(path))writes.push(rm(path,{force:!0}))}if(await Promise.all(writes),incremental)await mkdir(outDir,{recursive:!0});let emitted=performance.now(),checking=sources.has("js")?run2(command.command,[...command.prefix,...checkerArgs(checker,tsconfig)],cwd,command.shell).then((output)=>({output,at:performance.now()})):Promise.resolve({output:"",at:emitted}),compiled=[],cachePath=join6(outDir,COMPILE_CACHE),fingerprint=hash(JSON.stringify([version2,CACHE_FORMAT,version,configFingerprint(configDir,configFile)])),cache=incremental?await readFile(cachePath,"utf-8").then((text)=>JSON.parse(text)).then((c)=>c.fingerprint===fingerprint?c:void 0).catch(()=>{return})??{fingerprint,entries:{}}:{fingerprint,entries:{}},keys=files.map((path,i)=>hash(`${relative2(cwd,path)}\x00${texts[i]??""}`)),perFile=[];if(sources.has("svelte")){let missing=files.map((_,i)=>i).filter((i)=>cache.entries[keys[i]??""]===void 0);if(missing.length>0){let svelteConfig=await svelteConfigOf(configDir,configFile),fresh=await Promise.all(missing.map((i)=>preprocessedDiagnostics(texts[i]??"",relative2(cwd,files[i]??""),svelteDir,svelteConfig)));for(let[n,i]of missing.entries())cache.entries[keys[i]??""]=fresh[n]??[]}for(let key of keys)perFile.push(cache.entries[key]??[]);if(incremental){let kept=Object.fromEntries(keys.map((key)=>[key,cache.entries[key]??[]]));await writeFile(cachePath,JSON.stringify({fingerprint,entries:kept}))}}for(let[i,path]of files.entries())for(let d of perFile[i]??[]){let level=options.compilerWarnings?.[d.code];if(d.severity==="warning"&&level==="ignore")continue;compiled.push({file:path,...d,severity:level==="error"?"error":d.severity,source:"svelte"})}let compiledAt=performance.now(),{output:text,at:checked}=await checking,raw=parseDiagnostics(text),inOutput=(file)=>resolve3(cwd,file).startsWith(`${outDir}${sep2}`),syntax=raw.some((d)=>TYPE_CODE.test(d.code))?[]:raw.filter((d)=>inOutput(d.file)&&SYNTAX_CODE.test(d.code)&&!outputs.get(resolve3(cwd,d.file))?.kit);if(syntax.length>0||STOPPED.test(text))throw new EmitError(`Generated code has syntax errors:
|
|
79
86
|
${syntax.slice(0,20).map((d)=>`${d.file}(${d.line},${d.column}): ${d.code} ${d.message}`).join(`
|
|
80
|
-
`)}`);let locators=new Map,locator=(key,content)=>{let found=locators.get(key);if(!found)found=createLocator(content()),locators.set(key,found);return found},endOf=(source,offset,file)=>{let length=TOKEN.exec(source.slice(offset))?.[0].length??0,end=locator(file,()=>source).position(offset+length);return{endLine:end.line,endColumn:end.column}},diagnostics=[],fileFacts=await factsCache(join6(outDir,FACTS_CACHE),incremental),dropped=[],seen=new Set;for(let d of raw){if(d.file===""){if(d.message.includes(outDir))throw new EmitError(`${d.code}: ${d.message}`);diagnostics.push({...d,file:project.tsconfig??workspace,severity:"error",source:"ts"});continue}let abs=resolve3(cwd,d.file),gen=outputs.get(abs),mapped;if(gen){let offset=locator(abs,()=>gen.output.code).offset(d.line,d.column),source=gen.output.toSource(offset);if(source===null){let store=STORE_ERROR.test(d.code)?gen.emitted.storeDeclarations.find((s)=>s.start<=offset&&offset<s.end):void 0;if(store){for(let use of store.uses){let at=locator(gen.svelte,()=>gen.source).position(use),end=locator(gen.svelte,()=>gen.source).position(use+store.name.length+1);
|
|
87
|
+
`)}`);let locators=new Map,locator=(key,content)=>{let found=locators.get(key);if(!found)found=createLocator(content()),locators.set(key,found);return found},endOf=(source,offset,file)=>{let length=TOKEN.exec(source.slice(offset))?.[0].length??0,end=locator(file,()=>source).position(offset+length);return{endLine:end.line,endColumn:end.column}},diagnostics=[],fileFacts=await factsCache(join6(outDir,FACTS_CACHE),incremental),dropped=[],storeErrors=[],seen=new Set;for(let d of raw){if(d.file===""){if(d.message.includes(outDir))throw new EmitError(`${d.code}: ${d.message}`);diagnostics.push({...d,file:project.tsconfig??workspace,severity:"error",source:"ts"});continue}let abs=resolve3(cwd,d.file),gen=outputs.get(abs),mapped;if(gen){let offset=locator(abs,()=>gen.output.code).offset(d.line,d.column),source=gen.output.toSource(offset);if(source===null){let store=STORE_ERROR.test(d.code)?gen.emitted.storeDeclarations.find((s)=>s.start<=offset&&offset<s.end):void 0;if(store){for(let use of store.uses){let at=locator(gen.svelte,()=>gen.source).position(use),end=locator(gen.svelte,()=>gen.source).position(use+store.name.length+1);storeErrors.push({...d,file:gen.svelte,line:at.line,column:at.column,endLine:end.line,endColumn:end.column,severity:"error",source:gen.isTs?"ts":"js",message:`Cannot use '${store.name}' as a store. '${store.name}' needs to be an object with a subscribe method on it.
|
|
81
88
|
|
|
82
|
-
${d.message}`})}continue}let binding=d.code==="TS2322"?gen.emitted.bindingChecks.find((b)=>b.start<=offset&&offset<b.end):void 0;if(binding){let at=locator(gen.svelte,()=>gen.source).position(binding.from),end=locator(gen.svelte,()=>gen.source).position(binding.to);diagnostics.push({...d,file:gen.svelte,line:at.line,column:at.column,endLine:end.line,endColumn:end.column,severity:"error",source:gen.isTs?"ts":"js",message:nonBindableMessage(d.message)});continue}dropped.push({...d,file:abs,severity:"error",source:"ts"});continue}let within=(ranges)=>ranges.some(([from,to])=>from<=source&&source<to);if(REACTIVE_NOISE.test(d.code)&&within(gen.emitted.reactive)||d.code==="TS2554"&&d.message.startsWith("Expected 3 arguments")&&within(gen.emitted.transitions))continue;let start=locator(gen.svelte,()=>gen.source).position(source);mapped={...d,file:gen.svelte,line:start.line,column:start.column,...endOf(gen.source,source,gen.svelte),severity:"error",source:gen.isTs?"ts":"js"}}else if(inOutput(d.file)||!project.reports(abs)){if(inOutput(d.file))dropped.push({...d,file:abs,severity:"error",source:"ts"});continue}else{let content=readFileSync4(abs,"utf-8"),offset=locator(abs,()=>content).offset(d.line,d.column);mapped={...d,file:abs,...endOf(content,offset,abs),severity:"error",source:JS_FILE2.test(abs)?"js":"ts"}}let key=`${mapped.file}:${mapped.line}:${mapped.column}:${mapped.code}`;if(seen.has(key))continue;seen.add(key),diagnostics.push(mapped)}let generatedPath=new RegExp(`${escapeRegExp(`${toPosix2(genDir)}/`)}[^"'\\s]*`,"gi");for(let d of diagnostics)if(d.message=d.message.replace(generatedPath,(path)=>asTypeScriptPath(join6(root,relative2(toPosix2(genDir),path)).replace(GENERATED_NAME,"$1.svelte"))),process.platform==="win32")d.message=d.message.replace(DRIVE_PATH,(drive)=>drive.toLowerCase());if(diagnostics.push(...compiled),sources.has("js"))diagnostics.push(...parseErrors);if(sources.has("js")&&project.tsconfig&&!project.allowJs){let untyped=new Set(files.filter((path,i)=>!TS_SCRIPT.test(texts[i]??"")&&!existsSync4(`${path}.d.ts`))),resolveImport=importResolver([root,...project.rootDirs],project.paths),svelteImportsOf=(content,component)=>{if(!content.includes(".svelte"))return[];let lexed=component?lexComponent2(content):void 0,ranges=lexed?[lexed.module,lexed.instance].flatMap((script)=>script?[[script.content.start,script.content.end]]:[]):[[0,content.length]],locate=createLocator(content);return ranges.flatMap(([start,end])=>lexImportsExports(content.slice(start,end)).flatMap((statement)=>{let specifier=statement.source?.value;if(!specifier?.endsWith(".svelte"))return[];let at=locate.position(start+(statement.source?.start??0));return[[specifier,at.line,at.column]]}))},tsSources=[...files.filter((_,i)=>TS_SCRIPT.test(texts[i]??"")),...listedFiles.filter((path)=>TS_MODULE.test(path))];for(let path of tsSources)for(let[specifier,line,column]of fileFacts.of(path,"svelteImports",(content)=>svelteImportsOf(content,path.endsWith(".svelte")))){let target=resolveImport(path,specifier);if(!target||!untyped.has(target))continue;diagnostics.push({file:path,line,column,severity:"error",source:"ts",code:"TS7016",message:`Could not find a declaration file for module '${specifier}'. '${asTypeScriptPath(target)}' implicitly has an 'any' type.`})}}if(project.tsconfig&&project.inputSpecs&&listedFiles.length===0)diagnostics.push({file:project.tsconfig,line:1,column:1,severity:"error",source:"ts",code:"TS18003",message:`No inputs were found in config file '${asTypeScriptPath(project.tsconfig)}'. Specified 'include' paths were '${JSON.stringify(project.inputSpecs.include)}' and 'exclude' paths were '${JSON.stringify(project.inputSpecs.exclude)}'.`});else if(project.tsconfig&&!options.components&&files.length===0)diagnostics.push({file:project.tsconfig,line:1,column:1,endLine:1,endColumn:1,severity:"warning",source:"svelte",code:"100001",message:`No svelte input files were found in config file '${asTypeScriptPath(project.tsconfig)}'. Did you forget to add svelte files to the 'include' in your ${basename3(project.tsconfig)}? Specified 'include' paths were '${JSON.stringify(project.raw.include)}' and 'exclude' paths were '${JSON.stringify(project.raw.exclude)}'`});let reported=errorsOnly?diagnostics.filter((d)=>d.severity==="error"):diagnostics,generatedOf=new Map([...outputs].map(([genPath,gen])=>[gen.svelte,genPath])),listed=listedFiles,listedSet=new Set(listed),imports=new Map,order=programOrder([...listed,...[...new Set(reported.map((d)=>d.file))].filter((file)=>!listedSet.has(file)).sort(byFolder)],(file)=>fileFacts.of(generatedOf.get(file)??file,"specifiers",(code)=>[...code.matchAll(STATIC_IMPORT),...code.matchAll(DYNAMIC_IMPORT)].map((m)=>m[1]??"")),importResolver([root,...project.rootDirs],project.paths),imports),skipped=0;if(options.only){let shown=new Set(options.only.map((path)=>resolve3(cwd,path)));for(let[file,targets]of imports)for(let target of targets)if(options.only.some((path)=>resolve3(cwd,path)===target))shown.add(file);let kept=reported.filter((d)=>shown.has(d.file));skipped=reported.length-kept.length,reported.length=0,reported.push(...kept)}let sourceRank=(d)=>d.source==="svelte"?0:1;reported.sort((a,b)=>(order.get(a.file)??0)-(order.get(b.file)??0)||sourceRank(a)-sourceRank(b));let result={diagnostics:reported,workspace,tsconfig:project.tsconfig,components:files.length,skipped,dropped,failed,checker,checkerVersion:command.version,timings:{emit:emitted-started,check:checked-emitted,compile:compiledAt-emitted}},inputs=[...order.keys()].filter((path)=>!under(path,outDir));if(incremental)await fileFacts.save();if(incremental)await writeFile(resultPath,JSON.stringify({key:runKey,inputs,inputsKey:hash(JSON.stringify(statsOf(inputs))),result}));return result}var FACTS_CACHE="files.json";async function factsCache(path,enabled){let entries=enabled?await readFile(path,"utf-8").then((text)=>{let cache=JSON.parse(text);return cache.format===CACHE_FORMAT?cache.entries:{}}).catch(()=>({})):{},used={};return{of(file,kind,compute){let stat=statsOf([file])[0]??"",facts=used[file]??entries[file];if(facts?.stat!==stat)facts={stat};return used[file]=facts,facts[kind]??=compute(readFileSync4(file,"utf-8")),facts[kind]},save:()=>writeFile(path,JSON.stringify({format:CACHE_FORMAT,entries:used}))}}function statsOf(paths){return paths.map((path)=>{let stat=statSync(path,{throwIfNoEntry:!1});return stat?`${path}:${stat.size}:${stat.mtimeMs}`:`${path}:-`})}var PACKAGE_FILES=["package.json","bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];function packageFilesOf(dir){let found=[];for(let at=dir;;at=dirname5(at))if(found.push(...PACKAGE_FILES.map((name)=>join6(at,name))),dirname5(at)===at)return found}import{watch as watchFiles}from"node:fs";import{resolve as resolve4,sep as sep3}from"node:path";var WATCHED=/\.(?:svelte|[cm]?[jt]sx?|json)$/,DEBOUNCE_MS=100;function watch2(options,onResult){let cwd=resolve4(options.cwd??process.cwd()),workspace=resolve4(cwd,options.workspace??"."),run={...options,cwd,incremental:!0},timer,running=!1,again=!1,check=async()=>{if(running){again=!0;return}running=!0;try{onResult(await typecheck2(run))}catch(error){onResult(error)}if(running=!1,again)again=!1,await check()},ignored=(path)=>path.split(sep3).some((part)=>part==="node_modules"||part.startsWith(".")),watcher=watchFiles(workspace,{recursive:!0},(_,filename)=>{if(!filename||ignored(filename)||!WATCHED.test(filename))return;clearTimeout(timer),timer=setTimeout(check,DEBOUNCE_MS)});return check(),()=>{clearTimeout(timer),watcher.close()}}import{readFileSync as readFileSync5}from"node:fs";import{relative as relative3,sep as sep4}from"node:path";var LINE_BREAK3=/\r?\n/;function keyer(workspace){let lines=new Map,lineOf=(d)=>{let text=lines.get(d.file);if(!text){try{text=readFileSync5(d.file,"utf-8").split(LINE_BREAK3)}catch{text=[]}lines.set(d.file,text)}return(text[d.line-1]??"").trim()},prefix=`${workspace}${sep4}`;return(d)=>({file:relative3(workspace,d.file).split(sep4).join("/"),code:d.code,message:d.message.replaceAll(prefix,""),line:lineOf(d)})}var
|
|
89
|
+
${d.message}`})}continue}let binding=d.code==="TS2322"?gen.emitted.bindingChecks.find((b)=>b.start<=offset&&offset<b.end):void 0;if(binding){let at=locator(gen.svelte,()=>gen.source).position(binding.from),end=locator(gen.svelte,()=>gen.source).position(binding.to);diagnostics.push({...d,file:gen.svelte,line:at.line,column:at.column,endLine:end.line,endColumn:end.column,severity:"error",source:gen.isTs?"ts":"js",message:nonBindableMessage(d.message)});continue}dropped.push({...d,file:abs,severity:"error",source:"ts"});continue}let within=(ranges)=>ranges.some(([from,to])=>from<=source&&source<to);if(REACTIVE_NOISE.test(d.code)&&within(gen.emitted.reactive)||d.code==="TS2554"&&d.message.startsWith("Expected 3 arguments")&&within(gen.emitted.transitions))continue;let start=locator(gen.svelte,()=>gen.source).position(source);mapped=withHint({...d,file:gen.svelte,line:start.line,column:start.column,...endOf(gen.source,source,gen.svelte),severity:"error",source:gen.isTs?"ts":"js"},svelteMajor)}else if(inOutput(d.file)||!project.reports(abs)){if(inOutput(d.file))dropped.push({...d,file:abs,severity:"error",source:"ts"});continue}else{let content=readFileSync4(abs,"utf-8"),offset=locator(abs,()=>content).offset(d.line,d.column);mapped={...d,file:abs,...endOf(content,offset,abs),severity:"error",source:JS_FILE2.test(abs)?"js":"ts"}}let key=`${mapped.file}:${mapped.line}:${mapped.column}:${mapped.code}`;if(seen.has(key))continue;seen.add(key),diagnostics.push(mapped)}diagnostics.push(...storeErrors);let generatedPath=new RegExp(`${escapeRegExp(`${toPosix2(genDir)}/`)}[^"'\\s]*`,"gi");for(let d of diagnostics)if(d.message=d.message.replace(generatedPath,(path)=>asTypeScriptPath(join6(root,relative2(toPosix2(genDir),path)).replace(GENERATED_NAME,"$1.svelte"))),process.platform==="win32")d.message=d.message.replace(DRIVE_PATH,(drive)=>drive.toLowerCase());if(diagnostics.push(...compiled),sources.has("js"))diagnostics.push(...parseErrors);if(sources.has("js")&&project.tsconfig&&!project.allowJs){let untyped=new Set(files.filter((path,i)=>!TS_SCRIPT.test(texts[i]??"")&&!existsSync4(`${path}.d.ts`))),resolveImport=importResolver([root,...project.rootDirs],project.paths),svelteImportsOf=(content,component)=>{if(!content.includes(".svelte"))return[];let lexed=component?lexComponent2(content):void 0,ranges=lexed?[lexed.module,lexed.instance].flatMap((script)=>script?[[script.content.start,script.content.end]]:[]):[[0,content.length]],locate=createLocator(content);return ranges.flatMap(([start,end])=>lexImportsExports(content.slice(start,end)).flatMap((statement)=>{let specifier=statement.source?.value;if(!specifier?.endsWith(".svelte"))return[];let at=locate.position(start+(statement.source?.start??0));return[[specifier,at.line,at.column]]}))},tsSources=[...files.filter((_,i)=>TS_SCRIPT.test(texts[i]??"")),...listedFiles.filter((path)=>TS_MODULE.test(path))];for(let path of tsSources)for(let[specifier,line,column]of fileFacts.of(path,"svelteImports",(content)=>svelteImportsOf(content,path.endsWith(".svelte")))){let target=resolveImport(path,specifier);if(!target||!untyped.has(target))continue;diagnostics.push({file:path,line,column,severity:"error",source:"ts",code:"TS7016",message:`Could not find a declaration file for module '${specifier}'. '${asTypeScriptPath(target)}' implicitly has an 'any' type.`})}}if(project.tsconfig&&project.inputSpecs&&listedFiles.length===0)diagnostics.push({file:project.tsconfig,line:1,column:1,severity:"error",source:"ts",code:"TS18003",message:`No inputs were found in config file '${asTypeScriptPath(project.tsconfig)}'. Specified 'include' paths were '${JSON.stringify(project.inputSpecs.include)}' and 'exclude' paths were '${JSON.stringify(project.inputSpecs.exclude)}'.`});else if(project.tsconfig&&!options.components&&files.length===0)diagnostics.push({file:project.tsconfig,line:1,column:1,endLine:1,endColumn:1,severity:"warning",source:"svelte",code:"100001",message:`No svelte input files were found in config file '${asTypeScriptPath(project.tsconfig)}'. Did you forget to add svelte files to the 'include' in your ${basename3(project.tsconfig)}? Specified 'include' paths were '${JSON.stringify(project.raw.include)}' and 'exclude' paths were '${JSON.stringify(project.raw.exclude)}'`});let reported=errorsOnly?diagnostics.filter((d)=>d.severity==="error"):diagnostics,generatedOf=new Map([...outputs].map(([genPath,gen])=>[gen.svelte,genPath])),listed=listedFiles,listedSet=new Set(listed),imports=new Map,order=programOrder([...listed,...[...new Set(reported.map((d)=>d.file))].filter((file)=>!listedSet.has(file)).sort(byFolder)],(file)=>fileFacts.of(generatedOf.get(file)??file,"specifiers",(code)=>[...code.matchAll(STATIC_IMPORT),...code.matchAll(DYNAMIC_IMPORT)].map((m)=>m[1]??"")),importResolver([root,...project.rootDirs],project.paths),imports),skipped=0;if(options.only){let shown=new Set(options.only.map((path)=>resolve3(cwd,path)));for(let[file,targets]of imports)for(let target of targets)if(options.only.some((path)=>resolve3(cwd,path)===target))shown.add(file);let kept=reported.filter((d)=>shown.has(d.file));skipped=reported.length-kept.length,reported.length=0,reported.push(...kept)}let sourceRank=(d)=>d.source==="svelte"?0:1;reported.sort((a,b)=>(order.get(a.file)??0)-(order.get(b.file)??0)||sourceRank(a)-sourceRank(b));let result={diagnostics:reported,workspace,tsconfig:project.tsconfig,components:files.length,skipped,dropped,failed,checker,checkerVersion:command.version,timings:{emit:emitted-started,check:checked-emitted,compile:compiledAt-emitted}},inputs=[...order.keys()].filter((path)=>!under(path,outDir)).flatMap((path)=>[path,...declarationsBeside(path)]);if(incremental)await fileFacts.save();if(incremental)await writeFile(resultPath,JSON.stringify({key:runKey,inputs,inputsKey:hash(JSON.stringify(statsOf(inputs))),result}));return result}var FACTS_CACHE="files.json";async function factsCache(path,enabled){let entries=enabled?await readFile(path,"utf-8").then((text)=>{let cache=JSON.parse(text);return cache.format===CACHE_FORMAT?cache.entries:{}}).catch(()=>({})):{},used={};return{of(file,kind,compute){let stat=statsOf([file])[0]??"",facts=used[file]??entries[file];if(facts?.stat!==stat)facts={stat};return used[file]=facts,facts[kind]??=compute(readFileSync4(file,"utf-8")),facts[kind]},save:()=>writeFile(path,JSON.stringify({format:CACHE_FORMAT,entries:used}))}}function declarationsBeside(path){return JS_EXTENSION.test(path)?[path.replace(JS_EXTENSION,".d.$1ts")]:[]}function statsOf(paths){return paths.map((path)=>{let stat=statSync(path,{throwIfNoEntry:!1});return stat?`${path}:${stat.size}:${stat.mtimeMs}`:`${path}:-`})}var PACKAGE_FILES=["package.json","bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];function packageFilesOf(dir){let found=[];for(let at=dir;;at=dirname5(at))if(found.push(...PACKAGE_FILES.map((name)=>join6(at,name))),dirname5(at)===at)return found}import{watch as watchFiles}from"node:fs";import{resolve as resolve4,sep as sep3}from"node:path";var WATCHED=/\.(?:svelte|[cm]?[jt]sx?|json)$/,DEBOUNCE_MS=100;function watch2(options,onResult){let cwd=resolve4(options.cwd??process.cwd()),workspace=resolve4(cwd,options.workspace??"."),run={...options,cwd,incremental:!0},timer,running=!1,again=!1,check=async()=>{if(running){again=!0;return}running=!0;try{onResult(await typecheck2(run))}catch(error){onResult(error)}if(running=!1,again)again=!1,await check()},ignored=(path)=>path.split(sep3).some((part)=>part==="node_modules"||part.startsWith(".")),watcher=watchFiles(workspace,{recursive:!0},(_,filename)=>{if(!filename||ignored(filename)||!WATCHED.test(filename))return;clearTimeout(timer),timer=setTimeout(check,DEBOUNCE_MS)});return check(),()=>{clearTimeout(timer),watcher.close()}}import{readFileSync as readFileSync5}from"node:fs";import{relative as relative3,sep as sep4}from"node:path";var LINE_BREAK3=/\r?\n/;function keyer(workspace){let lines=new Map,lineOf=(d)=>{let text=lines.get(d.file);if(!text){try{text=readFileSync5(d.file,"utf-8").split(LINE_BREAK3)}catch{text=[]}lines.set(d.file,text)}return(text[d.line-1]??"").trim()},prefix=`${workspace}${sep4}`;return(d)=>({file:relative3(workspace,d.file).split(sep4).join("/"),code:d.code,message:d.message.replaceAll(prefix,""),line:lineOf(d)})}var keyOf2=(e)=>JSON.stringify([e.file,e.code,e.message,e.line]);function createBaseline2(diagnostics,workspace){let toEntry=keyer(workspace),entries=new Map;for(let d of diagnostics){let entry=toEntry(d),key=keyOf2(entry),found=entries.get(key);if(found)found.count++;else entries.set(key,{...entry,count:1})}return{version:1,diagnostics:[...entries.entries()].sort(([a],[b])=>a<b?-1:Number(a>b)).map(([,entry])=>entry)}}function applyBaseline2(diagnostics,baseline,workspace){let toEntry=keyer(workspace),left=new Map(baseline.diagnostics.map((e)=>[keyOf2(e),e.count])),fresh=[],known=0;for(let d of diagnostics){let key=keyOf2(toEntry(d)),count=left.get(key)??0;if(count>0)left.set(key,count-1),known++;else fresh.push(d)}let fixed=0;for(let count of left.values())fixed+=count;return{diagnostics:fresh,known,fixed}}
|
|
83
90
|
export{compilerDiagnostics2,EmitError,typecheck2,watch2,createBaseline2,applyBaseline2};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{version2,package_default}from"./shared-zgnhwdjy.js";export{package_default as default,version2 as version};
|
package/shims/shims.d.ts
CHANGED
|
@@ -106,11 +106,12 @@ type __sveltets_2_SvelteTransitionConfig = {
|
|
|
106
106
|
css?: (t: number, u: number) => string;
|
|
107
107
|
tick?: (t: number, u: number) => void;
|
|
108
108
|
};
|
|
109
|
+
type __sveltets_2_SvelteTransitionReturnType =
|
|
110
|
+
| __sveltets_2_SvelteTransitionConfig
|
|
111
|
+
| (() => __sveltets_2_SvelteTransitionConfig);
|
|
109
112
|
/** `transition:`, `in:` and `out:`. */
|
|
110
113
|
declare function __sveltets_2_ensureTransition(
|
|
111
|
-
transitionCall:
|
|
112
|
-
| __sveltets_2_SvelteTransitionConfig
|
|
113
|
-
| (() => __sveltets_2_SvelteTransitionConfig),
|
|
114
|
+
transitionCall: __sveltets_2_SvelteTransitionReturnType,
|
|
114
115
|
): {};
|
|
115
116
|
|
|
116
117
|
// --- `$$Props`, `$$Events`, `$$Slots`.
|
|
@@ -137,13 +138,16 @@ declare function __sveltets_2_createCreateSlot<
|
|
|
137
138
|
// --- `animate:`.
|
|
138
139
|
|
|
139
140
|
declare var __sveltets_2_AnimationMove: { from: DOMRect; to: DOMRect };
|
|
140
|
-
|
|
141
|
+
type __sveltets_2_SvelteAnimationReturnType = {
|
|
141
142
|
delay?: number;
|
|
142
143
|
duration?: number;
|
|
143
144
|
easing?: (t: number) => number;
|
|
144
145
|
css?: (t: number, u: number) => string;
|
|
145
146
|
tick?: (t: number, u: number) => void;
|
|
146
|
-
}
|
|
147
|
+
};
|
|
148
|
+
declare function __sveltets_2_ensureAnimation(
|
|
149
|
+
animationCall: __sveltets_2_SvelteAnimationReturnType,
|
|
150
|
+
): {};
|
|
147
151
|
|
|
148
152
|
// --- Events.
|
|
149
153
|
|
|
@@ -282,6 +286,22 @@ declare function __sveltets_2_partial_with_any<
|
|
|
282
286
|
exports?: Exports;
|
|
283
287
|
bindings?: Bindings;
|
|
284
288
|
};
|
|
289
|
+
/** A TypeScript component that reads `$$props` or `$$restProps`: any prop. */
|
|
290
|
+
declare function __sveltets_2_with_any<
|
|
291
|
+
Props = {},
|
|
292
|
+
Events = {},
|
|
293
|
+
Slots = {},
|
|
294
|
+
Exports = {},
|
|
295
|
+
Bindings = string,
|
|
296
|
+
>(
|
|
297
|
+
render: SvelteRender<Props, Events, Slots, Exports, Bindings>,
|
|
298
|
+
): {
|
|
299
|
+
props: Expand<Props & SvelteAllProps>;
|
|
300
|
+
events: Events;
|
|
301
|
+
slots: Slots;
|
|
302
|
+
exports?: Exports;
|
|
303
|
+
bindings?: Bindings;
|
|
304
|
+
};
|
|
285
305
|
/** Any event name, with a `CustomEvent`. */
|
|
286
306
|
declare function __sveltets_2_with_any_event<
|
|
287
307
|
Props = {},
|
|
@@ -396,3 +416,11 @@ declare function __sveltets_2_get_set_binding<T>(
|
|
|
396
416
|
get: (() => T) | null | undefined,
|
|
397
417
|
set: (t: T) => void,
|
|
398
418
|
): T;
|
|
419
|
+
/**
|
|
420
|
+
* A `<svelte:element>` tag, as `string` when it may be any element (a
|
|
421
|
+
* component's generic tag): typed as every element's tag, its attributes
|
|
422
|
+
* are a union TypeScript can't represent. A smaller union keeps its tags.
|
|
423
|
+
*/
|
|
424
|
+
declare function __sveltets_2_elementTag<T extends string>(
|
|
425
|
+
tag: T | undefined | null,
|
|
426
|
+
): keyof HTMLElementTagNameMap extends T ? string : T;
|
package/shared-9x993ww1.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{version2,package_default}from"./shared-a6ge4681.js";export{package_default as default,version2 as version};
|
package/shared-a6ge4681.js
DELETED