tjs-lang 0.7.8 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +14 -1
- package/CONTEXT.md +4 -0
- package/demo/docs.json +66 -696
- package/demo/src/ts-examples.ts +8 -8
- package/dist/eslint.config.d.ts +2 -0
- package/dist/index.js +137 -135
- package/dist/index.js.map +4 -4
- package/dist/src/lang/emitters/js-wasm.d.ts +5 -1
- package/dist/src/lang/emitters/js.d.ts +9 -0
- package/dist/src/lang/index.d.ts +1 -0
- package/dist/src/lang/module-loader.d.ts +125 -0
- package/dist/src/lang/parser-transforms.d.ts +79 -0
- package/dist/src/lang/parser-types.d.ts +33 -0
- package/dist/src/lang/wasm.d.ts +67 -1
- package/dist/tjs-batteries.js +2 -2
- package/dist/tjs-batteries.js.map +2 -2
- package/dist/tjs-eval.js +39 -37
- package/dist/tjs-eval.js.map +3 -3
- package/dist/tjs-from-ts.js +2 -2
- package/dist/tjs-from-ts.js.map +2 -2
- package/dist/tjs-lang.js +102 -102
- package/dist/tjs-lang.js.map +3 -3
- package/dist/tjs-vm.js +50 -48
- package/dist/tjs-vm.js.map +3 -3
- package/docs/README.md +2 -0
- package/docs/lm-studio-setup.md +143 -0
- package/docs/universal-endpoint.md +122 -0
- package/llms.txt +8 -2
- package/package.json +11 -6
- package/src/batteries/audit.ts +3 -3
- package/src/batteries/llm.ts +8 -3
- package/src/builder.ts +0 -3
- package/src/cli/commands/test.ts +1 -1
- package/src/lang/docs.test.ts +148 -1
- package/src/lang/docs.ts +49 -15
- package/src/lang/emitters/from-ts.ts +1 -1
- package/src/lang/emitters/js-wasm.ts +57 -65
- package/src/lang/emitters/js.ts +16 -2
- package/src/lang/features.test.ts +4 -3
- package/src/lang/index.ts +9 -0
- package/src/lang/linter.ts +1 -1
- package/src/lang/module-loader.test.ts +322 -0
- package/src/lang/module-loader.ts +418 -0
- package/src/lang/parser-params.ts +1 -1
- package/src/lang/parser-transforms.ts +339 -9
- package/src/lang/parser-types.ts +33 -0
- package/src/lang/parser.ts +43 -2
- package/src/lang/perf.test.ts +10 -4
- package/src/lang/runtime.ts +0 -1
- package/src/lang/wasm.test.ts +1293 -2
- package/src/lang/wasm.ts +470 -87
- package/src/linalg/index.tjs +119 -0
- package/src/linalg/linalg.test.ts +300 -0
- package/src/linalg/vector-search.bench.test.ts +416 -0
- package/src/types/Type.ts +6 -6
- package/src/use-cases/asymmetric-client-server.test.ts +0 -2
- package/src/use-cases/client-server.test.ts +1 -1
- package/src/use-cases/unbundled-imports.test.ts +0 -1
- package/src/vm/runtime.ts +3 -3
- package/src/vm/vm.ts +3 -1
- package/dist/examples/modules/dist/main.d.ts +0 -34
- package/dist/examples/modules/dist/math.d.ts +0 -120
package/dist/tjs-lang.js
CHANGED
|
@@ -1,57 +1,59 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),r=this.line-1,s=Math.max(0,r-n),o=Math.min(t.length-1,r+n),i=[],a=String(o+1).length;for(let c=s;c<=o;c++){let l=String(c+1).padStart(a),
|
|
3
|
-
`)}};function
|
|
4
|
-
`)
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`)
|
|
11
|
-
${
|
|
1
|
+
var os=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var xr=os((Ao,Ks)=>{Ks.exports={name:"tjs-lang",version:"0.8.1",description:"Type-safe JavaScript dialect with runtime validation, sandboxed VM execution, and AI agent orchestration. Transpiles TypeScript to validated JS with fuel-metered execution for untrusted code.",keywords:["typescript","transpiler","runtime-validation","type-safety","sandbox","virtual-machine","wasm-alternative","ai-agents","llm","orchestration","security","fuel-metering","capability-based","json-ast","untrusted-code"],license:"Apache-2.0",main:"./dist/index.js",types:"./dist/src/index.d.ts",exports:{".":{bun:"./src/index.ts",types:"./dist/src/index.d.ts",default:"./dist/index.js"},"./eval":{bun:"./src/lang/eval.ts",types:"./dist/src/lang/eval.d.ts",default:"./dist/tjs-eval.js"},"./lang":{bun:"./src/lang/transpiler.ts",types:"./dist/src/lang/transpiler.d.ts",default:"./dist/tjs-lang.js"},"./lang/from-ts":{bun:"./src/lang/emitters/from-ts.ts",types:"./dist/src/lang/emitters/from-ts.d.ts",default:"./dist/tjs-from-ts.js"},"./vm":{bun:"./src/vm/index.ts",types:"./dist/src/vm/index.d.ts",default:"./dist/tjs-vm.js"},"./batteries":{bun:"./src/batteries/index.ts",types:"./dist/src/batteries/index.d.ts",default:"./dist/tjs-batteries.js"},"./linalg":{bun:"./src/linalg/index.tjs",default:"./dist/tjs-linalg.js"},"./src":"./src/index.ts","./editors/monaco":"./editors/monaco/ajs-monarch.js","./editors/codemirror":"./editors/codemirror/ajs-language.js","./editors/ace":"./editors/ace/ajs-mode.js"},bin:{tjs:"./src/cli/tjs.ts",tjsx:"./src/cli/tjsx.ts","tjs-playground":"./src/cli/playground.ts","create-tjs-app":"./src/cli/create-app.ts","ajs-install-vscode":"./bin/install-vscode.sh","ajs-install-cursor":"./bin/install-cursor.sh"},type:"module",files:["dist","src","docs","editors","bin","demo","tjs-lang.svg","CONTEXT.md","CLAUDE.md","llms.txt"],sideEffects:!1,repository:{type:"git",url:"https://github.com/tonioloewald/tjs-lang.git"},devDependencies:{"@codemirror/lang-css":"^6.3.1","@codemirror/lang-html":"^6.4.11","@codemirror/lang-javascript":"^6.2.4","@codemirror/lang-markdown":"^6.5.0","@codemirror/state":"^6.5.3","@codemirror/theme-one-dark":"^6.1.3","@codemirror/view":"^6.39.9","@eslint/js":"^10.0.1","@happy-dom/global-registrator":"^20.1.0","@types/bun":"latest","@types/jsdom":"^21.1.7","acorn-walk":"^8.3.4",chokidar:"^4.0.3",codemirror:"^6.0.2",esbuild:"^0.28.0",eslint:"^10.4.1",firebase:"^10.12.0","firebase-admin":"^13.6.0","firebase-functions":"^7.0.5",globals:"^17.6.0",marked:"^9.1.6",prettier:"^2.8.8",tosijs:"^1.5.6","tosijs-ui":"^1.4.7",typescript:"^5.6.2","typescript-eslint":"^8.61.0",valibot:"^0.36.0",vitest:"^2.0.5"},scripts:{format:"bun eslint src --fix && bun prettier --write .",lint:"eslint src","build:grammars":"bun editors/build-grammars.ts","test:fast":"SKIP_LLM_TESTS=1 SKIP_BENCHMARKS=1 bun test","test:llm":"bun test src/batteries/models.integration.test.ts",bench:"bun bin/benchmarks.ts",make:"rm -rf dist && bun format && bun run build:grammars && tsc -p tsconfig.build.json && bun scripts/build.ts","build:bundles":"bun scripts/build.ts",typecheck:"tsc --noEmit",latest:"rm -rf node_modules && bun install",docs:"node bin/docs.js",dev:"bun run bin/dev.ts","build:demo":"bun scripts/build-demo.ts","build:cli":"bun build src/cli/tjs.ts --compile --outfile=dist/tjs && bun build src/cli/tjsx.ts --compile --outfile=dist/tjsx","functions:build":"cd functions && npm run build","functions:deploy":"cd functions && npm run deploy","functions:serve":"cd functions && npm run serve","deploy:hosting":"bun run build:demo && firebase deploy --only hosting",deploy:"bun run build:demo && bun run functions:deploy && firebase deploy --only hosting",start:"bun run build:demo && bun run dev"},dependencies:{acorn:"^8.15.0","acorn-walk":"^8.3.4","tosijs-schema":"^1.3.0"}}});import*as ir from"acorn";var U=class extends Error{line;column;source;filename;constructor(n,t,r,s){let o=`${s||"<source>"}:${t.line}:${t.column}`;super(`${n} at ${o}`),this.name="TranspileError",this.line=t.line,this.column=t.column,this.source=r,this.filename=s}},Z=class extends U{constructor(n,t,r,s){super(n,t,r,s),this.name="SyntaxError"}formatWithContext(n=2){if(!this.source)return this.message;let t=this.source.split(`
|
|
2
|
+
`),r=this.line-1,s=Math.max(0,r-n),o=Math.min(t.length-1,r+n),i=[],a=String(o+1).length;for(let c=s;c<=o;c++){let l=String(c+1).padStart(a),f=c===r?">":" ";if(i.push(`${f} ${l} | ${t[c]}`),c===r){let p=" ".repeat(a+4+this.column);i.push(`${p}^ ${this.message.split(" at ")[0]}`)}}return i.join(`
|
|
3
|
+
`)}};function re(e){return{depth:e.depth+1,locals:new Map,parent:e,parameters:e.parameters,atoms:e.atoms,warnings:e.warnings,source:e.source,filename:e.filename,options:e.options}}function J(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function as(e,n){let t=e.match(n);if(!t)return null;let r=t.index+t[0].length-1,s=1,o=r+1;for(;o<e.length&&s>0;)e[o]==="{"?s++:e[o]==="}"&&s--,o++;if(s!==0)return null;let i=e.slice(r,o),a=[t[0].slice(0,-1)+i,i];return a.index=t.index,a}function Nn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\btry\s*\{/);if(r){let o=t+r[0].length-1+1,i=1,a=o;for(;a<e.length&&i>0;){let l=e[a];l==="{"?i++:l==="}"&&i--,a++}if(i!==0){n+=e[t],t++;continue}if(e.slice(a).match(/^\s*(catch|finally)\b/))n+=e.slice(t,a),t=a;else{let l=e.slice(o,a-1);n+=`try {${l}} catch (__try_err) { return new (__tjs?.MonadicError ?? Error)(__try_err?.message || String(__try_err), 'try', undefined, undefined, __tjs?.getStack?.()) }`,t=a}}else n+=e[t],t++}return n}function Pn(e){let n=[],t="",r=0,s=0;for(;r<e.length;){let o=e.slice(r).match(/^\bwasm\s*\{/);if(o){let i=r,a=r+o[0].length,c=1,l=a;for(;l<e.length&&c>0;){let g=e[l];g==="{"?c++:g==="}"&&c--,l++}if(c!==0){t+=e[r],r++;continue}let f=e.slice(a,l-1),p,u=l,m=e.slice(l).match(/^\s*fallback\s*\{/);if(m){let g=l+m[0].length;c=1;let E=g;for(;E<e.length&&c>0;){let k=e[E];k==="{"?c++:k==="}"&&c--,E++}c===0&&(p=e.slice(g,E-1),u=E)}let h=us(f).map(g=>{let E=fs(e,i,g);return E?`${g}: ${E}`:g}),w={id:`__tjs_wasm_${s}`,body:f,fallback:p,captures:h,start:i,end:u};n.push(w);let S=p??f,$=h.map(g=>g.split(":")[0].trim()),b=$.length>0?$.join(", "):"",_=$.length>0?`globalThis.${w.id}(${b})`:`globalThis.${w.id}()`,x=`(globalThis.${w.id} ? ${_} : (() => {${S}})())`;t+=x,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function In(e){let n=[],t="",r=0;for(;r<e.length;){let s=/^\b(export\s+)?wasm\s+function\s+(\w+)\s*\(/,o=e.slice(r).match(s);if(!o){t+=e[r],r++;continue}let i=!!o[1],a=o[2],c=r,l=r+o[0].length,f=1,p=l;for(;p<e.length&&f>0;)e[p]==="("?f++:e[p]===")"&&f--,p++;if(f!==0){t+=e[r],r++;continue}let u=e.slice(l,p-1);if(u.match(/^\s*!/))throw new Z(`Unsafe wasm functions (with \`!\` marker) are reserved for a future phase. Remove the bang from \`wasm function ${a}\` to declare it as a regular (pure) wasm function, or wait until the unsafe variant is implemented.`,fe(e,c));let y,h=p,w=e.slice(p).match(/^\s*:\s*(\w+)/);w&&(y=w[1],h=p+w[0].length);let S=e.slice(h).match(/^\s*\{/);if(!S){t+=e[r],r++;continue}let $=h+S[0].length,b=1,_=$;for(;_<e.length&&b>0;)e[_]==="{"?b++:e[_]==="}"&&b--,_++;if(b!==0){t+=e[r],r++;continue}let x=e.slice($,_-1),g=cs(u),E=`__tjs_wasm_${a}`,k={id:E,name:a,returnType:y,body:x,captures:g,start:c,end:_};n.push(k);let j=g.map(N=>N.split(":")[0].trim()),M=`${i?"export ":""}function ${a}(${j.join(", ")}) { return globalThis.${E}(${j.join(", ")}) }`;t+=M,r=_}return{source:t,blocks:n}}function Bn(e,n){let{loader:t,importerPath:r}=n;if(!t)return{source:e,blocks:[]};let s=[],o=new Set;function i(l,f){if(!o.has(l.id)){s.push(l),o.add(l.id);for(let[p,u]of f){if(p===l.name||o.has(u.id))continue;new RegExp(`\\b${p}\\s*\\(`).test(l.body)&&i(u,f)}}}let a=/^(\s*)import\s*\{([^}]*?)\}\s*from\s*(['"])([^'"]+)\3\s*;?\s*$/gm;return{source:e.replace(a,(l,f,p,u,m)=>{let y=t.load(m,r);if(!y)return l;let h=new Map;for(let x of y.parseResult.wasmBlocks)x.name&&h.set(x.name,x);if(h.size===0)return l;let w=p.split(",").map(x=>x.trim()).filter(x=>x.length>0),S=[],$=[];for(let x of w){let g=x.match(/^(\w+)(?:\s+as\s+(\w+))?$/);if(!g){$.push(x);continue}let E=g[1],k=g[2]??g[1],j=h.get(E);if(!j){$.push(x);continue}i(j,h);let A=j.captures.map(M=>M.split(":")[0].trim());S.push(`function ${k}(${A.join(", ")}) { return globalThis.${j.id}(${A.join(", ")}) }`)}let b=S.join(`
|
|
4
|
+
`);if($.length===0)return b?`${f}${b}`:`${f}`;let _=`${f}import { ${$.join(", ")} } from '${m}'`;return b?`${_}
|
|
5
|
+
${f}${b}`:_}),blocks:s}}function cs(e){let n=e.trim();return n?n.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function ls(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function us(e){let n=e.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),t=new Set,r=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,s;for(;(s=r.exec(n))!==null;)t.add(s[1]);let o=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,i=new Set;for(;(s=o.exec(n))!==null;)i.add(s[1]);for(let u of t){if(!i.has(u))continue;let m=new RegExp(`(?<!\\.)\\b${u}\\b`,"g"),y=new RegExp(`\\.${u}\\b`,"g"),h=n.match(m)?.length||0,w=n.match(y)?.length||0;h<=w&&i.delete(u)}let a=new Set,c=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=c.exec(n))!==null;)a.add(s[1]);let l=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=l.exec(n))!==null;)a.add(s[1]);let f=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","let","const","var","new","this","true","false","null","undefined","typeof","instanceof","in","of","try","catch","finally","throw","async","await","class","extends","super","import","export","default","from","as","static","get","set","yield","console","Math","Array","Object","String","Number","Boolean","Date","JSON","Promise","Map","Set","WeakMap","WeakSet","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","ArrayBuffer","DataView","Error","TypeError","RangeError","length","push","pop","shift","unshift","slice","splice","map","filter","reduce","forEach","find","findIndex","indexOf","includes","globalThis","window","document","Infinity","NaN","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","eval","wasmBuffer"]),p=[];for(let u of i)!a.has(u)&&!f.has(u)&&!ls(u)&&p.push(u);return p.sort()}function fs(e,n,t){let r=e.slice(0,n),s=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,o=r.match(s);if(!o){let i=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,a=r.match(i);return a?An(a[1],t):void 0}return An(o[1],t)}function An(e,n){let t=e.split(",").map(r=>r.trim());for(let r of t){let s=r.match(new RegExp(`^${n}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(s)return s[1];let o=r.match(new RegExp(`^${n}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(o)return o[1]}}function Ue(e){let n=`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,t=new RegExp(n+"\\s+IsNot\\s+"+n,"g");e=e.replace(t,"IsNot($1, $2)");let r=new RegExp(n+"\\s+Is\\s+"+n,"g");return e=e.replace(r,"Is($1, $2)"),e}function On(e){let n=/^[\s]*[([`]/,t=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,r=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,s=e.split(`
|
|
6
|
+
`),o=[],i=!1;for(let a=0;a<s.length;a++){let c=s[a],l=a>0?s[a-1]:"";if(i){o.push(c),c.includes("*/")&&(i=!1);continue}let f=c.indexOf("/*"),p=c.indexOf("*/");if(f!==-1&&(p===-1||p<f)){i=!0,o.push(c);continue}if(a>0&&n.test(c)){let u=l.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!t.test(u)&&!r.test(u)){let m=c.match(/^(\s*)/),y=m?m[1]:"",h=c.slice(y.length);o.push(y+";"+h);continue}}o.push(c)}return o.join(`
|
|
7
|
+
`)}function ps(e){let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
|
|
8
|
+
`&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let c=t-1;for(;c>=0&&/\s/.test(e[c]);)c--;let l=c>=0?e[c]:"";if(!l||/[=(!,;:{[&|?+\-*%<>~^]/.test(l)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){t++,r="regex";continue}}if(i==="t"&&e.slice(t,t+6)==="typeof"&&(t===0||!/[\w$]/.test(e[t-1]))&&/\s/.test(e[t+6]??"")){let c=t+6;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&/[a-zA-Z_$]/.test(e[c])){let l=c;for(;c<e.length&&/[\w$]/.test(e[c]);)c++;for(;c<e.length;)if(e[c]==="."&&/[a-zA-Z_$]/.test(e[c+1]??""))for(c++;c<e.length&&/[\w$]/.test(e[c]);)c++;else if(e[c]==="?"&&e[c+1]==="."&&/[a-zA-Z_$]/.test(e[c+2]??""))for(c+=2;c<e.length&&/[\w$]/.test(e[c]);)c++;else break;n.push({keywordStart:t,operandEnd:c,operand:e.slice(l,c)}),t=c;continue}}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let a=n[i];o=o.slice(0,a.keywordStart)+`TypeOf(${a.operand})`+o.slice(a.operandEnd)}return o}function We(e){e=ps(e);let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
|
|
9
|
+
`&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let c=t-1;for(;c>=0&&/\s/.test(e[c]);)c--;let l=c>=0?e[c]:"";if(!l||/[=(!,;:{[&|?+\-*%<>~^]/.test(l)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){t++,r="regex";continue}}if(i==="="&&a==="="&&e[t+2]!=="="&&e[t-1]!=="!"){n.push({pos:t,op:"=="}),t+=2;continue}if(i==="!"&&a==="="&&e[t+2]!=="="){n.push({pos:t,op:"!="}),t+=2;continue}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let{pos:a,op:c}=n[i],l=c==="=="?"Eq":"NotEq",f=ms(o,a),p=ds(o,a+2),u=o.slice(f,a).trim(),m=o.slice(a+2,p).trim();if(u&&m){let y=o.slice(0,f),h=o.slice(p),S=/[a-zA-Z0-9_$]$/.test(y)?" ":"";o=`${y}${S}${l}(${u}, ${m})${h}`}}return o}function ms(e,n){let t=n-1;for(;t>=0&&/\s/.test(e[t]);)t--;if(t<0)return 0;let r=0,s=!1,o="";for(;t>=0;){let i=e[t],a=t>0?e[t-1]:"";if(s){i===o&&a!=="\\"&&(s=!1),t--;continue}if((i==='"'||i==="'"||i==="`")&&a!=="\\"){s=!0,o=i,t--;continue}if(i===")"||i==="]"||i==="}"){r++,t--;continue}if(i==="("||i==="["){if(r>0){r--,t--;continue}return t+1}if(i==="{"){if(r>0){r--,t--;continue}return t+1}if(r>0){t--;continue}if(i===";")return t+1;if(/[a-z]/.test(i)){let c=t+1,l=t;for(;l>0&&/[a-z]/i.test(e[l-1]);)l--;let f=e.slice(l,c),p=l>0?e[l-1]:"";if(!/[a-zA-Z0-9_$]/.test(p)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(f))return c;if(f==="new")return l}}if(i===">"&&a==="="||i==="="&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"||i==="&"&&a==="&"||i==="|"&&a==="|"||i==="?"||i===":"||i===",")return t+1;t--}return 0}function ds(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return e.length;let r=0,s=!1,o="";for(;t<e.length;){let i=e[t],a=t+1<e.length?e[t+1]:"";if(s){i===o&&e[t-1]!=="\\"&&(s=!1),t++;continue}if((i==='"'||i==="'"||i==="`")&&e[t-1]!=="\\"){s=!0,o=i,t++;continue}if(i==="("||i==="["||i==="{"){r++,t++;continue}if(i===")"||i==="]"||i==="}"){if(r>0){r--,t++;continue}return t}if(r>0){t++;continue}if(i===";"||i==="&"&&a==="&"||i==="|"&&a==="|"||i==="?"||i===":"||i===","||(i==="="||i==="!")&&a==="="&&e[t+2]!=="=")return t;t++}return e.length}function Dn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(r){let s=r[1],o=t+r[0].length,i=s,a=!1,c=e.slice(o).match(/^(['"`])([^]*?)\1\s*/);if(c){let u=o+c[0].length,m=e[u],y=m===void 0||u>=e.length||m!=="="&&m!=="{";if(m==="="||m==="{")i=c[2],a=!0,o=u;else if(y){let h=c[0].trim(),w=c[0].slice(h.length);n+=`const ${s} = Type('${s}', ${h})${w}`,t=u;continue}}let l,f=o,p=e.slice(o).match(/^=\s*/);if(p){o+=p[0].length;let u=e.slice(o).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(u){l=u[0],o+=u[0].length,f=o;let m=e.slice(o).match(/^\s*/);m&&(o+=m[0].length)}}if(e[o]==="{"){let u=o+1,m=1,y=u;for(;y<e.length&&m>0;){let x=e[y];x==="{"?m++:x==="}"&&m--,y++}if(m!==0){n+=e[t],t++;continue}let h=e.slice(u,y-1).trim(),w=y,S=h.match(/description\s*:\s*(['"`])([^]*?)\1/);S&&!a&&(i=S[2]);let $,b=h.match(/example\s*:\s*/);if(b){let x=b.index+b[0].length,g=nr(h,x);g&&($=g.value.trim())}let _=h.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(_&&$){let x=_[1].trim(),g=_[2].trim(),E=l?`, ${l}`:"";n+=`const ${s} = Type('${i}', (${x}) => { if (!globalThis.__tjs?.validate(${x}, globalThis.__tjs?.infer(${$}))) return false; ${g} }, ${$}${E})`}else if(_){let x=_[1].trim(),g=_[2].trim(),E=l?`, undefined, ${l}`:"";n+=`const ${s} = Type('${i}', (${x}) => { ${g} }${E})`}else if($){let x=l?`, ${l}`:"";n+=`const ${s} = Type('${i}', undefined, ${$}${x})`}else l?n+=`const ${s} = Type('${i}', ${l})`:n+=`const ${s} = Type('${i}')`;t=w;continue}else if(l){n+=`const ${s} = Type('${i}', ${l})`,t=f;continue}else if(!c){let u=e.slice(o).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(u){let m=u[0];n+=`const ${s} = Type('${s}', ${m})`,t=o+u[0].length;continue}}}n+=e[t],t++}return n}function Fn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bFunctionPredicate\s+([A-Z_][a-zA-Z0-9_]*)\s*(?:<([^>]+)>)?\s*/);if(r){let s=r[1],o=r[2],i=t+r[0].length;if(e[i]==="{"){let a=1,c=i+1;for(;c<e.length&&a>0;)e[c]==="{"?a++:e[c]==="}"&&a--,c++;if(a===0){let l=e.slice(i+1,c-1).trim(),f=as(l,/params\s*:\s*\{/),p=l.match(/returns\s*:\s*(.+?)(?:\n|$)/),u=l.match(/returnContract\s*:\s*['"](\w+)['"]/),m=l.match(/description\s*:\s*(['"])([^]*?)\1/),y=[];f&&y.push(`params: ${f[1]}`),p&&y.push(`returns: ${p[1].trim()}`),u&&y.push(`returnContract: '${u[1]}'`);let h=m?m[2]:s;if(o){let w=o.split(",").map($=>{let b=$.trim().split("=").map(_=>_.trim());if(b.length===2){let _=b[1]==="any"||b[1]==="undefined"?"null":b[1];return`['${b[0]}', ${_}]`}return`'${b[0]}'`}),S=o.split(",").map($=>$.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${h}', [${w.join(", ")}], (${S.join(", ")}) => ({ ${y.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${h}', { ${y.join(", ")} })`;t=c;continue}}if(e[i]==="("){let a=1,c=i+1;for(;c<e.length&&a>0;)e[c]==="("?a++:e[c]===")"&&a--,c++;if(a===0){let l=e.slice(i+1,c-1).trim(),f=l.indexOf(",");if(f!==-1){let p=l.slice(0,f).trim(),u=l.slice(f+1).trim();n+=`const ${s} = FunctionPredicate(${u}, ${p})`}else n+=`const ${s} = FunctionPredicate('${s}', ${l})`;t=c;continue}}}n+=e[t],t++}return n}function qn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(r){let s=r[1],o=r[2],a=t+r[0].length-1+1,c=1,l=a;for(;l<e.length&&c>0;){let $=e[l];$==="{"?c++:$==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let f=e.slice(a,l-1).trim(),p=l,u=o.split(",").map($=>{let b=$.trim().split("=").map(_=>_.trim());if(b.length===2){let _=b[1]==="any"||b[1]==="undefined"?"null":b[1];return`['${b[0]}', ${_}]`}return`'${b[0]}'`}),m=f,y=m.search(/\bdeclaration\s*\{/);if(y!==-1){let $=m.indexOf("{",y),b=1,_=$+1;for(;_<m.length&&b>0;)m[_]==="{"?b++:m[_]==="}"&&b--,_++;m=m.slice(0,y)+m.slice(_)}let h=m.match(/description\s*:\s*(['"`])([^]*?)\1/),w=m.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),S=h?h[2]:s;if(w){let $=w[1].trim().split(",").map(E=>E.trim()),b=w[2].trim(),_=$[0]||"x",x=$.slice(1),g=x.map(E=>`check${E}`);x.forEach((E,k)=>{b=b.replace(new RegExp(`\\b${E}\\s*\\(`,"g"),`${g[k]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${_}, ${g.join(", ")}) => { ${b} }, '${S}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${S}')`;t=p;continue}n+=e[t],t++}return n}function Un(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(r){let s=r[1],o=r[3],i=t+r[0].length;if(e[i]==="{"){let a=i+1,c=1,l=a;for(;l<e.length&&c>0;){let m=e[l];m==="{"?c++:m==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let f=e.slice(a,l-1).trim(),p=l,u=Rn(f);n+=`const ${s} = Union('${o}', [${u.join(", ")}])`,t=p;continue}else{let a=e.indexOf(`
|
|
10
|
+
`,i);a===-1&&(a=e.length);let c=e.slice(i,a).trim();if(c){let l=Rn(c);n+=`const ${s} = Union('${o}', [${l.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function Rn(e){let n=[],t=e.split("|").map(r=>r.trim());for(let r of t)r&&n.push(r);return n}function Wn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(r){let s=r[1],o=r[3],a=t+r[0].length-1+1,c=1,l=a;for(;l<e.length&&c>0;){let y=e[l];y==="{"?c++:y==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let f=e.slice(a,l-1).trim(),p=l,m=ys(f).map(([y,h])=>`${y}: ${h}`).join(", ");n+=`const ${s} = Enum('${o}', { ${m} })`,t=p;continue}n+=e[t],t++}return n}function ys(e){let n=[],t=0,r=e.split(/[\n,]/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("//"));for(let s of r){let o=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(o){let i=o[1],a=o[2]?.trim();if(a!==void 0){n.push([i,a]);let c=Number(a);isNaN(c)||(t=c+1)}else n.push([i,String(t)]),t++}}return n}function Ln(e){let n=new Map,t="",r=0;for(;r<e.length;){let s=e.slice(r),o=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/);if(!o){if(r===0||e[r-1]===`
|
|
11
|
+
`||e[r-1]===";"||e[r-1]==="}"){let b=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/)}t+=e[r],r++;continue}let i=o[1],a=o[2],c=r+o[0].length-1,l=qe(e,c),f=e.slice(c+1,l-1).trim(),p=[],u=0,m=e.slice(c+1,l-1);for(;u<m.length;){let b=m.slice(u).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!b){u++;continue}let _=b[1],x=!!b[2],g=b[3],E=u+b[0].length-1,k=1,j=E+1;for(;j<m.length&&k>0;)m[j]==="("&&k++,m[j]===")"&&k--,j++;let A=m.slice(E+1,j-1),M=j;for(;M<m.length&&/\s/.test(m[M]);)M++;if(m[M]==="="&&m[M+1]===">"){let V=fe(e,c+1+u);throw new Z(`Arrow functions are not allowed in extend blocks (method '${g}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,V)}if(m[M]!=="{"){u++;continue}let N=qe(m,M),R=m.slice(u,N).trim(),I=A.split(",").map(V=>V.trim()).filter(V=>V.length>0).map(V=>{let Q=V.match(/^(\w+)\s*:\s*(.+)$/);return Q?`${Q[1]} = ${Q[2]}`:V}).join(", "),O=x?"async ":"",L=m.slice(M+1,N-1);p.push({name:g,isAsync:x,fullText:`${g}: ${O}function(${I}) {${L}}`}),u=N}let y=!n.has(a);y&&n.set(a,new Set);let h=n.get(a);for(let $ of p)h.add($.name);let w=p.map($=>` ${$.fullText}`).join(`,
|
|
12
|
+
`),S;y?S=`${i}const __ext_${a} = {
|
|
13
|
+
${w}
|
|
12
14
|
${i}}
|
|
13
|
-
|
|
14
|
-
${
|
|
15
|
+
`:S=`${i}Object.assign(__ext_${a}, {
|
|
16
|
+
${w}
|
|
15
17
|
${i}})
|
|
16
|
-
`;for(let
|
|
17
|
-
`;t
|
|
18
|
-
`?(t++,r=0):r++;return{line:t,column:r}}function
|
|
19
|
-
`&&(o=!1),r++;continue}if(i){if(a==="*"&&c==="/"){i=!1,r+=2;continue}r++;continue}if(s){if(a==="\\"){r+=2;continue}a===s&&(s=!1),r++;continue}if(a==="/"&&c==="/"){o=!0,r+=2;continue}if(a==="/"&&c==="*"){i=!0,r+=2;continue}if(a==="'"||a==='"'||a==="`"){s=a,r++;continue}a==="{"&&t++,a==="}"&&t--,r++}return r}function
|
|
20
|
-
${
|
|
21
|
-
${
|
|
18
|
+
`;for(let $ of p)S+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${$.name}', __ext_${a}.${$.name}) }
|
|
19
|
+
`;t+=S,r=l}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function Le(e,n){if(n.size===0)return e;let t=new Map;for(let[s,o]of n)for(let i of o)t.has(i)||t.set(i,[]),t.get(i).push(s);let r=e;for(let[s,o]of t){if(!o.includes("String"))continue;let i=new RegExp(`('(?:[^'\\\\]|\\\\.)*')\\.(${s})\\((\\))?`,"g");r=r.replace(i,(l,f,p,u)=>u?`__ext_String.${p}.call(${f})`:`__ext_String.${p}.call(${f}, `);let a=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${s})\\((\\))?`,"g");r=r.replace(a,(l,f,p,u)=>u?`__ext_String.${p}.call(${f})`:`__ext_String.${p}.call(${f}, `);let c=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+s+"\\((\\))?","g");r=r.replace(c,(l,f,p)=>p?`__ext_String.${s}.call(${f})`:`__ext_String.${s}.call(${f}, `)}for(let[s,o]of t){if(!o.includes("Array"))continue;let i=`].${s}(`,a=0,c;for(;(c=r.indexOf(i,a))!==-1;){let l=1,f=c-1,p=!1;for(;f>=0&&l>0;){let u=r[f];p?u===p&&(f===0||r[f-1]!=="\\")&&(p=!1):(u==="]"&&l++,u==="["&&l--,(u==="'"||u==='"'||u==="`")&&(p=u)),f--}if(l===0){let u=r.slice(f+1,c+1),m=r.slice(0,f+1),y=r.slice(c+i.length);y[0]===")"?r=`${m}__ext_Array.${s}.call(${u})${y.slice(1)}`:r=`${m}__ext_Array.${s}.call(${u}, ${y}`}a=c+1}}for(let[s,o]of t){if(!o.includes("Number"))continue;let i=new RegExp(`(\\d+(?:\\.\\d+)?)\\.(${s})\\((\\))?`,"g");r=r.replace(i,(a,c,l,f)=>f?`__ext_Number.${l}.call(${c})`:`__ext_Number.${l}.call(${c}, `)}return r}function fe(e,n){let t=1,r=0;for(let s=0;s<n&&s<e.length;s++)e[s]===`
|
|
20
|
+
`?(t++,r=0):r++;return{line:t,column:r}}function Jn(e,n){let t=n.trim();return/^['"`]/.test(t)?`typeof ${e} === 'string'`:t==="true"||t==="false"?`typeof ${e} === 'boolean'`:t==="null"?`${e} === null`:t==="undefined"?`${e} === undefined`:t.startsWith("[")?`Array.isArray(${e})`:t.startsWith("{")?`(typeof ${e} === 'object' && ${e} !== null && !Array.isArray(${e}))`:/^\+\d+/.test(t)?`(typeof ${e} === 'number' && Number.isInteger(${e}) && ${e} >= 0)`:/^-?\d+\.\d+/.test(t)?`typeof ${e} === 'number'`:/^-?\d+$/.test(t)?`(typeof ${e} === 'number' && Number.isInteger(${e}))`:"true"}function st(e){let n=e.trim();return/^['"`]/.test(n)?"string":n==="true"||n==="false"?"boolean":n==="null"?"null":n==="undefined"?"undefined":n.startsWith("[")?"array":n.startsWith("{")?"object":/^\+\d+/.test(n)?"non-negative-integer":/^-?\d+\.\d+/.test(n)?"number":/^-?\d+$/.test(n)?"integer":"any"}function Rt(e,n){let t=[],r=0,s="",o=!1;for(let a=0;a<e.length;a++){let c=e[a];if(!o&&(c==="'"||c==='"'||c==="`")){o=c,s+=c;continue}if(o){if(s+=c,c==="\\"){a++,a<e.length&&(s+=e[a]);continue}c===o&&(o=!1);continue}if(c==="("||c==="["||c==="{"){r++,s+=c;continue}if(c===")"||c==="]"||c==="}"){r--,s+=c;continue}if(c===","&&r===0){let l=Mn(s.trim(),n);l&&t.push(l),s="";continue}s+=c}let i=s.trim();if(i){let a=Mn(i,n);a&&t.push(a)}return t}function Mn(e,n){let t=e.replace(/^\/\*\s*unsafe\s*\*\/\s*/,"");if(t.startsWith("..."))return null;let r=t.indexOf("=");if(r===-1)return{name:t.trim(),defaultValue:"",required:!0};let s=t.slice(0,r).trim(),o=t.slice(r+1).trim();return{name:s,defaultValue:o,required:n.has(s)}}function qe(e,n){let t=1,r=n+1,s=!1,o=!1,i=!1;for(;r<e.length&&t>0;){let a=e[r],c=r+1<e.length?e[r+1]:"";if(o){a===`
|
|
21
|
+
`&&(o=!1),r++;continue}if(i){if(a==="*"&&c==="/"){i=!1,r+=2;continue}r++;continue}if(s){if(a==="\\"){r+=2;continue}a===s&&(s=!1),r++;continue}if(a==="/"&&c==="/"){o=!0,r+=2;continue}if(a==="/"&&c==="*"){i=!0,r+=2;continue}if(a==="'"||a==='"'||a==="`"){s=a,r++;continue}a==="{"&&t++,a==="}"&&t--,r++}return r}function Vn(e,n){let t=new Set,r=/(?:^|(?<=[\n;{}]))\s*(export\s+)?(async\s+)?function\s+(\w+)\s*\(/gm,s=new Map,o,i=[];for(;(o=r.exec(e))!==null;){let p=!!o[1],u=!!o[2],m=o[3],y=o.index,h=y,S=o[0].indexOf("function");S>=0&&(h=y+S),i.push({name:m,fullMatchStart:y,funcKeywordStart:h,exported:p,isAsync:u})}for(let p of i)s.has(p.name)||s.set(p.name,[]);let a=new Map;for(let p of i)a.set(p.name,(a.get(p.name)||0)+1);let c=new Set;for(let[p,u]of a)u>1&&c.add(p);if(c.size===0)return{source:e,polymorphicNames:t};for(let p of i){if(!c.has(p.name))continue;let u=e.indexOf("(",p.funcKeywordStart);if(u===-1)continue;let m=1,y=u+1;for(;y<e.length&&m>0;)e[y]==="("&&m++,e[y]===")"&&m--,y++;let h=y-1,w=e.slice(u+1,h),S=y;for(;S<e.length&&e[S]!=="{";)S++;if(S>=e.length)continue;let $=qe(e,S),b=p.fullMatchStart;for(;b>0&&e[b-1]===" ";)b--;let _=s.get(p.name),x=Rt(w,n);if(w.includes("...")){let E=fe(e,p.funcKeywordStart);throw new Z(`Rest parameters are not supported in polymorphic function '${p.name}'. Use separate function names instead.`,E)}_.push({index:_.length+1,start:b,end:$,text:e.slice(b,$),exported:p.exported,isAsync:p.isAsync,params:x})}for(let[p,u]of s){if(u.length<2)continue;let m=u.filter(y=>y.isAsync).length;if(m>0&&m<u.length){let y=fe(e,u[0].start);throw new Z(`Polymorphic function '${p}': all variants must be either sync or async, not mixed.`,y)}for(let y=0;y<u.length;y++)for(let h=y+1;h<u.length;h++){let w=u[y],S=u[h];if(w.params.length!==S.params.length)continue;let $=!0;for(let b=0;b<w.params.length;b++){let _=w.params[b].defaultValue?st(w.params[b].defaultValue):"any",x=S.params[b].defaultValue?st(S.params[b].defaultValue):"any";if(_!==x){$=!1;break}}if($){let b=fe(e,S.start);throw new Z(`Polymorphic function '${p}': variants ${y+1} and ${h+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,b)}}}let l=[];for(let[p,u]of s)if(!(u.length<2))for(let m of u)l.push({name:p,variant:m});l.sort((p,u)=>u.variant.start-p.variant.start);let f=e;for(let{name:p,variant:u}of l){let m=u.isAsync?"async ":"",y=u.text.replace(new RegExp(`(?:export\\s+)?${m?m.replace(/\s+$/,"\\s+"):""}function\\s+${p}\\s*\\(`),`${m}function ${p}$$${u.index}(`);f=f.slice(0,u.start)+y+f.slice(u.end)}for(let[p,u]of s){if(u.length<2)continue;t.add(p);let m=u[0].isAsync,y=u.some(_=>_.exported),h=m?"async ":"",w=y?"export ":"",S=[...u].sort((_,x)=>{if(_.params.length!==x.params.length)return 0;let g=0,E=0;for(let k of _.params){let j=k.defaultValue?st(k.defaultValue):"any";j==="non-negative-integer"?g+=3:j==="integer"?g+=2:j!=="any"&&(g+=1)}for(let k of x.params){let j=k.defaultValue?st(k.defaultValue):"any";j==="non-negative-integer"?E+=3:j==="integer"?E+=2:j!=="any"&&(E+=1)}return E-g}),$=[];for(let _ of S){let x=[`__args.length === ${_.params.length}`],g=[];for(let E=0;E<_.params.length;E++){let k=_.params[E];if(g.push(`__args[${E}]`),k.defaultValue){let j=Jn(`__args[${E}]`,k.defaultValue);j!=="true"&&x.push(j)}}$.push(` if (${x.join(" && ")}) return ${p}$${_.index}(${g.join(", ")})`)}let b=`
|
|
22
|
+
${w}${h}function ${p}(...__args) {
|
|
23
|
+
${$.join(`
|
|
22
24
|
`)}
|
|
23
|
-
return __tjs.typeError('${
|
|
25
|
+
return __tjs.typeError('${p}', 'no matching overload', __args)
|
|
24
26
|
}
|
|
25
|
-
`;
|
|
26
|
-
`,m);m
|
|
27
|
-
${
|
|
28
|
-
`.repeat(
|
|
29
|
-
`&&
|
|
30
|
-
function ${c}$ctor$${
|
|
31
|
-
const __obj = Object.create(${c}.prototype)
|
|
32
|
-
;(function() {${
|
|
33
|
-
return __obj
|
|
27
|
+
`;f+=b}return{source:f,polymorphicNames:t}}function zn(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function Zn(e,n=!1){let t=[],r=[],s="",o=0;for(;o<e.length;){let i=e.slice(o).match(/^\btest\s+/);if(i){let a=o,c=o+i[0].length,l,f=e.slice(c).match(/^(['"`])([^]*?)\1\s*/);if(f&&(l=f[2],c+=f[0].length),e[c]==="{"){let p=c+1,u=1,m=p,y=null,h=!1;for(;m<e.length&&u>0;){let w=e[m];if(h){h=!1,m++;continue}if(w==="\\"&&y){h=!0,m++;continue}if(y){w===y&&(y=null),m++;continue}if(w==="/"&&e[m+1]==="/"){let S=e.indexOf(`
|
|
28
|
+
`,m);m=S===-1?e.length:S+1;continue}if(w==="/"&&e[m+1]==="*"){let S=e.indexOf("*/",m+2);m=S===-1?e.length:S+2;continue}if(w==="'"||w==='"'||w==="`"){y=w,m++;continue}w==="{"?u++:w==="}"&&u--,m++}if(u===0){let w=e.slice(p,m-1).trim(),S=m,$=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:l,body:w,start:a,end:S,line:$}),!n)try{new Function(w)()}catch(x){let g=l||`test at line ${$}`;r.push(`Test failed: ${g} (line ${$})
|
|
29
|
+
${x.message||x}`)}let _=(e.slice(a,S).match(/\n/g)||[]).length;s+=`
|
|
30
|
+
`.repeat(_),o=S;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function Gn(e,n){let t=new Set,r=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,s,o=[];for(;(s=r.exec(e))!==null;){let a=s[1],c=s[2]?.trim()||"",l=s.index+s[0].length-1,f=qe(e,l),p=e.slice(l,f);o.push({className:a,extendsClause:c,bodyStart:l,bodyEnd:f,body:p})}let i=e;for(let a=o.length-1;a>=0;a--){let{className:c,extendsClause:l,bodyStart:f,bodyEnd:p,body:u}=o[a],m=/\bconstructor\s*\(/g,y,h=[];for(;(y=m.exec(u))!==null;)h.push(y.index);if(h.length<2)continue;t.add(c);let w=[];for(let x=0;x<h.length;x++){let g=h[x],E=u.indexOf("(",g),k=1,j=E+1;for(;j<u.length&&k>0;)u[j]==="("&&k++,u[j]===")"&&k--,j++;let A=u.slice(E+1,j-1),M=j;for(;M<u.length&&u[M]!=="{";)M++;let N=qe(u,M),R=u.slice(M+1,N-1);w.push({index:x+1,paramStr:A,bodyText:R,fullStart:g,fullEnd:N})}let S=u;for(let x=w.length-1;x>=1;x--){let g=w[x],E=g.fullStart;for(;E>0&&S[E-1]===" ";)E--;E>0&&S[E-1]===`
|
|
31
|
+
`&&E--,S=S.slice(0,E)+S.slice(g.fullEnd)}let $="";for(let x=1;x<w.length;x++){let g=w[x],E=Rt(g.paramStr,n);if(g.paramStr.includes("...")){let j=fe(e,f+g.fullStart);throw new Z(`Rest parameters are not supported in polymorphic constructors for '${c}'.`,j)}$+=`
|
|
32
|
+
function ${c}$ctor$${g.index}(${g.paramStr}) {`,$+=`
|
|
33
|
+
const __obj = Object.create(${c}.prototype)`,$+=`
|
|
34
|
+
;(function() {${g.bodyText}}).call(__obj)`,$+=`
|
|
35
|
+
return __obj`,$+=`
|
|
34
36
|
}
|
|
35
|
-
`}let
|
|
37
|
+
`}let b=[];for(let x=0;x<w.length;x++){let g=w[x],E=Rt(g.paramStr,n),k=[`a.length === ${E.length}`];for(let j=0;j<E.length;j++){let A=E[j];if(A.defaultValue){let M=Jn(`a[${j}]`,A.defaultValue);M!=="true"&&k.push(M)}}if(x===0)b.push(` if (${k.join(" && ")}) return Reflect.construct(t, a)`);else{let j=E.map((A,M)=>`a[${M}]`).join(", ");b.push(` if (${k.join(" && ")}) return ${c}$ctor$${g.index}(${j})`)}}$+=`
|
|
36
38
|
function ${c}$dispatch(t, a) {
|
|
37
|
-
|
|
39
|
+
`,$+=b.join(`
|
|
38
40
|
`)+`
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
`,i=i.slice(0,
|
|
42
|
-
`&&(r="normal"),t++):r==="block-comment"?(n+=o,o==="*"&&i==="/"?(n+=i,r="normal",t+=2):t++):r==="string-single"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==="'"&&(r="normal"),t++)):r==="string-double"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==='"'&&(r="normal"),t++)):r==="string-template"?(n+=o,o==="\\"?(n+=i||"",t+=2):o==="`"?(s--,r=s>0?"string-template":"normal",t++):o==="$"&&i==="{"?(n+=i,t+=2,r="normal"):t++):(n+=o,t++)}return n}function
|
|
43
|
-
`&&(s="normal"),r++;continue;case"block-comment":if(a==="*"&&c==="/"){r+=2,s="normal";continue}r++;continue;case"regex":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="["){for(r++;r<e.length&&e[r]!=="]";)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}if(a==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)r++;s="normal";continue}r++;continue;case"normal":if(o.length>0){if(a==="{")o[o.length-1]++;else if(a==="}"&&(o[o.length-1]--,o[o.length-1]===0)){o.pop(),r++,s="template-string";continue}}if(a==="'"){r++,s="single-string";continue}if(a==='"'){r++,s="double-string";continue}if(a==="`"){r++,s="template-string";continue}if(a==="/"&&c==="/"){r+=2,s="line-comment";continue}if(a==="/"&&c==="*"){r+=2,s="block-comment";continue}if(a==="/"){let l=r-1;for(;l>=0&&/\s/.test(e[l]);)l--;let
|
|
44
|
-
`))return t;t++}return t}function ct(e,n){let t="",r=0,s,o,i="normal",a=[],c=[{type:"top-level",braceDepth:0}],l=0,
|
|
45
|
-
`&&(i="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&m==="/"){t+=m,r+=2,i="normal";continue}r++;continue;case"regex":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}if(u==="["){for(r++;r<e.length&&e[r]!=="]";)t+=e[r],e[r]==="\\"&&r+1<e.length?(t+=e[r+1],r+=2):r++;r<e.length&&(t+=e[r],r++);continue}if(u==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)t+=e[r],r++;i="normal";continue}r++;continue;case"normal":if(a.length>0){if(u==="{")a[a.length-1]++;else if(u==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),t+=u,r++,i="template-string";continue}}if(u==="'"){t+=u,r++,i="single-string";continue}if(u==='"'){t+=u,r++,i="double-string";continue}if(u==="`"){t+=u,r++,i="template-string";continue}if(u==="/"&&m==="/"){t+=u+m,r+=2,i="line-comment";continue}if(u==="/"&&m==="*"){t+=u+m,r+=2,i="block-comment";continue}if(u==="/"){let
|
|
46
|
-
`})()
|
|
47
|
-
`){s=!1,t+=a,i++;continue}if(o&&a==="*"&&c==="/"){o=!1,t+="*/",i+=2;continue}if(s||o){t+=a,i++;continue}a==="("||a==="{"||a==="["?(r++,t+=a):a===")"||a==="}"||a==="]"?(r--,t+=a):a===","&&r===0?(n.push(t),t=""):t+=a,i++}return t.trim()&&n.push(t),n}function
|
|
48
|
-
`,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function ut(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,c=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e)||n.vmTarget,l=c?{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0,tjsSafeAssign:!0};c&&(r="none");let
|
|
49
|
-
`),y=m.filter(
|
|
50
|
-
`)),t.description=u.trim(),t}}let o=r.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!o)return t;let i=o[0],a=i.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);a&&(t.description=a[1].trim());let c=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,l;for(;(l=c.exec(i))!==null;)t.params[l[1]]=l[2].trim();return t}import{parseExpressionAt as ys}from"acorn";function Y(e){switch(e.type){case"Literal":{let n=e.value;if(n===null)return{kind:"null"};if(typeof n=="string")return{kind:"string"};if(typeof n=="number"){let t=e.raw;return t&&t.includes(".")?{kind:"number"}:{kind:"integer"}}return typeof n=="boolean"?{kind:"boolean"}:{kind:"any"}}case"ArrayExpression":{let n=e.elements;if(n.length===0)return{kind:"array",items:{kind:"any"}};let t=n.filter(i=>i!=null).map(i=>Y(i));if(t.length===0)return{kind:"array",items:{kind:"any"}};let r=new Map;for(let i of t){let a=JSON.stringify(i);r.has(a)||r.set(a,i)}let s=[...r.values()];return{kind:"array",items:s.length===1?s[0]:{kind:"union",members:s}}}case"ObjectExpression":{let n=e.properties,t={};for(let r of n)if(r.type==="Property"&&r.key.type==="Identifier"){let s=r.key.name;t[s]=Y(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?Y(t):n==="&&"||n==="??"?Y(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=Y(t),o=Y(r);return o.kind==="null"?{...s,nullable:!0}:s.kind==="null"?{...o,nullable:!0}:{kind:"union",members:[s,o]}}return{kind:"any"}}case"Identifier":return e.name==="undefined"?{kind:"undefined"}:{kind:"any"};case"ArrowFunctionExpression":case"FunctionExpression":{let n=e,t=n.params.map(s=>gs(s)),r={kind:"any"};return n.type==="ArrowFunctionExpression"&&n.body&&n.body.type!=="BlockStatement"&&(r=Y(n.body)),{kind:"function",params:t,returns:r}}case"UnaryExpression":{let n=e.operator,t=e.argument;if(n==="+"&&t.type==="Literal"&&typeof t.value=="number")return{kind:"non-negative-integer"};if(n==="-"&&t.type==="Literal"&&typeof t.value=="number"){let s=t.raw;return s&&s.includes(".")?{kind:"number"}:{kind:"integer"}}return{kind:"any"}}default:return{kind:"any"}}}function gs(e){return e.type==="Identifier"?{name:e.name,type:{kind:"any"}}:e.type==="AssignmentPattern"&&e.left?.type==="Identifier"?{name:e.left.name,type:Y(e.right)}:e.type==="RestElement"&&e.argument?.type==="Identifier"?{name:`...${e.argument.name}`,type:{kind:"array",items:{kind:"any"}}}:{name:"?",type:{kind:"any"}}}function ye(e,n){if(e.type==="Identifier")return{name:e.name,type:{kind:"any"},required:!0};if(e.type==="AssignmentPattern"){let{left:t,right:r}=e;if(t.type!=="Identifier")throw new U("Only simple parameter names are supported",W(e));let s=t.name,o=n?.has(s)??!1,i=Y(r),a=oe(r);return{name:s,type:i,required:o,default:o?null:a,example:a,loc:{start:e.start,end:e.end}}}if(e.type==="ObjectPattern"){let t=e.properties,r={},s={};for(let o of t)if(o.type==="Property"){let i=o.key.type==="Identifier"?o.key.name:String(o.key.value);if(o.value.type==="Identifier")r[i]={kind:"any"},s[i]={name:i,type:{kind:"any"},required:!0};else if(o.value.type==="AssignmentPattern"){let a=ye(o.value,n),c=n?.has(i)??!1;r[i]=a.type,s[i]={name:i,type:a.type,required:c,default:c?null:a.example,example:a.example}}}return{name:"__destructured__",type:{kind:"object",shape:r,destructuredParams:s},required:!0}}throw new U(`Unsupported parameter pattern: ${e.type}`,W(e))}function oe(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?oe(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=oe(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=oe(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=oe(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?oe(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?oe(t)??oe(r):void 0}default:return}}function ir(e){try{let n=ys(e,0,{ecmaVersion:2022});return Y(n)}catch{return{kind:"any"}}}function It(e){switch(e.kind){case"string":return e.nullable?"string | null":"string";case"number":return e.nullable?"number | null":"number";case"integer":return e.nullable?"integer | null":"integer";case"non-negative-integer":return e.nullable?"non-negative integer | null":"non-negative integer";case"boolean":return e.nullable?"boolean | null":"boolean";case"null":return"null";case"any":return"any";case"array":{let n=e.items?It(e.items):"any";return e.nullable?`${n}[] | null`:`${n}[]`}case"object":{if(!e.shape||Object.keys(e.shape).length===0)return e.nullable?"object | null":"object";let n=Object.entries(e.shape).map(([t,r])=>`${t}: ${It(r)}`).join(", ");return e.nullable?`{ ${n} } | null`:`{ ${n} }`}case"union":return e.members?.map(It).join(" | ")||"any";default:return"any"}}function ft(e){switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{};case"undefined":return{};case"any":return{};case"array":return{type:"array",items:e.items?ft(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=ft(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(ft)}:{};default:return{}}}function hs(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=ft(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function Ot(e,n,t,r={},s){let o=Ve(n,e),i=new Map;for(let _ of e.params){let $=ye(_,s);if($.name==="__destructured__"&&$.type.kind==="object"&&$.type.destructuredParams)for(let[S,h]of Object.entries($.type.destructuredParams))i.set(S,{...h,description:o.params[S]});else $.description=o.params[$.name],i.set($.name,$)}let a;t&&(a=ir(t));let c={depth:0,locals:new Map,parameters:i,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r},l=ae(e.body,c),p=[],f=[],u=[];for(let[_,$]of i.entries())$.required?f.push(_):$.default!==void 0?u.push({name:_,defaultValue:$.default}):f.push(_);f.length>0&&p.push({op:"varsImport",keys:f});for(let{name:_,defaultValue:$}of u)p.push({op:"varsImport",keys:[_]}),p.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:_},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:_,value:$}]});p.push(...l);let m=Object.fromEntries(i),y={name:e.id?.name||"anonymous",description:o.description,parameters:m,returns:a},g=hs(m);return{ast:{op:"seq",steps:p,inputSchema:g},signature:y,warnings:c.warnings}}function ae(e,n){let t=[];for(let r of e.body){let s=ze(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function ze(e,n){switch(e.type){case"VariableDeclaration":return bs(e,n);case"ExpressionStatement":return xs(e,n);case"IfStatement":return ws(e,n);case"WhileStatement":return Ss(e,n);case"ForOfStatement":return $s(e,n);case"TryStatement":return Es(e,n);case"ReturnStatement":return Ts(e,n);case"ThrowStatement":throw new U("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",W(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:ae(e,ne(n))};case"EmptyStatement":return null;default:throw new U(`Unsupported statement type: ${e.type}`,W(e),n.source,n.filename)}}function bs(e,n){let t=[],r=e.kind==="const",s=r?"constSet":"varSet";for(let o of e.declarations){if(o.id.type!=="Identifier")throw new U("Only simple variable names are supported",W(o),n.source,n.filename);let i=o.id.name;if(o.init){let{step:a,resultVar:c}=xe(o.init,n,i,r);a?t.push(a):c!==i&&t.push({op:s,key:i,value:c});let l=Y(o.init);n.locals.set(i,l)}else{if(r)throw new U("const declarations must be initialized",W(o),n.source,n.filename);t.push({op:"varSet",key:i,value:null}),n.locals.set(i,{kind:"any",nullable:!0})}}return t}function xs(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return _s(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=xe(t,n);return r||(s?{op:"varSet",key:"_",value:s}:null)}return n.warnings.push({message:"Expression statement has no effect",line:W(e).line,column:W(e).column}),null}function _s(e,n){if(e.left.type!=="Identifier")throw new U("Only simple variable assignment is supported",W(e),n.source,n.filename);let t=e.left.name,{step:r,resultVar:s}=xe(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function ws(e,n){let t=F(e.test,n),r=e.consequent.type==="BlockStatement"?ae(e.consequent,ne(n)):[ze(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?ae(e.alternate,ne(n)):[ze(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function Ss(e,n){let t=F(e.test,n),r=e.body.type==="BlockStatement"?ae(e.body,ne(n)):[ze(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function $s(e,n){let t;if(e.left.type==="VariableDeclaration"){let i=e.left.declarations[0];if(i.id.type!=="Identifier")throw new U("Only simple variable names are supported in for...of",W(e.left),n.source,n.filename);t=i.id.name}else if(e.left.type==="Identifier")t=e.left.name;else throw new U("Unsupported for...of left-hand side",W(e.left),n.source,n.filename);let r=H(e.right,n),s=ne(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?ae(e.body,s):[ze(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function Es(e,n){let t=ae(e.block,ne(n)),r,s;if(e.handler){let o=ne(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=ae(e.handler.body,o)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function Ts(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=xe(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:H(e.argument,n)}}var ar=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),ks=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),Ze=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),js=new Set(["toUpperCase","toLowerCase","trim","trimStart","trimEnd","charAt","charCodeAt","codePointAt","concat","includes","indexOf","lastIndexOf","startsWith","endsWith","slice","substring","substr","replace","replaceAll","match","search","padStart","padEnd","repeat","normalize","localeCompare","toString","valueOf","at","reverse","sort","fill","copyWithin","flat","flatMap","every","some","forEach","add","remove","has","clear","toArray","union","intersection","diff","format","isBefore","isAfter"]);function vs(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return ks.has(n)||Ze.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(ar.has(t)||Ze.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(js.has(t))return!0}}return!1}function As(e){if(e.object.type==="Identifier"){let n=e.object.name;return ar.has(n)||Ze.has(n)}return!1}var or={RegExp:"RegExp is not available. Use string methods or the regexMatch atom.",Promise:"Promise is not needed. All operations are implicitly async.",Map:"Map is not available. Use plain objects instead.",WeakSet:"WeakSet is not available.",WeakMap:"WeakMap is not available.",Symbol:"Symbol is not available.",Proxy:"Proxy is not available.",Reflect:"Reflect is not available.",Function:"Function constructor is not available. Define functions normally.",eval:"eval is not available. Code is compiled, not evaluated.",setTimeout:"setTimeout is not available. Use the delay atom.",setInterval:"setInterval is not available. Use while loops with delay.",fetch:"fetch is not available. Use the httpFetch atom.",require:"require is not available. Atoms must be registered with the VM.",import:"import is not available. Atoms must be registered with the VM.",process:"process is not available. AsyncJS runs in a sandboxed environment.",window:"window is not available. AsyncJS runs in a sandboxed environment.",document:"document is not available. AsyncJS runs in a sandboxed environment.",global:"global is not available. AsyncJS runs in a sandboxed environment.",globalThis:"globalThis is not available. Use builtins directly."};function Rs(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(Ze.has(n))return or[n]||`${n} is not available in AsyncJS.`}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Ze.has(t))return or[t]||`${t} is not available in AsyncJS.`}}return null}function cr(e){return{Date:" Use Date() or Date('2024-01-15') instead - no 'new' needed.",Set:" Use Set([items]) instead - no 'new' needed.",Map:" Use plain objects instead of Map.",Array:" Use array literals like [1, 2, 3] instead.",Object:" Use object literals like { key: value } instead.",Error:" Return an error object like { error: 'message' } instead.",RegExp:" Use string methods or the regexMatch atom.",Promise:" Not needed - all operations are implicitly async.",WeakSet:" WeakSet is not available.",WeakMap:" WeakMap is not available."}[e]||" Use factory functions or object literals instead."}function xe(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return xe(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let c=cr(a);throw new U(`The 'new' keyword is not supported in AsyncJS.${c}`,W(e),n.source,n.filename)}if(e.type==="CallExpression"){let i=Rs(e);if(i)throw new U(i,W(e),n.source,n.filename)}if(e.type==="CallExpression"&&vs(e)){let i=F(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="MemberExpression"&&As(e)){let i=F(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="CallExpression")return Cs(e,n,t,r);if(e.type==="TemplateLiteral")return Ms(e,n,t,r);if(e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="UnaryExpression"){let i=F(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}return{step:null,resultVar:H(e,n)}}function Cs(e,n,t,r){let s,o=!1,i;if(e.callee.type==="Identifier")s=e.callee.name;else if(e.callee.type==="MemberExpression"){let c=e.callee;if(c.property.type==="Identifier")s=c.property.name,o=!0,i=H(c.object,n);else throw new U("Computed method names are not supported",W(e),n.source,n.filename)}else throw new U("Only named function calls are supported",W(e),n.source,n.filename);if(o)return Ns(s,i,e.arguments,n,t,r);s==="console"&&e.callee.type;let a=Ps(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function Ns(e,n,t,r,s,o){switch(e){case"map":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],c=a?.type==="Identifier"?a.name:"item",l=ne(r);l.locals.set(c,{kind:"any"});let p;if(i.body.type==="BlockStatement")p=ae(i.body,l);else{let{step:f,resultVar:u}=xe(i.body,l,"result");p=f?[f]:[{op:"varSet",key:"result",value:u}]}return{step:{op:"map",items:n,as:c,steps:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"filter":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],c=a?.type==="Identifier"?a.name:"item",l=ne(r);l.locals.set(c,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new U("filter callback must be an expression, not a block",W(t[0]),r.source,r.filename);return p=F(i.body,l),{step:{op:"filter",items:n,as:c,condition:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"find":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],c=a?.type==="Identifier"?a.name:"item",l=ne(r);l.locals.set(c,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new U("find callback must be an expression, not a block",W(t[0]),r.source,r.filename);return p=F(i.body,l),{step:{op:"find",items:n,as:c,condition:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"reduce":if(t.length>=2&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],c=i.params[1],l=a?.type==="Identifier"?a.name:"acc",p=c?.type==="Identifier"?c.name:"item",f=ne(r);f.locals.set(l,{kind:"any"}),f.locals.set(p,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=ae(i.body,f);else{let{step:y,resultVar:g}=xe(i.body,f,"result");u=y?[y]:[{op:"varSet",key:"result",value:g}]}let m=H(t[1],r);return{step:{op:"reduce",items:n,as:p,accumulator:l,initial:m,steps:u,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"slice":break;case"push":return{step:{op:"push",list:n,item:H(t[0],r),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?H(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?H(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}return r.warnings.push({message:`Unknown method '${e}' - treating as atom call`,line:0,column:0}),{step:{op:e,receiver:n,args:t.map(i=>H(i,r)),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}function Ms(e,n,t,r){let s="",o={};for(let i=0;i<e.quasis.length;i++)if(s+=e.quasis[i].value.cooked||e.quasis[i].value.raw,i<e.expressions.length){let a=e.expressions[i],c=`_${i}`;o[c]=H(a,n),s+=`{{${c}}}`}return{step:{op:"template",tmpl:s,vars:o,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function F(e,n){switch(e.type){case"Literal":return{$expr:"literal",value:e.value};case"Identifier":return{$expr:"ident",name:e.name};case"MemberExpression":{let t=e,r=F(t.object,n),s=t.optional===!0;if(t.computed){let i=t.property;return i.type==="Literal"?{$expr:"member",object:r,property:String(i.value),computed:!0,...s&&{optional:!0}}:{$expr:"member",object:r,property:F(i,n),computed:!0,...s&&{optional:!0}}}let o=t.property.name;return{$expr:"member",object:r,property:o,...s&&{optional:!0}}}case"ChainExpression":return F(e.expression,n);case"BinaryExpression":{let t=e;return{$expr:"binary",op:t.operator,left:F(t.left,n),right:F(t.right,n)}}case"LogicalExpression":{let t=e;return{$expr:"logical",op:t.operator,left:F(t.left,n),right:F(t.right,n)}}case"UnaryExpression":{let t=e;return{$expr:"unary",op:t.operator,argument:F(t.argument,n)}}case"ConditionalExpression":{let t=e;return{$expr:"conditional",test:F(t.test,n),consequent:F(t.consequent,n),alternate:F(t.alternate,n)}}case"ArrayExpression":return{$expr:"array",elements:e.elements.filter(r=>r!==null).map(r=>F(r,n))};case"ObjectExpression":{let t=e,r=[];for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r.push({key:o,value:F(s.value,n)})}return{$expr:"object",properties:r}}case"CallExpression":{let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,s=r.property.type==="Identifier"?r.property.name:String(r.property.value),o=r.optional===!0||t.optional===!0;return{$expr:"methodCall",object:F(r.object,n),method:s,arguments:t.arguments.map(i=>F(i,n)),...o&&{optional:!0}}}if(t.callee.type==="Identifier")return{$expr:"call",callee:t.callee.name,arguments:t.arguments.map(s=>F(s,n))};throw new U("Complex function calls in expressions should be lifted to statements",W(e),n.source,n.filename)}case"NewExpression":{let t=e,r="constructor";t.callee.type==="Identifier"&&(r=t.callee.name);let s=cr(r);throw new U(`The 'new' keyword is not supported in AsyncJS.${s}`,W(e),n.source,n.filename)}case"TemplateLiteral":throw new U("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",W(e),n.source,n.filename);default:throw new U(`Unsupported expression type in condition: ${e.type}`,W(e),n.source,n.filename)}}function H(e,n){switch(e.type){case"Literal":return e.value;case"Identifier":return e.name;case"MemberExpression":{let t=e;if(t.optional===!0)return F(e,n);let s=H(t.object,n);if(s&&typeof s=="object"&&s.$expr){let i=t.computed?String(t.property.value):t.property.name;return{$expr:"member",object:s,property:i,...t.computed&&{computed:!0}}}if(t.computed)return F(e,n);let o=t.property.name;return typeof s=="string"?`${s}.${o}`:s&&s.$kind==="arg"?{$kind:"arg",path:`${s.path}.${o}`}:`${s}.${o}`}case"ChainExpression":return H(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?H(t,n):null);case"ObjectExpression":{let t={};for(let r of e.properties)if(r.type==="Property"){let s=r.key.type==="Identifier"?r.key.name:String(r.key.value);t[s]=H(r.value,n)}return t}case"TemplateLiteral":return F(e,n);case"CallExpression":return F(e,n);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return F(e,n);default:return null}}function Ps(e,n){if(e.arguments.length===1&&e.arguments[0].type==="ObjectExpression"){let t=e.arguments[0],r={};for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r[o]=H(s.value,n)}return r}return{args:e.arguments.map(t=>H(t,n))}}import{parseExpressionAt as Lr}from"acorn";function Is(e,n){let t=n;for(;t>0&&e[t-1]!==`
|
|
51
|
-
`;)t--;if(e.slice(t,n).includes("//"))return!0;let s=0,o=!1;for(;s<n;)!o&&e.slice(s,s+2)==="/*"?(o=!0,s+=2):o&&e.slice(s,s+2)==="*/"?(o=!1,s+=2):s++;return o}function
|
|
41
|
+
`,$+=` return __tjs.typeError('${c}', 'no matching constructor', a)
|
|
42
|
+
`,$+=`}
|
|
43
|
+
`,i=i.slice(0,f)+S+i.slice(p);let _=f+S.length;i=i.slice(0,_)+$+i.slice(_)}return{source:i,polyCtorClasses:t}}function Kn(e,n=new Set){let t=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,r="",s=0,o;for(;(o=t.exec(e))!==null;){let i=o[1],a=o[2]||"",c=o.index,l=c+o[0].length-1,f=1,p=l+1;for(;p<e.length&&f>0;){let u=e[p];u==="{"?f++:u==="}"&&f--,p++}if(f===0){let u=p,m=e.slice(l,u);r+=e.slice(s,c),r+=`let ${i} = class ${i}${a} ${m}; `,n.has(i)?r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return ${i}$dispatch(t, a) }, construct(t, a) { return ${i}$dispatch(t, a) } });`:r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,s=u}}return r+=e.slice(s),r}function Yn(e){let n=[{pattern:/\bnew\s+Date\b/,message:"new Date() is not allowed in TjsDate mode. Use Timestamp.now() or Timestamp.from()"},{pattern:/\bDate\.now\b/,message:"Date.now() is not allowed in TjsDate mode. Use Timestamp.now()"},{pattern:/\bDate\.parse\b/,message:"Date.parse() is not allowed in TjsDate mode. Use Timestamp.parse()"},{pattern:/\bDate\.UTC\b/,message:"Date.UTC() is not allowed in TjsDate mode. Use Timestamp.from()"}];for(let{pattern:t,message:r}of n)if(t.test(e))throw new Error(r);return e}function Hn(e){let n=new Set,t=/\bconst!\s+(\w+)\b/g,r;for(;(r=t.exec(e))!==null;)n.add(r[1]);if(n.size===0)return e;e=e.replace(/\bconst!\s+/g,"const ");let s=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"");for(let o of n){if(new RegExp(`\\b${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])\\s*(?:=(?!=)|\\+\\+|--|\\+=|-=|\\*=|\\/=|%=|&&=|\\|\\|=|\\?\\?=|<<=|>>=|>>>=|\\^=|&=|\\|=)`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);if(new RegExp(`(?:\\+\\+|--)\\s*${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\bdelete\\s+${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);let l="push|pop|splice|shift|unshift|sort|reverse|fill|copyWithin|set";if(new RegExp(`\\b${o}\\s*\\.\\s*(?:${l})\\s*\\(`,"g").test(s))throw new Error(`Cannot call mutating method on immutable binding '${o}'. const! bindings are read-only at compile time.`)}return e}function Qn(e){if(/(?<![a-zA-Z_$])\bvar\s+/.test(e))throw new Error("var is not allowed in TjsNoVar mode. Use const or let instead.");return e}function Xn(e){if(/(?<![A-Za-z_$])\beval\s*\(/.test(e))throw new Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(e))throw new Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return e}function er(e){if(!e.includes("!."))return e;let n="",t=0,r="normal",s=0;for(;t<e.length;){let o=e[t],i=e[t+1];if(r==="normal"){if(o==="/"&&i==="/"){r="line-comment",n+=o,t++;continue}if(o==="/"&&i==="*"){r="block-comment",n+=o,t++;continue}if(o==="'"){r="string-single",n+=o,t++;continue}if(o==='"'){r="string-double",n+=o,t++;continue}if(o==="`"){r="string-template",s++,n+=o,t++;continue}if(o==="!"&&i==="."&&t+2<e.length&&/[a-zA-Z_$]/.test(e[t+2])){let a=n.length,c=gs(n);if(c<a){let l=n.slice(c);n=n.slice(0,c);let f=t+2;for(;f<e.length&&/[\w$]/.test(e[f]);)f++;let p=e.slice(t+2,f);n+=`__tjs.bang(${l},'${p}')`,t=f;continue}}n+=o,t++}else r==="line-comment"?(n+=o,o===`
|
|
44
|
+
`&&(r="normal"),t++):r==="block-comment"?(n+=o,o==="*"&&i==="/"?(n+=i,r="normal",t+=2):t++):r==="string-single"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==="'"&&(r="normal"),t++)):r==="string-double"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==='"'&&(r="normal"),t++)):r==="string-template"?(n+=o,o==="\\"?(n+=i||"",t+=2):o==="`"?(s--,r=s>0?"string-template":"normal",t++):o==="$"&&i==="{"?(n+=i,t+=2,r="normal"):t++):(n+=o,t++)}return n}function gs(e){let n=e.length-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return e.length;for(;n>=0;){let t=e[n];if(/[\w$]/.test(t)){for(;n>=0&&/[\w$]/.test(e[n]);)n--;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t===")"){if(n=Cn(e,n,"(",")"),n<0)return 0;if(n--,n>=0&&/[\w$]/.test(e[n]))continue;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t==="]"){if(n=Cn(e,n,"[","]"),n<0)return 0;if(n--,n>=0&&/[\w$]/.test(e[n]))continue;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else return n+1}return 0}function Cn(e,n,t,r){let s=1;for(n--;n>=0&&s>0;)e[n]===r?s++:e[n]===t&&s--,s>0&&n--;return n}function tr(e){let n=new Map;if(!e.includes("let "))return{source:e,annotations:n};let t=[],r=0,s="normal",o=[];for(;r<e.length;){let a=e[r],c=e[r+1];switch(s){case"single-string":if(a==="\\"&&r+1<e.length){r+=2;continue}a==="'"&&(s="normal"),r++;continue;case"double-string":if(a==="\\"&&r+1<e.length){r+=2;continue}a==='"'&&(s="normal"),r++;continue;case"template-string":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="$"&&c==="{"){r+=2,o.push(1),s="normal";continue}a==="`"&&(s="normal"),r++;continue;case"line-comment":a===`
|
|
45
|
+
`&&(s="normal"),r++;continue;case"block-comment":if(a==="*"&&c==="/"){r+=2,s="normal";continue}r++;continue;case"regex":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="["){for(r++;r<e.length&&e[r]!=="]";)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}if(a==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)r++;s="normal";continue}r++;continue;case"normal":if(o.length>0){if(a==="{")o[o.length-1]++;else if(a==="}"&&(o[o.length-1]--,o[o.length-1]===0)){o.pop(),r++,s="template-string";continue}}if(a==="'"){r++,s="single-string";continue}if(a==='"'){r++,s="double-string";continue}if(a==="`"){r++,s="template-string";continue}if(a==="/"&&c==="/"){r+=2,s="line-comment";continue}if(a==="/"&&c==="*"){r+=2,s="block-comment";continue}if(a==="/"){let l=r-1;for(;l>=0&&/\s/.test(e[l]);)l--;let f=l>=0?e[l]:"";if(!f||/[=(!,;:{[&|?+\-*%<>~^]/.test(f)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){r++,s="regex";continue}}if(a==="l"&&e.slice(r,r+4)==="let "&&(r===0||!/[\w$]/.test(e[r-1]))){let l=r+4;for(;l<e.length&&/\s/.test(e[l]);)l++;if(l<e.length&&/[a-zA-Z_$]/.test(e[l])){let f=l;for(;l<e.length&&/[\w$]/.test(e[l]);)l++;let p=l,u=e.slice(f,p),m=l;for(;m<e.length&&/\s/.test(e[m]);)m++;if(m<e.length&&e[m]===":"&&e[m+1]!==":"){let h=m+1;for(;h<e.length&&/[ \t]/.test(e[h]);)h++;let w=hs(e,h);if(w>h){let S=e.slice(h,w).trim();n.set(u,S),t.push({start:p,end:w,replacement:""}),r=w;continue}}}}break}r++}if(t.length===0)return{source:e,annotations:n};let i=e;for(let a=t.length-1;a>=0;a--){let c=t[a];i=i.slice(0,c.start)+c.replacement+i.slice(c.end)}return{source:i,annotations:n}}function hs(e,n){let t=n,r=0,s=0,o=0,i="normal",a=[];for(;t<e.length;){let c=e[t];if(i==="sq"){if(c==="\\"){t+=2;continue}c==="'"&&(i="normal"),t++;continue}if(i==="dq"){if(c==="\\"){t+=2;continue}c==='"'&&(i="normal"),t++;continue}if(i==="tpl"){if(c==="\\"){t+=2;continue}if(c==="$"&&e[t+1]==="{"){a.push(1),i="normal",t+=2;continue}c==="`"&&(i="normal"),t++;continue}if(a.length>0){if(c==="{")a[a.length-1]++;else if(c==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),i="tpl",t++;continue}}if(c==="'"){i="sq",t++;continue}if(c==='"'){i="dq",t++;continue}if(c==="`"){i="tpl",t++;continue}if(c==="("?r++:c===")"?r--:c==="{"?s++:c==="}"?s--:c==="["?o++:c==="]"&&o--,r===0&&s===0&&o===0&&(c==="="||c===","||c===";"||c===`
|
|
46
|
+
`))return t;t++}return t}function ct(e,n){let t="",r=0,s,o,i="normal",a=[],c=[{type:"top-level",braceDepth:0}],l=0,f=()=>c[c.length-1]?.type||"top-level",p=()=>{let u=c[c.length-1];return u?.type==="class-body"&&l===u.braceDepth+1};for(;r<e.length;){let u=e[r],m=e[r+1];switch(i){case"single-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}u==="'"&&(i="normal"),r++;continue;case"double-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}u==='"'&&(i="normal"),r++;continue;case"template-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}if(u==="$"&&m==="{"){t+=m,r+=2,a.push(1),i="normal";continue}u==="`"&&(i="normal"),r++;continue;case"line-comment":t+=u,u===`
|
|
47
|
+
`&&(i="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&m==="/"){t+=m,r+=2,i="normal";continue}r++;continue;case"regex":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}if(u==="["){for(r++;r<e.length&&e[r]!=="]";)t+=e[r],e[r]==="\\"&&r+1<e.length?(t+=e[r+1],r+=2):r++;r<e.length&&(t+=e[r],r++);continue}if(u==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)t+=e[r],r++;i="normal";continue}r++;continue;case"normal":if(a.length>0){if(u==="{")a[a.length-1]++;else if(u==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),t+=u,r++,i="template-string";continue}}if(u==="'"){t+=u,r++,i="single-string";continue}if(u==='"'){t+=u,r++,i="double-string";continue}if(u==="`"){t+=u,r++,i="template-string";continue}if(u==="/"&&m==="/"){t+=u+m,r+=2,i="line-comment";continue}if(u==="/"&&m==="*"){t+=u+m,r+=2,i="block-comment";continue}if(u==="/"){let b=t.trimEnd();if(!b[b.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(b)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(b)){t+=u,r++,i="regex";continue}}break}if(u==="{"){l++,t+=u,r++;continue}if(u==="}"){l--;let b=c[c.length-1];b&&l===b.braceDepth&&c.pop(),t+=u,r++;continue}let y=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(y){let b=y[0].slice(0,-1);t+=b,r+=b.length,c.push({type:"class-body",braceDepth:l});continue}let h=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(h){let b=h[1],_=h[0].length,x=e[r+_],g,E=r+_;(x==="?"||x==="!")&&(g=x,E++,g==="!"?n.unsafeFunctions.add(b):n.safeFunctions.add(b)),t+=`function ${b}(`,r=E;let k=it(e,r,"(",")");if(!k){t+=e[r],r++;continue}let{content:j,endPos:A}=k;r=A;let M=Ct(j,n,!0);t+=M+")";let N=r;for(;N<e.length&&/\s/.test(e[N]);)N++;if(e[N]===":"){let I=e.slice(N,N+2),O;for(I===":?"||I===":!"?(N+=2,O=I===":?"?"safe":"unsafe"):N+=1;N<e.length&&/\s/.test(e[N]);)N++;let L=Mt(e,N);L&&(s===void 0&&(s=L.type,O&&(o=O)),r=L.endPos)}let R=r;for(;R<e.length&&/\s/.test(e[R]);)R++;if(e[R]==="="&&e[R+1]===">")throw new Z("Unexpected '=>' after function declaration. Function declarations use `function name(params) { body }`, not arrow syntax. Remove the `=>`.",fe(n.originalSource,R),n.originalSource);continue}let w=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),S=(()=>{for(let b=t.length-1;b>=0;b--)if(!/\s/.test(t[b]))return t[b];return`
|
|
48
|
+
`})(),$=S!=="="&&S!==","&&S!=="("&&S!=="["&&S!==">";if(w&&p()&&!$){let b=w[1].length;t+=e.slice(r,r+b),r+=b;continue}if(w&&p()&&$){let b=w[1],_=w[0].length,x=r+_;t+=b+"(",r=x;let g=it(e,r,"(",")");if(!g){t+=e[r],r++;continue}let{content:E,endPos:k}=g;r=k;let j=Ct(E,n,!0);t+=j+")";let A=r;for(;A<e.length&&/\s/.test(e[A]);)A++;if(e[A]===":"){let N=e.slice(A,A+2);for(N===":?"||N===":!"?A+=2:A++;A<e.length&&/\s/.test(e[A]);)A++;let R=Mt(e,A);R&&(r=R.endPos)}let M=r;for(;M<e.length&&/\s/.test(e[M]);)M++;if(e[M]==="="&&e[M+1]===">")throw new Z("Unexpected '=>' after method declaration. Methods use `name(params) { body }`, not arrow syntax. Remove the `=>`.",fe(n.originalSource,M),n.originalSource);continue}if(e[r]==="("){let b=it(e,r+1,"(",")");if(!b){t+=e[r],r++;continue}let _=b.content,x=b.endPos,g=x;for(;g<e.length&&/\s/.test(e[g]);)g++;let E;if(e[g]===":"){let k=e.slice(g,g+2);for(k===":?"||k===":!"?g+=2:g++;g<e.length&&/\s/.test(e[g]);)g++;let j=Mt(e,g);if(j)for(E=j.type,g=j.endPos;g<e.length&&/\s/.test(e[g]);)g++}if(e.slice(g,g+2)==="=>"){let k=null,j=_,A=_.trimStart();A.startsWith("?")&&(A.length===1||/\s/.test(A[1]))?(k="?",j=A.slice(1)):A.startsWith("!")&&(A.length===1||/\s/.test(A[1]))&&(k="!",j=A.slice(1));let M=Ct(j,n,!1);for(t+=`(${k==="?"?"/* safe */ ":k==="!"?"/* unsafe */ ":""}${M})`,r=x;r<g&&/\s/.test(e[r]);)t+=e[r],r++;E&&(r=g)}else{let k=ct(_,n);t+=`(${k.source})`,r=x}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:o}}function it(e,n,t,r){let s=1,o=n,i=!1,a="";for(;o<e.length&&s>0;){let c=e[o];!i&&(c==="'"||c==='"'||c==="`")?(i=!0,a=c):i&&c===a&&e[o-1]!=="\\"?i=!1:i||(c===t?s++:c===r&&s--),o++}return s!==0?null:{content:e.slice(n,o-1),endPos:o}}function nr(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return null;let r=t,s=e[t];if(s==="{"||s==="["){let i=s==="{"?"}":"]",a=it(e,t+1,s,i);return a?{value:e.slice(r,a.endPos),endPos:a.endPos}:null}if(s==="'"||s==='"'||s==="`"){for(t++;t<e.length;){if(e[t]===s&&e[t-1]!=="\\")return t++,{value:e.slice(r,t),endPos:t};t++}return null}if(/[-+\d]/.test(s)){for(;t<e.length&&/[\d.eE+-]/.test(e[t]);)t++;return{value:e.slice(r,t),endPos:t}}let o=e.slice(t).match(/^(true|false|null|undefined)\b/);return o?{value:o[1],endPos:t+o[1].length}:null}function Je(e){return e.replace(/(?<!\|)\|(?!\|)/g," || ")}function Mt(e,n){let t=n,r=0,s=!1,o="",i=!1,a=c=>({type:Je(e.slice(n,c).trim()),endPos:c});for(;t<e.length;){let c=e[t];if(!s&&(c==="'"||c==='"'||c==="`")){s=!0,o=c,i=!0,t++;continue}if(s){if(c===o&&e[t-1]!=="\\"){if(s=!1,t++,r===0){let l=t;for(;l<e.length&&/\s/.test(e[l]);)l++;if(e[l]==="{"&&!e.slice(l+1).match(/^\s*(\w+)\s*:/)||e[l]!=="|"&&e[l]!=="&")return a(t)}continue}t++;continue}if(c==="{"||c==="["||c==="("){r++,i=!0,t++;continue}if(c==="}"||c==="]"||c===")"){if(r--,r===0){t++;let l=t;for(;l<e.length&&/\s/.test(e[l]);)l++;if(e[l]==="|"||e[l]==="&")continue;return a(t)}t++;continue}if(r===0&&c==="{"){if(i)return a(t);if(e.slice(t+1).match(/^\s*(\w+)\s*:/)){r++,i=!0,t++;continue}return a(t)}if(r===0&&(c==="|"||c==="&")){for(t++,t<e.length&&e[t]==="|"&&t++;t<e.length&&/\s/.test(e[t]);)t++;continue}if(r===0&&(/\d/.test(c)||c==="-"&&/\d/.test(e[t+1]))){let l=t;for(e[l]==="-"&&l++;l<e.length&&/\d/.test(e[l]);)l++;if(l<e.length&&e[l]==="."&&/\d/.test(e[l+1]))for(l++;l<e.length&&/\d/.test(e[l]);)l++;if(l<e.length&&(e[l]==="e"||e[l]==="E"))for(l++,l<e.length&&(e[l]==="+"||e[l]==="-")&&l++;l<e.length&&/\d/.test(e[l]);)l++;for(i=!0,t=l;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="{")return{type:Je(e.slice(n,l).trim()),endPos:l};if(e[t]!=="|"&&e[t]!=="&")return{type:Je(e.slice(n,l).trim()),endPos:l};continue}if(r===0&&/[a-zA-Z_]/.test(c)){let l=t;for(;l<e.length&&/\w/.test(e[l]);)l++;for(i=!0,t=l;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="("){r++,t++;continue}if(t<e.length&&e[t]==="{"&&!e.slice(t+1).match(/^\s*(\w+)\s*:/)){let p=l;for(;p>n&&/\s/.test(e[p-1]);)p--;return{type:Je(e.slice(n,p).trim()),endPos:l}}if(e[t]!=="|"&&e[t]!=="&")return{type:Je(e.slice(n,l).trim()),endPos:l};continue}t++}return i?a(t):null}function lt(e){let n=[],t="",r=0,s=!1,o=!1,i=0;for(;i<e.length;){let a=e[i],c=e[i+1];if(!o&&a==="/"&&c==="/"){s=!0,t+="//",i+=2;continue}if(!s&&a==="/"&&c==="*"){o=!0,t+="/*",i+=2;continue}if(s&&a===`
|
|
49
|
+
`){s=!1,t+=a,i++;continue}if(o&&a==="*"&&c==="/"){o=!1,t+="*/",i+=2;continue}if(s||o){t+=a,i++;continue}a==="("||a==="{"||a==="["?(r++,t+=a):a===")"||a==="}"||a==="]"?(r--,t+=a):a===","&&r===0?(n.push(t),t=""):t+=a,i++}return t.trim()&&n.push(t),n}function Ct(e,n,t){let r=ct(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=lt(r),o=!1,i=new Set,a=l=>{if(t&&/^\w+$/.test(l)){if(i.has(l))throw new Error(`Duplicate parameter name '${l}'`);i.add(l)}};return s.map(l=>{let f=l.trim();if(!f)return l;if(t&&f.startsWith("{")&&f.endsWith("}")){let m=f.slice(1,-1);return`{ ${rr(m,n)} }`}if(t&&f.startsWith("[")&&f.endsWith("]")){let m=f.slice(1,-1);return`[ ${rr(m,n)} ]`}if(f.startsWith("...")){let m=sr(f);return m!==-1?f.slice(0,m).trim():l}let p=f.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(p){let[,m,y]=p;return a(m),o=!0,`${m} = ${y}`}if(!bs(f)){let m=f.match(/^(\w+)\s*=/);return m&&a(m[1]),o=!0,l}let u=sr(f);if(u!==-1){let m=f.slice(0,u).trim(),y=f.slice(u+1).trim();return a(m),o&&t&&/^\w+$/.test(m),t&&/^\w+$/.test(m)&&n.requiredParams.add(m),`${m} = ${y}`}return l}).join(",")}function rr(e,n){return lt(e).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,l,f]=i;n.requiredParams.add(l);let p=ot(f);return`${l} = ${p}`}let a=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,l,f]=a;n.requiredParams.add(l);let p=at(f);return`${l} = ${p}`}let c=o.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(c){let[,l,f]=c;return n.requiredParams.add(l),`${l} = ${f}`}return s}).join(", ")}function ot(e){let n=e.slice(1,-1).trim();return`{ ${lt(n).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,p,u]=i;return`${p}: ${ot(u)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,p,u]=a;return`${p}: ${ot(u)}`}let c=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(c){let[,p,u]=c;return`${p}: ${at(u)}`}let l=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(l){let[,p,u]=l;return`${p}: ${at(u)}`}let f=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(f){let[,p,u]=f;return`${p}: ${u}`}return s}).join(", ")} }`}function at(e){let n=e.slice(1,-1).trim();return`[ ${lt(n).map(s=>{let o=s.trim();return o?o.startsWith("{")&&o.endsWith("}")?ot(o):o.startsWith("[")&&o.endsWith("]")?at(o):s:s}).join(", ")} ]`}function bs(e){let n=0,t=!1,r=!1,s=!1,o="";for(let i=0;i<e.length;i++){let a=e[i];if(!s&&(a==="'"||a==='"'||a==="`")){s=!0,o=a;continue}if(s){a===o&&e[i-1]!=="\\"&&(s=!1);continue}a==="("||a==="{"||a==="["?n++:a===")"||a==="}"||a==="]"?n--:n===0&&(a===":"&&(t=!0),a==="="&&e[i+1]!==">"&&(r=!0))}return t&&!r}function sr(e){let n=0,t=!1,r="";for(let s=0;s<e.length;s++){let o=e[s];if(!t&&(o==="'"||o==='"'||o==="`")){t=!0,r=o;continue}if(t){o===r&&e[s-1]!=="\\"&&(t=!1);continue}if(o==="("||o==="{"||o==="[")n++;else if(o===")"||o==="}"||o==="]")n--;else if(n===0&&o===":")return s}return-1}function Nt(e){let n="",t=0;for(;t<e.length;){let r=e[t];if(r==="'"||r==='"'||r==="`"){let s=r;for(n+=r,t++;t<e.length&&e[t]!==s;)e[t]==="\\"&&(n+=e[t++]),t<e.length&&(n+=e[t++]);t<e.length&&(n+=e[t++]);continue}if(r==="/"&&e[t+1]==="*"){let s=e.indexOf("*/",t+2),o=s===-1?e.slice(t):e.slice(t,s+2);n+=o,t+=o.length;continue}if(r==="/"&&e[t+1]==="/"){let s=e.indexOf(`
|
|
50
|
+
`,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function ut(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,c=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e)||n.vmTarget,l=c?{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0,tjsSafeAssign:!0};c&&(r="none");let f=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);f&&(r=f[2],e=e.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1"));let p=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval|TjsSafeAssign)\b/,u;for(;u=e.match(p);){let A=u[2];A==="TjsStrict"?(l.tjsEquals=!0,l.tjsClass=!0,l.tjsDate=!0,l.tjsNoeval=!0,l.tjsNoVar=!0,l.tjsStandard=!0,l.tjsSafeAssign=!0):A==="TjsCompat"?(l.tjsEquals=!1,l.tjsClass=!1,l.tjsDate=!1,l.tjsNoeval=!1,l.tjsNoVar=!1,l.tjsStandard=!1,l.tjsSafeEval=!1,l.tjsSafeAssign=!1):A==="TjsEquals"?l.tjsEquals=!0:A==="TjsClass"?l.tjsClass=!0:A==="TjsDate"?l.tjsDate=!0:A==="TjsNoeval"?l.tjsNoeval=!0:A==="TjsNoVar"?l.tjsNoVar=!0:A==="TjsStandard"?l.tjsStandard=!0:A==="TjsSafeEval"?l.tjsSafeEval=!0:A==="TjsSafeAssign"&&(l.tjsSafeAssign=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${A}\\s*`),"$1")}e=Nt(e),l.tjsStandard&&(e=On(e)),e=Hn(e),e=er(e);let m=tr(e);e=m.source;let y=m.annotations,h=In(e);e=h.source,e=Ue(e),l.tjsEquals&&!n.vmTarget&&(e=We(e)),e=Dn(e),e=qn(e),e=Fn(e),e=Un(e),e=Wn(e),e=zn(e);let w=Bn(e,{loader:n.moduleLoader,importerPath:n.filename});e=w.source;let{source:S,returnType:$,returnSafety:b}=ct(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=S;let _=Ln(e);e=_.source,e=Nn(e);let x=Vn(e,s);e=x.source;let g=Pn(e);e=g.source;let E=[...h.blocks,...w.blocks,...g.blocks],k=Zn(e,n.dangerouslySkipTests);e=k.source;let j=Gn(e,s);e=j.source;for(let A of j.polyCtorClasses)o.add(`${A}$dispatch`);return l.tjsClass&&(e=Kn(e,j.polyCtorClasses)),l.tjsDate&&(e=Yn(e)),l.tjsNoeval&&(e=Xn(e)),l.tjsNoVar&&(e=Qn(e)),e=Le(e,_.extensions),{source:e,returnType:$,returnSafety:b,moduleSafety:r,tjsModes:l,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:E,tests:k.tests,testErrors:k.errors,polymorphicNames:x.polymorphicNames,extensions:_.extensions,letAnnotations:y}}function be(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1}=n,{source:o,returnType:i,returnSafety:a,moduleSafety:c,originalSource:l,requiredParams:f,unsafeFunctions:p,safeFunctions:u,wasmBlocks:m,tests:y,testErrors:h,letAnnotations:w,tjsModes:S}=r?ut(e,{vmTarget:s,moduleLoader:n.moduleLoader,filename:n.filename}):{source:e,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:e,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[],letAnnotations:new Map,tjsModes:{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}};try{return{ast:ir.parse(o,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:i,returnSafety:a,moduleSafety:c,originalSource:l,requiredParams:f,unsafeFunctions:p,safeFunctions:u,wasmBlocks:m,tests:y,testErrors:h,letAnnotations:w,tjsModes:S}}catch($){let b=$.loc||{line:1,column:0};throw new Z($.message.replace(/\s*\(\d+:\d+\)$/,""),b,l,t)}}function or(e,n){for(let r of e.body){if(r.type==="ImportDeclaration")throw new Z("Imports are not supported. All atoms must be registered with the VM.",r.loc?.start||{line:1,column:0},void 0,n);if(r.type==="ExportNamedDeclaration"||r.type==="ExportDefaultDeclaration")throw new Z("Exports are not supported. The function is automatically exported.",r.loc?.start||{line:1,column:0},void 0,n);if(r.type==="ClassDeclaration")throw new Z("Classes are not supported. Agent99 uses functional composition.",r.loc?.start||{line:1,column:0},void 0,n)}let t=e.body.filter(r=>r.type==="FunctionDeclaration");if(t.length===0)throw new Z("Source must contain a function declaration",{line:1,column:0},void 0,n);if(t.length>1){let r=t[1];throw new Z("Only a single function per agent is allowed",r.loc?.start||{line:1,column:0},void 0,n)}return t[0]}function Ve(e,n){let t={params:{}};if(!n.loc)return t;let r=e.substring(0,n.start),s=[...r.matchAll(/\/\*#([\s\S]*?)\*\//g)];if(s.length>0){let f=s[s.length-1],p=r.substring(f.index+f[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(p)){let u=f[1],m=u.split(`
|
|
51
|
+
`),y=m.filter(h=>h.trim().length>0).reduce((h,w)=>{let S=w.match(/^(\s*)/)?.[1].length||0;return Math.min(h,S)},1/0);return y>0&&y<1/0&&(u=m.map(h=>h.slice(y)).join(`
|
|
52
|
+
`)),t.description=u.trim(),t}}let o=r.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!o)return t;let i=o[0],a=i.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);a&&(t.description=a[1].trim());let c=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,l;for(;(l=c.exec(i))!==null;)t.params[l[1]]=l[2].trim();return t}import{parseExpressionAt as _s}from"acorn";function Y(e){switch(e.type){case"Literal":{let n=e.value;if(n===null)return{kind:"null"};if(typeof n=="string")return{kind:"string"};if(typeof n=="number"){let t=e.raw;return t&&t.includes(".")?{kind:"number"}:{kind:"integer"}}return typeof n=="boolean"?{kind:"boolean"}:{kind:"any"}}case"ArrayExpression":{let n=e.elements;if(n.length===0)return{kind:"array",items:{kind:"any"}};let t=n.filter(i=>i!=null).map(i=>Y(i));if(t.length===0)return{kind:"array",items:{kind:"any"}};let r=new Map;for(let i of t){let a=JSON.stringify(i);r.has(a)||r.set(a,i)}let s=[...r.values()];return{kind:"array",items:s.length===1?s[0]:{kind:"union",members:s}}}case"ObjectExpression":{let n=e.properties,t={};for(let r of n)if(r.type==="Property"&&r.key.type==="Identifier"){let s=r.key.name;t[s]=Y(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?Y(t):n==="&&"||n==="??"?Y(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=Y(t),o=Y(r);return o.kind==="null"?{...s,nullable:!0}:s.kind==="null"?{...o,nullable:!0}:{kind:"union",members:[s,o]}}return{kind:"any"}}case"Identifier":return e.name==="undefined"?{kind:"undefined"}:{kind:"any"};case"ArrowFunctionExpression":case"FunctionExpression":{let n=e,t=n.params.map(s=>xs(s)),r={kind:"any"};return n.type==="ArrowFunctionExpression"&&n.body&&n.body.type!=="BlockStatement"&&(r=Y(n.body)),{kind:"function",params:t,returns:r}}case"UnaryExpression":{let n=e.operator,t=e.argument;if(n==="+"&&t.type==="Literal"&&typeof t.value=="number")return{kind:"non-negative-integer"};if(n==="-"&&t.type==="Literal"&&typeof t.value=="number"){let s=t.raw;return s&&s.includes(".")?{kind:"number"}:{kind:"integer"}}return{kind:"any"}}default:return{kind:"any"}}}function xs(e){return e.type==="Identifier"?{name:e.name,type:{kind:"any"}}:e.type==="AssignmentPattern"&&e.left?.type==="Identifier"?{name:e.left.name,type:Y(e.right)}:e.type==="RestElement"&&e.argument?.type==="Identifier"?{name:`...${e.argument.name}`,type:{kind:"array",items:{kind:"any"}}}:{name:"?",type:{kind:"any"}}}function ye(e,n){if(e.type==="Identifier")return{name:e.name,type:{kind:"any"},required:!0};if(e.type==="AssignmentPattern"){let{left:t,right:r}=e;if(t.type!=="Identifier")throw new U("Only simple parameter names are supported",J(e));let s=t.name,o=n?.has(s)??!1,i=Y(r),a=oe(r);return{name:s,type:i,required:o,default:o?null:a,example:a,loc:{start:e.start,end:e.end}}}if(e.type==="ObjectPattern"){let t=e.properties,r={},s={};for(let o of t)if(o.type==="Property"){let i=o.key.type==="Identifier"?o.key.name:String(o.key.value);if(o.value.type==="Identifier")r[i]={kind:"any"},s[i]={name:i,type:{kind:"any"},required:!0};else if(o.value.type==="AssignmentPattern"){let a=ye(o.value,n),c=n?.has(i)??!1;r[i]=a.type,s[i]={name:i,type:a.type,required:c,default:c?null:a.example,example:a.example}}}return{name:"__destructured__",type:{kind:"object",shape:r,destructuredParams:s},required:!0}}throw new U(`Unsupported parameter pattern: ${e.type}`,J(e))}function oe(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?oe(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=oe(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=oe(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=oe(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?oe(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?oe(t)??oe(r):void 0}default:return}}function ar(e){try{let n=_s(e,0,{ecmaVersion:2022});return Y(n)}catch{return{kind:"any"}}}function Pt(e){switch(e.kind){case"string":return e.nullable?"string | null":"string";case"number":return e.nullable?"number | null":"number";case"integer":return e.nullable?"integer | null":"integer";case"non-negative-integer":return e.nullable?"non-negative integer | null":"non-negative integer";case"boolean":return e.nullable?"boolean | null":"boolean";case"null":return"null";case"any":return"any";case"array":{let n=e.items?Pt(e.items):"any";return e.nullable?`${n}[] | null`:`${n}[]`}case"object":{if(!e.shape||Object.keys(e.shape).length===0)return e.nullable?"object | null":"object";let n=Object.entries(e.shape).map(([t,r])=>`${t}: ${Pt(r)}`).join(", ");return e.nullable?`{ ${n} } | null`:`{ ${n} }`}case"union":return e.members?.map(Pt).join(" | ")||"any";default:return"any"}}function ft(e){switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{};case"undefined":return{};case"any":return{};case"array":return{type:"array",items:e.items?ft(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=ft(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(ft)}:{};default:return{}}}function ws(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=ft(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function It(e,n,t,r={},s){let o=Ve(n,e),i=new Map;for(let w of e.params){let S=ye(w,s);if(S.name==="__destructured__"&&S.type.kind==="object"&&S.type.destructuredParams)for(let[$,b]of Object.entries(S.type.destructuredParams))i.set($,{...b,description:o.params[$]});else S.description=o.params[S.name],i.set(S.name,S)}let a;t&&(a=ar(t));let c={depth:0,locals:new Map,parameters:i,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r},l=ae(e.body,c),f=[],p=[],u=[];for(let[w,S]of i.entries())S.required?p.push(w):S.default!==void 0?u.push({name:w,defaultValue:S.default}):p.push(w);p.length>0&&f.push({op:"varsImport",keys:p});for(let{name:w,defaultValue:S}of u)f.push({op:"varsImport",keys:[w]}),f.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:w},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:w,value:S}]});f.push(...l);let m=Object.fromEntries(i),y={name:e.id?.name||"anonymous",description:o.description,parameters:m,returns:a},h=ws(m);return{ast:{op:"seq",steps:f,inputSchema:h},signature:y,warnings:c.warnings}}function ae(e,n){let t=[];for(let r of e.body){let s=ze(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function ze(e,n){switch(e.type){case"VariableDeclaration":return $s(e,n);case"ExpressionStatement":return Ss(e,n);case"IfStatement":return Ts(e,n);case"WhileStatement":return ks(e,n);case"ForOfStatement":return js(e,n);case"TryStatement":return vs(e,n);case"ReturnStatement":return As(e,n);case"ThrowStatement":throw new U("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",J(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:ae(e,re(n))};case"EmptyStatement":return null;default:throw new U(`Unsupported statement type: ${e.type}`,J(e),n.source,n.filename)}}function $s(e,n){let t=[],r=e.kind==="const",s=r?"constSet":"varSet";for(let o of e.declarations){if(o.id.type!=="Identifier")throw new U("Only simple variable names are supported",J(o),n.source,n.filename);let i=o.id.name;if(o.init){let{step:a,resultVar:c}=_e(o.init,n,i,r);a?t.push(a):c!==i&&t.push({op:s,key:i,value:c});let l=Y(o.init);n.locals.set(i,l)}else{if(r)throw new U("const declarations must be initialized",J(o),n.source,n.filename);t.push({op:"varSet",key:i,value:null}),n.locals.set(i,{kind:"any",nullable:!0})}}return t}function Ss(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return Es(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=_e(t,n);return r||(s?{op:"varSet",key:"_",value:s}:null)}return n.warnings.push({message:"Expression statement has no effect",line:J(e).line,column:J(e).column}),null}function Es(e,n){if(e.left.type!=="Identifier")throw new U("Only simple variable assignment is supported",J(e),n.source,n.filename);let t=e.left.name,{step:r,resultVar:s}=_e(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function Ts(e,n){let t=F(e.test,n),r=e.consequent.type==="BlockStatement"?ae(e.consequent,re(n)):[ze(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?ae(e.alternate,re(n)):[ze(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function ks(e,n){let t=F(e.test,n),r=e.body.type==="BlockStatement"?ae(e.body,re(n)):[ze(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function js(e,n){let t;if(e.left.type==="VariableDeclaration"){let i=e.left.declarations[0];if(i.id.type!=="Identifier")throw new U("Only simple variable names are supported in for...of",J(e.left),n.source,n.filename);t=i.id.name}else if(e.left.type==="Identifier")t=e.left.name;else throw new U("Unsupported for...of left-hand side",J(e.left),n.source,n.filename);let r=H(e.right,n),s=re(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?ae(e.body,s):[ze(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function vs(e,n){let t=ae(e.block,re(n)),r,s;if(e.handler){let o=re(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=ae(e.handler.body,o)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function As(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=_e(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:H(e.argument,n)}}var lr=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),Rs=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),Ze=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),Ms=new Set(["toUpperCase","toLowerCase","trim","trimStart","trimEnd","charAt","charCodeAt","codePointAt","concat","includes","indexOf","lastIndexOf","startsWith","endsWith","slice","substring","substr","replace","replaceAll","match","search","padStart","padEnd","repeat","normalize","localeCompare","toString","valueOf","at","reverse","sort","fill","copyWithin","flat","flatMap","every","some","forEach","add","remove","has","clear","toArray","union","intersection","diff","format","isBefore","isAfter"]);function Cs(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return Rs.has(n)||Ze.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(lr.has(t)||Ze.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(Ms.has(t))return!0}}return!1}function Ns(e){if(e.object.type==="Identifier"){let n=e.object.name;return lr.has(n)||Ze.has(n)}return!1}var cr={RegExp:"RegExp is not available. Use string methods or the regexMatch atom.",Promise:"Promise is not needed. All operations are implicitly async.",Map:"Map is not available. Use plain objects instead.",WeakSet:"WeakSet is not available.",WeakMap:"WeakMap is not available.",Symbol:"Symbol is not available.",Proxy:"Proxy is not available.",Reflect:"Reflect is not available.",Function:"Function constructor is not available. Define functions normally.",eval:"eval is not available. Code is compiled, not evaluated.",setTimeout:"setTimeout is not available. Use the delay atom.",setInterval:"setInterval is not available. Use while loops with delay.",fetch:"fetch is not available. Use the httpFetch atom.",require:"require is not available. Atoms must be registered with the VM.",import:"import is not available. Atoms must be registered with the VM.",process:"process is not available. AsyncJS runs in a sandboxed environment.",window:"window is not available. AsyncJS runs in a sandboxed environment.",document:"document is not available. AsyncJS runs in a sandboxed environment.",global:"global is not available. AsyncJS runs in a sandboxed environment.",globalThis:"globalThis is not available. Use builtins directly."};function Ps(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(Ze.has(n))return cr[n]||`${n} is not available in AsyncJS.`}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Ze.has(t))return cr[t]||`${t} is not available in AsyncJS.`}}return null}function ur(e){return{Date:" Use Date() or Date('2024-01-15') instead - no 'new' needed.",Set:" Use Set([items]) instead - no 'new' needed.",Map:" Use plain objects instead of Map.",Array:" Use array literals like [1, 2, 3] instead.",Object:" Use object literals like { key: value } instead.",Error:" Return an error object like { error: 'message' } instead.",RegExp:" Use string methods or the regexMatch atom.",Promise:" Not needed - all operations are implicitly async.",WeakSet:" WeakSet is not available.",WeakMap:" WeakMap is not available."}[e]||" Use factory functions or object literals instead."}function _e(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return _e(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let c=ur(a);throw new U(`The 'new' keyword is not supported in AsyncJS.${c}`,J(e),n.source,n.filename)}if(e.type==="CallExpression"){let i=Ps(e);if(i)throw new U(i,J(e),n.source,n.filename)}if(e.type==="CallExpression"&&Cs(e)){let i=F(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="MemberExpression"&&Ns(e)){let i=F(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="CallExpression")return Is(e,n,t,r);if(e.type==="TemplateLiteral")return Os(e,n,t,r);if(e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="UnaryExpression"){let i=F(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}return{step:null,resultVar:H(e,n)}}function Is(e,n,t,r){let s,o=!1,i;if(e.callee.type==="Identifier")s=e.callee.name;else if(e.callee.type==="MemberExpression"){let c=e.callee;if(c.property.type==="Identifier")s=c.property.name,o=!0,i=H(c.object,n);else throw new U("Computed method names are not supported",J(e),n.source,n.filename)}else throw new U("Only named function calls are supported",J(e),n.source,n.filename);if(o)return Bs(s,i,e.arguments,n,t,r);s==="console"&&e.callee.type;let a=Ds(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function Bs(e,n,t,r,s,o){switch(e){case"map":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],c=a?.type==="Identifier"?a.name:"item",l=re(r);l.locals.set(c,{kind:"any"});let f;if(i.body.type==="BlockStatement")f=ae(i.body,l);else{let{step:p,resultVar:u}=_e(i.body,l,"result");f=p?[p]:[{op:"varSet",key:"result",value:u}]}return{step:{op:"map",items:n,as:c,steps:f,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"filter":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],c=a?.type==="Identifier"?a.name:"item",l=re(r);l.locals.set(c,{kind:"any"});let f;if(i.body.type==="BlockStatement")throw new U("filter callback must be an expression, not a block",J(t[0]),r.source,r.filename);return f=F(i.body,l),{step:{op:"filter",items:n,as:c,condition:f,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"find":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],c=a?.type==="Identifier"?a.name:"item",l=re(r);l.locals.set(c,{kind:"any"});let f;if(i.body.type==="BlockStatement")throw new U("find callback must be an expression, not a block",J(t[0]),r.source,r.filename);return f=F(i.body,l),{step:{op:"find",items:n,as:c,condition:f,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"reduce":if(t.length>=2&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],c=i.params[1],l=a?.type==="Identifier"?a.name:"acc",f=c?.type==="Identifier"?c.name:"item",p=re(r);p.locals.set(l,{kind:"any"}),p.locals.set(f,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=ae(i.body,p);else{let{step:y,resultVar:h}=_e(i.body,p,"result");u=y?[y]:[{op:"varSet",key:"result",value:h}]}let m=H(t[1],r);return{step:{op:"reduce",items:n,as:f,accumulator:l,initial:m,steps:u,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"slice":break;case"push":return{step:{op:"push",list:n,item:H(t[0],r),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?H(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?H(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}return r.warnings.push({message:`Unknown method '${e}' - treating as atom call`,line:0,column:0}),{step:{op:e,receiver:n,args:t.map(i=>H(i,r)),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}function Os(e,n,t,r){let s="",o={};for(let i=0;i<e.quasis.length;i++)if(s+=e.quasis[i].value.cooked||e.quasis[i].value.raw,i<e.expressions.length){let a=e.expressions[i],c=`_${i}`;o[c]=H(a,n),s+=`{{${c}}}`}return{step:{op:"template",tmpl:s,vars:o,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function F(e,n){switch(e.type){case"Literal":return{$expr:"literal",value:e.value};case"Identifier":return{$expr:"ident",name:e.name};case"MemberExpression":{let t=e,r=F(t.object,n),s=t.optional===!0;if(t.computed){let i=t.property;return i.type==="Literal"?{$expr:"member",object:r,property:String(i.value),computed:!0,...s&&{optional:!0}}:{$expr:"member",object:r,property:F(i,n),computed:!0,...s&&{optional:!0}}}let o=t.property.name;return{$expr:"member",object:r,property:o,...s&&{optional:!0}}}case"ChainExpression":return F(e.expression,n);case"BinaryExpression":{let t=e;return{$expr:"binary",op:t.operator,left:F(t.left,n),right:F(t.right,n)}}case"LogicalExpression":{let t=e;return{$expr:"logical",op:t.operator,left:F(t.left,n),right:F(t.right,n)}}case"UnaryExpression":{let t=e;return{$expr:"unary",op:t.operator,argument:F(t.argument,n)}}case"ConditionalExpression":{let t=e;return{$expr:"conditional",test:F(t.test,n),consequent:F(t.consequent,n),alternate:F(t.alternate,n)}}case"ArrayExpression":return{$expr:"array",elements:e.elements.filter(r=>r!==null).map(r=>F(r,n))};case"ObjectExpression":{let t=e,r=[];for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r.push({key:o,value:F(s.value,n)})}return{$expr:"object",properties:r}}case"CallExpression":{let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,s=r.property.type==="Identifier"?r.property.name:String(r.property.value),o=r.optional===!0||t.optional===!0;return{$expr:"methodCall",object:F(r.object,n),method:s,arguments:t.arguments.map(i=>F(i,n)),...o&&{optional:!0}}}if(t.callee.type==="Identifier")return{$expr:"call",callee:t.callee.name,arguments:t.arguments.map(s=>F(s,n))};throw new U("Complex function calls in expressions should be lifted to statements",J(e),n.source,n.filename)}case"NewExpression":{let t=e,r="constructor";t.callee.type==="Identifier"&&(r=t.callee.name);let s=ur(r);throw new U(`The 'new' keyword is not supported in AsyncJS.${s}`,J(e),n.source,n.filename)}case"TemplateLiteral":throw new U("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",J(e),n.source,n.filename);default:throw new U(`Unsupported expression type in condition: ${e.type}`,J(e),n.source,n.filename)}}function H(e,n){switch(e.type){case"Literal":return e.value;case"Identifier":return e.name;case"MemberExpression":{let t=e;if(t.optional===!0)return F(e,n);let s=H(t.object,n);if(s&&typeof s=="object"&&s.$expr){let i=t.computed?String(t.property.value):t.property.name;return{$expr:"member",object:s,property:i,...t.computed&&{computed:!0}}}if(t.computed)return F(e,n);let o=t.property.name;return typeof s=="string"?`${s}.${o}`:s&&s.$kind==="arg"?{$kind:"arg",path:`${s.path}.${o}`}:`${s}.${o}`}case"ChainExpression":return H(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?H(t,n):null);case"ObjectExpression":{let t={};for(let r of e.properties)if(r.type==="Property"){let s=r.key.type==="Identifier"?r.key.name:String(r.key.value);t[s]=H(r.value,n)}return t}case"TemplateLiteral":return F(e,n);case"CallExpression":return F(e,n);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return F(e,n);default:return null}}function Ds(e,n){if(e.arguments.length===1&&e.arguments[0].type==="ObjectExpression"){let t=e.arguments[0],r={};for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r[o]=H(s.value,n)}return r}return{args:e.arguments.map(t=>H(t,n))}}import{parseExpressionAt as Vr}from"acorn";function Fs(e,n){let t=n;for(;t>0&&e[t-1]!==`
|
|
53
|
+
`;)t--;if(e.slice(t,n).includes("//"))return!0;let s=0,o=!1;for(;s<n;)!o&&e.slice(s,s+2)==="/*"?(o=!0,s+=2):o&&e.slice(s,s+2)==="*/"?(o=!1,s+=2):s++;return o}function qs(e){let n=[],t=/\/\*test\s+'([^']*)'\s*\{([\s\S]*?)\}\s*\*\/|\/\*test\s+"([^"]*)"\s*\{([\s\S]*?)\}\s*\*\/|\/\*test\s+`([^`]*)`\s*\{([\s\S]*?)\}\s*\*\/|\/\*test\s*\{([\s\S]*?)\}\s*\*\//g,r;for(;(r=t.exec(e))!==null;){let s=r[1]||r[3]||r[5]||`embedded test ${n.length+1}`,o=(r[2]||r[4]||r[6]||r[7]||"").trim();n.push({description:s,body:o,line:Bt(e,r.index)})}return n}function Ot(e){let n=[],t=[],r=qs(e);n.push(...r);let s=/test\s+'([^']*)'\s*\{|test\s+"([^"]*)"\s*\{|test\s+`([^`]*)`\s*\{|test\s*\(\s*'([^']*)'\s*\)\s*\{|test\s*\(\s*"([^"]*)"\s*\)\s*\{|test\s*\(\s*`([^`]*)`\s*\)\s*\{|test\s*\{/g,o=/mock\s*\{/g,i=e,a,c=[];for(;(a=s.exec(e))!==null;){let u=a.index;if(Fs(e,u))continue;let m=a[1]||a[2]||a[3]||a[4]||a[5]||a[6]||`test ${n.length+1}`,y=a.index+a[0].length,h=fr(e,y-1);if(h===-1)continue;let w=e.slice(y,h).trim();n.push({description:m,body:w,line:Bt(e,u)}),c.push({start:u,end:h+1,desc:m})}let l=[];for(;(a=o.exec(e))!==null;){let u=a.index,m=a.index+a[0].length,y=fr(e,m-1);if(y===-1)continue;let h=e.slice(m,y).trim();t.push({body:h,line:Bt(e,u)}),l.push({start:u,end:y+1})}let f=[...c,...l].sort((u,m)=>m.start-u.start);for(let u of f)i=i.slice(0,u.start)+i.slice(u.end);i=i.replace(/\n\s*\n\s*\n/g,`
|
|
52
54
|
|
|
53
|
-
`).trim();let
|
|
54
|
-
`).length}function
|
|
55
|
+
`).trim();let p=Us(n,t);return{code:i,tests:n,mocks:t,testRunner:p}}function fr(e,n){let t=0,r=null,s=!1;for(let o=n;o<e.length;o++){let i=e[o];if(s){s=!1;continue}if(i==="\\"){s=!0;continue}if(!r&&(i==='"'||i==="'"||i==="`")){r=i;continue}if(r===i){r=null;continue}if(!r&&(i==="{"&&t++,i==="}"&&(t--,t===0)))return o}return-1}function Bt(e,n){return e.slice(0,n).split(`
|
|
56
|
+
`).length}function Us(e,n){if(e.length===0)return"// No tests defined";let t=n.map(s=>s.body).join(`
|
|
55
57
|
`);return`(async () => {
|
|
56
58
|
const __results = []
|
|
57
59
|
|
|
@@ -74,13 +76,13 @@ const __failed = __results.filter(r => !r.passed).length
|
|
|
74
76
|
|
|
75
77
|
// Return summary
|
|
76
78
|
return { passed: __passed, failed: __failed, results: __results }
|
|
77
|
-
})()`.trim()}var
|
|
79
|
+
})()`.trim()}var pr=`
|
|
78
80
|
function assert(condition, message) {
|
|
79
81
|
if (!condition) {
|
|
80
82
|
throw new Error(message || 'Assertion failed')
|
|
81
83
|
}
|
|
82
84
|
}
|
|
83
|
-
`,
|
|
85
|
+
`,mr=`
|
|
84
86
|
function expect(actual) {
|
|
85
87
|
const deepEqual = (a, b) => {
|
|
86
88
|
if (a === b) return true
|
|
@@ -171,49 +173,49 @@ function expect(actual) {
|
|
|
171
173
|
}
|
|
172
174
|
}
|
|
173
175
|
}
|
|
174
|
-
`,
|
|
175
|
-
`+fr;import{validate as xr,s as yt}from"tosijs-schema";function Ce(e){if(e.nullable)return{anyOf:[Ce({...e,nullable:!1}),{type:"null"}]};switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"integer":return{type:"integer"};case"non-negative-integer":return{type:"integer",minimum:0};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"undefined":return{};case"any":return{};case"array":return e.items?{type:"array",items:Ce(e.items)}:{type:"array"};case"object":if(e.shape){let n={},t=[];for(let[r,s]of Object.entries(e.shape))n[r]=Ce(s),t.push(r);return{type:"object",properties:n,required:t,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{anyOf:e.members.map(Ce)}:{};default:return{}}}function Ne(e){if(e===null)return{type:"null"};if(e===void 0)return{};switch(typeof e){case"string":return{type:"string"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":{if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:Ne(e[0])};let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=Ne(s),t.push(r);return{type:"object",properties:n,required:t,additionalProperties:!1}}default:return{}}}function Ft(e){let n={},t=[];for(let[o,i]of Object.entries(e.params))i?.type?.kind?n[o]=Ce(i.type):i?.example!==void 0?n[o]=Ne(i.example):n[o]={},i?.required!==!1&&t.push(o),i?.example!==void 0&&(n[o].examples=[i.example]);let r={type:"object",properties:n,required:t},s;return e.returns&&(e.returns.type?.kind?s=Ce(e.returns.type):e.returns.example!==void 0&&(s=Ne(e.returns.example))),{input:r,output:s}}import{validate as qt,filter as Fs,s as pt}from"tosijs-schema";function _e(e){return e!==null&&typeof e=="object"&&"__runtimeType"in e&&e.__runtimeType===!0}function pr(e){return e!==null&&typeof e=="object"&&"schema"in e&&typeof e.schema=="object"}function qs(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function Z(e,n,t,r){let s,o,i,a=t,c=r;if(typeof e=="string")if(s=e,typeof n=="function")o=n,a!==void 0&&(i=pt.infer(a));else if(n===void 0&&a!==void 0)i=pt.infer(a);else if(pr(n))i=n;else if(qs(n))i=n;else if(n!==void 0)a=n,c=a,i=pt.infer(a);else throw new Error("Type(description) requires a predicate, schema, or example");else pr(e),i=e,s=Us(i);let l;if(i){let f=i?.schema??i;f&&typeof f=="object"&&Array.isArray(f.examples)&&(l=f.examples)}return a===void 0&&l&&l.length>0&&(a=l[0]),{description:s,check:f=>o?o(f):i?qt(f,i):!1,schema:i,predicate:o,example:a,examples:l,default:c,toJSONSchema(){if(i){let f=i?.schema??i;if(f&&typeof f=="object"&&"type"in f)return f}return a!==void 0?Ne(a):{description:s}},strip(f){return i?Fs(f,i):f},__runtimeType:!0}}function Us(e){let n=e?.schema??e;if(n&&typeof n=="object"&&"type"in n){let t=n;switch(t.type){case"string":return t.format?`string (${t.format})`:t.pattern?`string matching ${t.pattern}`:t.minLength!==void 0&&t.maxLength!==void 0?`string (${t.minLength}-${t.maxLength} chars)`:"string";case"number":case"integer":return t.minimum!==void 0&&t.maximum!==void 0?`${t.type} (${t.minimum}-${t.maximum})`:t.minimum!==void 0?`${t.type} >= ${t.minimum}`:t.maximum!==void 0?`${t.type} <= ${t.maximum}`:t.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var Ut=Z("string",e=>typeof e=="string"?!0:`expected string, got ${e===null?"null":typeof e}`),Lt=Z("number",e=>typeof e=="number"?!0:`expected number, got ${e===null?"null":typeof e}`),Wt=Z("boolean",e=>typeof e=="boolean"?!0:`expected boolean, got ${e===null?"null":typeof e}`),Jt=Z("integer",e=>typeof e!="number"?`expected integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?!0:`${e} is not an integer`),Vt=Z("positive integer",e=>typeof e!="number"?`expected positive integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?e<=0?`${e} is not positive`:!0:`${e} is not an integer`),zt=Z("non-empty string",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:e.length===0?"string is empty":!0),Zt=Z("email address",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?!0:`"${e}" is not a valid email`),mr=e=>{try{return new URL(e),!0}catch{return!1}},Gt=Z("URL",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:mr(e)?!0:`"${e}" is not a valid URL`),Kt=Z("UUID",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)?!0:`"${e}" is not a valid UUID`),dr=e=>{let n=new Date(e);return!isNaN(n.getTime())&&e.includes("T")},yr=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let n=new Date(e+"T00:00:00Z");return!isNaN(n.getTime())},gr=Z("ISO 8601 timestamp",e=>typeof e=="string"&&dr(e)),hr=Z("date (YYYY-MM-DD)",e=>typeof e=="string"&&yr(e));function Yt(e){return Z(`${e.description} or null`,n=>n===null||e.check(n)===!0)}function Ht(e){return Z(`${e.description} (optional)`,n=>n==null||e.check(n)===!0)}function Qt(e,n,...t){if(typeof e=="string"&&Array.isArray(n)){let o=e,i=n,a=new Set(i);return{description:o,check:l=>a.has(l),toJSONSchema:()=>({enum:i}),strip:l=>l,__runtimeType:!0,values:i}}let r=[];_e(e)&&r.push(e),_e(n)&&r.push(n),r.push(...t);let s=r.map(o=>o.description).join(" | ");return Z(s,o=>r.some(i=>i.check(o)===!0))}function Xt(e){return Z(`array of ${e.description}`,n=>Array.isArray(n)&&n.every(t=>e.check(t)===!0))}function Ls(e){if(_e(e))return t=>e.check(t)===!0;if(e&&typeof e=="object"&&"schema"in e)return t=>qt(t,e);let n=pt.infer(e);return t=>qt(t,n)}function Ge(e,n,t){let r=[],s=[];for(let i of e)typeof i=="string"?(r.push(i),s.push(void 0)):(r.push(i[0]),s.push(i[1]));let o=(...i)=>{let a=r.map((l,p)=>{let f=p<i.length?i[p]:s[p];return f===void 0?()=>!0:Ls(f)}),c=t;return r.forEach((l,p)=>{let f=p<i.length?i[p]:s[p],u="any";_e(f)?u=f.description:f!==void 0&&(u=typeof f=="string"?"string":JSON.stringify(f)),c=c.replace(new RegExp(`\\b${l}\\b`,"g"),u)}),Z(c,l=>n(l,...a))};return o.params=r,o.description=t,o}var en=Ge(["T","U"],(e,n,t)=>Array.isArray(e)&&e.length===2&&n(e[0])&&t(e[1]),"Pair<T, U>"),tn=Ge(["V"],(e,n)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(n),"Record<string, V>");function nn(e,n){let t=Object.values(n),r=new Set(t),s=Object.keys(n),o={};for(let[a,c]of Object.entries(n))o[c]=a;return{description:e,check:a=>r.has(a),toJSONSchema:()=>({enum:t}),strip:a=>a,__runtimeType:!0,members:n,names:o,values:t,keys:s}}function Ws(e){if(e===null)return"null";if(e===void 0)return"undefined";switch(typeof e){case"string":return"string";case"boolean":return"boolean";case"number":return Number.isInteger(e)?"integer":"number";case"object":return Array.isArray(e)?"array":"object";default:return null}}function mt(e,n,t){if(Array.isArray(n)&&t){let r=n,s=[],o=[];for(let a of r)Array.isArray(a)?(s.push(a[0]),o.push(a[1])):(s.push(a),o.push(void 0));let i=((...a)=>{let c=s.map((p,f)=>f<a.length?a[f]:o[f]),l=t(...c);return mt(e,l)});return Object.defineProperties(i,{typeParamNames:{value:s,enumerable:!0},description:{value:e,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),i}return Js(e,n)}function Js(e,n){let t={},r,s="assertReturns";if(typeof n=="function"){let i=n.__tjs;if(i){if(i.params)for(let[a,c]of Object.entries(i.params))t[a]=c?.example??null;i.returns&&(r=i.returns?.example??null),i.safeReturn?s="checkedReturns":i.unsafe?s="assertReturns":s="returns"}}else t=n.params??{},r=n.returns,s=n.returnContract??"assertReturns";return{description:e,params:t,returns:r,returnContract:s,toJSONSchema:()=>({description:e,type:"function"}),strip:i=>i,check:i=>{if(typeof i!="function")return`expected function, got ${i===null?"null":typeof i}`;let a=Object.keys(t).length;if(a>0){let l=i.__tjs;if(l?.params){let p=Object.keys(l.params).length;if(p!==a)return`expected ${a} params, got ${p}`;let f=Object.keys(t),u=Object.keys(l.params);for(let m=0;m<f.length;m++){let y=l.params[u[m]],g=t[f[m]];if(y?.type?.kind&&g!==void 0){let _=Ws(g);if(_&&y.type.kind!==_&&y.type.kind!=="any")return`param '${f[m]}' expected ${_}, got ${y.type.kind}`}}}}return!0},__runtimeType:!0}}var zs=br(),fe=zs.version,Ke=Symbol.for("tjs.equals");function gt(e){let[n=0,t=0,r=0]=e.split(".").map(Number);return{major:n,minor:t,patch:r}}function sn(e,n){let t=gt(e),r=gt(n);return t.major!==r.major?t.major<r.major?-1:1:t.minor!==r.minor?t.minor<r.minor?-1:1:t.patch!==r.patch?t.patch<r.patch?-1:1:0}function on(e,n){let t=gt(e),r=gt(n);return t.major===r.major}var ge=class e extends Error{path;expected;actual;callStack;reason;constructor(n,t,r,s,o,i){super(n),this.name="MonadicError",this.path=t,this.expected=r,this.actual=s,this.callStack=o,this.reason=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function Zs(e,n,t,r){let s=t===null?"null":typeof t,o=q.callStacks||q.debug?cn():void 0,i=r?`Expected ${n} for '${e}': ${r}`:`Expected ${n} for '${e}', got ${s}`,a=new ge(i,e,n,s,o,r);if(q.trackErrors!==!1){let c=q.maxErrors??ht;wr[Me]=a,Me=(Me+1)%c,$e<c&&$e++,bt++}if(q.logTypeErrors&&console.error(`[TJS TypeError] ${a.message}`),q.throwTypeErrors)throw a;return a}function rn(e){return e instanceof Error&&e.name==="MonadicError"&&"path"in e}var an={debug:!1,safety:"inputs",requireReturnTypes:!1,callStacks:!1,maxStackSize:64,trackErrors:!0,maxErrors:64},q={...an},Ye=64,_r=new Array(Ye).fill(""),Se=0,me=0,ht=64,wr=new Array(ht).fill(null),Me=0,$e=0,bt=0,Oe=0;function Gs(){Oe++}function Ks(){Oe>0&&Oe--}function Ys(){return Oe>0}function Hs(e){q={...q,...e}}function Qs(){return{...q}}function Sr(e){if((q.callStacks||q.debug)&&e){let n=q.maxStackSize??Ye;_r[Se]=e,Se=(Se+1)%n,me<n&&me++}}function dt(){if((q.callStacks||q.debug)&&me>0){let e=q.maxStackSize??Ye;Se=(Se-1+e)%e,me--}}function cn(){if(me===0)return[];let e=q.maxStackSize??Ye,n=[],t=(Se-me+e)%e;for(let r=0;r<me;r++)n.push(_r[(t+r)%e]);return n}function $r(){if(q.trackErrors===!1||$e===0)return[];let e=q.maxErrors??ht,n=[],t=(Me-$e+e)%e;for(let r=0;r<$e;r++)n.push(wr[(t+r)%e]);return n}function Xs(){let e=$r();return Me=0,$e=0,bt=0,e}function ei(){return bt}function ti(){q={...an},Se=0,me=0,Me=0,$e=0,bt=0,Oe=0}function Pe(e,n){if(e!==null&&typeof e=="object"&&typeof e[Ke]=="function")return e[Ke](n);if(n!==null&&typeof n=="object"&&typeof n[Ke]=="function")return n[Ke](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(n);if(n!==null&&typeof n=="object"&&typeof n.Equals=="function")return n.Equals(e);if((e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(n instanceof String||n instanceof Number||n instanceof Boolean)&&(n=n.valueOf()),e===n||typeof e=="number"&&typeof n=="number"&&isNaN(e)&&isNaN(n)||e==null&&n==null)return!0;if(e==null||n===null||n===void 0||typeof e!=typeof n||typeof e!="object")return!1;if(e instanceof Set&&n instanceof Set){if(e.size!==n.size)return!1;for(let s of e)if(!n.has(s))return!1;return!0}if(e instanceof Map&&n instanceof Map){if(e.size!==n.size)return!1;for(let[s,o]of e)if(!n.has(s)||!Pe(o,n.get(s)))return!1;return!0}if(e instanceof Date&&n instanceof Date)return e.getTime()===n.getTime();if(e instanceof RegExp&&n instanceof RegExp)return e.toString()===n.toString();if(Array.isArray(e)&&Array.isArray(n))return e.length!==n.length?!1:e.every((s,o)=>Pe(s,n[o]));if(Array.isArray(e)!==Array.isArray(n))return!1;let t=Object.keys(e),r=Object.keys(n);return t.length!==r.length?!1:t.every(s=>Pe(e[s],n[s]))}function Er(e,n){return!Pe(e,n)}function Tr(e){return e===null?"null":typeof e}function kr(e){return e instanceof Boolean||e instanceof Number||e instanceof String?!!e.valueOf():!!e}function ln(e,n){return(e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(n instanceof String||n instanceof Number||n instanceof Boolean)&&(n=n.valueOf()),!!(e===n||typeof e=="number"&&typeof n=="number"&&isNaN(e)&&isNaN(n)||e==null&&n==null)}function jr(e,n){return!ln(e,n)}function pe(e){return e!==null&&typeof e=="object"&&e.$error===!0}function ce(e,n){let t={$error:!0,message:e,...n};if((q.callStacks||q.debug)&&me>0){let r=cn(),s=n?.path?[...r,n.path]:r;t.stack=s}return t}function un(e,n){if(e.length===0)return ce("Unknown error");if(e.length===1)return e[0];let t=e.map(s=>{if(s.path){let o=s.path.split(".");return o[o.length-1]}return"unknown"}).join(", "),r=`Multiple parameter errors in ${n||"function"}: ${t}`;return ce(r,{path:n,errors:e})}function Ie(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";let n=typeof e;if(n!=="object")return n;let t=e.constructor?.name;return t&&t!=="Object"?t:"object"}function vr(e,n){if(e==null||typeof e!="object"&&typeof e!="function")return!1;let t=e;for(;t!==null;){if(t.constructor?.name===n)return!0;t=Object.getPrototypeOf(t)}return!1}function Ee(e,n,t){if(pe(e))return e;if(typeof n=="object"&&n!==null&&"check"in n){let s=n.check(e);if(s===!0)return null;let o=typeof s=="string"?s:void 0,i=o?`Expected ${n.description} for '${t}': ${o}`:`Expected ${n.description} but got ${Ie(e)}`;return ce(i,{path:t,expected:n.description,actual:Ie(e),reason:o})}let r=Ie(e);return n==="any"||n===r||n==="number"&&r==="number"||n==="integer"&&r==="number"&&Number.isInteger(e)||n==="non-negative-integer"&&r==="number"&&Number.isInteger(e)&&e>=0||n==="object"&&r==="object"?null:ce(`Expected ${n} but got ${r}`,{path:t,expected:n,actual:r})}function Ar(e,n,t,r){if(typeof e!="function")return e;let s=e.__tjs;if(!s||!s.params)return e;let o=Object.entries(s.params);for(let i=0;i<n.length;i++){let a=n[i];if(a==="any")continue;let c=o[i];if(!c)continue;let l=c[1]?.type?.kind;if(!(!l||l==="any")&&l!==a)return new ge(`Expected (...arg${i}: ${a}, ...) for '${r}', but callback declares arg${i} as ${l}`,`${r}(arg${i})`,a,l)}if(t!=="any"&&s.returns){let i=s.returns.type?.kind??s.returns.kind;if(i&&i!=="any"&&i!==t)return new ge(`Expected callback returning ${t} for '${r}', but callback returns ${i}`,`${r}(return)`,t,i)}return e}function fn(e,n,t){for(let[r,s]of Object.entries(n.params)){let o=e[r];if(pe(o))return o;if(s.required&&o===void 0){let a=typeof s.type=="string"?s.type:s.type.description;return ce(`Missing required parameter '${r}'`,{path:t?`${t}.${r}`:r,expected:a,actual:"undefined",loc:s.loc})}if(o===void 0)continue;let i=Ee(o,s.type,t?`${t}.${r}`:r);if(i)return s.loc&&(i.loc=s.loc),i}return null}function pn(e,n){if(e.__tjs=n,e.__tjs.schema=()=>Ft(n),!(!n.polymorphic&&(n.safe||n.safeReturn||q.safety!=="none"&&!n.unsafe||n.returns&&q.safety==="all"&&!n.unsafeReturn)))return e;let r=!!n.returns,s=!!n.unsafe,o=!!n.safe,i=!!n.unsafeReturn,a=!!n.safeReturn,c=n.returns?.defaults,l=Object.entries(n.params),p=l.length,f=e.name||n.name||"anonymous",u=function(...m){if(Oe>0)return e.apply(this,m);let y=o||!s&&q.safety!=="none",g=r&&(a||!i&&q.safety==="all");if(!y&&!g)return e.apply(this,m);if(m.length>0&&pe(m[0]))return m[0];if(y){let $=m.length===1&&typeof m[0]=="object"&&m[0]!==null&&!Array.isArray(m[0]),S=[];if($){let h=m[0];for(let b=0;b<p;b++){let[E,x]=l[b],w=h[E];if(pe(w)){S.push(w);continue}if(x.required&&w===void 0){S.push(ce(`Missing required parameter '${E}'`,{path:`${f}.${E}`,expected:typeof x.type=="string"?x.type:x.type?.description||"value",actual:"undefined",loc:x.loc}));continue}if(w!==void 0){let k=Ee(w,x.type,`${f}.${E}`);k&&(x.loc&&(k.loc=x.loc),S.push(k))}}}else for(let h=0;h<p;h++){let[b,E]=l[h],x=m[h];if(pe(x)){S.push(x);continue}if(E.required&&x===void 0){S.push(ce(`Missing required parameter '${b}'`,{path:`${f}.${b}`,expected:typeof E.type=="string"?E.type:E.type?.description||"value",actual:"undefined",loc:E.loc}));continue}if(x!==void 0){let w=Ee(x,E.type,`${f}.${b}`);w&&(E.loc&&(w.loc=E.loc),S.push(w))}}if(S.length>0)return un(S,f)}let _=q.callStacks||q.debug;_&&Sr(f);try{let $=e.apply(this,m);if(g&&n.returns&&!pe($)){let S=c&&typeof $=="object"&&$!==null?Object.assign({},c,$):$,h=Ee(S,n.returns.type,`${f}()`);if(h)return _&&dt(),h}return _&&dt(),$}catch($){return _&&dt(),ce($.message||String($),{path:f,cause:$})}};return Object.defineProperty(u,"name",{value:e.name}),u.__tjs=n,u.__tjs.schema=()=>Ft(n),u}function Rr(e){let n=new Proxy(e,{construct(t,r,s){return Reflect.construct(t,r,s)},apply(t,r,s){return Reflect.construct(t,s)}});Object.defineProperty(n,"name",{value:e.name});for(let t of Object.getOwnPropertyNames(e))t!=="length"&&t!=="name"&&t!=="prototype"&&Object.defineProperty(n,t,Object.getOwnPropertyDescriptor(e,t));return n}function Cr(){let e={...q},n=e.maxStackSize??Ye,t=new Array(n).fill(""),r=0,s=0,o=e.maxErrors??ht,i=new Array(o).fill(null),a=0,c=0,l=0,p=0;function f(j){e={...e,...j}}function u(){return{...e}}function m(j){(e.callStacks||e.debug)&&j&&(t[r]=j,r=(r+1)%n,s<n&&s++)}function y(){(e.callStacks||e.debug)&&s>0&&(r=(r-1+n)%n,s--)}function g(){if(s===0)return[];let j=[],M=(r-s+n)%n;for(let P=0;P<s;P++)j.push(t[(M+P)%n]);return j}function _(){e={...an},r=0,s=0,a=0,c=0,l=0,p=0}function $(){p++}function S(){p>0&&p--}function h(){return p>0}let b=new Map;function E(j,M,P){b.has(j)||b.set(j,new Map),b.get(j).set(M,P)}function x(j,M){let P=typeof j,L;if(j==null)return;if(P==="string")L="String";else if(P==="number")L="Number";else if(P==="boolean")L="Boolean";else if(Array.isArray(j))L="Array";else if(P==="object")L=j.constructor?.name||"Object";else return;let V=L;for(;V;){let Ae=b.get(V);if(Ae?.has(M))return Ae.get(M);if(P==="object"&&!Array.isArray(j)){if(V=Object.getPrototypeOf(V===L?j:Object.getPrototypeOf(j))?.constructor?.name,V==="Object"||V===L)break}else break}let Q=b.get("Object");if(Q?.has(M))return Q.get(M)}function w(j,M,P){let L=P===null?"null":typeof P,V=e.callStacks||e.debug?g():void 0,Q=new ge(`Expected ${M} for '${j}', got ${L}`,j,M,L,V);if(e.trackErrors!==!1&&(i[a]=Q,a=(a+1)%o,c<o&&c++,l++),e.logTypeErrors&&console.error(`[TJS TypeError] ${Q.message}`),e.throwTypeErrors)throw Q;return Q}function k(){if(e.trackErrors===!1||c===0)return[];let j=[],M=(a-c+o)%o;for(let P=0;P<c;P++)j.push(i[(M+P)%o]);return j}function A(){let j=k();return a=0,c=0,l=0,j}function R(){return l}function C(j,M){let P={$error:!0,message:j,...M};if((e.callStacks||e.debug)&&s>0){let L=M?.path?[...g(),M.path]:g();P.stack=L}return P}function N(j,M){return j==null?w(`bang.${M}`,"non-null",j):rn(j)?j:j[M]}return{version:fe,MonadicError:ge,typeError:w,isMonadicError:rn,bang:N,isError:pe,error:C,composeErrors:un,typeOf:Ie,isNativeType:vr,checkType:Ee,validateArgs:fn,wrap:pn,checkFnShape:Ar,wrapClass:Rr,compareVersions:sn,versionsCompatible:on,createRuntime:Cr,configure:f,getConfig:u,pushStack:m,popStack:y,getStack:g,errors:k,clearErrors:A,getErrorCount:R,resetRuntime:_,enterUnsafe:$,exitUnsafe:S,isUnsafeMode:h,validate:xr,infer:yt.infer.bind(yt),Type:Z,isRuntimeType:_e,Union:Qt,Generic:Ge,Enum:nn,FunctionPredicate:mt,Nullable:Yt,Optional:Ht,TArray:Xt,TString:Ut,TNumber:Lt,TBoolean:Wt,TInteger:Jt,TPositiveInt:Vt,TNonEmptyString:zt,TEmail:Zt,TUrl:Gt,TUuid:Kt,TPair:en,TRecord:tn,Is:Pe,IsNot:Er,Eq:ln,NotEq:jr,TypeOf:Tr,toBool:kr,tjsEquals:Ke,registerExtension:E,resolveExtension:x}}var we={version:fe,MonadicError:ge,typeError:Zs,isMonadicError:rn,isError:pe,error:ce,composeErrors:un,typeOf:Ie,isNativeType:vr,checkType:Ee,validateArgs:fn,wrap:pn,checkFnShape:Ar,wrapClass:Rr,compareVersions:sn,versionsCompatible:on,configure:Hs,getConfig:Qs,pushStack:Sr,popStack:dt,getStack:cn,errors:$r,clearErrors:Xs,getErrorCount:ei,resetRuntime:ti,enterUnsafe:Gs,exitUnsafe:Ks,isUnsafeMode:Ys,createRuntime:Cr,validate:xr,infer:yt.infer.bind(yt),Type:Z,isRuntimeType:_e,Union:Qt,Generic:Ge,Enum:nn,FunctionPredicate:mt,Nullable:Yt,Optional:Ht,TArray:Xt,TString:Ut,TNumber:Lt,TBoolean:Wt,TInteger:Jt,TPositiveInt:Vt,TNonEmptyString:zt,TEmail:Zt,TUrl:Gt,TUuid:Kt,Timestamp:gr,LegalDate:hr,TPair:en,TRecord:tn,Is:Pe,IsNot:Er,Eq:ln,NotEq:jr,TypeOf:Tr,toBool:kr};function mn(){let e=globalThis;if(e.__tjs){let n=e.__tjs.version;if(typeof n!="string")return e.__tjs=we,we;let t=sn(fe,n);return t===0||(on(fe,n)?t>0?(console.info(`TJS runtime: upgrading ${n} \u2192 ${fe}`),e.__tjs=we):console.info(`TJS runtime: keeping ${n} (newer than ${fe})`):(console.warn(`TJS runtime version conflict: ${n} vs ${fe} (major version mismatch)`),t>0&&(console.warn(`Upgrading to ${fe} - check for breaking changes`),e.__tjs=we))),e.__tjs}return e.__tjs=we,we}function ni(e){return`
|
|
176
|
+
`,Ws=pr+`
|
|
177
|
+
`+mr;import{validate as wr,s as yt}from"tosijs-schema";function Me(e){if(e.nullable)return{anyOf:[Me({...e,nullable:!1}),{type:"null"}]};switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"integer":return{type:"integer"};case"non-negative-integer":return{type:"integer",minimum:0};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"undefined":return{};case"any":return{};case"array":return e.items?{type:"array",items:Me(e.items)}:{type:"array"};case"object":if(e.shape){let n={},t=[];for(let[r,s]of Object.entries(e.shape))n[r]=Me(s),t.push(r);return{type:"object",properties:n,required:t,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{anyOf:e.members.map(Me)}:{};default:return{}}}function Ce(e){if(e===null)return{type:"null"};if(e===void 0)return{};switch(typeof e){case"string":return{type:"string"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":{if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:Ce(e[0])};let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=Ce(s),t.push(r);return{type:"object",properties:n,required:t,additionalProperties:!1}}default:return{}}}function Dt(e){let n={},t=[];for(let[o,i]of Object.entries(e.params))i?.type?.kind?n[o]=Me(i.type):i?.example!==void 0?n[o]=Ce(i.example):n[o]={},i?.required!==!1&&t.push(o),i?.example!==void 0&&(n[o].examples=[i.example]);let r={type:"object",properties:n,required:t},s;return e.returns&&(e.returns.type?.kind?s=Me(e.returns.type):e.returns.example!==void 0&&(s=Ce(e.returns.example))),{input:r,output:s}}import{validate as Ft,filter as Ls,s as pt}from"tosijs-schema";function xe(e){return e!==null&&typeof e=="object"&&"__runtimeType"in e&&e.__runtimeType===!0}function dr(e){return e!==null&&typeof e=="object"&&"schema"in e&&typeof e.schema=="object"}function Js(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function G(e,n,t,r){let s,o,i,a=t,c=r;if(typeof e=="string")if(s=e,typeof n=="function")o=n,a!==void 0&&(i=pt.infer(a));else if(n===void 0&&a!==void 0)i=pt.infer(a);else if(dr(n))i=n;else if(Js(n))i=n;else if(n!==void 0)a=n,c=a,i=pt.infer(a);else throw new Error("Type(description) requires a predicate, schema, or example");else dr(e),i=e,s=Vs(i);let l;if(i){let p=i?.schema??i;p&&typeof p=="object"&&Array.isArray(p.examples)&&(l=p.examples)}return a===void 0&&l&&l.length>0&&(a=l[0]),{description:s,check:p=>o?o(p):i?Ft(p,i):!1,schema:i,predicate:o,example:a,examples:l,default:c,toJSONSchema(){if(i){let p=i?.schema??i;if(p&&typeof p=="object"&&"type"in p)return p}return a!==void 0?Ce(a):{description:s}},strip(p){return i?Ls(p,i):p},__runtimeType:!0}}function Vs(e){let n=e?.schema??e;if(n&&typeof n=="object"&&"type"in n){let t=n;switch(t.type){case"string":return t.format?`string (${t.format})`:t.pattern?`string matching ${t.pattern}`:t.minLength!==void 0&&t.maxLength!==void 0?`string (${t.minLength}-${t.maxLength} chars)`:"string";case"number":case"integer":return t.minimum!==void 0&&t.maximum!==void 0?`${t.type} (${t.minimum}-${t.maximum})`:t.minimum!==void 0?`${t.type} >= ${t.minimum}`:t.maximum!==void 0?`${t.type} <= ${t.maximum}`:t.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var qt=G("string",e=>typeof e=="string"?!0:`expected string, got ${e===null?"null":typeof e}`),Ut=G("number",e=>typeof e=="number"?!0:`expected number, got ${e===null?"null":typeof e}`),Wt=G("boolean",e=>typeof e=="boolean"?!0:`expected boolean, got ${e===null?"null":typeof e}`),Lt=G("integer",e=>typeof e!="number"?`expected integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?!0:`${e} is not an integer`),Jt=G("positive integer",e=>typeof e!="number"?`expected positive integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?e<=0?`${e} is not positive`:!0:`${e} is not an integer`),Vt=G("non-empty string",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:e.length===0?"string is empty":!0),zt=G("email address",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?!0:`"${e}" is not a valid email`),yr=e=>{try{return new URL(e),!0}catch{return!1}},Zt=G("URL",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:yr(e)?!0:`"${e}" is not a valid URL`),Gt=G("UUID",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)?!0:`"${e}" is not a valid UUID`),gr=e=>{let n=new Date(e);return!isNaN(n.getTime())&&e.includes("T")},hr=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let n=new Date(e+"T00:00:00Z");return!isNaN(n.getTime())},br=G("ISO 8601 timestamp",e=>typeof e=="string"&&gr(e)),_r=G("date (YYYY-MM-DD)",e=>typeof e=="string"&&hr(e));function Kt(e){return G(`${e.description} or null`,n=>n===null||e.check(n)===!0)}function Yt(e){return G(`${e.description} (optional)`,n=>n==null||e.check(n)===!0)}function Ht(e,n,...t){if(typeof e=="string"&&Array.isArray(n)){let o=e,i=n,a=new Set(i);return{description:o,check:l=>a.has(l),toJSONSchema:()=>({enum:i}),strip:l=>l,__runtimeType:!0,values:i}}let r=[];xe(e)&&r.push(e),xe(n)&&r.push(n),r.push(...t);let s=r.map(o=>o.description).join(" | ");return G(s,o=>r.some(i=>i.check(o)===!0))}function Qt(e){return G(`array of ${e.description}`,n=>Array.isArray(n)&&n.every(t=>e.check(t)===!0))}function zs(e){if(xe(e))return t=>e.check(t)===!0;if(e&&typeof e=="object"&&"schema"in e)return t=>Ft(t,e);let n=pt.infer(e);return t=>Ft(t,n)}function Ge(e,n,t){let r=[],s=[];for(let i of e)typeof i=="string"?(r.push(i),s.push(void 0)):(r.push(i[0]),s.push(i[1]));let o=(...i)=>{let a=r.map((l,f)=>{let p=f<i.length?i[f]:s[f];return p===void 0?()=>!0:zs(p)}),c=t;return r.forEach((l,f)=>{let p=f<i.length?i[f]:s[f],u="any";xe(p)?u=p.description:p!==void 0&&(u=typeof p=="string"?"string":JSON.stringify(p)),c=c.replace(new RegExp(`\\b${l}\\b`,"g"),u)}),G(c,l=>n(l,...a))};return o.params=r,o.description=t,o}var Xt=Ge(["T","U"],(e,n,t)=>Array.isArray(e)&&e.length===2&&n(e[0])&&t(e[1]),"Pair<T, U>"),en=Ge(["V"],(e,n)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(n),"Record<string, V>");function tn(e,n){let t=Object.values(n),r=new Set(t),s=Object.keys(n),o={};for(let[a,c]of Object.entries(n))o[c]=a;return{description:e,check:a=>r.has(a),toJSONSchema:()=>({enum:t}),strip:a=>a,__runtimeType:!0,members:n,names:o,values:t,keys:s}}function Zs(e){if(e===null)return"null";if(e===void 0)return"undefined";switch(typeof e){case"string":return"string";case"boolean":return"boolean";case"number":return Number.isInteger(e)?"integer":"number";case"object":return Array.isArray(e)?"array":"object";default:return null}}function mt(e,n,t){if(Array.isArray(n)&&t){let r=n,s=[],o=[];for(let a of r)Array.isArray(a)?(s.push(a[0]),o.push(a[1])):(s.push(a),o.push(void 0));let i=((...a)=>{let c=s.map((f,p)=>p<a.length?a[p]:o[p]),l=t(...c);return mt(e,l)});return Object.defineProperties(i,{typeParamNames:{value:s,enumerable:!0},description:{value:e,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),i}return Gs(e,n)}function Gs(e,n){let t={},r,s="assertReturns";if(typeof n=="function"){let i=n.__tjs;if(i){if(i.params)for(let[a,c]of Object.entries(i.params))t[a]=c?.example??null;i.returns&&(r=i.returns?.example??null),i.safeReturn?s="checkedReturns":i.unsafe?s="assertReturns":s="returns"}}else t=n.params??{},r=n.returns,s=n.returnContract??"assertReturns";return{description:e,params:t,returns:r,returnContract:s,toJSONSchema:()=>({description:e,type:"function"}),strip:i=>i,check:i=>{if(typeof i!="function")return`expected function, got ${i===null?"null":typeof i}`;let a=Object.keys(t).length;if(a>0){let l=i.__tjs;if(l?.params){let f=Object.keys(l.params).length;if(f!==a)return`expected ${a} params, got ${f}`;let p=Object.keys(t),u=Object.keys(l.params);for(let m=0;m<p.length;m++){let y=l.params[u[m]],h=t[p[m]];if(y?.type?.kind&&h!==void 0){let w=Zs(h);if(w&&y.type.kind!==w&&y.type.kind!=="any")return`param '${p[m]}' expected ${w}, got ${y.type.kind}`}}}}return!0},__runtimeType:!0}}var Ys=xr(),pe=Ys.version,Ke=Symbol.for("tjs.equals");function gt(e){let[n=0,t=0,r=0]=e.split(".").map(Number);return{major:n,minor:t,patch:r}}function rn(e,n){let t=gt(e),r=gt(n);return t.major!==r.major?t.major<r.major?-1:1:t.minor!==r.minor?t.minor<r.minor?-1:1:t.patch!==r.patch?t.patch<r.patch?-1:1:0}function sn(e,n){let t=gt(e),r=gt(n);return t.major===r.major}var ge=class e extends Error{path;expected;actual;callStack;reason;constructor(n,t,r,s,o,i){super(n),this.name="MonadicError",this.path=t,this.expected=r,this.actual=s,this.callStack=o,this.reason=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function Hs(e,n,t,r){let s=t===null?"null":typeof t,o=q.callStacks||q.debug?an():void 0,i=r?`Expected ${n} for '${e}': ${r}`:`Expected ${n} for '${e}', got ${s}`,a=new ge(i,e,n,s,o,r);if(q.trackErrors!==!1){let c=q.maxErrors??ht;Sr[Ne]=a,Ne=(Ne+1)%c,Se<c&&Se++,bt++}if(q.logTypeErrors&&console.error(`[TJS TypeError] ${a.message}`),q.throwTypeErrors)throw a;return a}function nn(e){return e instanceof Error&&e.name==="MonadicError"&&"path"in e}var on={debug:!1,safety:"inputs",requireReturnTypes:!1,callStacks:!1,maxStackSize:64,trackErrors:!0,maxErrors:64},q={...on},Ye=64,$r=new Array(Ye).fill(""),$e=0,de=0,ht=64,Sr=new Array(ht).fill(null),Ne=0,Se=0,bt=0,Be=0;function Qs(){Be++}function Xs(){Be>0&&Be--}function ei(){return Be>0}function ti(e){q={...q,...e}}function ni(){return{...q}}function Er(e){if((q.callStacks||q.debug)&&e){let n=q.maxStackSize??Ye;$r[$e]=e,$e=($e+1)%n,de<n&&de++}}function dt(){if((q.callStacks||q.debug)&&de>0){let e=q.maxStackSize??Ye;$e=($e-1+e)%e,de--}}function an(){if(de===0)return[];let e=q.maxStackSize??Ye,n=[],t=($e-de+e)%e;for(let r=0;r<de;r++)n.push($r[(t+r)%e]);return n}function Tr(){if(q.trackErrors===!1||Se===0)return[];let e=q.maxErrors??ht,n=[],t=(Ne-Se+e)%e;for(let r=0;r<Se;r++)n.push(Sr[(t+r)%e]);return n}function ri(){let e=Tr();return Ne=0,Se=0,bt=0,e}function si(){return bt}function ii(){q={...on},$e=0,de=0,Ne=0,Se=0,bt=0,Be=0}function Pe(e,n){if(e!==null&&typeof e=="object"&&typeof e[Ke]=="function")return e[Ke](n);if(n!==null&&typeof n=="object"&&typeof n[Ke]=="function")return n[Ke](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(n);if(n!==null&&typeof n=="object"&&typeof n.Equals=="function")return n.Equals(e);if((e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(n instanceof String||n instanceof Number||n instanceof Boolean)&&(n=n.valueOf()),e===n||typeof e=="number"&&typeof n=="number"&&isNaN(e)&&isNaN(n)||e==null&&n==null)return!0;if(e==null||n===null||n===void 0||typeof e!=typeof n||typeof e!="object")return!1;if(e instanceof Set&&n instanceof Set){if(e.size!==n.size)return!1;for(let s of e)if(!n.has(s))return!1;return!0}if(e instanceof Map&&n instanceof Map){if(e.size!==n.size)return!1;for(let[s,o]of e)if(!n.has(s)||!Pe(o,n.get(s)))return!1;return!0}if(e instanceof Date&&n instanceof Date)return e.getTime()===n.getTime();if(e instanceof RegExp&&n instanceof RegExp)return e.toString()===n.toString();if(Array.isArray(e)&&Array.isArray(n))return e.length!==n.length?!1:e.every((s,o)=>Pe(s,n[o]));if(Array.isArray(e)!==Array.isArray(n))return!1;let t=Object.keys(e),r=Object.keys(n);return t.length!==r.length?!1:t.every(s=>Pe(e[s],n[s]))}function kr(e,n){return!Pe(e,n)}function jr(e){return e===null?"null":typeof e}function vr(e){return e instanceof Boolean||e instanceof Number||e instanceof String?!!e.valueOf():!!e}function cn(e,n){return(e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(n instanceof String||n instanceof Number||n instanceof Boolean)&&(n=n.valueOf()),!!(e===n||typeof e=="number"&&typeof n=="number"&&isNaN(e)&&isNaN(n)||e==null&&n==null)}function Ar(e,n){return!cn(e,n)}function me(e){return e!==null&&typeof e=="object"&&e.$error===!0}function ce(e,n){let t={$error:!0,message:e,...n};if((q.callStacks||q.debug)&&de>0){let r=an(),s=n?.path?[...r,n.path]:r;t.stack=s}return t}function ln(e,n){if(e.length===0)return ce("Unknown error");if(e.length===1)return e[0];let t=e.map(s=>{if(s.path){let o=s.path.split(".");return o[o.length-1]}return"unknown"}).join(", "),r=`Multiple parameter errors in ${n||"function"}: ${t}`;return ce(r,{path:n,errors:e})}function Ie(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";let n=typeof e;if(n!=="object")return n;let t=e.constructor?.name;return t&&t!=="Object"?t:"object"}function Rr(e,n){if(e==null||typeof e!="object"&&typeof e!="function")return!1;let t=e;for(;t!==null;){if(t.constructor?.name===n)return!0;t=Object.getPrototypeOf(t)}return!1}function Ee(e,n,t){if(me(e))return e;if(typeof n=="object"&&n!==null&&"check"in n){let s=n.check(e);if(s===!0)return null;let o=typeof s=="string"?s:void 0,i=o?`Expected ${n.description} for '${t}': ${o}`:`Expected ${n.description} but got ${Ie(e)}`;return ce(i,{path:t,expected:n.description,actual:Ie(e),reason:o})}let r=Ie(e);return n==="any"||n===r||n==="number"&&r==="number"||n==="integer"&&r==="number"&&Number.isInteger(e)||n==="non-negative-integer"&&r==="number"&&Number.isInteger(e)&&e>=0||n==="object"&&r==="object"?null:ce(`Expected ${n} but got ${r}`,{path:t,expected:n,actual:r})}function Mr(e,n,t,r){if(typeof e!="function")return e;let s=e.__tjs;if(!s||!s.params)return e;let o=Object.entries(s.params);for(let i=0;i<n.length;i++){let a=n[i];if(a==="any")continue;let c=o[i];if(!c)continue;let l=c[1]?.type?.kind;if(!(!l||l==="any")&&l!==a)return new ge(`Expected (...arg${i}: ${a}, ...) for '${r}', but callback declares arg${i} as ${l}`,`${r}(arg${i})`,a,l)}if(t!=="any"&&s.returns){let i=s.returns.type?.kind??s.returns.kind;if(i&&i!=="any"&&i!==t)return new ge(`Expected callback returning ${t} for '${r}', but callback returns ${i}`,`${r}(return)`,t,i)}return e}function un(e,n,t){for(let[r,s]of Object.entries(n.params)){let o=e[r];if(me(o))return o;if(s.required&&o===void 0){let a=typeof s.type=="string"?s.type:s.type.description;return ce(`Missing required parameter '${r}'`,{path:t?`${t}.${r}`:r,expected:a,actual:"undefined",loc:s.loc})}if(o===void 0)continue;let i=Ee(o,s.type,t?`${t}.${r}`:r);if(i)return s.loc&&(i.loc=s.loc),i}return null}function fn(e,n){if(e.__tjs=n,e.__tjs.schema=()=>Dt(n),!(!n.polymorphic&&(n.safe||n.safeReturn||q.safety!=="none"&&!n.unsafe||n.returns&&q.safety==="all"&&!n.unsafeReturn)))return e;let r=!!n.returns,s=!!n.unsafe,o=!!n.safe,i=!!n.unsafeReturn,a=!!n.safeReturn,c=n.returns?.defaults,l=Object.entries(n.params),f=l.length,p=e.name||n.name||"anonymous",u=function(...m){if(Be>0)return e.apply(this,m);let y=o||!s&&q.safety!=="none",h=r&&(a||!i&&q.safety==="all");if(!y&&!h)return e.apply(this,m);if(m.length>0&&me(m[0]))return m[0];if(y){let S=m.length===1&&typeof m[0]=="object"&&m[0]!==null&&!Array.isArray(m[0]),$=[];if(S){let b=m[0];for(let _=0;_<f;_++){let[x,g]=l[_],E=b[x];if(me(E)){$.push(E);continue}if(g.required&&E===void 0){$.push(ce(`Missing required parameter '${x}'`,{path:`${p}.${x}`,expected:typeof g.type=="string"?g.type:g.type?.description||"value",actual:"undefined",loc:g.loc}));continue}if(E!==void 0){let k=Ee(E,g.type,`${p}.${x}`);k&&(g.loc&&(k.loc=g.loc),$.push(k))}}}else for(let b=0;b<f;b++){let[_,x]=l[b],g=m[b];if(me(g)){$.push(g);continue}if(x.required&&g===void 0){$.push(ce(`Missing required parameter '${_}'`,{path:`${p}.${_}`,expected:typeof x.type=="string"?x.type:x.type?.description||"value",actual:"undefined",loc:x.loc}));continue}if(g!==void 0){let E=Ee(g,x.type,`${p}.${_}`);E&&(x.loc&&(E.loc=x.loc),$.push(E))}}if($.length>0)return ln($,p)}let w=q.callStacks||q.debug;w&&Er(p);try{let S=e.apply(this,m);if(h&&n.returns&&!me(S)){let $=c&&typeof S=="object"&&S!==null?Object.assign({},c,S):S,b=Ee($,n.returns.type,`${p}()`);if(b)return w&&dt(),b}return w&&dt(),S}catch(S){return w&&dt(),ce(S.message||String(S),{path:p,cause:S})}};return Object.defineProperty(u,"name",{value:e.name}),u.__tjs=n,u.__tjs.schema=()=>Dt(n),u}function Cr(e){let n=new Proxy(e,{construct(t,r,s){return Reflect.construct(t,r,s)},apply(t,r,s){return Reflect.construct(t,s)}});Object.defineProperty(n,"name",{value:e.name});for(let t of Object.getOwnPropertyNames(e))t!=="length"&&t!=="name"&&t!=="prototype"&&Object.defineProperty(n,t,Object.getOwnPropertyDescriptor(e,t));return n}function Nr(){let e={...q},n=e.maxStackSize??Ye,t=new Array(n).fill(""),r=0,s=0,o=e.maxErrors??ht,i=new Array(o).fill(null),a=0,c=0,l=0,f=0;function p(R){e={...e,...R}}function u(){return{...e}}function m(R){(e.callStacks||e.debug)&&R&&(t[r]=R,r=(r+1)%n,s<n&&s++)}function y(){(e.callStacks||e.debug)&&s>0&&(r=(r-1+n)%n,s--)}function h(){if(s===0)return[];let R=[],I=(r-s+n)%n;for(let O=0;O<s;O++)R.push(t[(I+O)%n]);return R}function w(){e={...on},r=0,s=0,a=0,c=0,l=0,f=0}function S(){f++}function $(){f>0&&f--}function b(){return f>0}let _=new Map;function x(R,I,O){_.has(R)||_.set(R,new Map),_.get(R).set(I,O)}function g(R,I){let O=typeof R,L;if(R==null)return;if(O==="string")L="String";else if(O==="number")L="Number";else if(O==="boolean")L="Boolean";else if(Array.isArray(R))L="Array";else if(O==="object")L=R.constructor?.name||"Object";else return;let V=L;for(;V;){let Ae=_.get(V);if(Ae?.has(I))return Ae.get(I);if(O==="object"&&!Array.isArray(R)){if(V=Object.getPrototypeOf(V===L?R:Object.getPrototypeOf(R))?.constructor?.name,V==="Object"||V===L)break}else break}let Q=_.get("Object");if(Q?.has(I))return Q.get(I)}function E(R,I,O){let L=O===null?"null":typeof O,V=e.callStacks||e.debug?h():void 0,Q=new ge(`Expected ${I} for '${R}', got ${L}`,R,I,L,V);if(e.trackErrors!==!1&&(i[a]=Q,a=(a+1)%o,c<o&&c++,l++),e.logTypeErrors&&console.error(`[TJS TypeError] ${Q.message}`),e.throwTypeErrors)throw Q;return Q}function k(){if(e.trackErrors===!1||c===0)return[];let R=[],I=(a-c+o)%o;for(let O=0;O<c;O++)R.push(i[(I+O)%o]);return R}function j(){let R=k();return a=0,c=0,l=0,R}function A(){return l}function M(R,I){let O={$error:!0,message:R,...I};if((e.callStacks||e.debug)&&s>0){let L=I?.path?[...h(),I.path]:h();O.stack=L}return O}function N(R,I){return R==null?E(`bang.${I}`,"non-null",R):nn(R)?R:R[I]}return{version:pe,MonadicError:ge,typeError:E,isMonadicError:nn,bang:N,isError:me,error:M,composeErrors:ln,typeOf:Ie,isNativeType:Rr,checkType:Ee,validateArgs:un,wrap:fn,checkFnShape:Mr,wrapClass:Cr,compareVersions:rn,versionsCompatible:sn,createRuntime:Nr,configure:p,getConfig:u,pushStack:m,popStack:y,getStack:h,errors:k,clearErrors:j,getErrorCount:A,resetRuntime:w,enterUnsafe:S,exitUnsafe:$,isUnsafeMode:b,validate:wr,infer:yt.infer.bind(yt),Type:G,isRuntimeType:xe,Union:Ht,Generic:Ge,Enum:tn,FunctionPredicate:mt,Nullable:Kt,Optional:Yt,TArray:Qt,TString:qt,TNumber:Ut,TBoolean:Wt,TInteger:Lt,TPositiveInt:Jt,TNonEmptyString:Vt,TEmail:zt,TUrl:Zt,TUuid:Gt,TPair:Xt,TRecord:en,Is:Pe,IsNot:kr,Eq:cn,NotEq:Ar,TypeOf:jr,toBool:vr,tjsEquals:Ke,registerExtension:x,resolveExtension:g}}var we={version:pe,MonadicError:ge,typeError:Hs,isMonadicError:nn,isError:me,error:ce,composeErrors:ln,typeOf:Ie,isNativeType:Rr,checkType:Ee,validateArgs:un,wrap:fn,checkFnShape:Mr,wrapClass:Cr,compareVersions:rn,versionsCompatible:sn,configure:ti,getConfig:ni,pushStack:Er,popStack:dt,getStack:an,errors:Tr,clearErrors:ri,getErrorCount:si,resetRuntime:ii,enterUnsafe:Qs,exitUnsafe:Xs,isUnsafeMode:ei,createRuntime:Nr,validate:wr,infer:yt.infer.bind(yt),Type:G,isRuntimeType:xe,Union:Ht,Generic:Ge,Enum:tn,FunctionPredicate:mt,Nullable:Kt,Optional:Yt,TArray:Qt,TString:qt,TNumber:Ut,TBoolean:Wt,TInteger:Lt,TPositiveInt:Jt,TNonEmptyString:Vt,TEmail:zt,TUrl:Zt,TUuid:Gt,Timestamp:br,LegalDate:_r,TPair:Xt,TRecord:en,Is:Pe,IsNot:kr,Eq:cn,NotEq:Ar,TypeOf:jr,toBool:vr};function pn(){let e=globalThis;if(e.__tjs){let n=e.__tjs.version;if(typeof n!="string")return e.__tjs=we,we;let t=rn(pe,n);return t===0||(sn(pe,n)?t>0?(console.info(`TJS runtime: upgrading ${n} \u2192 ${pe}`),e.__tjs=we):console.info(`TJS runtime: keeping ${n} (newer than ${pe})`):(console.warn(`TJS runtime version conflict: ${n} vs ${pe} (major version mismatch)`),t>0&&(console.warn(`Upgrading to ${pe} - check for breaking changes`),e.__tjs=we))),e.__tjs}return e.__tjs=we,we}function oi(e){return`
|
|
176
178
|
// TJS runtime wrapper (skips unsafe functions)
|
|
177
179
|
if (typeof ${e}.__tjs === 'object' && !${e}.__tjs.unsafe && typeof globalThis.__tjs?.wrap === 'function') {
|
|
178
180
|
${e} = globalThis.__tjs.wrap(${e}, ${e}.__tjs)
|
|
179
181
|
}
|
|
180
|
-
`.trim()}function
|
|
182
|
+
`.trim()}function ai(e,n,t=1e-9){if(e===n)return!0;if(typeof e=="number"&&typeof n=="number"&&(!Number.isInteger(e)||!Number.isInteger(n))){let r=Math.abs(e-n),s=Math.max(Math.abs(e),Math.abs(n),1);return r/s<t}return!1}function dn(e,n){if(e===n||typeof e=="number"&&typeof n=="number"&&Number.isNaN(e)&&Number.isNaN(n)||ai(e,n))return!0;if(e===null||n===null||e===void 0||n===void 0)return e===n;if(typeof e!=typeof n||typeof e!="object")return!1;if(Array.isArray(e)&&Array.isArray(n))return e.length!==n.length?!1:e.every((s,o)=>dn(s,n[o]));if(Array.isArray(e)!==Array.isArray(n))return!1;let t=Object.keys(e),r=Object.keys(n);return t.length!==r.length?!1:t.every(s=>dn(e[s],n[s]))}function yn(e,n,t=""){if(n===null)return e===null?{matches:!0}:{matches:!1,error:`Expected null at '${t}', got ${Te(e)}`};if(n===void 0)return e===void 0?{matches:!0}:{matches:!1,error:`Expected undefined at '${t}', got ${Te(e)}`};if(typeof n=="number")return typeof e=="number"?{matches:!0}:{matches:!1,error:`Expected number at '${t}', got ${Te(e)}`};if(typeof n=="string")return typeof e=="string"?{matches:!0}:{matches:!1,error:`Expected string at '${t}', got ${Te(e)}`};if(typeof n=="boolean")return typeof e=="boolean"?{matches:!0}:{matches:!1,error:`Expected boolean at '${t}', got ${Te(e)}`};if(Array.isArray(n)){if(!Array.isArray(e))return{matches:!1,error:`Expected array at '${t}', got ${Te(e)}`};if(n.length===0)return{matches:!0};let r=n[0];for(let s=0;s<e.length;s++){let o=yn(e[s],r,`${t}[${s}]`);if(!o.matches)return o}return{matches:!0}}if(typeof n=="object"&&n!==null){if(typeof e!="object"||e===null||Array.isArray(e))return{matches:!1,error:`Expected object at '${t}', got ${Te(e)}`};for(let r of Object.keys(n)){let s=t?`${t}.${r}`:r;if(!(r in e))return{matches:!1,error:`Missing property '${s}'`};let o=yn(e[r],n[r],s);if(!o.matches)return o}return{matches:!0}}return e===n?{matches:!0}:{matches:!1,error:`Type mismatch at '${t}'`}}function Te(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}function He(e,n=0){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.length===0?"[]":e.length<=3?`[${e.map(t=>He(t,n)).join(", ")}]`:`[${e.slice(0,3).map(t=>He(t,n)).join(", ")}, ...]`;if(typeof e=="object"){let t=Object.entries(e);if(t.length===0)return"{}";let r=c=>/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(c)?c:JSON.stringify(c);if(t.length<=2)return`{${t.map(([l,f])=>`${r(l)}: ${He(f,n)}`).join(", ")}}`;let s=" ".repeat(n+1),o=" ".repeat(n),i=t.slice(0,8).map(([c,l])=>`${s}${r(c)}: ${He(l,n+1)}`).join(`,
|
|
181
183
|
`),a=t.length>8?`,
|
|
182
184
|
${s}...`:"";return`{
|
|
183
185
|
${i}${a}
|
|
184
|
-
${o}}`}return String(e)}function
|
|
186
|
+
${o}}`}return String(e)}function ci(e){let n=e.replace(/\/\*[\s\S]*?\*\//g,t=>{let r=t.split(`
|
|
185
187
|
`).length-1;return`
|
|
186
|
-
`.repeat(r)});return n=n.replace(/\/\/[^\n]*/g,""),n}function
|
|
187
|
-
`)}function
|
|
188
|
-
`).length;if(
|
|
189
|
-
`).length,
|
|
190
|
-
`),u="const { Is, IsNot, Eq, NotEq, TypeOf } = globalThis.__tjs ?? {};",m=e.map((
|
|
191
|
-
// Test ${
|
|
188
|
+
`.repeat(r)});return n=n.replace(/\/\/[^\n]*/g,""),n}function Ir(e){let n=e.replace(/^import\s+.*?from\s+['"][^'"]+['"];?\s*$/gm,"");return n=n.replace(/^import\s+['"][^'"]+['"];?\s*$/gm,""),n=n.replace(/^export\s+default\s+/gm,""),n=n.replace(/^export\s+/gm,""),n=n.replace(/^(\s*)((?:const|let|var)\s+\w+\s*=\s*)?await\s+.+$/gm,"$1/* top-level await removed for test execution */"),n}function li(e){if(Object.keys(e).length===0)return"";let n=[];for(let[t,r]of Object.entries(e)){let s=Ir(r);n.push(`// Resolved import: ${t}`),n.push(s)}return n.join(`
|
|
189
|
+
`)}function Pr(e){let n={},t=e.trim();if(!t.startsWith("{")||!t.includes("="))try{return{pattern:new Function(`return ${e}`)(),defaults:n}}catch{return null}let r="",s=0,o=0;for(;o<t.length;){let i=t[o];if(i==="{"||i==="["||i==="(")s++,r+=i,o++;else if(i==="}"||i==="]"||i===")")s--,r+=i,o++;else if(i==="'"||i==='"'||i==="`"){let a=i;for(r+=i,o++;o<t.length&&t[o]!==a;)t[o]==="\\"&&(r+=t[o++]),r+=t[o++];o<t.length&&(r+=t[o++])}else if(s===1&&i==="="){let l=(r.slice(r.lastIndexOf("{")+1).split(",").pop()||"").match(/\s*(\w+)\s*$/);if(l){let f=o+1;for(;f<t.length&&/\s/.test(t[f]);)f++;let p="",u=0;for(;f<t.length;){let m=t[f];if(m==="{"||m==="["||m==="(")u++;else if(m==="}"||m==="]"||m===")"){if(u===0)break;u--}else if(m===","&&u===0)break;p+=m,f++}try{n[l[1]]=new Function(`return ${p.trim()}`)()}catch{}r+=":",o++;continue}r+=i,o++}else r+=i,o++}try{return{pattern:new Function(`return ${r}`)(),defaults:n}}catch{return null}}function Br(e){let n=[],t=ci(e),r=/(async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*(:[?!]?)\s*/g,s;for(;(s=r.exec(t))!==null;){let a=!!s[1],c=s[2],l=s[3],f=s[4],p=t.slice(0,s.index).split(`
|
|
190
|
+
`).length;if(f===":!")continue;let u=t.slice(s.index+s[0].length),m=_t(u);if(!m)continue;let y=mn(l);if(!(l.trim()&&y.length===0))try{let h=Pr(m);if(!h)continue;let w=y.map(S=>new Function(`return ${S}`)());n.push({funcName:c,args:w,expected:h.pattern,defaults:Object.keys(h.defaults).length>0?h.defaults:void 0,line:p,isAsync:a})}catch{}}let o=/class\s+(\w+)(?:\s+extends\s+\w+)?\s*\{/g,i;for(;(i=o.exec(t))!==null;){let a=i[1],c=i.index+i[0].length,l=1,f=c;for(let b=c;b<t.length;b++)if(t[b]==="{")l++;else if(t[b]==="}"&&(l--,l===0)){f=b;break}let p=t.slice(c,f),m=/constructor\s*\(([^)]*)\)/.exec(p);if(!m)continue;let y=m[1],h=mn(y);if(y.trim()&&h.length===0)continue;let w;try{w=h.map(b=>new Function(`return ${b}`)())}catch{continue}let S=/(async\s+)?(\w+)\s*\(([^)]*)\)\s*(:[?!]?)\s*/g,$;for(;($=S.exec(p))!==null;){let b=$[2];if(b==="constructor")continue;let _=!!$[1],x=$[3];if($[4]===":!")continue;let E=c+$.index,k=t.slice(0,E).split(`
|
|
191
|
+
`).length,j=p.slice($.index+$[0].length),A=_t(j);if(!A)continue;let M=mn(x);if(!(x.trim()&&M.length===0))try{let N=Pr(A);if(!N)continue;let R=M.map(I=>new Function(`return ${I}`)());n.push({funcName:b,args:R,expected:N.pattern,defaults:Object.keys(N.defaults).length>0?N.defaults:void 0,line:k,isAsync:_,className:a,constructorArgs:w})}catch{}}}return n}function Or(e,n,t,r,s={},o=new Map){let i=[];if(e.length===0&&t.length===0)return i;let a=r.match(/^import\s+.*?from\s+['"]([^'"]+)['"];?\s*$/gm)||[],c=a.length>0&&a.some(_=>{let x=_.match(/from\s+['"]([^'"]+)['"]/);return x&&!(x[1]in s)}),l=Ir(r),f=li(s),p=n.map(_=>_.body).join(`
|
|
192
|
+
`),u="const { Is, IsNot, Eq, NotEq, TypeOf } = globalThis.__tjs ?? {};",m=e.map((_,x)=>{let g=o.size>0?Le(_.body,o):_.body;return`
|
|
193
|
+
// Test ${x}: ${_.description}
|
|
192
194
|
try {
|
|
193
195
|
${u}
|
|
194
|
-
${
|
|
195
|
-
__testResults.push({ idx: ${
|
|
196
|
+
${g}
|
|
197
|
+
__testResults.push({ idx: ${x}, passed: true });
|
|
196
198
|
} catch (e) {
|
|
197
|
-
__testResults.push({ idx: ${
|
|
199
|
+
__testResults.push({ idx: ${x}, passed: false, error: e.message || String(e) });
|
|
198
200
|
}
|
|
199
201
|
`}).join(`
|
|
200
|
-
`),y=t.filter(
|
|
201
|
-
// Signature test ${
|
|
202
|
+
`),y=t.filter(_=>!_.isAsync),h=t.filter(_=>_.isAsync),w=y.map((_,x)=>{let g=_.className?`${_.className}.${_.funcName}`:_.funcName,E=_.className?`new ${_.className}(${(_.constructorArgs||[]).map(k=>JSON.stringify(k)).join(", ")}).${_.funcName}(${_.args.map(k=>JSON.stringify(k)).join(", ")})`:`${_.funcName}(${_.args.map(k=>JSON.stringify(k)).join(", ")})`;return`
|
|
203
|
+
// Signature test ${x}: ${g}
|
|
202
204
|
try {
|
|
203
|
-
let __actual = ${
|
|
204
|
-
const __expected = ${JSON.stringify(
|
|
205
|
-
const __defaults = ${JSON.stringify(
|
|
205
|
+
let __actual = ${E};
|
|
206
|
+
const __expected = ${JSON.stringify(_.expected)};${_.defaults?`
|
|
207
|
+
const __defaults = ${JSON.stringify(_.defaults)};
|
|
206
208
|
if (typeof __actual === 'object' && __actual !== null) __actual = Object.assign({}, __defaults, __actual);`:""}
|
|
207
209
|
if (__deepEqual(__actual, __expected)) {
|
|
208
|
-
__sigTestResults.push({ idx: ${
|
|
210
|
+
__sigTestResults.push({ idx: ${x}, passed: true });
|
|
209
211
|
} else {
|
|
210
|
-
__sigTestResults.push({ idx: ${
|
|
212
|
+
__sigTestResults.push({ idx: ${x}, passed: false, error: 'Expected ' + __format(__expected) + ' at \\'${g}\\', got ' + __format(__actual) });
|
|
211
213
|
}
|
|
212
214
|
} catch (e) {
|
|
213
|
-
__sigTestResults.push({ idx: ${
|
|
215
|
+
__sigTestResults.push({ idx: ${x}, passed: false, error: e.message || String(e) });
|
|
214
216
|
}
|
|
215
217
|
`}).join(`
|
|
216
|
-
`);
|
|
218
|
+
`);pn();let b=`
|
|
217
219
|
|
|
218
220
|
const __saved_tjs = globalThis.__tjs;
|
|
219
221
|
|
|
@@ -281,75 +283,73 @@ ${o}}`}return String(e)}function si(e){let n=e.replace(/\/\*[\s\S]*?\*\//g,t=>{l
|
|
|
281
283
|
}
|
|
282
284
|
|
|
283
285
|
// Inject resolved imports first (they may be dependencies)
|
|
284
|
-
${
|
|
286
|
+
${f}
|
|
285
287
|
|
|
286
288
|
// Execute the module code ONCE
|
|
287
289
|
${l}
|
|
288
|
-
${
|
|
290
|
+
${p}
|
|
289
291
|
|
|
290
292
|
// Run explicit test blocks
|
|
291
293
|
${m}
|
|
292
294
|
|
|
293
295
|
// Run signature tests
|
|
294
|
-
${
|
|
296
|
+
${w}
|
|
295
297
|
|
|
296
298
|
} finally {
|
|
297
299
|
globalThis.__tjs = __saved_tjs;
|
|
298
300
|
}
|
|
299
301
|
return { testResults: __testResults, sigTestResults: __sigTestResults };
|
|
300
|
-
`;try{let
|
|
301
|
-
`)}var wt={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:d.i32_load8_s,storeOp:d.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:d.i32_load8_u,storeOp:d.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:d.i32_load8_u,storeOp:d.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:d.i32_load16_s,storeOp:d.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:d.i32_load16_u,storeOp:d.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:d.i32_load,storeOp:d.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:d.i32_load,storeOp:d.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:d.f32_load,storeOp:d.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:d.f64_load,storeOp:d.f64_store}};function fi(e){let n={params:e,locals:new Map,nextLocalIndex:e.length,localTypes:[],warnings:[],errors:[],loopDepth:0,needsMathImports:new Set,needsMemory:!1,hasReturn:!1,wat:[],watIndent:1};return e.forEach((t,r)=>{n.locals.set(t.name,{index:r,type:t.type})}),n}function _t(e,n,t){if(e.locals.has(n))return e.errors.push(`Duplicate local declaration: ${n}`),e.locals.get(n).index;let r=e.nextLocalIndex++;return e.locals.set(n,{index:r,type:t}),e.localTypes.push(t),r}function ke(e,n){return e.locals.get(n)}function Be(e,n){switch(e.type){case"ExpressionStatement":{let t=e.expression;return[...D(t,n),d.drop]}case"ReturnStatement":{let t=e;if(n.hasReturn=!0,!t.argument)return[d.return];let r=D(t.argument,n),s=J(t.argument,n);return s==="i32"?r.push(d.f64_convert_i32_s):s==="f32"&&r.push(d.f64_promote_f32),r.push(d.return),r}case"VariableDeclaration":{let t=e,r=[];for(let s of t.declarations){if(s.id.type!=="Identifier"){n.errors.push("Destructuring not supported in WASM blocks");continue}let o=s.id.name,i="f64";s.init&&(i=J(s.init,n));let a=_t(n,o,i);s.init&&(r.push(...D(s.init,n)),r.push(d.local_set,...O(a)))}return r}case"ForStatement":return pi(e,n);case"IfStatement":return mi(e,n);case"BlockStatement":{let t=e,r=[];for(let s of t.body)r.push(...Be(s,n));return r}default:return n.errors.push(`Unsupported statement type: ${e.type}`),[]}}function pi(e,n){let t=[];return e.init&&(e.init.type==="VariableDeclaration"?t.push(...Be(e.init,n)):t.push(...D(e.init,n))),t.push(d.block,ie.void),t.push(d.loop,ie.void),e.test&&(t.push(...D(e.test,n)),t.push(d.i32_eqz),t.push(d.br_if,1)),n.loopDepth++,e.body&&t.push(...Be(e.body,n)),n.loopDepth--,e.update&&(t.push(...D(e.update,n)),t.push(d.drop)),t.push(d.br,0),t.push(d.end),t.push(d.end),t}function mi(e,n){let t=[];return t.push(...D(e.test,n)),t.push(d.if,ie.void),t.push(...Be(e.consequent,n)),e.alternate&&(t.push(d.else),t.push(...Be(e.alternate,n))),t.push(d.end),t}function J(e,n){switch(e.type){case"Literal":{let t=e;return typeof t.value=="number"?t.raw&&(t.raw.includes(".")||t.raw.includes("e"))?"f64":Number.isInteger(t.value)&&t.value>=-2147483648&&t.value<=2147483647?"i32":"f64":"f64"}case"Identifier":return ke(n,e.name)?.type??"f64";case"BinaryExpression":case"AssignmentExpression":{let t=e;if(["<",">","<=",">=","==","!=","===","!=="].includes(t.operator)||["|","&","^","<<",">>",">>>"].includes(t.operator))return"i32";let r=J(t.left,n),s=J(t.right,n);return r==="v128"||s==="v128"?"v128":r==="f64"||s==="f64"?"f64":r==="f32"||s==="f32"?"f32":"i32"}case"UnaryExpression":{let t=e;return t.operator==="!"?"i32":J(t.argument,n)}case"MemberExpression":{let t=e;if(t.object.type==="Identifier"&&ke(n,t.object.name)){let s=n.params.find(o=>o.name===t.object.name);if(s?.arrayType){let o=wt[s.arrayType];if(o)return o.elementType}}return"f64"}case"CallExpression":{let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee;if(r.object.type==="Identifier"&&r.object.name==="Math")return"f64"}if(t.callee.type==="Identifier"){let r=t.callee.name;if(r==="f32x4_extract_lane")return"f32";if(r.startsWith("f32x4_")||r==="v128_load")return"v128"}return"f64"}default:return"f64"}}function D(e,n){switch(e.type){case"Literal":{let t=e;if(typeof t.value=="number"){let r=J(e,n);return r==="i32"?[d.i32_const,...tt(t.value|0)]:r==="f32"?[d.f32_const,...xn(t.value)]:[d.f64_const,...re(t.value)]}return n.errors.push(`Unsupported literal type: ${typeof t.value}`),[d.f64_const,...re(0)]}case"Identifier":{let t=e.name,r=ke(n,t);return r?[d.local_get,...O(r.index)]:(n.errors.push(`Unknown identifier: ${t}`),[d.f64_const,...re(0)])}case"BinaryExpression":return di(e,n);case"UnaryExpression":return yi(e,n);case"AssignmentExpression":return gi(e,n);case"UpdateExpression":return hi(e,n);case"MemberExpression":return bi(e,n);case"CallExpression":return _i(e,n);case"SequenceExpression":{let t=e,r=[];for(let s=0;s<t.expressions.length;s++)r.push(...D(t.expressions[s],n)),s<t.expressions.length-1&&r.push(d.drop);return r}default:return n.errors.push(`Unsupported expression type: ${e.type}`),[d.f64_const,...re(0)]}}function di(e,n){let t=D(e.left,n),r=D(e.right,n),s=J(e,n),o=J(e.left,n),i=J(e.right,n),a=["<",">","<=",">=","==","===","!=","!=="].includes(e.operator),c;o==="f64"||i==="f64"?c="f64":o==="f32"||i==="f32"?c="f32":c="i32",!a&&s==="f64"&&(c="f64");let l=t,p=r;c==="f64"?(o==="i32"?l=[...t,d.f64_convert_i32_s]:o==="f32"&&(l=[...t,d.f64_promote_f32]),i==="i32"?p=[...r,d.f64_convert_i32_s]:i==="f32"&&(p=[...r,d.f64_promote_f32])):c==="f32"&&(o==="i32"&&(l=[...t,d.f32_convert_i32_s]),i==="i32"&&(p=[...r,d.f32_convert_i32_s]));let u={"+":{i32:d.i32_add,f32:d.f32_add,f64:d.f64_add},"-":{i32:d.i32_sub,f32:d.f32_sub,f64:d.f64_sub},"*":{i32:d.i32_mul,f32:d.f32_mul,f64:d.f64_mul},"/":{i32:d.i32_div_s,f32:d.f32_div,f64:d.f64_div},"%":{i32:d.i32_rem_s},"<":{i32:d.i32_lt_s,f32:d.f32_lt,f64:d.f64_lt},">":{i32:d.i32_gt_s,f32:d.f32_gt,f64:d.f64_gt},"<=":{i32:d.i32_le_s,f32:d.f32_le,f64:d.f64_le},">=":{i32:d.i32_ge_s,f32:d.f32_ge,f64:d.f64_ge},"==":{i32:d.i32_eq,f32:d.f32_eq,f64:d.f64_eq},"===":{i32:d.i32_eq,f32:d.f32_eq,f64:d.f64_eq},"!=":{i32:d.i32_ne,f32:d.f32_ne,f64:d.f64_ne},"!==":{i32:d.i32_ne,f32:d.f32_ne,f64:d.f64_ne},"|":{i32:d.i32_or},"&":{i32:d.i32_and},"^":{i32:d.i32_xor},"<<":{i32:d.i32_shl},">>":{i32:d.i32_shr_s},">>>":{i32:d.i32_shr_u}}[e.operator];if(!u)return n.errors.push(`Unsupported operator: ${e.operator}`),[d.f64_const,...re(0)];let m=u[c]??u.f64??u.i32;return m===void 0?(n.errors.push(`Operator ${e.operator} not supported for type ${c}`),[d.f64_const,...re(0)]):[...l,...p,m]}function yi(e,n){let t=D(e.argument,n),r=J(e.argument,n);switch(e.operator){case"-":return r==="i32"?[d.i32_const,0,...t,d.i32_sub]:r==="f32"?[...t,d.f32_neg]:[...t,d.f64_neg];case"!":return[...t,d.i32_eqz];case"~":return[...t,d.i32_const,...tt(-1),d.i32_xor];default:return n.errors.push(`Unsupported unary operator: ${e.operator}`),t}}function gi(e,n){if(e.left.type==="MemberExpression")return xi(e.left,e.right,e.operator,n);if(e.left.type!=="Identifier")return n.errors.push("Assignment target must be identifier or array element"),[];let t=e.left.name,r=ke(n,t);if(!r)return n.errors.push(`Unknown variable: ${t}`),[];let s=[];if(e.operator==="="){s.push(...D(e.right,n));let o=J(e.right,n);r.type==="f64"&&o==="i32"?s.push(d.f64_convert_i32_s):r.type==="f64"&&o==="f32"?s.push(d.f64_promote_f32):r.type==="i32"&&o==="f64"?s.push(d.i32_trunc_f64_s):r.type==="i32"&&o==="f32"?s.push(d.i32_trunc_f32_s):r.type==="f32"&&o==="i32"?s.push(d.f32_convert_i32_s):r.type==="f32"&&o==="f64"&&s.push(d.f32_demote_f64)}else{let o=J(e.right,n),i=r.type;o==="f64"||r.type==="f64"?i="f64":(o==="f32"||r.type==="f32")&&(i="f32"),s.push(d.local_get,...O(r.index)),i==="f64"&&r.type==="i32"?s.push(d.f64_convert_i32_s):i==="f64"&&r.type==="f32"?s.push(d.f64_promote_f32):i==="f32"&&r.type==="i32"&&s.push(d.f32_convert_i32_s),s.push(...D(e.right,n)),i==="f64"&&o==="i32"?s.push(d.f64_convert_i32_s):i==="f64"&&o==="f32"?s.push(d.f64_promote_f32):i==="f32"&&o==="i32"&&s.push(d.f32_convert_i32_s);let a=e.operator.slice(0,-1),l={"+":{i32:d.i32_add,f32:d.f32_add,f64:d.f64_add},"-":{i32:d.i32_sub,f32:d.f32_sub,f64:d.f64_sub},"*":{i32:d.i32_mul,f32:d.f32_mul,f64:d.f64_mul},"/":{i32:d.i32_div_s,f32:d.f32_div,f64:d.f64_div}}[a]?.[i];if(!l)return n.errors.push(`Unsupported compound assignment: ${e.operator}`),[];s.push(l),r.type==="i32"&&i==="f64"?s.push(d.i32_trunc_f64_s):r.type==="i32"&&i==="f32"?s.push(d.i32_trunc_f32_s):r.type==="f32"&&i==="f64"&&s.push(d.f32_demote_f64)}return s.push(d.local_tee,...O(r.index)),s}function hi(e,n){if(e.argument.type!=="Identifier")return n.errors.push("Update expression argument must be identifier"),[];let t=e.argument.name,r=ke(n,t);if(!r)return n.errors.push(`Unknown variable: ${t}`),[];let s=[],o=r.type==="i32";return e.prefix?(s.push(d.local_get,...O(r.index)),o?(s.push(d.i32_const,1),s.push(e.operator==="++"?d.i32_add:d.i32_sub)):(s.push(d.f64_const,...re(1)),s.push(e.operator==="++"?d.f64_add:d.f64_sub)),s.push(d.local_tee,...O(r.index))):(s.push(d.local_get,...O(r.index)),s.push(d.local_get,...O(r.index)),o?(s.push(d.i32_const,1),s.push(e.operator==="++"?d.i32_add:d.i32_sub)):(s.push(d.f64_const,...re(1)),s.push(e.operator==="++"?d.f64_add:d.f64_sub)),s.push(d.local_set,...O(r.index))),s}function bi(e,n){if(e.object.type!=="Identifier")return n.errors.push("Array access requires identifier"),[];let t=e.object.name,r=n.params.find(l=>l.name===t);if(!r?.isArray||!r.arrayType)return n.errors.push(`${t} is not a typed array parameter`),[];let s=wt[r.arrayType];if(!s)return n.errors.push(`Unknown array type: ${r.arrayType}`),[];n.needsMemory=!0;let o=[],i=ke(n,t);if(!i)return n.errors.push(`Unknown array: ${t}`),[];if(o.push(d.local_get,...O(i.index)),!e.computed||!e.property)return n.errors.push("Array access requires computed index"),[];let a=D(e.property,n),c=J(e.property,n);return o.push(...a),c==="f64"&&o.push(d.i32_trunc_f64_s),s.bytesPerElement>1&&(o.push(d.i32_const,...tt(s.bytesPerElement)),o.push(d.i32_mul)),o.push(d.i32_add),o.push(s.loadOp,0,0),o}function xi(e,n,t,r){if(e.object.type!=="Identifier")return r.errors.push("Array store requires identifier"),[];let s=e.object.name,o=r.params.find(y=>y.name===s);if(!o?.isArray||!o.arrayType)return r.errors.push(`${s} is not a typed array parameter`),[];let i=wt[o.arrayType];if(!i)return r.errors.push(`Unknown array type: ${o.arrayType}`),[];r.needsMemory=!0;let a=[],c=ke(r,s);if(!c)return[];if(!e.computed||!e.property)return r.errors.push("Array store requires computed index"),[];let l=D(e.property,r),p=J(e.property,r),f=()=>{let y=[];return y.push(d.local_get,...O(c.index)),y.push(...l),p==="f64"&&y.push(d.i32_trunc_f64_s),i.bytesPerElement>1&&(y.push(d.i32_const,...tt(i.bytesPerElement)),y.push(d.i32_mul)),y.push(d.i32_add),y};if(t==="=")a.push(...D(n,r));else{let y=_t(r,`__addr_${r.nextLocalIndex}`,"i32");a.push(...f()),a.push(d.local_tee,...O(y)),a.push(i.loadOp,0,0),a.push(...D(n,r));let g=J(n,r);i.elementType==="f32"&&g==="f64"?a.push(d.f32_demote_f64):i.elementType==="f64"&&g==="f32"?a.push(d.f64_promote_f32):i.elementType==="f32"&&g==="i32"?a.push(d.f32_convert_i32_s):i.elementType==="f64"&&g==="i32"?a.push(d.f64_convert_i32_s):i.elementType==="i32"&&g==="f64"?a.push(d.i32_trunc_f64_s):i.elementType==="i32"&&g==="f32"&&a.push(d.i32_trunc_f32_s);let _=t.slice(0,-1),$={"+":i.elementType==="i32"?d.i32_add:i.elementType==="f32"?d.f32_add:d.f64_add,"-":i.elementType==="i32"?d.i32_sub:i.elementType==="f32"?d.f32_sub:d.f64_sub,"*":i.elementType==="i32"?d.i32_mul:i.elementType==="f32"?d.f32_mul:d.f64_mul};a.push($[_]??d.f64_add);let S=_t(r,`__val_${r.nextLocalIndex}`,i.elementType);return a.push(d.local_set,...O(S)),a.push(d.local_get,...O(y)),a.push(d.local_get,...O(S)),a.push(i.storeOp,0,0),a.push(d.local_get,...O(S)),a}let u=J(n,r);i.elementType==="f32"&&u==="f64"?a.push(d.f32_demote_f64):i.elementType==="f64"&&u==="f32"?a.push(d.f64_promote_f32):i.elementType==="i32"&&u==="f64"&&a.push(d.i32_trunc_f64_s);let m=_t(r,`__tmp_${r.nextLocalIndex}`,i.elementType);return a.push(d.local_set,...O(m)),a.push(d.local_get,...O(c.index)),a.push(...l),p==="f64"&&a.push(d.i32_trunc_f64_s),i.bytesPerElement>1&&(a.push(d.i32_const,...tt(i.bytesPerElement)),a.push(d.i32_mul)),a.push(d.i32_add),a.push(d.local_get,...O(m)),a.push(i.storeOp,0,0),a.push(d.local_get,...O(m)),a}function _i(e,n){if(e.callee.type==="MemberExpression"){let t=e.callee;if(t.object.type==="Identifier"&&t.object.name==="Math"&&t.property.type==="Identifier"){let r=t.property.name;return Si(r,e.arguments,n)}}if(e.callee.type==="Identifier"){let t=e.callee.name;if(t.startsWith("f32x4_")||t.startsWith("v128_"))return wi(t,e.arguments,n)}return n.errors.push(`Unsupported function call: ${e.callee.type}`),[d.f64_const,...re(0)]}function wi(e,n,t){t.needsMemory=!0;let r=[];switch(e){case"v128_load":case"f32x4_load":{r.push(...D(n[0],t)),J(n[0],t)==="f64"&&r.push(d.i32_trunc_f64_s),r.push(...D(n[1],t));let o=J(n[1],t);return o==="f64"?r.push(d.i32_trunc_f64_s):o==="f32"&&r.push(d.i32_trunc_f32_s),r.push(d.i32_add),r.push(...Or(K.v128_load,2,0)),r}case"v128_store":case"f32x4_store":{r.push(...D(n[0],t)),J(n[0],t)==="f64"&&r.push(d.i32_trunc_f64_s),r.push(...D(n[1],t));let o=J(n[1],t);return o==="f64"?r.push(d.i32_trunc_f64_s):o==="f32"&&r.push(d.i32_trunc_f32_s),r.push(d.i32_add),r.push(...D(n[2],t)),r.push(...Or(K.v128_store,2,0)),r.push(d.i32_const,0),r}case"f32x4_splat":{r.push(...D(n[0],t));let s=J(n[0],t);return s==="i32"?r.push(d.f32_convert_i32_s):s==="f64"&&r.push(d.f32_demote_f64),r.push(...hn(K.f32x4_splat)),r}case"f32x4_extract_lane":{r.push(...D(n[0],t));let s=n[1].value;return!Number.isInteger(s)||s<0||s>3?(t.errors.push(`f32x4_extract_lane: lane must be 0-3, got ${s}`),[d.f32_const,...xn(0)]):(r.push(et,...O(K.f32x4_extract_lane),s),r)}case"f32x4_replace_lane":{r.push(...D(n[0],t));let s=n[1].value;if(!Number.isInteger(s)||s<0||s>3)return t.errors.push(`f32x4_replace_lane: lane must be 0-3, got ${s}`),[d.f32_const,...xn(0)];r.push(...D(n[2],t));let o=J(n[2],t);return o==="i32"?r.push(d.f32_convert_i32_s):o==="f64"&&r.push(d.f32_demote_f64),r.push(et,...O(K.f32x4_replace_lane),s),r}case"f32x4_add":case"f32x4_sub":case"f32x4_mul":case"f32x4_div":{r.push(...D(n[0],t)),r.push(...D(n[1],t));let s={f32x4_add:K.f32x4_add,f32x4_sub:K.f32x4_sub,f32x4_mul:K.f32x4_mul,f32x4_div:K.f32x4_div};return r.push(...hn(s[e])),r}case"f32x4_neg":case"f32x4_sqrt":{r.push(...D(n[0],t));let s={f32x4_neg:K.f32x4_neg,f32x4_sqrt:K.f32x4_sqrt};return r.push(...hn(s[e])),r}default:return t.errors.push(`Unknown SIMD intrinsic: ${e}`),[d.f64_const,...re(0)]}}function Si(e,n,t){let r=[];for(let a of n){r.push(...D(a,t));let c=J(a,t);c==="i32"?r.push(d.f64_convert_i32_s):c==="f32"&&r.push(d.f64_promote_f32)}let o={abs:d.f64_abs,ceil:d.f64_ceil,floor:d.f64_floor,trunc:d.f64_trunc,sqrt:d.f64_sqrt,min:d.f64_min,max:d.f64_max}[e];return o!==void 0?(r.push(o),r):["sin","cos","tan","asin","acos","atan","atan2","exp","log","pow"].includes(e)?(t.needsMathImports.add(e),t.errors.push(`Math.${e} requires JS import (not yet implemented)`),[d.f64_const,...re(0)]):(t.errors.push(`Unknown Math method: ${e}`),[d.f64_const,...re(0)])}function $i(e){let n=e.split(":").map(o=>o.trim()),t=n[0];if(n.length===1)return{name:t,type:"f64"};let r=n[1];return wt[r]?{name:t,type:"i32",isArray:!0,arrayType:r}:{name:t,type:{i32:"i32",i64:"i64",f32:"f32",f64:"f64",number:"f64",int:"i32"}[r]??"f64"}}function Ei(e,n,t,r,s){let o=[0,97,115,109,1,0,0,0],i=e.map(S=>ie[S.type]),a=s?[1,ie.f64]:[0],c=Xe(Qe.type,[1,96,...O(e.length),...i,...a]),l=[],p=[];r&&(p=Xe(Qe.import,[1,...bn("env"),...bn("memory"),2,0,1]));let f=Xe(Qe.function,[1,0]),u=Xe(Qe.export,[1,...bn("compute"),0,0]),m=[];if(t.length>0){let S=t[0],h=1;for(let b=1;b<t.length;b++)t[b]===S?h++:(m.push([...O(h),ie[S]]),S=t[b],h=1);m.push([...O(h),ie[S]])}let g=[...[...O(m.length),...m.flat()],...n,d.end],_=Xe(Qe.code,[1,...O(g.length),...g]),$=[...o,...c];return p.length>0&&$.push(...p),$.push(...f,...u,..._),$}function Dr(e){try{let n=e.captures.map($i),t;try{let l=`function __wasm__(${n.map(p=>p.name).join(", ")}) { ${e.body} }`;t=Br.parse(l,{ecmaVersion:2022})}catch(l){return{bytes:new Uint8Array,warnings:[],success:!1,error:`Parse error: ${l.message}`}}let s=t.body[0].body.body,o=fi(n),i=[];for(let l of s)i.push(...Be(l,o));if(o.errors.length>0)return{bytes:new Uint8Array,warnings:o.warnings,success:!1,error:o.errors.join("; ")};let a=Ei(n,i,o.localTypes,o.needsMemory,o.hasReturn),c=ui(i,n,o.localTypes);return{bytes:new Uint8Array(a),warnings:o.warnings,success:!0,needsMemory:o.needsMemory,wat:c}}catch(n){return{bytes:new Uint8Array,warnings:[],success:!1,error:n.message}}}function Fr(e){let n=[],t=[];for(let a of e){let c=Dr(a);if(c.success){let l=btoa(String.fromCharCode(...c.bytes));t.push({id:a.id,base64:l,captures:a.captures,needsMemory:c.needsMemory??!1,wat:c.wat??""}),n.push({id:a.id,success:!0,byteLength:c.bytes.length})}else n.push({id:a.id,success:!1,error:c.error})}if(t.length===0)return{code:"",results:n};let r=t.map(a=>{let c=a.wat.split(`
|
|
302
|
-
`).map(
|
|
303
|
-
* WASM: ${
|
|
304
|
-
${
|
|
302
|
+
`;try{let _=new Function("__deepEqual","__format","__typeMatches",b),{testResults:x,sigTestResults:g}=_(dn,He,yn);for(let E of x){let k=e[E.idx],j=c&&!E.passed&&E.error&&/is not defined$/.test(E.error);i.push({description:k.description,passed:j?!0:E.passed,error:j?void 0:E.error,line:k.line})}for(let E of g){let k=y[E.idx],j=c&&!E.passed&&E.error&&/is not defined$/.test(E.error),A=k.className?`${k.className}.${k.funcName}`:k.funcName;i.push({description:`${A} signature example`,passed:j?!0:E.passed,error:j?void 0:E.error,isSignatureTest:!0,line:k.line})}}catch(_){let x=c&&_ instanceof ReferenceError;for(let g of e)i.push({description:g.description,passed:x,error:x?void 0:`Module execution failed: ${_.message}`});for(let g of y){let E=g.className?`${g.className}.${g.funcName}`:g.funcName;i.push({description:`${E} signature example`,passed:x,error:x?void 0:`Module execution failed: ${_.message}`,isSignatureTest:!0})}}for(let _ of h){let x=_.className?`${_.className}.${_.funcName}`:_.funcName;i.push({description:`${x} signature example`,passed:!0,isSignatureTest:!0,line:_.line})}return i}function _t(e){let n="",t=0,r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(i==="{"||i==="["||i==="("){if(i==="{"&&t===0&&r)break;t++,n+=i,r=!0}else i==="}"||i==="]"||i===")"?(t--,n+=i):/\s/.test(i)?n+=i:(n+=i,r=!0)}return n.trim()||null}function mn(e){if(!e.trim())return[];let n=[],t=ui(e);for(let r of t){let s=r.trim(),o=s.match(/^\.\.\.(\w+)\s*[:=]\s*(\[.+\])$/);if(o){try{let a=new Function(`return ${o[2]}`)();if(Array.isArray(a))for(let c of a)n.push(JSON.stringify(c))}catch{}continue}if(s.startsWith("..."))continue;let i=s.match(/(?:\(\s*[?!]\s*)?(\w+)\s*[:=]\s*(.+?)(?:\))?$/);if(i)n.push(i[2].trim());else return[]}return n}function ui(e){let n=[],t="",r=0;for(let s of e){if(s==="("||s==="["||s==="{")r++;else if(s===")"||s==="]"||s==="}")r--;else if(s===","&&r===0){n.push(t.trim()),t="";continue}t+=s}return t.trim()&&n.push(t.trim()),n}import*as Fr from"acorn";var ie={i32:127,i64:126,f32:125,f64:124,v128:123,funcref:112,externref:111,void:64},Qe={custom:0,type:1,import:2,function:3,table:4,memory:5,global:6,export:7,start:8,element:9,code:10,data:11},d={unreachable:0,nop:1,block:2,loop:3,if:4,else:5,end:11,br:12,br_if:13,br_table:14,return:15,call:16,call_indirect:17,drop:26,select:27,local_get:32,local_set:33,local_tee:34,global_get:35,global_set:36,i32_load:40,i64_load:41,f32_load:42,f64_load:43,i32_load8_s:44,i32_load8_u:45,i32_load16_s:46,i32_load16_u:47,i32_store:54,i64_store:55,f32_store:56,f64_store:57,i32_store8:58,i32_store16:59,memory_size:63,memory_grow:64,i32_const:65,i64_const:66,f32_const:67,f64_const:68,i32_eqz:69,i32_eq:70,i32_ne:71,i32_lt_s:72,i32_lt_u:73,i32_gt_s:74,i32_gt_u:75,i32_le_s:76,i32_le_u:77,i32_ge_s:78,i32_ge_u:79,i64_eqz:80,i64_eq:81,i64_ne:82,i64_lt_s:83,i64_lt_u:84,i64_gt_s:85,i64_gt_u:86,i64_le_s:87,i64_le_u:88,i64_ge_s:89,i64_ge_u:90,f32_eq:91,f32_ne:92,f32_lt:93,f32_gt:94,f32_le:95,f32_ge:96,f64_eq:97,f64_ne:98,f64_lt:99,f64_gt:100,f64_le:101,f64_ge:102,i32_clz:103,i32_ctz:104,i32_popcnt:105,i32_add:106,i32_sub:107,i32_mul:108,i32_div_s:109,i32_div_u:110,i32_rem_s:111,i32_rem_u:112,i32_and:113,i32_or:114,i32_xor:115,i32_shl:116,i32_shr_s:117,i32_shr_u:118,i32_rotl:119,i32_rotr:120,i64_add:124,i64_sub:125,i64_mul:126,i64_div_s:127,f32_abs:139,f32_neg:140,f32_ceil:141,f32_floor:142,f32_trunc:143,f32_nearest:144,f32_sqrt:145,f32_add:146,f32_sub:147,f32_mul:148,f32_div:149,f32_min:150,f32_max:151,f32_copysign:152,f64_abs:153,f64_neg:154,f64_ceil:155,f64_floor:156,f64_trunc:157,f64_nearest:158,f64_sqrt:159,f64_add:160,f64_sub:161,f64_mul:162,f64_div:163,f64_min:164,f64_max:165,f64_copysign:166,i32_wrap_i64:167,i32_trunc_f32_s:168,i32_trunc_f32_u:169,i32_trunc_f64_s:170,i32_trunc_f64_u:171,i64_extend_i32_s:172,i64_extend_i32_u:173,f32_convert_i32_s:178,f32_convert_i32_u:179,f32_convert_i64_s:180,f32_demote_f64:182,f64_convert_i32_s:183,f64_convert_i32_u:184,f64_convert_i64_s:185,f64_promote_f32:187,i32_reinterpret_f32:188,f32_reinterpret_i32:190,f64_reinterpret_i64:191,i32_extend8_s:192,i32_extend16_s:193},fi=Object.fromEntries(Object.entries(d).map(([e,n])=>[n,e.replace(/_/g,".")])),et=253,K={v128_load:0,v128_store:11,v128_const:12,f32x4_splat:19,f32x4_extract_lane:31,f32x4_replace_lane:32,f32x4_neg:225,f32x4_sqrt:227,f32x4_add:228,f32x4_sub:229,f32x4_mul:230,f32x4_div:231},pi=Object.fromEntries(Object.entries(K).map(([e,n])=>[n,e.replace(/_/g,".")]));function gn(e){return[et,...C(e)]}function Dr(e,n,t){return[et,...C(e),...C(n),...C(t)]}function C(e){let n=[];do{let t=e&127;e>>>=7,e!==0&&(t|=128),n.push(t)}while(e!==0);return n}function tt(e){let n=[],t=!0;for(;t;){let r=e&127;e>>=7,e===0&&(r&64)===0||e===-1&&(r&64)!==0?t=!1:r|=128,n.push(r)}return n}function hn(e){let n=new ArrayBuffer(4);return new Float32Array(n)[0]=e,[...new Uint8Array(n)]}function ne(e){let n=new ArrayBuffer(8);return new Float64Array(n)[0]=e,[...new Uint8Array(n)]}function bn(e){let n=new TextEncoder().encode(e);return[...C(n.length),...n]}function Xe(e,n){return[e,...C(n.length),...n]}function he(e,n){let t=0,r=0,s=n;for(;s<e.length;){let o=e[s];if(t|=(o&127)<<r,s++,(o&128)===0)break;r+=7}return[t,s-n]}function mi(e,n){let t=new ArrayBuffer(8),r=new Uint8Array(t);for(let s=0;s<8;s++)r[s]=e[n+s];return new Float64Array(t)[0]}function di(e,n,t){let r=[],s=1,o=()=>" ".repeat(s),i=n.map((l,f)=>`(param $${l.name} ${l.type})`).join(" "),a=t.map((l,f)=>`(local $L${n.length+f} ${l})`).join(" ");r.push(`(func (export "compute") ${i} (result f64)`),a&&r.push(` ${a}`);let c=0;for(;c<e.length;){let l=e[c],f=fi[l]||`unknown(0x${l.toString(16)})`;if(c++,l===d.local_get||l===d.local_set||l===d.local_tee){let[p,u]=he(e,c);c+=u;let m=p<n.length?`$${n[p].name}`:`$L${p}`;r.push(`${o()}${f} ${m}`)}else if(l===d.br||l===d.br_if){let[p,u]=he(e,c);c+=u,r.push(`${o()}${f} ${p}`)}else if(l===d.i32_const){let[p,u]=he(e,c);c+=u,r.push(`${o()}i32.const ${p}`)}else if(l===d.f32_const){let p=new ArrayBuffer(4),u=new Uint8Array(p);for(let y=0;y<4;y++)u[y]=e[c+y];let m=new Float32Array(p)[0];c+=4,r.push(`${o()}f32.const ${m}`)}else if(l===d.f64_const){let p=mi(e,c);c+=8,r.push(`${o()}f64.const ${p}`)}else if(l===d.block||l===d.loop){let p=e[c];c++,r.push(`${o()}${f}${p===ie.void?"":` (result ${p===ie.f64?"f64":"i32"})`}`),s++}else if(l===d.if){let p=e[c];c++,r.push(`${o()}if${p===ie.void?"":` (result ${p===ie.f64?"f64":"i32"})`}`),s++}else if(l===d.else)s--,r.push(`${o()}else`),s++;else if(l===d.end)s=Math.max(1,s-1),r.push(`${o()}end`);else if(l===d.f64_load||l===d.f64_store||l===d.f32_load||l===d.f32_store||l===d.i32_load||l===d.i32_store){let[p,u]=he(e,c);c+=u;let[m,y]=he(e,c);c+=y,r.push(`${o()}${f}${m?` offset=${m}`:""}`)}else if(l===et){let[p,u]=he(e,c);c+=u;let m=pi[p]||`simd.unknown(0x${p.toString(16)})`;if(p===K.v128_load||p===K.v128_store){let[y,h]=he(e,c);c+=h;let[w,S]=he(e,c);c+=S,r.push(`${o()}${m}${w?` offset=${w}`:""}`)}else if(p===K.v128_const){let y=e.slice(c,c+16);c+=16,r.push(`${o()}v128.const ${y.map(h=>"0x"+h.toString(16).padStart(2,"0")).join(" ")}`)}else if(p===K.f32x4_extract_lane||p===K.f32x4_replace_lane){let y=e[c];c++,r.push(`${o()}${m} ${y}`)}else r.push(`${o()}${m}`)}else r.push(`${o()}${f}`)}return r.push(")"),r.join(`
|
|
303
|
+
`)}var wt={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:d.i32_load8_s,storeOp:d.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:d.i32_load8_u,storeOp:d.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:d.i32_load8_u,storeOp:d.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:d.i32_load16_s,storeOp:d.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:d.i32_load16_u,storeOp:d.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:d.i32_load,storeOp:d.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:d.i32_load,storeOp:d.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:d.f32_load,storeOp:d.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:d.f64_load,storeOp:d.f64_store}};function yi(e,n=new Map){let t={params:e,locals:new Map,nextLocalIndex:e.length,localTypes:[],warnings:[],errors:[],loopDepth:0,needsMathImports:new Set,needsMemory:!1,hasReturn:!1,wat:[],watIndent:1,moduleFunctions:n};return e.forEach((r,s)=>{t.locals.set(r.name,{index:s,type:r.type})}),t}function xt(e,n,t){if(e.locals.has(n))return e.errors.push(`Duplicate local declaration: ${n}`),e.locals.get(n).index;let r=e.nextLocalIndex++;return e.locals.set(n,{index:r,type:t}),e.localTypes.push(t),r}function ke(e,n){return e.locals.get(n)}function Oe(e,n){switch(e.type){case"ExpressionStatement":{let t=e.expression;return[...D(t,n),d.drop]}case"ReturnStatement":{let t=e;if(n.hasReturn=!0,!t.argument)return[d.return];let r=D(t.argument,n),s=W(t.argument,n);return s==="i32"?r.push(d.f64_convert_i32_s):s==="f32"&&r.push(d.f64_promote_f32),r.push(d.return),r}case"VariableDeclaration":{let t=e,r=[];for(let s of t.declarations){if(s.id.type!=="Identifier"){n.errors.push("Destructuring not supported in WASM blocks");continue}let o=s.id.name,i="f64";s.init&&(i=W(s.init,n));let a=xt(n,o,i);s.init&&(r.push(...D(s.init,n)),r.push(d.local_set,...C(a)))}return r}case"ForStatement":return gi(e,n);case"IfStatement":return hi(e,n);case"BlockStatement":{let t=e,r=[];for(let s of t.body)r.push(...Oe(s,n));return r}default:return n.errors.push(`Unsupported statement type: ${e.type}`),[]}}function gi(e,n){let t=[];return e.init&&(e.init.type==="VariableDeclaration"?t.push(...Oe(e.init,n)):t.push(...D(e.init,n))),t.push(d.block,ie.void),t.push(d.loop,ie.void),e.test&&(t.push(...D(e.test,n)),t.push(d.i32_eqz),t.push(d.br_if,1)),n.loopDepth++,e.body&&t.push(...Oe(e.body,n)),n.loopDepth--,e.update&&(t.push(...D(e.update,n)),t.push(d.drop)),t.push(d.br,0),t.push(d.end),t.push(d.end),t}function hi(e,n){let t=[];return t.push(...D(e.test,n)),t.push(d.if,ie.void),t.push(...Oe(e.consequent,n)),e.alternate&&(t.push(d.else),t.push(...Oe(e.alternate,n))),t.push(d.end),t}function W(e,n){switch(e.type){case"Literal":{let t=e;return typeof t.value=="number"?t.raw&&(t.raw.includes(".")||t.raw.includes("e"))?"f64":Number.isInteger(t.value)&&t.value>=-2147483648&&t.value<=2147483647?"i32":"f64":"f64"}case"Identifier":return ke(n,e.name)?.type??"f64";case"BinaryExpression":case"AssignmentExpression":{let t=e;if(["<",">","<=",">=","==","!=","===","!=="].includes(t.operator)||["|","&","^","<<",">>",">>>"].includes(t.operator))return"i32";let r=W(t.left,n),s=W(t.right,n);return r==="v128"||s==="v128"?"v128":r==="f64"||s==="f64"?"f64":r==="f32"||s==="f32"?"f32":"i32"}case"UnaryExpression":{let t=e;return t.operator==="!"?"i32":W(t.argument,n)}case"MemberExpression":{let t=e;if(t.object.type==="Identifier"&&ke(n,t.object.name)){let s=n.params.find(o=>o.name===t.object.name);if(s?.arrayType){let o=wt[s.arrayType];if(o)return o.elementType}}return"f64"}case"CallExpression":{let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee;if(r.object.type==="Identifier"&&r.object.name==="Math")return"f64"}if(t.callee.type==="Identifier"){let r=t.callee.name;if(r==="f32x4_extract_lane")return"f32";if(r.startsWith("f32x4_")||r==="v128_load")return"v128";let s=n.moduleFunctions.get(r);if(s)return s.hasReturn?"f64":"i32"}return"f64"}default:return"f64"}}function D(e,n){switch(e.type){case"Literal":{let t=e;if(typeof t.value=="number"){let r=W(e,n);return r==="i32"?[d.i32_const,...tt(t.value|0)]:r==="f32"?[d.f32_const,...hn(t.value)]:[d.f64_const,...ne(t.value)]}return n.errors.push(`Unsupported literal type: ${typeof t.value}`),[d.f64_const,...ne(0)]}case"Identifier":{let t=e.name,r=ke(n,t);return r?[d.local_get,...C(r.index)]:(n.errors.push(`Unknown identifier: ${t}`),[d.f64_const,...ne(0)])}case"BinaryExpression":return bi(e,n);case"UnaryExpression":return _i(e,n);case"AssignmentExpression":return xi(e,n);case"UpdateExpression":return wi(e,n);case"MemberExpression":return $i(e,n);case"CallExpression":return Ei(e,n);case"SequenceExpression":{let t=e,r=[];for(let s=0;s<t.expressions.length;s++)r.push(...D(t.expressions[s],n)),s<t.expressions.length-1&&r.push(d.drop);return r}default:return n.errors.push(`Unsupported expression type: ${e.type}`),[d.f64_const,...ne(0)]}}function bi(e,n){let t=D(e.left,n),r=D(e.right,n),s=W(e,n),o=W(e.left,n),i=W(e.right,n),a=["<",">","<=",">=","==","===","!=","!=="].includes(e.operator),c;o==="f64"||i==="f64"?c="f64":o==="f32"||i==="f32"?c="f32":c="i32",!a&&s==="f64"&&(c="f64");let l=t,f=r;c==="f64"?(o==="i32"?l=[...t,d.f64_convert_i32_s]:o==="f32"&&(l=[...t,d.f64_promote_f32]),i==="i32"?f=[...r,d.f64_convert_i32_s]:i==="f32"&&(f=[...r,d.f64_promote_f32])):c==="f32"&&(o==="i32"&&(l=[...t,d.f32_convert_i32_s]),i==="i32"&&(f=[...r,d.f32_convert_i32_s]));let u={"+":{i32:d.i32_add,f32:d.f32_add,f64:d.f64_add},"-":{i32:d.i32_sub,f32:d.f32_sub,f64:d.f64_sub},"*":{i32:d.i32_mul,f32:d.f32_mul,f64:d.f64_mul},"/":{i32:d.i32_div_s,f32:d.f32_div,f64:d.f64_div},"%":{i32:d.i32_rem_s},"<":{i32:d.i32_lt_s,f32:d.f32_lt,f64:d.f64_lt},">":{i32:d.i32_gt_s,f32:d.f32_gt,f64:d.f64_gt},"<=":{i32:d.i32_le_s,f32:d.f32_le,f64:d.f64_le},">=":{i32:d.i32_ge_s,f32:d.f32_ge,f64:d.f64_ge},"==":{i32:d.i32_eq,f32:d.f32_eq,f64:d.f64_eq},"===":{i32:d.i32_eq,f32:d.f32_eq,f64:d.f64_eq},"!=":{i32:d.i32_ne,f32:d.f32_ne,f64:d.f64_ne},"!==":{i32:d.i32_ne,f32:d.f32_ne,f64:d.f64_ne},"|":{i32:d.i32_or},"&":{i32:d.i32_and},"^":{i32:d.i32_xor},"<<":{i32:d.i32_shl},">>":{i32:d.i32_shr_s},">>>":{i32:d.i32_shr_u}}[e.operator];if(!u)return n.errors.push(`Unsupported operator: ${e.operator}`),[d.f64_const,...ne(0)];let m=u[c]??u.f64??u.i32;return m===void 0?(n.errors.push(`Operator ${e.operator} not supported for type ${c}`),[d.f64_const,...ne(0)]):[...l,...f,m]}function _i(e,n){let t=D(e.argument,n),r=W(e.argument,n);switch(e.operator){case"-":return r==="i32"?[d.i32_const,0,...t,d.i32_sub]:r==="f32"?[...t,d.f32_neg]:[...t,d.f64_neg];case"!":return[...t,d.i32_eqz];case"~":return[...t,d.i32_const,...tt(-1),d.i32_xor];default:return n.errors.push(`Unsupported unary operator: ${e.operator}`),t}}function xi(e,n){if(e.left.type==="MemberExpression")return Si(e.left,e.right,e.operator,n);if(e.left.type!=="Identifier")return n.errors.push("Assignment target must be identifier or array element"),[];let t=e.left.name,r=ke(n,t);if(!r)return n.errors.push(`Unknown variable: ${t}`),[];let s=[];if(e.operator==="="){s.push(...D(e.right,n));let o=W(e.right,n);r.type==="f64"&&o==="i32"?s.push(d.f64_convert_i32_s):r.type==="f64"&&o==="f32"?s.push(d.f64_promote_f32):r.type==="i32"&&o==="f64"?s.push(d.i32_trunc_f64_s):r.type==="i32"&&o==="f32"?s.push(d.i32_trunc_f32_s):r.type==="f32"&&o==="i32"?s.push(d.f32_convert_i32_s):r.type==="f32"&&o==="f64"&&s.push(d.f32_demote_f64)}else{let o=W(e.right,n),i=r.type;o==="f64"||r.type==="f64"?i="f64":(o==="f32"||r.type==="f32")&&(i="f32"),s.push(d.local_get,...C(r.index)),i==="f64"&&r.type==="i32"?s.push(d.f64_convert_i32_s):i==="f64"&&r.type==="f32"?s.push(d.f64_promote_f32):i==="f32"&&r.type==="i32"&&s.push(d.f32_convert_i32_s),s.push(...D(e.right,n)),i==="f64"&&o==="i32"?s.push(d.f64_convert_i32_s):i==="f64"&&o==="f32"?s.push(d.f64_promote_f32):i==="f32"&&o==="i32"&&s.push(d.f32_convert_i32_s);let a=e.operator.slice(0,-1),l={"+":{i32:d.i32_add,f32:d.f32_add,f64:d.f64_add},"-":{i32:d.i32_sub,f32:d.f32_sub,f64:d.f64_sub},"*":{i32:d.i32_mul,f32:d.f32_mul,f64:d.f64_mul},"/":{i32:d.i32_div_s,f32:d.f32_div,f64:d.f64_div}}[a]?.[i];if(!l)return n.errors.push(`Unsupported compound assignment: ${e.operator}`),[];s.push(l),r.type==="i32"&&i==="f64"?s.push(d.i32_trunc_f64_s):r.type==="i32"&&i==="f32"?s.push(d.i32_trunc_f32_s):r.type==="f32"&&i==="f64"&&s.push(d.f32_demote_f64)}return s.push(d.local_tee,...C(r.index)),s}function wi(e,n){if(e.argument.type!=="Identifier")return n.errors.push("Update expression argument must be identifier"),[];let t=e.argument.name,r=ke(n,t);if(!r)return n.errors.push(`Unknown variable: ${t}`),[];let s=[],o=r.type==="i32";return e.prefix?(s.push(d.local_get,...C(r.index)),o?(s.push(d.i32_const,1),s.push(e.operator==="++"?d.i32_add:d.i32_sub)):(s.push(d.f64_const,...ne(1)),s.push(e.operator==="++"?d.f64_add:d.f64_sub)),s.push(d.local_tee,...C(r.index))):(s.push(d.local_get,...C(r.index)),s.push(d.local_get,...C(r.index)),o?(s.push(d.i32_const,1),s.push(e.operator==="++"?d.i32_add:d.i32_sub)):(s.push(d.f64_const,...ne(1)),s.push(e.operator==="++"?d.f64_add:d.f64_sub)),s.push(d.local_set,...C(r.index))),s}function $i(e,n){if(e.object.type!=="Identifier")return n.errors.push("Array access requires identifier"),[];let t=e.object.name,r=n.params.find(l=>l.name===t);if(!r?.isArray||!r.arrayType)return n.errors.push(`${t} is not a typed array parameter`),[];let s=wt[r.arrayType];if(!s)return n.errors.push(`Unknown array type: ${r.arrayType}`),[];n.needsMemory=!0;let o=[],i=ke(n,t);if(!i)return n.errors.push(`Unknown array: ${t}`),[];if(o.push(d.local_get,...C(i.index)),!e.computed||!e.property)return n.errors.push("Array access requires computed index"),[];let a=D(e.property,n),c=W(e.property,n);return o.push(...a),c==="f64"&&o.push(d.i32_trunc_f64_s),s.bytesPerElement>1&&(o.push(d.i32_const,...tt(s.bytesPerElement)),o.push(d.i32_mul)),o.push(d.i32_add),o.push(s.loadOp,0,0),o}function Si(e,n,t,r){if(e.object.type!=="Identifier")return r.errors.push("Array store requires identifier"),[];let s=e.object.name,o=r.params.find(y=>y.name===s);if(!o?.isArray||!o.arrayType)return r.errors.push(`${s} is not a typed array parameter`),[];let i=wt[o.arrayType];if(!i)return r.errors.push(`Unknown array type: ${o.arrayType}`),[];r.needsMemory=!0;let a=[],c=ke(r,s);if(!c)return[];if(!e.computed||!e.property)return r.errors.push("Array store requires computed index"),[];let l=D(e.property,r),f=W(e.property,r),p=()=>{let y=[];return y.push(d.local_get,...C(c.index)),y.push(...l),f==="f64"&&y.push(d.i32_trunc_f64_s),i.bytesPerElement>1&&(y.push(d.i32_const,...tt(i.bytesPerElement)),y.push(d.i32_mul)),y.push(d.i32_add),y};if(t==="=")a.push(...D(n,r));else{let y=xt(r,`__addr_${r.nextLocalIndex}`,"i32");a.push(...p()),a.push(d.local_tee,...C(y)),a.push(i.loadOp,0,0),a.push(...D(n,r));let h=W(n,r);i.elementType==="f32"&&h==="f64"?a.push(d.f32_demote_f64):i.elementType==="f64"&&h==="f32"?a.push(d.f64_promote_f32):i.elementType==="f32"&&h==="i32"?a.push(d.f32_convert_i32_s):i.elementType==="f64"&&h==="i32"?a.push(d.f64_convert_i32_s):i.elementType==="i32"&&h==="f64"?a.push(d.i32_trunc_f64_s):i.elementType==="i32"&&h==="f32"&&a.push(d.i32_trunc_f32_s);let w=t.slice(0,-1),S={"+":i.elementType==="i32"?d.i32_add:i.elementType==="f32"?d.f32_add:d.f64_add,"-":i.elementType==="i32"?d.i32_sub:i.elementType==="f32"?d.f32_sub:d.f64_sub,"*":i.elementType==="i32"?d.i32_mul:i.elementType==="f32"?d.f32_mul:d.f64_mul};a.push(S[w]??d.f64_add);let $=xt(r,`__val_${r.nextLocalIndex}`,i.elementType);return a.push(d.local_set,...C($)),a.push(d.local_get,...C(y)),a.push(d.local_get,...C($)),a.push(i.storeOp,0,0),a.push(d.local_get,...C($)),a}let u=W(n,r);i.elementType==="f32"&&u==="f64"?a.push(d.f32_demote_f64):i.elementType==="f64"&&u==="f32"?a.push(d.f64_promote_f32):i.elementType==="i32"&&u==="f64"&&a.push(d.i32_trunc_f64_s);let m=xt(r,`__tmp_${r.nextLocalIndex}`,i.elementType);return a.push(d.local_set,...C(m)),a.push(d.local_get,...C(c.index)),a.push(...l),f==="f64"&&a.push(d.i32_trunc_f64_s),i.bytesPerElement>1&&(a.push(d.i32_const,...tt(i.bytesPerElement)),a.push(d.i32_mul)),a.push(d.i32_add),a.push(d.local_get,...C(m)),a.push(i.storeOp,0,0),a.push(d.local_get,...C(m)),a}function Ei(e,n){if(e.callee.type==="MemberExpression"){let t=e.callee;if(t.object.type==="Identifier"&&t.object.name==="Math"&&t.property.type==="Identifier"){let r=t.property.name;return vi(r,e.arguments,n)}}if(e.callee.type==="Identifier"){let t=e.callee.name;if(t.startsWith("f32x4_")||t.startsWith("v128_"))return ji(t,e.arguments,n);let r=n.moduleFunctions.get(t);if(r)return Ti(r,t,e.arguments,n)}return n.errors.push(`Unsupported function call: ${e.callee.type}`),[d.f64_const,...ne(0)]}function Ti(e,n,t,r){if(t.length!==e.params.length)return r.errors.push(`wasm function ${n} expects ${e.params.length} arguments, got ${t.length}`),[d.f64_const,...ne(0)];let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e.params[o].type,c=W(i,r);if(s.push(...D(i,r)),c!==a){let l=ki(c,a);l===void 0?r.errors.push(`wasm function ${n} param ${o} expects ${a}, got ${c} (no conversion available)`):l!==null&&s.push(l)}}return s.push(d.call,...C(e.index)),e.hasReturn||s.push(d.i32_const,0),s}function ki(e,n){if(e===n)return null;if(!(e==="v128"||n==="v128")&&!(e==="i64"||n==="i64"))switch(`${e}->${n}`){case"f64->i32":return d.i32_trunc_f64_s;case"f32->i32":return d.i32_trunc_f32_s;case"i32->f64":return d.f64_convert_i32_s;case"i32->f32":return d.f32_convert_i32_s;case"f32->f64":return d.f64_promote_f32;case"f64->f32":return d.f32_demote_f64;default:return}}function ji(e,n,t){t.needsMemory=!0;let r=[];switch(e){case"v128_load":case"f32x4_load":{r.push(...D(n[0],t)),W(n[0],t)==="f64"&&r.push(d.i32_trunc_f64_s),r.push(...D(n[1],t));let o=W(n[1],t);return o==="f64"?r.push(d.i32_trunc_f64_s):o==="f32"&&r.push(d.i32_trunc_f32_s),r.push(d.i32_add),r.push(...Dr(K.v128_load,2,0)),r}case"v128_store":case"f32x4_store":{r.push(...D(n[0],t)),W(n[0],t)==="f64"&&r.push(d.i32_trunc_f64_s),r.push(...D(n[1],t));let o=W(n[1],t);return o==="f64"?r.push(d.i32_trunc_f64_s):o==="f32"&&r.push(d.i32_trunc_f32_s),r.push(d.i32_add),r.push(...D(n[2],t)),r.push(...Dr(K.v128_store,2,0)),r.push(d.i32_const,0),r}case"f32x4_splat":{r.push(...D(n[0],t));let s=W(n[0],t);return s==="i32"?r.push(d.f32_convert_i32_s):s==="f64"&&r.push(d.f32_demote_f64),r.push(...gn(K.f32x4_splat)),r}case"f32x4_extract_lane":{r.push(...D(n[0],t));let s=n[1].value;return!Number.isInteger(s)||s<0||s>3?(t.errors.push(`f32x4_extract_lane: lane must be 0-3, got ${s}`),[d.f32_const,...hn(0)]):(r.push(et,...C(K.f32x4_extract_lane),s),r)}case"f32x4_replace_lane":{r.push(...D(n[0],t));let s=n[1].value;if(!Number.isInteger(s)||s<0||s>3)return t.errors.push(`f32x4_replace_lane: lane must be 0-3, got ${s}`),[d.f32_const,...hn(0)];r.push(...D(n[2],t));let o=W(n[2],t);return o==="i32"?r.push(d.f32_convert_i32_s):o==="f64"&&r.push(d.f32_demote_f64),r.push(et,...C(K.f32x4_replace_lane),s),r}case"f32x4_add":case"f32x4_sub":case"f32x4_mul":case"f32x4_div":{r.push(...D(n[0],t)),r.push(...D(n[1],t));let s={f32x4_add:K.f32x4_add,f32x4_sub:K.f32x4_sub,f32x4_mul:K.f32x4_mul,f32x4_div:K.f32x4_div};return r.push(...gn(s[e])),r}case"f32x4_neg":case"f32x4_sqrt":{r.push(...D(n[0],t));let s={f32x4_neg:K.f32x4_neg,f32x4_sqrt:K.f32x4_sqrt};return r.push(...gn(s[e])),r}default:return t.errors.push(`Unknown SIMD intrinsic: ${e}`),[d.f64_const,...ne(0)]}}function vi(e,n,t){let r=[];for(let a of n){r.push(...D(a,t));let c=W(a,t);c==="i32"?r.push(d.f64_convert_i32_s):c==="f32"&&r.push(d.f64_promote_f32)}let o={abs:d.f64_abs,ceil:d.f64_ceil,floor:d.f64_floor,trunc:d.f64_trunc,sqrt:d.f64_sqrt,min:d.f64_min,max:d.f64_max}[e];return o!==void 0?(r.push(o),r):["sin","cos","tan","asin","acos","atan","atan2","exp","log","pow"].includes(e)?(t.needsMathImports.add(e),t.errors.push(`Math.${e} requires JS import (not yet implemented)`),[d.f64_const,...ne(0)]):(t.errors.push(`Unknown Math method: ${e}`),[d.f64_const,...ne(0)])}function qr(e){let n=e.split(":").map(o=>o.trim()),t=n[0];if(n.length===1)return{name:t,type:"f64"};let r=n[1];return wt[r]?{name:t,type:"i32",isArray:!0,arrayType:r}:{name:t,type:{i32:"i32",i64:"i64",f32:"f32",f64:"f64",number:"f64",int:"i32"}[r]??"f64"}}function Ai(e,n){let t=e.map(s=>ie[s.type]),r=n?[1,ie.f64]:[0];return[96,...C(e.length),...t,...r]}function Ri(e,n){let t=[];if(n.length>0){let o=n[0],i=1;for(let a=1;a<n.length;a++)n[a]===o?i++:(t.push([...C(i),ie[o]]),o=n[a],i=1);t.push([...C(i),ie[o]])}let s=[...[...C(t.length),...t.flat()],...e,d.end];return[...C(s.length),...s]}function Mi(){return Xe(Qe.import,[1,...bn("env"),...bn("memory"),2,0,1])}function Ci(e,n){if(e.length!==n.length)throw new Error("functions and exportNames length mismatch");let t=[0,97,115,109,1,0,0,0],r=e.map(u=>Ai(u.params,u.hasReturn)),s=Xe(Qe.type,[...C(r.length),...r.flat()]),i=e.some(u=>u.needsMemory)?Mi():[],a=Xe(Qe.function,[...C(e.length),...e.map((u,m)=>C(m)).flat()]),c=Xe(Qe.export,[...C(e.length),...n.map((u,m)=>[...bn(u),0,...C(m)]).flat()]),l=e.map(u=>Ri(u.bodyCode,u.localTypes)),f=Xe(Qe.code,[...C(l.length),...l.flat()]),p=[...t,...s];return i.length>0&&p.push(...i),p.push(...a,...c,...f),p}function Ni(e,n=new Map){try{let t=e.captures.map(qr),r;try{let c=`function __wasm__(${t.map(l=>l.name).join(", ")}) { ${e.body} }`;r=Fr.parse(c,{ecmaVersion:2022})}catch(c){return{success:!1,warnings:[],error:`Parse error: ${c.message}`}}let o=r.body[0].body.body,i=yi(t,n),a=[];for(let c of o)a.push(...Oe(c,i));return i.errors.length>0?{success:!1,warnings:i.warnings,error:i.errors.join("; ")}:{success:!0,fn:{params:t,bodyCode:a,localTypes:i.localTypes,needsMemory:i.needsMemory,hasReturn:i.hasReturn},wat:di(a,t,i.localTypes),warnings:i.warnings}}catch(t){return{success:!1,warnings:[],error:t.message}}}function Ur(e){let n=new Map,t=[];for(let c=0;c<e.length;c++){let l=e[c],f=l.captures.map(qr),p=l.returnType!==void 0;t.push({params:f,hasReturn:p}),l.name&&n.set(l.name,{index:c,params:f,hasReturn:p})}let r=[],s=[],o=[],i=[];for(let c=0;c<e.length;c++){let l=e[c],f=Ni(l,n);if(i.push(...f.warnings),!f.success||!f.fn){r.push({id:l.id,success:!1,error:f.error}),s.push(Pi(t[c])),o.push({id:l.id,exportName:`compute_${c}`,captures:l.captures,needsMemory:!1,wat:`(failed: ${f.error??"unknown error"})`});continue}s.push(f.fn),o.push({id:l.id,exportName:`compute_${c}`,captures:l.captures,needsMemory:f.fn.needsMemory,wat:f.wat??""}),r.push({id:l.id,success:!0,exportIndex:c})}if(s.length===0)return{bytes:new Uint8Array,results:r,exports:[],needsMemory:!1,warnings:i};let a=Ci(s,o.map(c=>c.exportName));return{bytes:new Uint8Array(a),results:r,exports:o,needsMemory:o.some(c=>c.needsMemory),warnings:i}}function Pi(e){let n=e.hasReturn?[d.f64_const,...ne(0)]:[];return{params:e.params,bodyCode:n,localTypes:[],needsMemory:!1,hasReturn:e.hasReturn}}function Wr(e){let n=Ur(e),t=new Map(n.exports.map(f=>[f.id,f])),r=n.results.map(f=>{if(!f.success)return{id:f.id,success:!1,error:f.error};let p=t.get(f.id);return{id:f.id,success:!0,byteLength:n.bytes.length,_exportName:p.exportName}});if(n.exports.length===0)return{code:"",results:r};let s=n.exports.map(f=>{let p=f.wat.split(`
|
|
304
|
+
`).map(u=>` * ${u}`);return`/**
|
|
305
|
+
* WASM: ${f.id} (export: ${f.exportName})
|
|
306
|
+
${p.join(`
|
|
305
307
|
`)}
|
|
306
308
|
*/`}).join(`
|
|
307
|
-
`),
|
|
309
|
+
`),o=n.exports.map(f=>`{id:${JSON.stringify(f.id)},n:${JSON.stringify(f.exportName)},c:${JSON.stringify(f.captures)},m:${f.needsMemory}}`).join(","),i=btoa(String.fromCharCode(...n.bytes)),a=n.needsMemory,c=`${s}
|
|
308
310
|
;(async()=>{
|
|
309
|
-
const
|
|
311
|
+
const __wasmExports=[${o}];
|
|
312
|
+
const __wasmModuleB64=${JSON.stringify(i)};
|
|
310
313
|
const __b64ToBytes=s=>{const b=atob(s),a=new Uint8Array(b.length);for(let i=0;i<b.length;i++)a[i]=b.charCodeAt(i);return a};
|
|
311
314
|
const __parseType=c=>{const m=c.match(/^(\\w+)\\s*:\\s*(\\w+)$/);if(!m)return{n:c,t:'f64',a:false};const[,n,ts]=m;const at={Float32Array:'f32',Float64Array:'f64',Int32Array:'i32',Uint8Array:'i32'};if(at[ts])return{n,t:'i32',a:true,at:ts};return{n,t:'f64',a:false}};
|
|
312
|
-
${
|
|
315
|
+
${a?`const __wasmMem=new WebAssembly.Memory({initial:1024});
|
|
313
316
|
let __woff=0;
|
|
314
317
|
globalThis.wasmBuffer=function(Ctor,len){const bytes=len*Ctor.BYTES_PER_ELEMENT;const align=Math.max(Ctor.BYTES_PER_ELEMENT,16);__woff=(__woff+align-1)&~(align-1);const arr=new Ctor(__wasmMem.buffer,__woff,len);__woff+=bytes;return arr};`:""}
|
|
315
|
-
|
|
316
|
-
|
|
318
|
+
const __wasmInst=await WebAssembly.instantiate(await WebAssembly.compile(__b64ToBytes(__wasmModuleB64)),${a?"{env:{memory:__wasmMem}}":"{}"});
|
|
319
|
+
for(const{id,n,c,m}of __wasmExports){
|
|
320
|
+
const compute=__wasmInst.exports[n];
|
|
317
321
|
const params=c.map(__parseType);
|
|
318
322
|
const hasArrays=params.some(p=>p.a);
|
|
319
|
-
const mem=m?__wasmMem:null;
|
|
320
|
-
const imp=mem?{env:{memory:mem}}:{};
|
|
321
|
-
const inst=await WebAssembly.instantiate(await WebAssembly.compile(bytes),imp);
|
|
322
|
-
const compute=inst.exports.compute;
|
|
323
323
|
if(!hasArrays){globalThis[id]=compute;continue}
|
|
324
324
|
globalThis[id]=function(...args){
|
|
325
|
-
const mv=new Uint8Array(
|
|
325
|
+
const mv=new Uint8Array(__wasmMem.buffer);let off=__woff;const ptrs=[];
|
|
326
326
|
for(let i=0;i<params.length;i++){const p=params[i],a=args[i];
|
|
327
327
|
if(p.a&&a?.buffer){
|
|
328
|
-
if(a.buffer===
|
|
328
|
+
if(a.buffer===__wasmMem.buffer){ptrs.push(a.byteOffset)}
|
|
329
329
|
else{const ab=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);off=(off+15)&~15;mv.set(ab,off);ptrs.push(off);off+=ab.length}
|
|
330
330
|
} else ptrs.push(a)}
|
|
331
331
|
const r=compute(...ptrs);off=__woff;
|
|
332
332
|
for(let i=0;i<params.length;i++){const p=params[i],a=args[i];
|
|
333
333
|
if(p.a&&a?.buffer){
|
|
334
|
-
if(a.buffer===
|
|
334
|
+
if(a.buffer===__wasmMem.buffer) continue;
|
|
335
335
|
const ab=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);off=(off+15)&~15;ab.set(mv.slice(off,off+ab.length));off+=ab.length}}
|
|
336
336
|
return r};
|
|
337
337
|
}})();
|
|
338
|
-
`.trim(),results:
|
|
339
|
-
`),suffix:"__tjs.popStack();"})}let i=Object.entries(n.params);if(i.length===0)return null;for(let[a]of i)r.push(`if (${a} instanceof Error) return ${a};`);for(let[a,c]of i){let l=`${s}${e}.${a}`;c.type.kind==="array"&&r.push(`if (Array.isArray(${a})) { for (const __i of ${a}) { if (__i instanceof Error && __i.path !== undefined) return __i } }`);let
|
|
340
|
-
`),suffix:"__tjs.popStack();"})}function
|
|
341
|
-
${
|
|
338
|
+
`.trim(),l=r.map(({_exportName:f,...p})=>p);return{code:c,results:l}}import*as Lr from"acorn";function xn(e,n){let t=[];function r(o){t.push({start:o.start,end:o.end,newText:`__tjs.toBool(${te(o,n)})`})}function s(o){if(!(!o||typeof o!="object"||!("type"in o))){switch(o.type){case"IfStatement":case"WhileStatement":case"DoWhileStatement":{let i=o;r(i.test),i.consequent&&s(i.consequent),i.alternate&&s(i.alternate),i.body&&s(i.body);return}case"ForStatement":{let i=o;i.init&&s(i.init),i.test&&r(i.test),i.update&&s(i.update),i.body&&s(i.body);return}case"ConditionalExpression":{let i=o;t.push({start:i.start,end:i.end,newText:`__tjs.toBool(${te(i.test,n)})?(${te(i.consequent,n)}):(${te(i.alternate,n)})`});return}case"LogicalExpression":{let i=o;if(i.operator==="&&"||i.operator==="||"){t.push({start:i.start,end:i.end,newText:te(o,n)});return}break}case"UnaryExpression":{let i=o;if(i.operator==="!"){t.push({start:i.start,end:i.end,newText:`!__tjs.toBool(${te(i.argument,n)})`});return}break}case"CallExpression":{let i=o;if(i.callee&&i.callee.type==="Identifier"&&i.callee.name==="Boolean"&&i.arguments.length===1&&i.arguments[0].type!=="SpreadElement"){t.push({start:i.start,end:i.end,newText:`__tjs.toBool(${te(i.arguments[0],n)})`});return}break}}Ii(o,s)}}return s(e),Bi(t)}function te(e,n){if(!e)return"";switch(e.type){case"LogicalExpression":{let t=e,r=te(t.left,n),s=te(t.right,n);return t.operator==="&&"?`((__tjs__t)=>__tjs.toBool(__tjs__t)?(${s}):__tjs__t)(${r})`:t.operator==="||"?`((__tjs__t)=>__tjs.toBool(__tjs__t)?__tjs__t:(${s}))(${r})`:`(${r})??(${s})`}case"ConditionalExpression":{let t=e;return`__tjs.toBool(${te(t.test,n)})?(${te(t.consequent,n)}):(${te(t.alternate,n)})`}case"UnaryExpression":{let t=e;return t.operator==="!"?`!__tjs.toBool(${te(t.argument,n)})`:_n(e,n)}case"CallExpression":{let t=e;return t.callee&&t.callee.type==="Identifier"&&t.callee.name==="Boolean"&&t.arguments.length===1&&t.arguments[0].type!=="SpreadElement"?`__tjs.toBool(${te(t.arguments[0],n)})`:_n(e,n)}}return _n(e,n)}function _n(e,n){let t=e.start,r=e.end;if(typeof t!="number"||typeof r!="number")return"";let s=Jr(e);if(s.length===0)return n.slice(t,r);s.sort((a,c)=>a.start-c.start);let o="",i=t;for(let a of s)a.start<i||(a.start>i&&(o+=n.slice(i,a.start)),o+=te(a,n),i=a.end);return i<r&&(o+=n.slice(i,r)),o}function Ii(e,n){for(let t of Jr(e))n(t)}function Jr(e){let n=[];for(let t in e){if(t==="type"||t==="start"||t==="end"||t==="loc")continue;let r=e[t];if(Array.isArray(r))for(let s of r)s&&typeof s=="object"&&typeof s.type=="string"&&n.push(s);else r&&typeof r=="object"&&typeof r.type=="string"&&n.push(r)}return n}function Bi(e){let n=[...e].sort((s,o)=>s.start-o.start||o.end-s.end),t=[],r=-1;for(let s of n)s.start>=r&&(t.push(s),r=s.end);return t}function wn(e){let n;try{n=Lr.parse(`function __wrap__(){${e}}`,{ecmaVersion:2022,sourceType:"module",locations:!1})}catch{return e}let t=`function __wrap__(){${e}}`,r=xn(n,t);if(r.length===0)return e;r.sort((a,c)=>c.start-a.start);let s=t;for(let a of r)s=s.slice(0,a.start)+a.newText+s.slice(a.end);return s.slice("function __wrap__(){".length,s.length-"}".length)}function Oi(e,n,t){if(!e||!n)return!1;let r=new RegExp(`function\\s+${n}\\s*\\([^)]*?\\b${t}\\s*([=:])`,"s"),s=e.match(r);return s?s[1]===":":!1}function Di(e,n,t,r,s){let o=[],i=Ve(n,e),a={},c=!1,l,f;if(e.params.length===1&&(e.params[0].type==="ObjectPattern"||e.params[0].type==="AssignmentPattern"&&e.params[0].left.type==="ObjectPattern")){c=!0;let m=e.params[0],y=m.type==="ObjectPattern"?m:m.left,h=ye(y,t);if(h.type.kind==="object"&&h.type.destructuredParams){l={},f=new Set;for(let[w,S]of Object.entries(h.type.destructuredParams))a[w]={...S,description:i.params[w]},l[w]=S.type,S.required&&f.add(w)}}else for(let m of e.params)if(m.type==="Identifier"){let y=ye(m,t);a[m.name]={...y,required:t.has(m.name),description:i.params[m.name]}}else if(m.type==="AssignmentPattern"&&m.left.type==="Identifier"){let y=ye(m,t),h=Oi(s||"",e.id?.name||"",m.left.name);a[m.left.name]={...y,required:h,default:h?null:y.example??y.default,description:i.params[m.left.name]}}else if(m.type==="ObjectPattern"){let y=ye(m,t);if(y.type.kind==="object"&&y.type.destructuredParams)for(let[h,w]of Object.entries(y.type.destructuredParams))a[h]={...w,description:i.params[h]}}else if(m.type==="RestElement"&&m.argument?.type==="Identifier"){let y=m.argument.name,h=n.match(new RegExp(`\\.\\.\\.${y}\\s*:\\s*([^)]+?)\\s*\\)`));if(h)try{let w=Vr(h[1].trim(),0,{ecmaVersion:2022}),S=Y(w);a[y]={name:y,type:S,required:!1,description:i.params[y]}}catch{a[y]={name:y,type:{kind:"array"},required:!1,description:i.params[y]}}else a[y]={name:y,type:{kind:"array"},required:!1,description:i.params[y]}}let p;if(r)try{let m=r.includes("=")?Zr(r):r,y=Vr(m,0,{ecmaVersion:2022});p=Y(y)}catch{p={kind:"any"},o.push(`Could not parse return type: ${r}`)}return{types:{name:e.id?.name||"anonymous",params:a,returns:p,description:i.description,isDestructuredParam:c,destructuredShape:l,destructuredRequired:f},warnings:o}}function Fi(e,n,t){let r=[],s=t?`${t}:`:"",o=t?`${t}:${e}`:e;if(n.isDestructuredParam&&n.destructuredShape){let a=n.destructuredShape,c=n.destructuredRequired||new Set,l=Object.keys(a);if(l.length===0)return null;for(let f of l)r.push(`if (${f} instanceof Error) return ${f};`);for(let[f,p]of Object.entries(a)){let u=c.has(f),m=`${s}${e}.${f}`,y=$t(f,p);if(y){let h=p.kind;u?r.push(`if (${y}) return __tjs.typeError('${m}', '${h}', ${f});`):r.push(`if (${f} !== undefined && ${y}) return __tjs.typeError('${m}', '${h}', ${f});`)}}return r.length===0?null:(r.unshift(`__tjs.pushStack('${o}');`),{preamble:r.join(`
|
|
339
|
+
`),suffix:"__tjs.popStack();"})}let i=Object.entries(n.params);if(i.length===0)return null;for(let[a]of i)r.push(`if (${a} instanceof Error) return ${a};`);for(let[a,c]of i){let l=`${s}${e}.${a}`;c.type.kind==="array"&&r.push(`if (Array.isArray(${a})) { for (const __i of ${a}) { if (__i instanceof Error && __i.path !== undefined) return __i } }`);let f=$t(a,c.type);if(f){let p=c.type.kind==="union"?c.type.members.map(u=>u.kind).join(" | "):c.type.kind;c.required?r.push(`if (${f}) return __tjs.typeError('${l}', '${p}', ${a});`):r.push(`if (${a} !== undefined && ${f}) return __tjs.typeError('${l}', '${p}', ${a});`)}if(c.type.kind==="function"){let p=zi(a,c.type,l);p&&(r.push(p),r.push(`if (${a} instanceof Error) return ${a};`))}}return r.length===0?null:(r.unshift(`__tjs.pushStack('${o}');`),{preamble:r.join(`
|
|
340
|
+
`),suffix:"__tjs.popStack();"})}function Zr(e){let n="",t=0;for(let r=0;r<e.length;r++){let s=e[r];if(s==="{"||s==="["||s==="(")t++,n+=s;else if(s==="}"||s==="]"||s===")")t--,n+=s;else if(s==="'"||s==='"'||s==="`"){for(n+=s,r++;r<e.length&&e[r]!==s;)e[r]==="\\"&&(n+=e[r++]),n+=e[r++];r<e.length&&(n+=e[r])}else t===1&&s==="="&&e[r-1]!=="!"&&e[r+1]!=="="?n+=":":n+=s}return n}function qi(e,n){let r=new RegExp(`function\\s+${n}\\s*\\([^)]*\\)\\s*(:[?!]?)\\s*`,"g").exec(e);if(!r)return null;let s=e.slice(r.index+r[0].length);return _t(s)}function Ui(e,n){let r=new RegExp(`function\\s+${n}\\s*\\([^)]*\\)\\s*:([?!]?)`,"g").exec(e);if(!r)return;let s=r[1];if(s==="?")return"safe";if(s==="!")return"unsafe"}function Wi(e){let n=e.match(/^\/\*\s*tjs\s*<-\s*([^*]+?)\s*\*\//);return n?n[1].trim():void 0}function Li(e,n){let t=new RegExp(`\\/\\*\\s*line\\s+(\\d+)\\s*\\*\\/\\s*(?:async\\s+)?function\\s+${n}\\s*\\(`,"m"),r=e.match(t);return r?parseInt(r[1],10):void 0}function St(e,n={}){let{filename:t="<source>",runTests:r=!0,debug:s=!1,resolvedImports:o={}}=n,i=[];e=Nt(e);let c=Wi(e)||t,{code:l,tests:f,mocks:p,testRunner:u}=Ot(e),{ast:m,originalSource:y,requiredParams:h,unsafeFunctions:w}=be(l,{filename:t,colonShorthand:!0,moduleLoader:n.moduleLoader}),S=Ji(m),$=ut(l,{moduleLoader:n.moduleLoader,filename:t});for(let v of f)v.body=Ue(v.body),$.tjsModes.tjsEquals&&(v.body=We(v.body)),$.tjsModes.tjsStandard&&(v.body=wn(v.body));for(let v of p)v.body=Ue(v.body),$.tjsModes.tjsEquals&&(v.body=We(v.body)),$.tjsModes.tjsStandard&&(v.body=wn(v.body));let b={},_=[],x=[];for(let v of S){let B=v.id?.name||"anonymous",P=qi(l,B),se;if(P&&P.includes("="))try{let z=P.matchAll(/(\w+)\s*=\s*/g),X=Zr(P),ue=new Function(`return ${X}`)(),ee={};for(let At of z){let Fe=At[1];Fe in ue&&(ee[Fe]=ue[Fe])}Object.keys(ee).length>0&&(se=ee)}catch{}let{types:le,warnings:Xr}=Di(v,y,h,P,l);i.push(...Xr),b[B]=le;for(let z of v.params)if(z.type==="AssignmentPattern"&&z.left.type==="Identifier"&&z.right.type==="Identifier"){let X=z.left.name,ue=z.right.name,ee=b[ue];if(ee&&le.params[X]){let At=Object.entries(ee.params).map(([ss,is])=>({name:ss,type:is.type})),Fe=ee.returns??{kind:"any"};le.params[X].type={kind:"function",params:At,returns:Fe}}}for(let z of v.params)if(z.type==="AssignmentPattern"){let X=z.left?.name||z.left?.value,ue=X?le.params[X]:null;if(ue?.required&&ue.default===null)x.push({start:z.left.end,end:z.right.end});else{let ee=z.right;ee.type==="BinaryExpression"&&ee.operator==="|"&&x.push({start:ee.left.end,end:ee.end})}}let jn=$.moduleSafety==="none"||w.has(B),es=$.safeFunctions.has(B),ts=Ui(l,B),ns=Li(e,B),Re={file:c,line:ns??v.loc?.start.line??0,column:v.loc?.start.column??0},rs={unsafe:jn,safe:es,returnSafety:ts},vn=$.polymorphicNames.has(B),vt;if(vn){let z=[];for(let ue of S){let ee=ue.id?.name||"";ee.startsWith(B+"$")&&z.push(ee)}let X={polymorphic:!0,variants:z};Re&&(X.source=`${Re.file}:${Re.line}`),vt=`${B}.__tjs = ${JSON.stringify(X,null,2)}`}else vt=Vi(B,le,rs,{debug:s,source:Re,returnDefaults:se});if(_.push({position:v.end,text:`
|
|
341
|
+
${vt}`}),!jn&&!vn){let z=`${Re.file}:${Re.line}`,X=Fi(B,le,z);X&&v.body&&v.body.start!==void 0&&(_.push({position:v.body.start+1,text:`
|
|
342
342
|
${X.preamble}
|
|
343
|
-
`}),X.suffix&&
|
|
343
|
+
`}),X.suffix&&_.push({position:v.body.end-1,text:`
|
|
344
344
|
${X.suffix}
|
|
345
|
-
`}))}}if(
|
|
345
|
+
`}))}}if($.tjsModes.tjsStandard){let v=xn(m,$.source);for(let B of v)x.push({start:B.start,end:B.end}),_.push({position:B.start,text:B.newText})}x.sort((v,B)=>B.start-v.start);let g=$.source;for(let{start:v,end:B}of x)g=g.slice(0,v)+g.slice(B);for(let v of _){let B=0;for(let P of x)P.start<v.position&&(B+=P.end-P.start);v.position-=B}_.sort((v,B)=>B.position-v.position);for(let{position:v,text:B}of _)g=g.slice(0,v)+B+g.slice(v);let E=g.includes("__tjs.typeError("),k=g.includes("__tjs.pushStack("),j=g.includes("Is("),A=g.includes("IsNot("),M=g.includes("Eq("),N=g.includes("NotEq("),R=g.includes("TypeOf("),I=/\bType\(/.test(g),O=/\bGeneric\(/.test(g),L=/\bFunctionPredicate\(/.test(g),V=/\bEnum\(/.test(g),Q=/\bUnion\(/.test(g),Ae=g.includes("__tjs.bang("),rt=g.includes("__tjs.toBool("),jt=g.includes("__tjs.checkFnShape("),Tn=$.tjsModes.tjsSafeEval;if(E||k||j||A||M||N||R||I||O||L||V||Q||Ae||rt||jt||Tn){let v=[];E&&v.push("class MonadicError extends Error{constructor(m,p,e,a,c,r){super(m);this.name='MonadicError';this.path=p;this.expected=e;this.actual=a;this.callStack=c;this.reason=r}}",`function typeError(p,e,v,r){const a=v===null?'null':typeof v;const m=r?'Expected '+e+" for '"+p+"': "+r:'Expected '+e+" for '"+p+"', got "+a;const err=new MonadicError(m,p,e,a,undefined,r);const c=globalThis.__tjs?.getConfig?.();if(c?.logTypeErrors)console.error('[TJS TypeError] '+err.message);if(c?.throwTypeErrors)throw err;return err}`,"function isMonadicError(v){return v instanceof Error&&v.name==='MonadicError'&&'path' in v}"),k&&v.push("const __stack=[];function pushStack(n){__stack.push(n)}function popStack(){__stack.pop()}function getStack(){return[...__stack]}"),M&&v.push("function Eq(a,b){if(a instanceof String||a instanceof Number||a instanceof Boolean)a=a.valueOf();if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();if(a===b)return true;if(typeof a==='number'&&typeof b==='number'&&isNaN(a)&&isNaN(b))return true;if((a===null||a===undefined)&&(b===null||b===undefined))return true;return false}"),N&&v.push("function NotEq(a,b){return!Eq(a,b)}"),R&&v.push("function TypeOf(v){return v===null?'null':typeof v}"),j&&v.push("const tjsEquals=Symbol.for('tjs.equals');function Is(a,b){if(a!=null&&typeof a==='object'&&typeof a[tjsEquals]==='function')return a[tjsEquals](b);if(b!=null&&typeof b==='object'&&typeof b[tjsEquals]==='function')return b[tjsEquals](a);if(a!=null&&typeof a==='object'&&typeof a.Equals==='function')return a.Equals(b);if(b!=null&&typeof b==='object'&&typeof b.Equals==='function')return b.Equals(a);if(a instanceof String||a instanceof Number||a instanceof Boolean)a=a.valueOf();if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();if(a===b)return true;if(typeof a==='number'&&typeof b==='number'&&isNaN(a)&&isNaN(b))return true;if((a==null)&&(b==null))return true;if(a==null||b==null)return false;if(typeof a!==typeof b)return false;if(typeof a!=='object')return false;if(a instanceof Set&&b instanceof Set){if(a.size!==b.size)return false;for(const v of a)if(!b.has(v))return false;return true}if(a instanceof Map&&b instanceof Map){if(a.size!==b.size)return false;for(const[k,v]of a)if(!b.has(k)||!Is(v,b.get(k)))return false;return true}if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.toString()===b.toString();if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return false;return a.every((v,i)=>Is(v,b[i]))}if(Array.isArray(a)!==Array.isArray(b))return false;const ka=Object.keys(a),kb=Object.keys(b);if(ka.length!==kb.length)return false;return ka.every(k=>Is(a[k],b[k]))}"),A&&v.push("function IsNot(a,b){return!Is(a,b)}"),I&&v.push("function Type(d,p,e){const t={description:d,__runtimeType:true};if(typeof p==='function'){t.check=p;t.default=e??null}else{const ex=e??p;t.default=ex;t.check=v=>{if(ex===null)return true;return typeof v===typeof ex}}return t}"),O&&v.push("function Generic(tp,pred,d){const f=(...args)=>{const t={description:d||'generic',__runtimeType:true,check:v=>pred(v,...args)};return t};f.__runtimeType=true;f.description=d;return f}"),L&&v.push("function FunctionPredicate(n,s,b){if(Array.isArray(s)&&b){const f=(...a)=>FunctionPredicate(n,b(...a));f.typeParamNames=s.map(p=>Array.isArray(p)?p[0]:p);f.description=n;f.__runtimeType=true;return f}const spec=typeof s==='function'?{}:s||{};return{description:n,params:spec.params||{},returns:spec.returns,returnContract:spec.returnContract||'assertReturns',check:v=>typeof v==='function',__runtimeType:true}}"),V&&v.push("function Enum(d,m){const vals=typeof m==='object'?Object.values(m):[];return{description:d,check:v=>vals.includes(v),values:vals,__runtimeType:true}}"),Q&&v.push("function Union(d,...v){const vals=v.flat();return{description:d,check:x=>vals.includes(x),values:vals,__runtimeType:true}}"),rt&&v.push("function toBool(v){if(v instanceof Boolean||v instanceof Number||v instanceof String)return Boolean(v.valueOf());return Boolean(v)}"),jt&&(E||v.push("class MonadicError extends Error{constructor(m,p,e,a,c,r){super(m);this.name='MonadicError';this.path=p;this.expected=e;this.actual=a;this.callStack=c;this.reason=r}}",`function typeError(p,e,v,r){const a=v===null?'null':typeof v;const m=r?'Expected '+e+" for '"+p+"': "+r:'Expected '+e+" for '"+p+"', got "+a;const err=new MonadicError(m,p,e,a,undefined,r);const c=globalThis.__tjs?.getConfig?.();if(c?.logTypeErrors)console.error('[TJS TypeError] '+err.message);if(c?.throwTypeErrors)throw err;return err}`,"function isMonadicError(v){return v instanceof Error&&v.name==='MonadicError'&&'path' in v}"),v.push(`function checkFnShape(fn,expectedParams,expectedReturn,path){if(typeof fn!=='function')return fn;const meta=fn.__tjs;if(!meta||!meta.params)return fn;const entries=Object.entries(meta.params);for(let i=0;i<expectedParams.length;i++){const e=expectedParams[i];if(e==='any')continue;const a=entries[i];if(!a)continue;const ak=a[1]&&a[1].type&&a[1].type.kind;if(!ak||ak==='any')continue;if(ak!==e)return new MonadicError("Expected (...arg"+i+": "+e+", ...) for '"+path+"', but callback declares arg"+i+" as "+ak,path+"(arg"+i+")",e,ak)}if(expectedReturn!=='any'&&meta.returns){const ar=(meta.returns.type&&meta.returns.type.kind)||meta.returns.kind;if(ar&&ar!=='any'&&ar!==expectedReturn)return new MonadicError("Expected callback returning "+expectedReturn+" for '"+path+"', but callback returns "+ar,path+"(return)",expectedReturn,ar)}return fn}`)),Ae&&(E||v.push("class MonadicError extends Error{constructor(m,p,e,a,c,r){super(m);this.name='MonadicError';this.path=p;this.expected=e;this.actual=a;this.callStack=c;this.reason=r}}",`function typeError(p,e,v,r){const a=v===null?'null':typeof v;const m=r?'Expected '+e+" for '"+p+"': "+r:'Expected '+e+" for '"+p+"', got "+a;const err=new MonadicError(m,p,e,a,undefined,r);const c=globalThis.__tjs?.getConfig?.();if(c?.logTypeErrors)console.error('[TJS TypeError] '+err.message);if(c?.throwTypeErrors)throw err;return err}`,"function isMonadicError(v){return v instanceof Error&&v.name==='MonadicError'&&'path' in v}"),v.push("function bang(o,p){if(o===null||o===undefined)return typeError('bang.'+p,'non-null',o);if(isMonadicError(o))return o;return o[p]}"));let B=v.length>0?v.join(`;
|
|
346
346
|
`)+`;
|
|
347
|
-
`:"",
|
|
348
|
-
`+
|
|
349
|
-
`+
|
|
347
|
+
`:"",P=[];E&&P.push("typeError","isMonadicError"),k&&P.push("pushStack","popStack","getStack"),M&&P.push("Eq"),N&&P.push("NotEq"),R&&P.push("TypeOf"),j&&P.push("Is","tjsEquals"),A&&P.push("IsNot"),I&&P.push("Type"),O&&P.push("Generic"),L&&P.push("FunctionPredicate"),V&&P.push("Enum"),Q&&P.push("Union"),rt&&P.push("toBool"),jt&&(P.push("checkFnShape"),E||P.push("typeError","isMonadicError")),Ae&&(P.push("bang"),E||P.push("typeError","isMonadicError"));let se=P.length>0?`{${P.join(",")}}`:"undefined";g=B+`const __tjs = globalThis.__tjs?.createRuntime?.() ?? ${se};
|
|
348
|
+
`+g}Tn&&(g=`import { Eval, SafeFunction } from 'tjs-lang';
|
|
349
|
+
`+g);let De;if(r){let v=Br(e);De=Or(f,p,v,g,o,$.extensions);let B=De.filter(P=>!P.passed);if(B.length>0&&r===!0){let P=B.map(se=>{if(se.isSignatureTest)return` Function signature example is inconsistent:
|
|
350
350
|
${se.error}`;let le=se.line?` (line ${se.line})`:"";return` Test '${se.description}'${le} failed:
|
|
351
351
|
${se.error}`});throw new Error(`Transpile-time test failures:
|
|
352
|
-
${
|
|
353
|
-
`)}`)}}if(r==="only")return{code:"",types:
|
|
354
|
-
`+x),vt=v.results}return{code:x,types:h,metadata:h,warnings:i.length>0?i:void 0,testRunner:p.length>0?u:void 0,testCount:p.length>0?p.length:void 0,testResults:De,wasmCompiled:vt}}function Pi(e){let n=[];for(let t of e.body)t.type==="FunctionDeclaration"?n.push(t):(t.type==="ExportNamedDeclaration"&&t.declaration?.type==="FunctionDeclaration"||t.type==="ExportDefaultDeclaration"&&t.declaration?.type==="FunctionDeclaration")&&n.push(t.declaration);return n}function nt(e){let n={kind:e.kind};return e.nullable&&(n.nullable=!0),e.items&&(n.items=nt(e.items)),e.shape&&(n.shape=Object.fromEntries(Object.entries(e.shape).map(([t,r])=>[t,nt(r)]))),e.members&&(n.members=e.members.map(nt)),n}function Ii(e,n,t={},r={}){let s={};for(let[i,a]of Object.entries(n.params))s[i]={type:nt(a.type),required:a.required},a.default!==void 0&&(s[i].default=a.default),a.description&&(s[i].description=a.description);let o={params:s};if(n.returns&&(o.returns={type:nt(n.returns)},r.returnDefaults&&(o.returns.defaults=r.returnDefaults),t.returnSafety==="safe"?o.safeReturn=!0:t.returnSafety==="unsafe"&&(o.unsafeReturn=!0)),n.description&&(o.description=n.description),t.unsafe&&(o.unsafe=!0),t.safe&&(o.safe=!0),r.source){let{file:i,line:a}=r.source;o.source=`${i}:${a}`}return`${e}.__tjs = ${JSON.stringify(o,null,2)}`}function St(e,n){let t;switch(n.kind){case"string":t=`typeof ${e} !== 'string'`;break;case"number":t=`typeof ${e} !== 'number'`;break;case"integer":t=`(typeof ${e} !== 'number' || !Number.isInteger(${e}))`;break;case"non-negative-integer":t=`(typeof ${e} !== 'number' || !Number.isInteger(${e}) || ${e} < 0)`;break;case"boolean":t=`typeof ${e} !== 'boolean'`;break;case"null":return`${e} !== null`;case"undefined":return`${e} !== undefined`;case"array":{let r=n.items&&n.items.kind!=="any"?St("__a",n.items):null;r?t=`(!Array.isArray(${e}) || ${e}.some(__a => ${r}))`:t=`!Array.isArray(${e})`;break}case"object":t=`(typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e}))`;break;case"function":t=`typeof ${e} !== 'function'`;break;case"union":{let r=n.members.map(s=>St(e,s)).filter(s=>s!==null);if(r.length===0)return null;t=`(${r.join(" && ")})`;break}case"any":return null;default:return null}return t&&n.nullable&&(t=`(${e} !== null && ${t})`),t}var Wr=new Set(["string","number","integer","non-negative-integer","boolean","function","any","undefined","null","object"]);function Oi(e,n,t){let r=n.params??[],s=n.returns??{kind:"any"},o=r.map(l=>l.type?.kind),i=o.every(l=>l&&Wr.has(l))&&Wr.has(s.kind),a=o.some(l=>l!=="any")||s.kind!=="any";if(!i||!a)return null;let c=JSON.stringify(o);return`if (typeof ${e} === 'function') ${e} = __tjs.checkFnShape(${e}, ${c}, '${s.kind}', '${t}');`}function Tt(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=be(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),i=sr(t,n.filename),{ast:a,signature:c,warnings:l}=Ot(i,s,r,n,o);return{ast:a,signature:c,warnings:l}}function Bi(e,...n){if(typeof e=="string")return Tt(e).ast;let t=e.reduce((r,s,o)=>r+s+(n[o]!==void 0?String(n[o]):""),"");return Tt(t).ast}function Di(e,n,t){let{ast:r,signature:s}=Tt(e),o=async i=>(await n.run(r,i,t)).result;return o.signature=s,o.ast=r,o}function Et(e){switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"array":return{type:"array",items:e.items?Et(e.items):{}};case"object":return e.shape?{type:"object",properties:Object.fromEntries(Object.entries(e.shape).map(([n,t])=>[n,Et(t)]))}:{type:"object"};case"union":return e.members?{anyOf:e.members.map(Et)}:{};default:return{}}}function Fi(e){return Object.entries(e).map(([n,t])=>{let r=t.signature,s={},o=[];for(let[i,a]of Object.entries(r.parameters))s[i]=Et(a.type),a.description&&(s[i].description=a.description),a.required&&o.push(i);return{type:"function",function:{name:n,description:r.description,parameters:{type:"object",properties:s,required:o}}}})}function qi(e,n,...t){if(typeof e=="string")return $t(e,n);let r=n!==void 0?[n,...t]:t,s=e.reduce((o,i,a)=>o+i+(r[a]!==void 0?String(r[a]):""),"");return $t(s)}import{s as Vr}from"tosijs-schema";function zr(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}function kt(e){return Vr.infer(e)}function $n(e){return kt(e)}$n.type=zr;$n.infer=kt;var Ui=new Proxy($n,{get(e,n){return n==="type"?zr:n==="infer"?kt:Vr[n]},apply(e,n,t){return kt(t[0])}});function je(e,n,t,r,s){t||(t=T),(function o(i,a,c){var l=c||i.type;t[l](i,a,o),n[l]&&n[l](i,a)})(e,r,s)}function Zr(e,n,t,r,s){var o=[];t||(t=T),(function i(a,c,l){var p=l||a.type,f=a!==o[o.length-1];f&&o.push(a),t[p](a,c,i),n[p]&&n[p](a,c||o,o),f&&o.pop()})(e,r,s)}function En(e,n,t){t(e,n)}function ve(e,n,t){}var T={};T.Program=T.BlockStatement=T.StaticBlock=function(e,n,t){for(var r=0,s=e.body;r<s.length;r+=1){var o=s[r];t(o,n,"Statement")}};T.Statement=En;T.EmptyStatement=ve;T.ExpressionStatement=T.ParenthesizedExpression=T.ChainExpression=function(e,n,t){return t(e.expression,n,"Expression")};T.IfStatement=function(e,n,t){t(e.test,n,"Expression"),t(e.consequent,n,"Statement"),e.alternate&&t(e.alternate,n,"Statement")};T.LabeledStatement=function(e,n,t){return t(e.body,n,"Statement")};T.BreakStatement=T.ContinueStatement=ve;T.WithStatement=function(e,n,t){t(e.object,n,"Expression"),t(e.body,n,"Statement")};T.SwitchStatement=function(e,n,t){t(e.discriminant,n,"Expression");for(var r=0,s=e.cases;r<s.length;r+=1){var o=s[r];t(o,n)}};T.SwitchCase=function(e,n,t){e.test&&t(e.test,n,"Expression");for(var r=0,s=e.consequent;r<s.length;r+=1){var o=s[r];t(o,n,"Statement")}};T.ReturnStatement=T.YieldExpression=T.AwaitExpression=function(e,n,t){e.argument&&t(e.argument,n,"Expression")};T.ThrowStatement=T.SpreadElement=function(e,n,t){return t(e.argument,n,"Expression")};T.TryStatement=function(e,n,t){t(e.block,n,"Statement"),e.handler&&t(e.handler,n),e.finalizer&&t(e.finalizer,n,"Statement")};T.CatchClause=function(e,n,t){e.param&&t(e.param,n,"Pattern"),t(e.body,n,"Statement")};T.WhileStatement=T.DoWhileStatement=function(e,n,t){t(e.test,n,"Expression"),t(e.body,n,"Statement")};T.ForStatement=function(e,n,t){e.init&&t(e.init,n,"ForInit"),e.test&&t(e.test,n,"Expression"),e.update&&t(e.update,n,"Expression"),t(e.body,n,"Statement")};T.ForInStatement=T.ForOfStatement=function(e,n,t){t(e.left,n,"ForInit"),t(e.right,n,"Expression"),t(e.body,n,"Statement")};T.ForInit=function(e,n,t){e.type==="VariableDeclaration"?t(e,n):t(e,n,"Expression")};T.DebuggerStatement=ve;T.FunctionDeclaration=function(e,n,t){return t(e,n,"Function")};T.VariableDeclaration=function(e,n,t){for(var r=0,s=e.declarations;r<s.length;r+=1){var o=s[r];t(o,n)}};T.VariableDeclarator=function(e,n,t){t(e.id,n,"Pattern"),e.init&&t(e.init,n,"Expression")};T.Function=function(e,n,t){e.id&&t(e.id,n,"Pattern");for(var r=0,s=e.params;r<s.length;r+=1){var o=s[r];t(o,n,"Pattern")}t(e.body,n,e.expression?"Expression":"Statement")};T.Pattern=function(e,n,t){e.type==="Identifier"?t(e,n,"VariablePattern"):e.type==="MemberExpression"?t(e,n,"MemberPattern"):t(e,n)};T.VariablePattern=ve;T.MemberPattern=En;T.RestElement=function(e,n,t){return t(e.argument,n,"Pattern")};T.ArrayPattern=function(e,n,t){for(var r=0,s=e.elements;r<s.length;r+=1){var o=s[r];o&&t(o,n,"Pattern")}};T.ObjectPattern=function(e,n,t){for(var r=0,s=e.properties;r<s.length;r+=1){var o=s[r];o.type==="Property"?(o.computed&&t(o.key,n,"Expression"),t(o.value,n,"Pattern")):o.type==="RestElement"&&t(o.argument,n,"Pattern")}};T.Expression=En;T.ThisExpression=T.Super=T.MetaProperty=ve;T.ArrayExpression=function(e,n,t){for(var r=0,s=e.elements;r<s.length;r+=1){var o=s[r];o&&t(o,n,"Expression")}};T.ObjectExpression=function(e,n,t){for(var r=0,s=e.properties;r<s.length;r+=1){var o=s[r];t(o,n)}};T.FunctionExpression=T.ArrowFunctionExpression=T.FunctionDeclaration;T.SequenceExpression=function(e,n,t){for(var r=0,s=e.expressions;r<s.length;r+=1){var o=s[r];t(o,n,"Expression")}};T.TemplateLiteral=function(e,n,t){for(var r=0,s=e.quasis;r<s.length;r+=1){var o=s[r];t(o,n)}for(var i=0,a=e.expressions;i<a.length;i+=1){var c=a[i];t(c,n,"Expression")}};T.TemplateElement=ve;T.UnaryExpression=T.UpdateExpression=function(e,n,t){t(e.argument,n,"Expression")};T.BinaryExpression=T.LogicalExpression=function(e,n,t){t(e.left,n,"Expression"),t(e.right,n,"Expression")};T.AssignmentExpression=T.AssignmentPattern=function(e,n,t){t(e.left,n,"Pattern"),t(e.right,n,"Expression")};T.ConditionalExpression=function(e,n,t){t(e.test,n,"Expression"),t(e.consequent,n,"Expression"),t(e.alternate,n,"Expression")};T.NewExpression=T.CallExpression=function(e,n,t){if(t(e.callee,n,"Expression"),e.arguments)for(var r=0,s=e.arguments;r<s.length;r+=1){var o=s[r];t(o,n,"Expression")}};T.MemberExpression=function(e,n,t){t(e.object,n,"Expression"),e.computed&&t(e.property,n,"Expression")};T.ExportNamedDeclaration=T.ExportDefaultDeclaration=function(e,n,t){e.declaration&&t(e.declaration,n,e.type==="ExportNamedDeclaration"||e.declaration.id?"Statement":"Expression"),e.source&&t(e.source,n,"Expression")};T.ExportAllDeclaration=function(e,n,t){e.exported&&t(e.exported,n),t(e.source,n,"Expression")};T.ImportDeclaration=function(e,n,t){for(var r=0,s=e.specifiers;r<s.length;r+=1){var o=s[r];t(o,n)}t(e.source,n,"Expression")};T.ImportExpression=function(e,n,t){t(e.source,n,"Expression")};T.ImportSpecifier=T.ImportDefaultSpecifier=T.ImportNamespaceSpecifier=T.Identifier=T.PrivateIdentifier=T.Literal=ve;T.TaggedTemplateExpression=function(e,n,t){t(e.tag,n,"Expression"),t(e.quasi,n,"Expression")};T.ClassDeclaration=T.ClassExpression=function(e,n,t){return t(e,n,"Class")};T.Class=function(e,n,t){e.id&&t(e.id,n,"Pattern"),e.superClass&&t(e.superClass,n,"Expression"),t(e.body,n)};T.ClassBody=function(e,n,t){for(var r=0,s=e.body;r<s.length;r+=1){var o=s[r];t(o,n)}};T.MethodDefinition=T.PropertyDefinition=T.Property=function(e,n,t){e.computed&&t(e.key,n,"Expression"),e.value&&t(e.value,n,"Expression")};var Wi={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function Ji(e,n={}){let t={...Wi,...n},r=[],s,o=new Map,i=!1;try{let p=be(e,{filename:t.filename,colonShorthand:!0});s=p.ast,o=p.letAnnotations,i=p.tjsModes.tjsSafeAssign}catch(p){return{diagnostics:[{severity:"error",message:p.message,line:p.loc?.line,column:p.loc?.column,rule:"parse-error"}],valid:!1}}let a=t.safeAssign!==void 0?t.safeAssign:i,c=t.strict?"error":"warning",l=[Gr()];if(Zr(s,{FunctionDeclaration(p,f,u){let m=Gr();l.push(m);for(let y of p.params)Vi(m,y,"parameter");p.id&&(l[l.length-2]||l[0]).declarations.set(p.id.name,{node:p.id,kind:"function",used:!1})},VariableDeclaration(p){let f=l[l.length-1];for(let u of p.declarations)u.id.type==="Identifier"&&f.declarations.set(u.id.name,{node:u.id,kind:p.kind,used:!1})}}),je(s,{Identifier(p){for(let f=l.length-1;f>=0;f--){let u=l[f].declarations.get(p.name);if(u){u.used=!0;break}}}}),t.unusedVariables)for(let p of l)for(let[f,u]of p.declarations)f.startsWith("_")||!u.used&&u.kind!=="function"&&r.push({severity:"warning",message:`'${f}' is declared but never used`,line:u.node.loc?.start?.line,column:u.node.loc?.start?.column,rule:"no-unused-vars"});if(t.unreachableCode&&je(s,{BlockStatement(p){let f=!1;for(let u of p.body){if(f){r.push({severity:"warning",message:"Unreachable code after return statement",line:u.loc?.start?.line,column:u.loc?.start?.column,rule:"no-unreachable"});break}u.type==="ReturnStatement"&&(f=!0)}}}),a){let p=new Set;je(s,{VariableDeclaration(f){if(f.kind==="let")for(let u of f.declarations){if(u.id.type!=="Identifier")continue;let m=u.id.name,y=o.has(m),g=u.init;(y||g&&!Tn(g))&&p.add(m)}}}),je(s,{VariableDeclaration(f){if(f.kind==="let")for(let u of f.declarations){if(u.id.type!=="Identifier")continue;let m=u.id.name;o.has(m)||(u.init?Tn(u.init)&&r.push({severity:c,message:`'let ${m}' is initialized to ${Kr(u.init)} with no type annotation. Annotate (let ${m}: <example>) to record the intended type.`,line:u.loc?.start?.line,column:u.loc?.start?.column,rule:"safe-assign-let-needs-type"}):r.push({severity:c,message:`'let ${m}' has no initializer or type annotation. Add an initializer (let ${m} = ...) or annotate (let ${m}: <example>).`,line:u.loc?.start?.line,column:u.loc?.start?.column,rule:"safe-assign-let-needs-type"}))}}}),je(s,{AssignmentExpression(f){if(f.operator!=="="||f.left.type!=="Identifier")return;let u=f.left.name;p.has(u)&&Tn(f.right)&&r.push({severity:c,message:`Cannot assign ${Kr(f.right)} to typed let '${u}'.`,line:f.loc?.start?.line,column:f.loc?.start?.column,rule:"safe-assign-no-nullish"})}})}return t.noExplicitNew&&je(s,{NewExpression(p){let f="class";p.callee.type==="Identifier"?f=p.callee.name:p.callee.type==="MemberExpression"&&p.callee.property.type==="Identifier"&&(f=p.callee.property.name),r.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${f}(...) instead of new ${f}(...)`,line:p.loc?.start?.line,column:p.loc?.start?.column,rule:"no-explicit-new"})}}),{diagnostics:r,valid:r.filter(p=>p.severity==="error").length===0}}function Gr(){return{declarations:new Map}}function Tn(e){return e?e.type==="Identifier"&&e.name==="undefined"||e.type==="Literal"&&e.value===null||e.type==="UnaryExpression"&&e.operator==="void":!1}function Kr(e){return e.type==="Identifier"?"undefined":e.type==="Literal"&&e.value===null?"null":e.type==="UnaryExpression"&&e.operator==="void"?"void <expr> (undefined)":"a nullish value"}function Vi(e,n,t){n.type==="Identifier"?e.declarations.set(n.name,{node:n,kind:t,used:!1}):n.type==="AssignmentPattern"&&n.left.type==="Identifier"&&e.declarations.set(n.left.name,{node:n.left,kind:t,used:!1})}export{Ui as Schema,fe as TJS_VERSION,Bi as ajs,ur as assertFunction,Ee as checkType,Di as createAgent,ni as emitRuntimeWrapper,ce as error,fr as expectFunction,oe as extractLiteralValue,Ve as extractTDoc,Dt as extractTests,Fi as getToolDefinitions,Y as inferTypeFromValue,mn as installRuntime,pe as isError,Ji as lint,be as parse,ye as parseParameter,ir as parseReturnType,ut as preprocess,we as runtime,Ds as testUtils,qi as tjs,Ot as transformFunction,Tt as transpile,$t as transpileToJS,Ie as typeOf,It as typeToString,fn as validateArgs,pn as wrap};
|
|
352
|
+
${P.join(`
|
|
353
|
+
`)}`)}}if(r==="only")return{code:"",types:b,metadata:b,testResults:De,testCount:De?.length};let kn;if($.wasmBlocks.length>0){let v=Wr($.wasmBlocks);v.code&&(g=v.code+`
|
|
354
|
+
`+g),kn=v.results}return{code:g,types:b,metadata:b,warnings:i.length>0?i:void 0,testRunner:f.length>0?u:void 0,testCount:f.length>0?f.length:void 0,testResults:De,wasmCompiled:kn}}function Ji(e){let n=[];for(let t of e.body)t.type==="FunctionDeclaration"?n.push(t):(t.type==="ExportNamedDeclaration"&&t.declaration?.type==="FunctionDeclaration"||t.type==="ExportDefaultDeclaration"&&t.declaration?.type==="FunctionDeclaration")&&n.push(t.declaration);return n}function nt(e){let n={kind:e.kind};return e.nullable&&(n.nullable=!0),e.items&&(n.items=nt(e.items)),e.shape&&(n.shape=Object.fromEntries(Object.entries(e.shape).map(([t,r])=>[t,nt(r)]))),e.members&&(n.members=e.members.map(nt)),n}function Vi(e,n,t={},r={}){let s={};for(let[i,a]of Object.entries(n.params))s[i]={type:nt(a.type),required:a.required},a.default!==void 0&&(s[i].default=a.default),a.description&&(s[i].description=a.description);let o={params:s};if(n.returns&&(o.returns={type:nt(n.returns)},r.returnDefaults&&(o.returns.defaults=r.returnDefaults),t.returnSafety==="safe"?o.safeReturn=!0:t.returnSafety==="unsafe"&&(o.unsafeReturn=!0)),n.description&&(o.description=n.description),t.unsafe&&(o.unsafe=!0),t.safe&&(o.safe=!0),r.source){let{file:i,line:a}=r.source;o.source=`${i}:${a}`}return`${e}.__tjs = ${JSON.stringify(o,null,2)}`}function $t(e,n){let t;switch(n.kind){case"string":t=`typeof ${e} !== 'string'`;break;case"number":t=`typeof ${e} !== 'number'`;break;case"integer":t=`(typeof ${e} !== 'number' || !Number.isInteger(${e}))`;break;case"non-negative-integer":t=`(typeof ${e} !== 'number' || !Number.isInteger(${e}) || ${e} < 0)`;break;case"boolean":t=`typeof ${e} !== 'boolean'`;break;case"null":return`${e} !== null`;case"undefined":return`${e} !== undefined`;case"array":{let r=n.items&&n.items.kind!=="any"?$t("__a",n.items):null;r?t=`(!Array.isArray(${e}) || ${e}.some(__a => ${r}))`:t=`!Array.isArray(${e})`;break}case"object":t=`(typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e}))`;break;case"function":t=`typeof ${e} !== 'function'`;break;case"union":{let r=n.members.map(s=>$t(e,s)).filter(s=>s!==null);if(r.length===0)return null;t=`(${r.join(" && ")})`;break}case"any":return null;default:return null}return t&&n.nullable&&(t=`(${e} !== null && ${t})`),t}var zr=new Set(["string","number","integer","non-negative-integer","boolean","function","any","undefined","null","object"]);function zi(e,n,t){let r=n.params??[],s=n.returns??{kind:"any"},o=r.map(l=>l.type?.kind),i=o.every(l=>l&&zr.has(l))&&zr.has(s.kind),a=o.some(l=>l!=="any")||s.kind!=="any";if(!i||!a)return null;let c=JSON.stringify(o);return`if (typeof ${e} === 'function') ${e} = __tjs.checkFnShape(${e}, ${c}, '${s.kind}', '${t}');`}function Tt(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=be(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),i=or(t,n.filename),{ast:a,signature:c,warnings:l}=It(i,s,r,n,o);return{ast:a,signature:c,warnings:l}}function Zi(e,...n){if(typeof e=="string")return Tt(e).ast;let t=e.reduce((r,s,o)=>r+s+(n[o]!==void 0?String(n[o]):""),"");return Tt(t).ast}function Gi(e,n,t){let{ast:r,signature:s}=Tt(e),o=async i=>(await n.run(r,i,t)).result;return o.signature=s,o.ast=r,o}function Et(e){switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"array":return{type:"array",items:e.items?Et(e.items):{}};case"object":return e.shape?{type:"object",properties:Object.fromEntries(Object.entries(e.shape).map(([n,t])=>[n,Et(t)]))}:{type:"object"};case"union":return e.members?{anyOf:e.members.map(Et)}:{};default:return{}}}function Ki(e){return Object.entries(e).map(([n,t])=>{let r=t.signature,s={},o=[];for(let[i,a]of Object.entries(r.parameters))s[i]=Et(a.type),a.description&&(s[i].description=a.description),a.required&&o.push(i);return{type:"function",function:{name:n,description:r.description,parameters:{type:"object",properties:s,required:o}}}})}function Yi(e,n,...t){if(typeof e=="string")return St(e,n);let r=n!==void 0?[n,...t]:t,s=e.reduce((o,i,a)=>o+i+(r[a]!==void 0?String(r[a]):""),"");return St(s)}import{s as Gr}from"tosijs-schema";function Kr(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}function kt(e){return Gr.infer(e)}function $n(e){return kt(e)}$n.type=Kr;$n.infer=kt;var Hi=new Proxy($n,{get(e,n){return n==="type"?Kr:n==="infer"?kt:Gr[n]},apply(e,n,t){return kt(t[0])}});function je(e,n,t,r,s){t||(t=T),(function o(i,a,c){var l=c||i.type;t[l](i,a,o),n[l]&&n[l](i,a)})(e,r,s)}function Yr(e,n,t,r,s){var o=[];t||(t=T),(function i(a,c,l){var f=l||a.type,p=a!==o[o.length-1];p&&o.push(a),t[f](a,c,i),n[f]&&n[f](a,c||o,o),p&&o.pop()})(e,r,s)}function Sn(e,n,t){t(e,n)}function ve(e,n,t){}var T={};T.Program=T.BlockStatement=T.StaticBlock=function(e,n,t){for(var r=0,s=e.body;r<s.length;r+=1){var o=s[r];t(o,n,"Statement")}};T.Statement=Sn;T.EmptyStatement=ve;T.ExpressionStatement=T.ParenthesizedExpression=T.ChainExpression=function(e,n,t){return t(e.expression,n,"Expression")};T.IfStatement=function(e,n,t){t(e.test,n,"Expression"),t(e.consequent,n,"Statement"),e.alternate&&t(e.alternate,n,"Statement")};T.LabeledStatement=function(e,n,t){return t(e.body,n,"Statement")};T.BreakStatement=T.ContinueStatement=ve;T.WithStatement=function(e,n,t){t(e.object,n,"Expression"),t(e.body,n,"Statement")};T.SwitchStatement=function(e,n,t){t(e.discriminant,n,"Expression");for(var r=0,s=e.cases;r<s.length;r+=1){var o=s[r];t(o,n)}};T.SwitchCase=function(e,n,t){e.test&&t(e.test,n,"Expression");for(var r=0,s=e.consequent;r<s.length;r+=1){var o=s[r];t(o,n,"Statement")}};T.ReturnStatement=T.YieldExpression=T.AwaitExpression=function(e,n,t){e.argument&&t(e.argument,n,"Expression")};T.ThrowStatement=T.SpreadElement=function(e,n,t){return t(e.argument,n,"Expression")};T.TryStatement=function(e,n,t){t(e.block,n,"Statement"),e.handler&&t(e.handler,n),e.finalizer&&t(e.finalizer,n,"Statement")};T.CatchClause=function(e,n,t){e.param&&t(e.param,n,"Pattern"),t(e.body,n,"Statement")};T.WhileStatement=T.DoWhileStatement=function(e,n,t){t(e.test,n,"Expression"),t(e.body,n,"Statement")};T.ForStatement=function(e,n,t){e.init&&t(e.init,n,"ForInit"),e.test&&t(e.test,n,"Expression"),e.update&&t(e.update,n,"Expression"),t(e.body,n,"Statement")};T.ForInStatement=T.ForOfStatement=function(e,n,t){t(e.left,n,"ForInit"),t(e.right,n,"Expression"),t(e.body,n,"Statement")};T.ForInit=function(e,n,t){e.type==="VariableDeclaration"?t(e,n):t(e,n,"Expression")};T.DebuggerStatement=ve;T.FunctionDeclaration=function(e,n,t){return t(e,n,"Function")};T.VariableDeclaration=function(e,n,t){for(var r=0,s=e.declarations;r<s.length;r+=1){var o=s[r];t(o,n)}};T.VariableDeclarator=function(e,n,t){t(e.id,n,"Pattern"),e.init&&t(e.init,n,"Expression")};T.Function=function(e,n,t){e.id&&t(e.id,n,"Pattern");for(var r=0,s=e.params;r<s.length;r+=1){var o=s[r];t(o,n,"Pattern")}t(e.body,n,e.expression?"Expression":"Statement")};T.Pattern=function(e,n,t){e.type==="Identifier"?t(e,n,"VariablePattern"):e.type==="MemberExpression"?t(e,n,"MemberPattern"):t(e,n)};T.VariablePattern=ve;T.MemberPattern=Sn;T.RestElement=function(e,n,t){return t(e.argument,n,"Pattern")};T.ArrayPattern=function(e,n,t){for(var r=0,s=e.elements;r<s.length;r+=1){var o=s[r];o&&t(o,n,"Pattern")}};T.ObjectPattern=function(e,n,t){for(var r=0,s=e.properties;r<s.length;r+=1){var o=s[r];o.type==="Property"?(o.computed&&t(o.key,n,"Expression"),t(o.value,n,"Pattern")):o.type==="RestElement"&&t(o.argument,n,"Pattern")}};T.Expression=Sn;T.ThisExpression=T.Super=T.MetaProperty=ve;T.ArrayExpression=function(e,n,t){for(var r=0,s=e.elements;r<s.length;r+=1){var o=s[r];o&&t(o,n,"Expression")}};T.ObjectExpression=function(e,n,t){for(var r=0,s=e.properties;r<s.length;r+=1){var o=s[r];t(o,n)}};T.FunctionExpression=T.ArrowFunctionExpression=T.FunctionDeclaration;T.SequenceExpression=function(e,n,t){for(var r=0,s=e.expressions;r<s.length;r+=1){var o=s[r];t(o,n,"Expression")}};T.TemplateLiteral=function(e,n,t){for(var r=0,s=e.quasis;r<s.length;r+=1){var o=s[r];t(o,n)}for(var i=0,a=e.expressions;i<a.length;i+=1){var c=a[i];t(c,n,"Expression")}};T.TemplateElement=ve;T.UnaryExpression=T.UpdateExpression=function(e,n,t){t(e.argument,n,"Expression")};T.BinaryExpression=T.LogicalExpression=function(e,n,t){t(e.left,n,"Expression"),t(e.right,n,"Expression")};T.AssignmentExpression=T.AssignmentPattern=function(e,n,t){t(e.left,n,"Pattern"),t(e.right,n,"Expression")};T.ConditionalExpression=function(e,n,t){t(e.test,n,"Expression"),t(e.consequent,n,"Expression"),t(e.alternate,n,"Expression")};T.NewExpression=T.CallExpression=function(e,n,t){if(t(e.callee,n,"Expression"),e.arguments)for(var r=0,s=e.arguments;r<s.length;r+=1){var o=s[r];t(o,n,"Expression")}};T.MemberExpression=function(e,n,t){t(e.object,n,"Expression"),e.computed&&t(e.property,n,"Expression")};T.ExportNamedDeclaration=T.ExportDefaultDeclaration=function(e,n,t){e.declaration&&t(e.declaration,n,e.type==="ExportNamedDeclaration"||e.declaration.id?"Statement":"Expression"),e.source&&t(e.source,n,"Expression")};T.ExportAllDeclaration=function(e,n,t){e.exported&&t(e.exported,n),t(e.source,n,"Expression")};T.ImportDeclaration=function(e,n,t){for(var r=0,s=e.specifiers;r<s.length;r+=1){var o=s[r];t(o,n)}t(e.source,n,"Expression")};T.ImportExpression=function(e,n,t){t(e.source,n,"Expression")};T.ImportSpecifier=T.ImportDefaultSpecifier=T.ImportNamespaceSpecifier=T.Identifier=T.PrivateIdentifier=T.Literal=ve;T.TaggedTemplateExpression=function(e,n,t){t(e.tag,n,"Expression"),t(e.quasi,n,"Expression")};T.ClassDeclaration=T.ClassExpression=function(e,n,t){return t(e,n,"Class")};T.Class=function(e,n,t){e.id&&t(e.id,n,"Pattern"),e.superClass&&t(e.superClass,n,"Expression"),t(e.body,n)};T.ClassBody=function(e,n,t){for(var r=0,s=e.body;r<s.length;r+=1){var o=s[r];t(o,n)}};T.MethodDefinition=T.PropertyDefinition=T.Property=function(e,n,t){e.computed&&t(e.key,n,"Expression"),e.value&&t(e.value,n,"Expression")};var Xi={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function eo(e,n={}){let t={...Xi,...n},r=[],s,o=new Map,i;try{let f=be(e,{filename:t.filename,colonShorthand:!0});s=f.ast,o=f.letAnnotations,i=f.tjsModes.tjsSafeAssign}catch(f){return{diagnostics:[{severity:"error",message:f.message,line:f.loc?.line,column:f.loc?.column,rule:"parse-error"}],valid:!1}}let a=t.safeAssign!==void 0?t.safeAssign:i,c=t.strict?"error":"warning",l=[Hr()];if(Yr(s,{FunctionDeclaration(f,p,u){let m=Hr();l.push(m);for(let y of f.params)to(m,y,"parameter");f.id&&(l[l.length-2]||l[0]).declarations.set(f.id.name,{node:f.id,kind:"function",used:!1})},VariableDeclaration(f){let p=l[l.length-1];for(let u of f.declarations)u.id.type==="Identifier"&&p.declarations.set(u.id.name,{node:u.id,kind:f.kind,used:!1})}}),je(s,{Identifier(f){for(let p=l.length-1;p>=0;p--){let u=l[p].declarations.get(f.name);if(u){u.used=!0;break}}}}),t.unusedVariables)for(let f of l)for(let[p,u]of f.declarations)p.startsWith("_")||!u.used&&u.kind!=="function"&&r.push({severity:"warning",message:`'${p}' is declared but never used`,line:u.node.loc?.start?.line,column:u.node.loc?.start?.column,rule:"no-unused-vars"});if(t.unreachableCode&&je(s,{BlockStatement(f){let p=!1;for(let u of f.body){if(p){r.push({severity:"warning",message:"Unreachable code after return statement",line:u.loc?.start?.line,column:u.loc?.start?.column,rule:"no-unreachable"});break}u.type==="ReturnStatement"&&(p=!0)}}}),a){let f=new Set;je(s,{VariableDeclaration(p){if(p.kind==="let")for(let u of p.declarations){if(u.id.type!=="Identifier")continue;let m=u.id.name,y=o.has(m),h=u.init;(y||h&&!En(h))&&f.add(m)}}}),je(s,{VariableDeclaration(p){if(p.kind==="let")for(let u of p.declarations){if(u.id.type!=="Identifier")continue;let m=u.id.name;o.has(m)||(u.init?En(u.init)&&r.push({severity:c,message:`'let ${m}' is initialized to ${Qr(u.init)} with no type annotation. Annotate (let ${m}: <example>) to record the intended type.`,line:u.loc?.start?.line,column:u.loc?.start?.column,rule:"safe-assign-let-needs-type"}):r.push({severity:c,message:`'let ${m}' has no initializer or type annotation. Add an initializer (let ${m} = ...) or annotate (let ${m}: <example>).`,line:u.loc?.start?.line,column:u.loc?.start?.column,rule:"safe-assign-let-needs-type"}))}}}),je(s,{AssignmentExpression(p){if(p.operator!=="="||p.left.type!=="Identifier")return;let u=p.left.name;f.has(u)&&En(p.right)&&r.push({severity:c,message:`Cannot assign ${Qr(p.right)} to typed let '${u}'.`,line:p.loc?.start?.line,column:p.loc?.start?.column,rule:"safe-assign-no-nullish"})}})}return t.noExplicitNew&&je(s,{NewExpression(f){let p="class";f.callee.type==="Identifier"?p=f.callee.name:f.callee.type==="MemberExpression"&&f.callee.property.type==="Identifier"&&(p=f.callee.property.name),r.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${p}(...) instead of new ${p}(...)`,line:f.loc?.start?.line,column:f.loc?.start?.column,rule:"no-explicit-new"})}}),{diagnostics:r,valid:r.filter(f=>f.severity==="error").length===0}}function Hr(){return{declarations:new Map}}function En(e){return e?e.type==="Identifier"&&e.name==="undefined"||e.type==="Literal"&&e.value===null||e.type==="UnaryExpression"&&e.operator==="void":!1}function Qr(e){return e.type==="Identifier"?"undefined":e.type==="Literal"&&e.value===null?"null":e.type==="UnaryExpression"&&e.operator==="void"?"void <expr> (undefined)":"a nullish value"}function to(e,n,t){n.type==="Identifier"?e.declarations.set(n.name,{node:n,kind:t,used:!1}):n.type==="AssignmentPattern"&&n.left.type==="Identifier"&&e.declarations.set(n.left.name,{node:n.left,kind:t,used:!1})}export{Hi as Schema,pe as TJS_VERSION,Zi as ajs,pr as assertFunction,Ee as checkType,Gi as createAgent,oi as emitRuntimeWrapper,ce as error,mr as expectFunction,oe as extractLiteralValue,Ve as extractTDoc,Ot as extractTests,Ki as getToolDefinitions,Y as inferTypeFromValue,pn as installRuntime,me as isError,eo as lint,be as parse,ye as parseParameter,ar as parseReturnType,ut as preprocess,we as runtime,Ws as testUtils,Yi as tjs,It as transformFunction,Tt as transpile,St as transpileToJS,Ie as typeOf,Pt as typeToString,un as validateArgs,fn as wrap};
|
|
355
355
|
//# sourceMappingURL=tjs-lang.js.map
|