tjs-lang 0.7.7 → 0.7.8
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 +90 -33
- package/bin/docs.js +4 -1
- package/demo/docs.json +45 -11
- package/demo/src/examples.test.ts +1 -0
- package/demo/src/imports.test.ts +16 -4
- package/demo/src/imports.ts +60 -15
- package/demo/src/playground-shared.ts +9 -8
- package/demo/src/tfs-worker.js +205 -147
- package/demo/src/tjs-playground.ts +34 -10
- package/demo/src/ts-playground.ts +24 -8
- package/dist/index.js +118 -101
- package/dist/index.js.map +4 -4
- package/dist/src/lang/bool-coercion.d.ts +50 -0
- package/dist/src/lang/docs.d.ts +31 -6
- package/dist/src/lang/linter.d.ts +8 -0
- package/dist/src/lang/parser-transforms.d.ts +18 -0
- package/dist/src/lang/parser-types.d.ts +2 -0
- package/dist/src/lang/parser.d.ts +3 -0
- package/dist/src/lang/runtime.d.ts +34 -0
- package/dist/src/lang/types.d.ts +9 -1
- package/dist/src/rbac/index.d.ts +1 -1
- package/dist/src/vm/runtime.d.ts +1 -1
- package/dist/tjs-eval.js +38 -36
- package/dist/tjs-eval.js.map +4 -4
- package/dist/tjs-from-ts.js +20 -20
- package/dist/tjs-from-ts.js.map +3 -3
- package/dist/tjs-lang.js +85 -83
- package/dist/tjs-lang.js.map +4 -4
- package/dist/tjs-vm.js +47 -45
- package/dist/tjs-vm.js.map +4 -4
- package/llms.txt +79 -0
- package/package.json +3 -2
- package/src/cli/commands/convert.test.ts +16 -21
- package/src/lang/bool-coercion.test.ts +203 -0
- package/src/lang/bool-coercion.ts +314 -0
- package/src/lang/codegen.test.ts +137 -0
- package/src/lang/docs.test.ts +328 -1
- package/src/lang/docs.ts +424 -24
- package/src/lang/emitters/ast.ts +11 -12
- package/src/lang/emitters/dts.test.ts +41 -0
- package/src/lang/emitters/dts.ts +9 -0
- package/src/lang/emitters/js-tests.ts +9 -4
- package/src/lang/emitters/js.ts +182 -2
- package/src/lang/inference.ts +54 -0
- package/src/lang/linter.test.ts +104 -1
- package/src/lang/linter.ts +124 -1
- package/src/lang/parser-params.ts +31 -0
- package/src/lang/parser-transforms.ts +304 -0
- package/src/lang/parser-types.ts +2 -0
- package/src/lang/parser.test.ts +73 -1
- package/src/lang/parser.ts +34 -1
- package/src/lang/runtime.ts +98 -0
- package/src/lang/types.ts +6 -0
- package/src/rbac/index.ts +2 -2
- package/src/rbac/rules.tjs.d.ts +9 -0
- package/src/vm/atoms/batteries.ts +2 -2
- package/src/vm/runtime.ts +10 -3
- package/dist/src/rbac/rules.d.ts +0 -184
- package/src/rbac/rules.js +0 -338
package/dist/tjs-lang.js
CHANGED
|
@@ -1,55 +1,57 @@
|
|
|
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
|
-
`,i);a===-1&&(a=e.length);let c=e.slice(i,a).trim();if(c){let l=Tn(c);n+=`const ${s} = Union('${o}', [${l.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function Tn(e){let n=[],t=e.split("|").map(r=>r.trim());for(let r of t)r&&n.push(r);return n}function In(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 d=e.slice(a,l-1).trim(),f=l,p=Yr(d).map(([y,x])=>`${y}: ${x}`).join(", ");n+=`const ${s} = Enum('${o}', { ${p} })`,t=f;continue}n+=e[t],t++}return n}function Yr(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 On(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]===`
|
|
12
|
-
`||e[r-1]===";"||e[r-1]==="}"){let h=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=De(e,c),d=e.slice(c+1,l-1).trim(),f=[],u=0,p=e.slice(c+1,l-1);for(;u<p.length;){let h=p.slice(u).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!h){u++;continue}let g=h[1],S=!!h[2],b=h[3],E=u+h[0].length-1,k=1,j=E+1;for(;j<p.length&&k>0;)p[j]==="("&&k++,p[j]===")"&&k--,j++;let R=p.slice(E+1,j-1),C=j;for(;C<p.length&&/\s/.test(p[C]);)C++;if(p[C]==="="&&p[C+1]===">"){let J=Be(e,c+1+u);throw new Y(`Arrow functions are not allowed in extend blocks (method '${b}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,J)}if(p[C]!=="{"){u++;continue}let N=De(p,C),v=p.slice(u,N).trim(),M=R.split(",").map(J=>J.trim()).filter(J=>J.length>0).map(J=>{let K=J.match(/^(\w+)\s*:\s*(.+)$/);return K?`${K[1]} = ${K[2]}`:J}).join(", "),P=S?"async ":"",V=p.slice(C+1,N-1);f.push({name:b,isAsync:S,fullText:`${b}: ${P}function(${M}) {${V}}`}),u=N}let y=!n.has(a);y&&n.set(a,new Set);let x=n.get(a);for(let $ of f)x.add($.name);let _=f.map($=>` ${$.fullText}`).join(`,
|
|
13
|
-
`),w;y?w=`${i}const __ext_${a} = {
|
|
1
|
+
var rs=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var br=rs((xo,Vs)=>{Vs.exports={name:"tjs-lang",version:"0.7.8",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"},"./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","@happy-dom/global-registrator":"^20.1.0","@types/bun":"latest","@types/jsdom":"^21.1.7","@typescript-eslint/eslint-plugin":"^5.62.0","@typescript-eslint/parser":"^5.62.0","acorn-walk":"^8.3.4",chokidar:"^4.0.3",codemirror:"^6.0.2",esbuild:"^0.28.0",eslint:"^8.57.1",firebase:"^10.12.0","firebase-admin":"^13.6.0","firebase-functions":"^7.0.5",marked:"^9.1.6",prettier:"^2.8.8",tosijs:"^1.5.6","tosijs-ui":"^1.4.7",typescript:"^5.6.2",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":"firebase deploy --only hosting",deploy:"npm run build:demo && npm 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 rr 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}},G=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),p=c===r?">":" ";if(i.push(`${p} ${l} | ${t[c]}`),c===r){let f=" ".repeat(a+4+this.column);i.push(`${f}^ ${this.message.split(" at ")[0]}`)}}return i.join(`
|
|
3
|
+
`)}};function ne(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 W(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function ss(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 Mn(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 x=e[l];x==="{"?c++:x==="}"&&c--,l++}if(c!==0){t+=e[r],r++;continue}let p=e.slice(a,l-1),f,u=l,m=e.slice(l).match(/^\s*fallback\s*\{/);if(m){let x=l+m[0].length;c=1;let w=x;for(;w<e.length&&c>0;){let k=e[w];k==="{"?c++:k==="}"&&c--,w++}c===0&&(f=e.slice(x,w-1),u=w)}let g=os(p).map(x=>{let w=as(e,i,x);return w?`${x}: ${w}`:x}),_={id:`__tjs_wasm_${s}`,body:p,fallback:f,captures:g,start:i,end:u};n.push(_);let $=f??p,S=g.map(x=>x.split(":")[0].trim()),h=S.length>0?S.join(", "):"",b=S.length>0?`globalThis.${_.id}(${h})`:`globalThis.${_.id}()`,E=`(globalThis.${_.id} ? ${b} : (() => {${$}})())`;t+=E,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function is(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function os(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"),g=n.match(m)?.length||0,_=n.match(y)?.length||0;g<=_&&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 p=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"]),f=[];for(let u of i)!a.has(u)&&!p.has(u)&&!is(u)&&f.push(u);return f.sort()}function as(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 In(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(`
|
|
4
|
+
`),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 p=c.indexOf("/*"),f=c.indexOf("*/");if(p!==-1&&(f===-1||f<p)){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]:"",g=c.slice(y.length);o.push(y+";"+g);continue}}o.push(c)}return o.join(`
|
|
5
|
+
`)}function cs(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===`
|
|
6
|
+
`&&(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 Le(e){e=cs(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===`
|
|
7
|
+
`&&(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",p=ls(o,a),f=us(o,a+2),u=o.slice(p,a).trim(),m=o.slice(a+2,f).trim();if(u&&m){let y=o.slice(0,p),g=o.slice(f),$=/[a-zA-Z0-9_$]$/.test(y)?" ":"";o=`${y}${$}${l}(${u}, ${m})${g}`}}return o}function ls(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 p=e.slice(l,c),f=l>0?e[l-1]:"";if(!/[a-zA-Z0-9_$]/.test(f)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(p))return c;if(p==="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 us(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 On(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 g=c[0].trim(),_=c[0].slice(g.length);n+=`const ${s} = Type('${s}', ${g})${_}`,t=u;continue}}let l,p=o,f=e.slice(o).match(/^=\s*/);if(f){o+=f[0].length;let u=e.slice(o).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(u){l=u[0],o+=u[0].length,p=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 E=e[y];E==="{"?m++:E==="}"&&m--,y++}if(m!==0){n+=e[t],t++;continue}let g=e.slice(u,y-1).trim(),_=y,$=g.match(/description\s*:\s*(['"`])([^]*?)\1/);$&&!a&&(i=$[2]);let S,h=g.match(/example\s*:\s*/);if(h){let E=h.index+h[0].length,x=er(g,E);x&&(S=x.value.trim())}let b=g.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(b&&S){let E=b[1].trim(),x=b[2].trim(),w=l?`, ${l}`:"";n+=`const ${s} = Type('${i}', (${E}) => { if (!globalThis.__tjs?.validate(${E}, globalThis.__tjs?.infer(${S}))) return false; ${x} }, ${S}${w})`}else if(b){let E=b[1].trim(),x=b[2].trim(),w=l?`, undefined, ${l}`:"";n+=`const ${s} = Type('${i}', (${E}) => { ${x} }${w})`}else if(S){let E=l?`, ${l}`:"";n+=`const ${s} = Type('${i}', undefined, ${S}${E})`}else l?n+=`const ${s} = Type('${i}', ${l})`:n+=`const ${s} = Type('${i}')`;t=_;continue}else if(l){n+=`const ${s} = Type('${i}', ${l})`,t=p;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 Bn(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(),p=ss(l,/params\s*:\s*\{/),f=l.match(/returns\s*:\s*(.+?)(?:\n|$)/),u=l.match(/returnContract\s*:\s*['"](\w+)['"]/),m=l.match(/description\s*:\s*(['"])([^]*?)\1/),y=[];p&&y.push(`params: ${p[1]}`),f&&y.push(`returns: ${f[1].trim()}`),u&&y.push(`returnContract: '${u[1]}'`);let g=m?m[2]:s;if(o){let _=o.split(",").map(S=>{let h=S.trim().split("=").map(b=>b.trim());if(h.length===2){let b=h[1]==="any"||h[1]==="undefined"?"null":h[1];return`['${h[0]}', ${b}]`}return`'${h[0]}'`}),$=o.split(",").map(S=>S.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${g}', [${_.join(", ")}], (${$.join(", ")}) => ({ ${y.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${g}', { ${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(),p=l.indexOf(",");if(p!==-1){let f=l.slice(0,p).trim(),u=l.slice(p+1).trim();n+=`const ${s} = FunctionPredicate(${u}, ${f})`}else n+=`const ${s} = FunctionPredicate('${s}', ${l})`;t=c;continue}}}n+=e[t],t++}return n}function Dn(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 S=e[l];S==="{"?c++:S==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let p=e.slice(a,l-1).trim(),f=l,u=o.split(",").map(S=>{let h=S.trim().split("=").map(b=>b.trim());if(h.length===2){let b=h[1]==="any"||h[1]==="undefined"?"null":h[1];return`['${h[0]}', ${b}]`}return`'${h[0]}'`}),m=p,y=m.search(/\bdeclaration\s*\{/);if(y!==-1){let S=m.indexOf("{",y),h=1,b=S+1;for(;b<m.length&&h>0;)m[b]==="{"?h++:m[b]==="}"&&h--,b++;m=m.slice(0,y)+m.slice(b)}let g=m.match(/description\s*:\s*(['"`])([^]*?)\1/),_=m.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),$=g?g[2]:s;if(_){let S=_[1].trim().split(",").map(w=>w.trim()),h=_[2].trim(),b=S[0]||"x",E=S.slice(1),x=E.map(w=>`check${w}`);E.forEach((w,k)=>{h=h.replace(new RegExp(`\\b${w}\\s*\\(`,"g"),`${x[k]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${b}, ${x.join(", ")}) => { ${h} }, '${$}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${$}')`;t=f;continue}n+=e[t],t++}return n}function Fn(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 p=e.slice(a,l-1).trim(),f=l,u=Rn(p);n+=`const ${s} = Union('${o}', [${u.join(", ")}])`,t=f;continue}else{let a=e.indexOf(`
|
|
8
|
+
`,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 qn(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 p=e.slice(a,l-1).trim(),f=l,m=fs(p).map(([y,g])=>`${y}: ${g}`).join(", ");n+=`const ${s} = Enum('${o}', { ${m} })`,t=f;continue}n+=e[t],t++}return n}function fs(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 Un(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]===`
|
|
9
|
+
`||e[r-1]===";"||e[r-1]==="}"){let h=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),p=e.slice(c+1,l-1).trim(),f=[],u=0,m=e.slice(c+1,l-1);for(;u<m.length;){let h=m.slice(u).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!h){u++;continue}let b=h[1],E=!!h[2],x=h[3],w=u+h[0].length-1,k=1,A=w+1;for(;A<m.length&&k>0;)m[A]==="("&&k++,m[A]===")"&&k--,A++;let R=m.slice(w+1,A-1),C=A;for(;C<m.length&&/\s/.test(m[C]);)C++;if(m[C]==="="&&m[C+1]===">"){let V=de(e,c+1+u);throw new G(`Arrow functions are not allowed in extend blocks (method '${x}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,V)}if(m[C]!=="{"){u++;continue}let N=qe(m,C),j=m.slice(u,N).trim(),M=R.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(", "),P=E?"async ":"",L=m.slice(C+1,N-1);f.push({name:x,isAsync:E,fullText:`${x}: ${P}function(${M}) {${L}}`}),u=N}let y=!n.has(a);y&&n.set(a,new Set);let g=n.get(a);for(let S of f)g.add(S.name);let _=f.map(S=>` ${S.fullText}`).join(`,
|
|
10
|
+
`),$;y?$=`${i}const __ext_${a} = {
|
|
14
11
|
${_}
|
|
15
12
|
${i}}
|
|
16
|
-
|
|
13
|
+
`:$=`${i}Object.assign(__ext_${a}, {
|
|
17
14
|
${_}
|
|
18
15
|
${i}})
|
|
19
|
-
`;for(let
|
|
20
|
-
`;t
|
|
21
|
-
`?(t++,r=0):r++;return{line:t,column:r}}function
|
|
22
|
-
`&&(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
|
|
23
|
-
${_}${
|
|
24
|
-
${
|
|
16
|
+
`;for(let S of f)$+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${S.name}', __ext_${a}.${S.name}) }
|
|
17
|
+
`;t+=$,r=l}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function We(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,p,f,u)=>u?`__ext_String.${f}.call(${p})`:`__ext_String.${f}.call(${p}, `);let a=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${s})\\((\\))?`,"g");r=r.replace(a,(l,p,f,u)=>u?`__ext_String.${f}.call(${p})`:`__ext_String.${f}.call(${p}, `);let c=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+s+"\\((\\))?","g");r=r.replace(c,(l,p,f)=>f?`__ext_String.${s}.call(${p})`:`__ext_String.${s}.call(${p}, `)}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,p=c-1,f=!1;for(;p>=0&&l>0;){let u=r[p];f?u===f&&(p===0||r[p-1]!=="\\")&&(f=!1):(u==="]"&&l++,u==="["&&l--,(u==="'"||u==='"'||u==="`")&&(f=u)),p--}if(l===0){let u=r.slice(p+1,c+1),m=r.slice(0,p+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,p)=>p?`__ext_Number.${l}.call(${c})`:`__ext_Number.${l}.call(${c}, `)}return r}function de(e,n){let t=1,r=0;for(let s=0;s<n&&s<e.length;s++)e[s]===`
|
|
18
|
+
`?(t++,r=0):r++;return{line:t,column:r}}function Ln(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 Ct(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=Cn(s.trim(),n);l&&t.push(l),s="";continue}s+=c}let i=s.trim();if(i){let a=Cn(i,n);a&&t.push(a)}return t}function Cn(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===`
|
|
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 Wn(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 f=!!o[1],u=!!o[2],m=o[3],y=o.index,g=y,$=o[0].indexOf("function");$>=0&&(g=y+$),i.push({name:m,fullMatchStart:y,funcKeywordStart:g,exported:f,isAsync:u})}for(let f of i)s.has(f.name)||s.set(f.name,[]);let a=new Map;for(let f of i)a.set(f.name,(a.get(f.name)||0)+1);let c=new Set;for(let[f,u]of a)u>1&&c.add(f);if(c.size===0)return{source:e,polymorphicNames:t};for(let f of i){if(!c.has(f.name))continue;let u=e.indexOf("(",f.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 g=y-1,_=e.slice(u+1,g),$=y;for(;$<e.length&&e[$]!=="{";)$++;if($>=e.length)continue;let S=qe(e,$),h=f.fullMatchStart;for(;h>0&&e[h-1]===" ";)h--;let b=s.get(f.name),E=Ct(_,n);if(_.includes("...")){let w=de(e,f.funcKeywordStart);throw new G(`Rest parameters are not supported in polymorphic function '${f.name}'. Use separate function names instead.`,w)}b.push({index:b.length+1,start:h,end:S,text:e.slice(h,S),exported:f.exported,isAsync:f.isAsync,params:E})}for(let[f,u]of s){if(u.length<2)continue;let m=u.filter(y=>y.isAsync).length;if(m>0&&m<u.length){let y=de(e,u[0].start);throw new G(`Polymorphic function '${f}': all variants must be either sync or async, not mixed.`,y)}for(let y=0;y<u.length;y++)for(let g=y+1;g<u.length;g++){let _=u[y],$=u[g];if(_.params.length!==$.params.length)continue;let S=!0;for(let h=0;h<_.params.length;h++){let b=_.params[h].defaultValue?st(_.params[h].defaultValue):"any",E=$.params[h].defaultValue?st($.params[h].defaultValue):"any";if(b!==E){S=!1;break}}if(S){let h=de(e,$.start);throw new G(`Polymorphic function '${f}': variants ${y+1} and ${g+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,h)}}}let l=[];for(let[f,u]of s)if(!(u.length<2))for(let m of u)l.push({name:f,variant:m});l.sort((f,u)=>u.variant.start-f.variant.start);let p=e;for(let{name:f,variant:u}of l){let m=u.isAsync?"async ":"",y=u.text.replace(new RegExp(`(?:export\\s+)?${m?m.replace(/\s+$/,"\\s+"):""}function\\s+${f}\\s*\\(`),`${m}function ${f}$$${u.index}(`);p=p.slice(0,u.start)+y+p.slice(u.end)}for(let[f,u]of s){if(u.length<2)continue;t.add(f);let m=u[0].isAsync,y=u.some(b=>b.exported),g=m?"async ":"",_=y?"export ":"",$=[...u].sort((b,E)=>{if(b.params.length!==E.params.length)return 0;let x=0,w=0;for(let k of b.params){let A=k.defaultValue?st(k.defaultValue):"any";A==="non-negative-integer"?x+=3:A==="integer"?x+=2:A!=="any"&&(x+=1)}for(let k of E.params){let A=k.defaultValue?st(k.defaultValue):"any";A==="non-negative-integer"?w+=3:A==="integer"?w+=2:A!=="any"&&(w+=1)}return w-x}),S=[];for(let b of $){let E=[`__args.length === ${b.params.length}`],x=[];for(let w=0;w<b.params.length;w++){let k=b.params[w];if(x.push(`__args[${w}]`),k.defaultValue){let A=Ln(`__args[${w}]`,k.defaultValue);A!=="true"&&E.push(A)}}S.push(` if (${E.join(" && ")}) return ${f}$${b.index}(${x.join(", ")})`)}let h=`
|
|
20
|
+
${_}${g}function ${f}(...__args) {
|
|
21
|
+
${S.join(`
|
|
25
22
|
`)}
|
|
26
23
|
return __tjs.typeError('${f}', 'no matching overload', __args)
|
|
27
24
|
}
|
|
28
|
-
`;
|
|
29
|
-
`,
|
|
30
|
-
${
|
|
31
|
-
`.repeat(
|
|
32
|
-
`&&
|
|
33
|
-
function ${c}$ctor$${k.index}(${k.paramStr}) {`,
|
|
34
|
-
const __obj = Object.create(${c}.prototype)`,
|
|
35
|
-
;(function() {${k.bodyText}}).call(__obj)`,
|
|
36
|
-
return __obj`,
|
|
25
|
+
`;p+=h}return{source:p,polymorphicNames:t}}function Jn(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function Vn(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,p=e.slice(c).match(/^(['"`])([^]*?)\1\s*/);if(p&&(l=p[2],c+=p[0].length),e[c]==="{"){let f=c+1,u=1,m=f,y=null,g=!1;for(;m<e.length&&u>0;){let _=e[m];if(g){g=!1,m++;continue}if(_==="\\"&&y){g=!0,m++;continue}if(y){_===y&&(y=null),m++;continue}if(_==="/"&&e[m+1]==="/"){let $=e.indexOf(`
|
|
26
|
+
`,m);m=$===-1?e.length:$+1;continue}if(_==="/"&&e[m+1]==="*"){let $=e.indexOf("*/",m+2);m=$===-1?e.length:$+2;continue}if(_==="'"||_==='"'||_==="`"){y=_,m++;continue}_==="{"?u++:_==="}"&&u--,m++}if(u===0){let _=e.slice(f,m-1).trim(),$=m,S=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:l,body:_,start:a,end:$,line:S}),!n)try{new Function(_)()}catch(E){let x=l||`test at line ${S}`;r.push(`Test failed: ${x} (line ${S})
|
|
27
|
+
${E.message||E}`)}let b=(e.slice(a,$).match(/\n/g)||[]).length;s+=`
|
|
28
|
+
`.repeat(b),o=$;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function zn(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,p=qe(e,l),f=e.slice(l,p);o.push({className:a,extendsClause:c,bodyStart:l,bodyEnd:p,body:f})}let i=e;for(let a=o.length-1;a>=0;a--){let{className:c,extendsClause:l,bodyStart:p,bodyEnd:f,body:u}=o[a],m=/\bconstructor\s*\(/g,y,g=[];for(;(y=m.exec(u))!==null;)g.push(y.index);if(g.length<2)continue;t.add(c);let _=[];for(let w=0;w<g.length;w++){let k=g[w],A=u.indexOf("(",k),R=1,C=A+1;for(;C<u.length&&R>0;)u[C]==="("&&R++,u[C]===")"&&R--,C++;let N=u.slice(A+1,C-1),j=C;for(;j<u.length&&u[j]!=="{";)j++;let M=qe(u,j),P=u.slice(j+1,M-1);_.push({index:w+1,paramStr:N,bodyText:P,fullStart:k,fullEnd:M})}let $=u.slice(0,_[0].fullEnd),S=_[_.length-1].fullEnd;$+=u.slice(S);let h=u;for(let w=_.length-1;w>=1;w--){let k=_[w],A=k.fullStart;for(;A>0&&h[A-1]===" ";)A--;A>0&&h[A-1]===`
|
|
29
|
+
`&&A--,h=h.slice(0,A)+h.slice(k.fullEnd)}let b="";for(let w=1;w<_.length;w++){let k=_[w],A=Ct(k.paramStr,n);if(k.paramStr.includes("...")){let C=de(e,p+k.fullStart);throw new G(`Rest parameters are not supported in polymorphic constructors for '${c}'.`,C)}b+=`
|
|
30
|
+
function ${c}$ctor$${k.index}(${k.paramStr}) {`,b+=`
|
|
31
|
+
const __obj = Object.create(${c}.prototype)`,b+=`
|
|
32
|
+
;(function() {${k.bodyText}}).call(__obj)`,b+=`
|
|
33
|
+
return __obj`,b+=`
|
|
37
34
|
}
|
|
38
|
-
`}let
|
|
35
|
+
`}let E=[];for(let w=0;w<_.length;w++){let k=_[w],A=Ct(k.paramStr,n),R=[`a.length === ${A.length}`];for(let C=0;C<A.length;C++){let N=A[C];if(N.defaultValue){let j=Ln(`a[${C}]`,N.defaultValue);j!=="true"&&R.push(j)}}if(w===0)E.push(` if (${R.join(" && ")}) return Reflect.construct(t, a)`);else{let C=A.map((N,j)=>`a[${j}]`).join(", ");E.push(` if (${R.join(" && ")}) return ${c}$ctor$${k.index}(${C})`)}}b+=`
|
|
39
36
|
function ${c}$dispatch(t, a) {
|
|
40
|
-
`,
|
|
37
|
+
`,b+=E.join(`
|
|
41
38
|
`)+`
|
|
42
|
-
`,
|
|
43
|
-
`,
|
|
44
|
-
`,i=i.slice(0,
|
|
45
|
-
`&&(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
|
|
46
|
-
|
|
47
|
-
`),
|
|
48
|
-
`)),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 Qr}from"acorn";function H(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=>H(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]=H(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?H(t):n==="&&"||n==="??"?H(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=H(t),o=H(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"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 fe(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=H(r),a=ie(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=fe(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 ie(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?ie(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=ie(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=ie(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=ie(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?ie(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?ie(t)??ie(r):void 0}default:return}}function Yn(e){try{let n=Qr(e,0,{ecmaVersion:2022});return H(n)}catch{return{kind:"any"}}}function Ct(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?Ct(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}: ${Ct(r)}`).join(", ");return e.nullable?`{ ${n} } | null`:`{ ${n} }`}case"union":return e.members?.map(Ct).join(" | ")||"any";default:return"any"}}function at(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?at(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=at(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(at)}:{};default:return{}}}function Xr(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=at(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function Nt(e,n,t,r={},s){let o=We(n,e),i=new Map;for(let _ of e.params){let w=fe(_,s);if(w.name==="__destructured__"&&w.type.kind==="object"&&w.type.destructuredParams)for(let[$,h]of Object.entries(w.type.destructuredParams))i.set($,{...h,description:o.params[$]});else w.description=o.params[w.name],i.set(w.name,w)}let a;t&&(a=Yn(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=oe(e.body,c),d=[],f=[],u=[];for(let[_,w]of i.entries())w.required?f.push(_):w.default!==void 0?u.push({name:_,defaultValue:w.default}):f.push(_);f.length>0&&d.push({op:"varsImport",keys:f});for(let{name:_,defaultValue:w}of u)d.push({op:"varsImport",keys:[_]}),d.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:_},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:_,value:w}]});d.push(...l);let p=Object.fromEntries(i),y={name:e.id?.name||"anonymous",description:o.description,parameters:p,returns:a},x=Xr(p);return{ast:{op:"seq",steps:d,inputSchema:x},signature:y,warnings:c.warnings}}function oe(e,n){let t=[];for(let r of e.body){let s=Le(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function Le(e,n){switch(e.type){case"VariableDeclaration":return es(e,n);case"ExpressionStatement":return ts(e,n);case"IfStatement":return rs(e,n);case"WhileStatement":return ss(e,n);case"ForOfStatement":return is(e,n);case"TryStatement":return os(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",W(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:oe(e,ee(n))};case"EmptyStatement":return null;default:throw new U(`Unsupported statement type: ${e.type}`,W(e),n.source,n.filename)}}function es(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}=ge(o.init,n,i,r);a?t.push(a):c!==i&&t.push({op:s,key:i,value:c});let l=H(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 ts(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return ns(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=ge(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 ns(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}=ge(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function rs(e,n){let t=q(e.test,n),r=e.consequent.type==="BlockStatement"?oe(e.consequent,ee(n)):[Le(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?oe(e.alternate,ee(n)):[Le(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function ss(e,n){let t=q(e.test,n),r=e.body.type==="BlockStatement"?oe(e.body,ee(n)):[Le(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function is(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=Z(e.right,n),s=ee(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?oe(e.body,s):[Le(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function os(e,n){let t=oe(e.block,ee(n)),r,s;if(e.handler){let o=ee(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=oe(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}=ge(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:Z(e.argument,n)}}var Qn=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),cs=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),Je=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),ls=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 us(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return cs.has(n)||Je.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Qn.has(t)||Je.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(ls.has(t))return!0}}return!1}function fs(e){if(e.object.type==="Identifier"){let n=e.object.name;return Qn.has(n)||Je.has(n)}return!1}var Hn={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(Je.has(n))return Hn[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(Je.has(t))return Hn[t]||`${t} is not available in AsyncJS.`}}return null}function Xn(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 ge(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return ge(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let c=Xn(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=ps(e);if(i)throw new U(i,W(e),n.source,n.filename)}if(e.type==="CallExpression"&&us(e)){let i=q(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="MemberExpression"&&fs(e)){let i=q(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="CallExpression")return ms(e,n,t,r);if(e.type==="TemplateLiteral")return ys(e,n,t,r);if(e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="UnaryExpression"){let i=q(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}return{step:null,resultVar:Z(e,n)}}function ms(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=Z(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 ds(s,i,e.arguments,n,t,r);s==="console"&&e.callee.type;let a=gs(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function ds(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=ee(r);l.locals.set(c,{kind:"any"});let d;if(i.body.type==="BlockStatement")d=oe(i.body,l);else{let{step:f,resultVar:u}=ge(i.body,l,"result");d=f?[f]:[{op:"varSet",key:"result",value:u}]}return{step:{op:"map",items:n,as:c,steps:d,...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=ee(r);l.locals.set(c,{kind:"any"});let d;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 d=q(i.body,l),{step:{op:"filter",items:n,as:c,condition:d,...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=ee(r);l.locals.set(c,{kind:"any"});let d;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 d=q(i.body,l),{step:{op:"find",items:n,as:c,condition:d,...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",d=c?.type==="Identifier"?c.name:"item",f=ee(r);f.locals.set(l,{kind:"any"}),f.locals.set(d,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=oe(i.body,f);else{let{step:y,resultVar:x}=ge(i.body,f,"result");u=y?[y]:[{op:"varSet",key:"result",value:x}]}let p=Z(t[1],r);return{step:{op:"reduce",items:n,as:d,accumulator:l,initial:p,steps:u,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"slice":break;case"push":return{step:{op:"push",list:n,item:Z(t[0],r),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?Z(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?Z(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=>Z(i,r)),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}function ys(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]=Z(a,n),s+=`{{${c}}}`}return{step:{op:"template",tmpl:s,vars:o,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function q(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=q(t.object,n),s=t.optional===!0;if(t.computed){let i=t.property;if(i.type==="Literal")return{$expr:"member",object:r,property:String(i.value),computed:!0,...s&&{optional:!0}};throw new U("Computed member access with variables not yet supported",W(e),n.source,n.filename)}let o=t.property.name;return{$expr:"member",object:r,property:o,...s&&{optional:!0}}}case"ChainExpression":return q(e.expression,n);case"BinaryExpression":{let t=e;return{$expr:"binary",op:t.operator,left:q(t.left,n),right:q(t.right,n)}}case"LogicalExpression":{let t=e;return{$expr:"logical",op:t.operator,left:q(t.left,n),right:q(t.right,n)}}case"UnaryExpression":{let t=e;return{$expr:"unary",op:t.operator,argument:q(t.argument,n)}}case"ConditionalExpression":{let t=e;return{$expr:"conditional",test:q(t.test,n),consequent:q(t.consequent,n),alternate:q(t.alternate,n)}}case"ArrayExpression":return{$expr:"array",elements:e.elements.filter(r=>r!==null).map(r=>q(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:q(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:q(r.object,n),method:s,arguments:t.arguments.map(i=>q(i,n)),...o&&{optional:!0}}}if(t.callee.type==="Identifier")return{$expr:"call",callee:t.callee.name,arguments:t.arguments.map(s=>q(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=Xn(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 Z(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 q(e,n);let s=Z(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`${s}[${Z(t.property,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 Z(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?Z(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]=Z(r.value,n)}return t}case"TemplateLiteral":return q(e,n);case"CallExpression":return q(e,n);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return q(e,n);default:return null}}function gs(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]=Z(s.value,n)}return r}return{args:e.arguments.map(t=>Z(t,n))}}import{parseExpressionAt as Ar}from"acorn";function hs(e,n){let t=n;for(;t>0&&e[t-1]!==`
|
|
49
|
-
|
|
39
|
+
`,b+=` return __tjs.typeError('${c}', 'no matching constructor', a)
|
|
40
|
+
`,b+=`}
|
|
41
|
+
`,i=i.slice(0,p)+h+i.slice(f);let x=p+h.length;i=i.slice(0,x)+b+i.slice(x)}return{source:i,polyCtorClasses:t}}function Zn(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,p=1,f=l+1;for(;f<e.length&&p>0;){let u=e[f];u==="{"?p++:u==="}"&&p--,f++}if(p===0){let u=f,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 Gn(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 Kn(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 Yn(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 Hn(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 Qn(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=ps(n);if(c<a){let l=n.slice(c);n=n.slice(0,c);let p=t+2;for(;p<e.length&&/[\w$]/.test(e[p]);)p++;let f=e.slice(t+2,p);n+=`__tjs.bang(${l},'${f}')`,t=p;continue}}n+=o,t++}else r==="line-comment"?(n+=o,o===`
|
|
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 ps(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=Nn(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=Nn(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 Nn(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 Xn(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===`
|
|
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 p=l>=0?e[l]:"";if(!p||/[=(!,;:{[&|?+\-*%<>~^]/.test(p)||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 p=l;for(;l<e.length&&/[\w$]/.test(e[l]);)l++;let f=l,u=e.slice(p,f),m=l;for(;m<e.length&&/\s/.test(e[m]);)m++;if(m<e.length&&e[m]===":"&&e[m+1]!==":"){let g=m+1;for(;g<e.length&&/[ \t]/.test(e[g]);)g++;let _=ms(e,g);if(_>g){let $=e.slice(g,_).trim();n.set(u,$),t.push({start:f,end:_,replacement:""}),r=_;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 ms(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===`
|
|
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,p=()=>c[c.length-1]?.type||"top-level",f=()=>{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===`
|
|
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 h=t.trimEnd();if(!h[h.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(h)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(h)){t+=u,r++,i="regex";continue}}break}if(u==="{"){l++,t+=u,r++;continue}if(u==="}"){l--;let h=c[c.length-1];h&&l===h.braceDepth&&c.pop(),t+=u,r++;continue}let y=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(y){let h=y[0].slice(0,-1);t+=h,r+=h.length,c.push({type:"class-body",braceDepth:l});continue}let g=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(g){let h=g[1],b=g[0].length,E=e[r+b],x=null,w=r+b;(E==="?"||E==="!")&&(x=E,w++,x==="!"?n.unsafeFunctions.add(h):n.safeFunctions.add(h)),t+=`function ${h}(`,r=w;let k=it(e,r,"(",")");if(!k){t+=e[r],r++;continue}let{content:A,endPos:R}=k;r=R;let C=Mt(A,n,!0);t+=C+")";let N=r;for(;N<e.length&&/\s/.test(e[N]);)N++;if(e[N]===":"){let M=e.slice(N,N+2),P;for(M===":?"||M===":!"?(N+=2,P=M===":?"?"safe":"unsafe"):N+=1;N<e.length&&/\s/.test(e[N]);)N++;let L=Nt(e,N);L&&(s===void 0&&(s=L.type,P&&(o=P)),r=L.endPos)}let j=r;for(;j<e.length&&/\s/.test(e[j]);)j++;if(e[j]==="="&&e[j+1]===">")throw new G("Unexpected '=>' after function declaration. Function declarations use `function name(params) { body }`, not arrow syntax. Remove the `=>`.",de(n.originalSource,j),n.originalSource);continue}let _=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),$=(()=>{for(let h=t.length-1;h>=0;h--)if(!/\s/.test(t[h]))return t[h];return`
|
|
46
|
+
`})(),S=$!=="="&&$!==","&&$!=="("&&$!=="["&&$!==">";if(_&&f()&&!S){let h=_[1].length;t+=e.slice(r,r+h),r+=h;continue}if(_&&f()&&S){let h=_[1],b=_[0].length,E=r+b;t+=h+"(",r=E;let x=it(e,r,"(",")");if(!x){t+=e[r],r++;continue}let{content:w,endPos:k}=x;r=k;let A=Mt(w,n,!0);t+=A+")";let R=r;for(;R<e.length&&/\s/.test(e[R]);)R++;if(e[R]===":"){let N=e.slice(R,R+2);for(N===":?"||N===":!"?R+=2:R++;R<e.length&&/\s/.test(e[R]);)R++;let j=Nt(e,R);j&&(r=j.endPos)}let C=r;for(;C<e.length&&/\s/.test(e[C]);)C++;if(e[C]==="="&&e[C+1]===">")throw new G("Unexpected '=>' after method declaration. Methods use `name(params) { body }`, not arrow syntax. Remove the `=>`.",de(n.originalSource,C),n.originalSource);continue}if(e[r]==="("){let h=it(e,r+1,"(",")");if(!h){t+=e[r],r++;continue}let b=h.content,E=h.endPos,x=E;for(;x<e.length&&/\s/.test(e[x]);)x++;let w;if(e[x]===":"){let k=e.slice(x,x+2);for(k===":?"||k===":!"?x+=2:x++;x<e.length&&/\s/.test(e[x]);)x++;let A=Nt(e,x);if(A)for(w=A.type,x=A.endPos;x<e.length&&/\s/.test(e[x]);)x++}if(e.slice(x,x+2)==="=>"){let k=null,A=b,R=b.trimStart();R.startsWith("?")&&(R.length===1||/\s/.test(R[1]))?(k="?",A=R.slice(1)):R.startsWith("!")&&(R.length===1||/\s/.test(R[1]))&&(k="!",A=R.slice(1));let C=Mt(A,n,!1);for(t+=`(${k==="?"?"/* safe */ ":k==="!"?"/* unsafe */ ":""}${C})`,r=E;r<x&&/\s/.test(e[r]);)t+=e[r],r++;w&&(r=x)}else{let k=ct(b,n);t+=`(${k.source})`,r=E}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 er(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 Nt(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 f=l;for(;f>n&&/\s/.test(e[f-1]);)f--;return{type:Je(e.slice(n,f).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===`
|
|
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 Mt(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 p=l.trim();if(!p)return l;if(t&&p.startsWith("{")&&p.endsWith("}")){let m=p.slice(1,-1);return`{ ${tr(m,n)} }`}if(t&&p.startsWith("[")&&p.endsWith("]")){let m=p.slice(1,-1);return`[ ${tr(m,n)} ]`}if(p.startsWith("...")){let m=nr(p);return m!==-1?p.slice(0,m).trim():l}let f=p.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(f){let[,m,y]=f;return a(m),o=!0,`${m} = ${y}`}if(!ds(p)){let m=p.match(/^(\w+)\s*=/);return m&&a(m[1]),o=!0,l}let u=nr(p);if(u!==-1){let m=p.slice(0,u).trim(),y=p.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 tr(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,p]=i;n.requiredParams.add(l);let f=ot(p);return`${l} = ${f}`}let a=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,l,p]=a;n.requiredParams.add(l);let f=at(p);return`${l} = ${f}`}let c=o.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(c){let[,l,p]=c;return n.requiredParams.add(l),`${l} = ${p}`}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[,f,u]=i;return`${f}: ${ot(u)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,f,u]=a;return`${f}: ${ot(u)}`}let c=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(c){let[,f,u]=c;return`${f}: ${at(u)}`}let l=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(l){let[,f,u]=l;return`${f}: ${at(u)}`}let p=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(p){let[,f,u]=p;return`${f}: ${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 ds(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 nr(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 Pt(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(`
|
|
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 p=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);p&&(r=p[2],e=e.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1"));let f=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval|TjsSafeAssign)\b/,u;for(;u=e.match(f);){let w=u[2];w==="TjsStrict"?(l.tjsEquals=!0,l.tjsClass=!0,l.tjsDate=!0,l.tjsNoeval=!0,l.tjsNoVar=!0,l.tjsStandard=!0,l.tjsSafeAssign=!0):w==="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):w==="TjsEquals"?l.tjsEquals=!0:w==="TjsClass"?l.tjsClass=!0:w==="TjsDate"?l.tjsDate=!0:w==="TjsNoeval"?l.tjsNoeval=!0:w==="TjsNoVar"?l.tjsNoVar=!0:w==="TjsStandard"?l.tjsStandard=!0:w==="TjsSafeEval"?l.tjsSafeEval=!0:w==="TjsSafeAssign"&&(l.tjsSafeAssign=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${w}\\s*`),"$1")}e=Pt(e),l.tjsStandard&&(e=In(e)),e=Kn(e),e=Qn(e);let m=Xn(e);e=m.source;let y=m.annotations;e=Ue(e),l.tjsEquals&&!n.vmTarget&&(e=Le(e)),e=On(e),e=Dn(e),e=Bn(e),e=Fn(e),e=qn(e),e=Jn(e);let{source:g,returnType:_,returnSafety:$}=ct(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=g;let S=Un(e);e=S.source,e=Mn(e);let h=Wn(e,s);e=h.source;let b=Pn(e);e=b.source;let E=Vn(e,n.dangerouslySkipTests);e=E.source;let x=zn(e,s);e=x.source;for(let w of x.polyCtorClasses)o.add(`${w}$dispatch`);return l.tjsClass&&(e=Zn(e,x.polyCtorClasses)),l.tjsDate&&(e=Gn(e)),l.tjsNoeval&&(e=Hn(e)),l.tjsNoVar&&(e=Yn(e)),e=We(e,S.extensions),{source:e,returnType:_,returnSafety:$,moduleSafety:r,tjsModes:l,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:b.blocks,tests:E.tests,testErrors:E.errors,polymorphicNames:h.polymorphicNames,extensions:S.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:p,unsafeFunctions:f,safeFunctions:u,wasmBlocks:m,tests:y,testErrors:g,letAnnotations:_,tjsModes:$}=r?ut(e,{vmTarget:s}):{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:rr.parse(o,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:i,returnSafety:a,moduleSafety:c,originalSource:l,requiredParams:p,unsafeFunctions:f,safeFunctions:u,wasmBlocks:m,tests:y,testErrors:g,letAnnotations:_,tjsModes:$}}catch(S){let h=S.loc||{line:1,column:0};throw new G(S.message.replace(/\s*\(\d+:\d+\)$/,""),h,l,t)}}function sr(e,n){for(let r of e.body){if(r.type==="ImportDeclaration")throw new G("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 G("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 G("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 G("Source must contain a function declaration",{line:1,column:0},void 0,n);if(t.length>1){let r=t[1];throw new G("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 p=s[s.length-1],f=r.substring(p.index+p[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(f)){let u=p[1],m=u.split(`
|
|
49
|
+
`),y=m.filter(g=>g.trim().length>0).reduce((g,_)=>{let $=_.match(/^(\s*)/)?.[1].length||0;return Math.min(g,$)},1/0);return y>0&&y<1/0&&(u=m.map(g=>g.slice(y)).join(`
|
|
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 Os(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 Dt(e){let n=[],t=[],r=Os(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(Is(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,g=lr(e,y-1);if(g===-1)continue;let _=e.slice(y,g).trim();n.push({description:m,body:_,line:Bt(e,u)}),c.push({start:u,end:g+1,desc:m})}let l=[];for(;(a=o.exec(e))!==null;){let u=a.index,m=a.index+a[0].length,y=lr(e,m-1);if(y===-1)continue;let g=e.slice(m,y).trim();t.push({body:g,line:Bt(e,u)}),l.push({start:u,end:y+1})}let p=[...c,...l].sort((u,m)=>m.start-u.start);for(let u of p)i=i.slice(0,u.start)+i.slice(u.end);i=i.replace(/\n\s*\n\s*\n/g,`
|
|
50
52
|
|
|
51
|
-
`).trim();let f=
|
|
52
|
-
`).length}function
|
|
53
|
+
`).trim();let f=Bs(n,t);return{code:i,tests:n,mocks:t,testRunner:f}}function lr(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(`
|
|
54
|
+
`).length}function Bs(e,n){if(e.length===0)return"// No tests defined";let t=n.map(s=>s.body).join(`
|
|
53
55
|
`);return`(async () => {
|
|
54
56
|
const __results = []
|
|
55
57
|
|
|
@@ -72,13 +74,13 @@ const __failed = __results.filter(r => !r.passed).length
|
|
|
72
74
|
|
|
73
75
|
// Return summary
|
|
74
76
|
return { passed: __passed, failed: __failed, results: __results }
|
|
75
|
-
})()`.trim()}var
|
|
77
|
+
})()`.trim()}var ur=`
|
|
76
78
|
function assert(condition, message) {
|
|
77
79
|
if (!condition) {
|
|
78
80
|
throw new Error(message || 'Assertion failed')
|
|
79
81
|
}
|
|
80
82
|
}
|
|
81
|
-
`,
|
|
83
|
+
`,fr=`
|
|
82
84
|
function expect(actual) {
|
|
83
85
|
const deepEqual = (a, b) => {
|
|
84
86
|
if (a === b) return true
|
|
@@ -169,49 +171,49 @@ function expect(actual) {
|
|
|
169
171
|
}
|
|
170
172
|
}
|
|
171
173
|
}
|
|
172
|
-
`,
|
|
173
|
-
`+nr;import{validate as ur,s as ft}from"tosijs-schema";function je(e){if(e.nullable)return{anyOf:[je({...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:je(e.items)}:{type:"array"};case"object":if(e.shape){let n={},t=[];for(let[r,s]of Object.entries(e.shape))n[r]=je(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(je)}:{};default:return{}}}function ve(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:ve(e[0])};let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=ve(s),t.push(r);return{type:"object",properties:n,required:t,additionalProperties:!1}}default:return{}}}function It(e){let n={},t=[];for(let[o,i]of Object.entries(e.params))i?.type?.kind?n[o]=je(i.type):i?.example!==void 0?n[o]=ve(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=je(e.returns.type):e.returns.example!==void 0&&(s=ve(e.returns.example))),{input:r,output:s}}import{validate as Ot,filter as ws,s as ct}from"tosijs-schema";function he(e){return e!==null&&typeof e=="object"&&"__runtimeType"in e&&e.__runtimeType===!0}function rr(e){return e!==null&&typeof e=="object"&&"schema"in e&&typeof e.schema=="object"}function Ss(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=ct.infer(a));else if(n===void 0&&a!==void 0)i=ct.infer(a);else if(rr(n))i=n;else if(Ss(n))i=n;else if(n!==void 0)a=n,c=a,i=ct.infer(a);else throw new Error("Type(description) requires a predicate, schema, or example");else rr(e),i=e,s=$s(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?Ot(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?ve(a):{description:s}},strip(f){return i?ws(f,i):f},__runtimeType:!0}}function $s(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 Bt=z("string",e=>typeof e=="string"?!0:`expected string, got ${e===null?"null":typeof e}`),Dt=z("number",e=>typeof e=="number"?!0:`expected number, got ${e===null?"null":typeof e}`),Ft=z("boolean",e=>typeof e=="boolean"?!0:`expected boolean, got ${e===null?"null":typeof e}`),qt=z("integer",e=>typeof e!="number"?`expected integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?!0:`${e} is not an integer`),Ut=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`),Wt=z("non-empty string",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:e.length===0?"string is empty":!0),Lt=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`),sr=e=>{try{return new URL(e),!0}catch{return!1}},Jt=z("URL",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:sr(e)?!0:`"${e}" is not a valid URL`),Vt=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`),ir=e=>{let n=new Date(e);return!isNaN(n.getTime())&&e.includes("T")},or=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let n=new Date(e+"T00:00:00Z");return!isNaN(n.getTime())},ar=z("ISO 8601 timestamp",e=>typeof e=="string"&&ir(e)),cr=z("date (YYYY-MM-DD)",e=>typeof e=="string"&&or(e));function zt(e){return z(`${e.description} or null`,n=>n===null||e.check(n)===!0)}function Zt(e){return z(`${e.description} (optional)`,n=>n==null||e.check(n)===!0)}function Gt(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=[];he(e)&&r.push(e),he(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 Kt(e){return z(`array of ${e.description}`,n=>Array.isArray(n)&&n.every(t=>e.check(t)===!0))}function Es(e){if(he(e))return t=>e.check(t)===!0;if(e&&typeof e=="object"&&"schema"in e)return t=>Ot(t,e);let n=ct.infer(e);return t=>Ot(t,n)}function Ve(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,d)=>{let f=d<i.length?i[d]:s[d];return f===void 0?()=>!0:Es(f)}),c=t;return r.forEach((l,d)=>{let f=d<i.length?i[d]:s[d],u="any";he(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 Yt=Ve(["T","U"],(e,n,t)=>Array.isArray(e)&&e.length===2&&n(e[0])&&t(e[1]),"Pair<T, U>"),Ht=Ve(["V"],(e,n)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(n),"Record<string, V>");function Qt(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 Ts(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 lt(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((d,f)=>f<a.length?a[f]:o[f]),l=t(...c);return lt(e,l)});return Object.defineProperties(i,{typeParamNames:{value:s,enumerable:!0},description:{value:e,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),i}return ks(e,n)}function ks(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 d=Object.keys(l.params).length;if(d!==a)return`expected ${a} params, got ${d}`;let f=Object.keys(t),u=Object.keys(l.params);for(let p=0;p<f.length;p++){let y=l.params[u[p]],x=t[f[p]];if(y?.type?.kind&&x!==void 0){let _=Ts(x);if(_&&y.type.kind!==_&&y.type.kind!=="any")return`param '${f[p]}' expected ${_}, got ${y.type.kind}`}}}}return!0},__runtimeType:!0}}var vs=lr(),ce=vs.version,ze=Symbol.for("tjs.equals");function pt(e){let[n=0,t=0,r=0]=e.split(".").map(Number);return{major:n,minor:t,patch:r}}function en(e,n){let t=pt(e),r=pt(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 tn(e,n){let t=pt(e),r=pt(n);return t.major===r.major}var Ne=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 As(e,n,t,r){let s=t===null?"null":typeof t,o=D.callStacks||D.debug?rn():void 0,i=r?`Expected ${n} for '${e}': ${r}`:`Expected ${n} for '${e}', got ${s}`,a=new Ne(i,e,n,s,o,r);if(D.trackErrors!==!1){let c=D.maxErrors??mt;pr[Ae]=a,Ae=(Ae+1)%c,_e<c&&_e++,dt++}if(D.logTypeErrors&&console.error(`[TJS TypeError] ${a.message}`),D.throwTypeErrors)throw a;return a}function Xt(e){return e instanceof Error&&e.name==="MonadicError"&&"path"in e}var nn={debug:!1,safety:"inputs",requireReturnTypes:!1,callStacks:!1,maxStackSize:64,trackErrors:!0,maxErrors:64},D={...nn},Ze=64,fr=new Array(Ze).fill(""),xe=0,ue=0,mt=64,pr=new Array(mt).fill(null),Ae=0,_e=0,dt=0,Me=0;function Rs(){Me++}function Cs(){Me>0&&Me--}function Ns(){return Me>0}function Ms(e){D={...D,...e}}function Ps(){return{...D}}function mr(e){if((D.callStacks||D.debug)&&e){let n=D.maxStackSize??Ze;fr[xe]=e,xe=(xe+1)%n,ue<n&&ue++}}function ut(){if((D.callStacks||D.debug)&&ue>0){let e=D.maxStackSize??Ze;xe=(xe-1+e)%e,ue--}}function rn(){if(ue===0)return[];let e=D.maxStackSize??Ze,n=[],t=(xe-ue+e)%e;for(let r=0;r<ue;r++)n.push(fr[(t+r)%e]);return n}function dr(){if(D.trackErrors===!1||_e===0)return[];let e=D.maxErrors??mt,n=[],t=(Ae-_e+e)%e;for(let r=0;r<_e;r++)n.push(pr[(t+r)%e]);return n}function Is(){let e=dr();return Ae=0,_e=0,dt=0,e}function Os(){return dt}function Bs(){D={...nn},xe=0,ue=0,Ae=0,_e=0,dt=0,Me=0}function Re(e,n){if(e!==null&&typeof e=="object"&&typeof e[ze]=="function")return e[ze](n);if(n!==null&&typeof n=="object"&&typeof n[ze]=="function")return n[ze](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)||!Re(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)=>Re(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=>Re(e[s],n[s]))}function yr(e,n){return!Re(e,n)}function gr(e){return e===null?"null":typeof e}function sn(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 hr(e,n){return!sn(e,n)}function le(e){return e!==null&&typeof e=="object"&&e.$error===!0}function ae(e,n){let t={$error:!0,message:e,...n};if((D.callStacks||D.debug)&&ue>0){let r=rn(),s=n?.path?[...r,n.path]:r;t.stack=s}return t}function on(e,n){if(e.length===0)return ae("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 ae(r,{path:n,errors:e})}function Ce(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 br(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 we(e,n,t){if(le(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 ${Ce(e)}`;return ae(i,{path:t,expected:n.description,actual:Ce(e),reason:o})}let r=Ce(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:ae(`Expected ${n} but got ${r}`,{path:t,expected:n,actual:r})}function an(e,n,t){for(let[r,s]of Object.entries(n.params)){let o=e[r];if(le(o))return o;if(s.required&&o===void 0){let a=typeof s.type=="string"?s.type:s.type.description;return ae(`Missing required parameter '${r}'`,{path:t?`${t}.${r}`:r,expected:a,actual:"undefined",loc:s.loc})}if(o===void 0)continue;let i=we(o,s.type,t?`${t}.${r}`:r);if(i)return s.loc&&(i.loc=s.loc),i}return null}function cn(e,n){if(e.__tjs=n,e.__tjs.schema=()=>It(n),!(!n.polymorphic&&(n.safe||n.safeReturn||D.safety!=="none"&&!n.unsafe||n.returns&&D.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),d=l.length,f=e.name||n.name||"anonymous",u=function(...p){if(Me>0)return e.apply(this,p);let y=o||!s&&D.safety!=="none",x=r&&(a||!i&&D.safety==="all");if(!y&&!x)return e.apply(this,p);if(p.length>0&&le(p[0]))return p[0];if(y){let w=p.length===1&&typeof p[0]=="object"&&p[0]!==null&&!Array.isArray(p[0]),$=[];if(w){let h=p[0];for(let g=0;g<d;g++){let[S,b]=l[g],E=h[S];if(le(E)){$.push(E);continue}if(b.required&&E===void 0){$.push(ae(`Missing required parameter '${S}'`,{path:`${f}.${S}`,expected:typeof b.type=="string"?b.type:b.type?.description||"value",actual:"undefined",loc:b.loc}));continue}if(E!==void 0){let k=we(E,b.type,`${f}.${S}`);k&&(b.loc&&(k.loc=b.loc),$.push(k))}}}else for(let h=0;h<d;h++){let[g,S]=l[h],b=p[h];if(le(b)){$.push(b);continue}if(S.required&&b===void 0){$.push(ae(`Missing required parameter '${g}'`,{path:`${f}.${g}`,expected:typeof S.type=="string"?S.type:S.type?.description||"value",actual:"undefined",loc:S.loc}));continue}if(b!==void 0){let E=we(b,S.type,`${f}.${g}`);E&&(S.loc&&(E.loc=S.loc),$.push(E))}}if($.length>0)return on($,f)}let _=D.callStacks||D.debug;_&&mr(f);try{let w=e.apply(this,p);if(x&&n.returns&&!le(w)){let $=c&&typeof w=="object"&&w!==null?Object.assign({},c,w):w,h=we($,n.returns.type,`${f}()`);if(h)return _&&ut(),h}return _&&ut(),w}catch(w){return _&&ut(),ae(w.message||String(w),{path:f,cause:w})}};return Object.defineProperty(u,"name",{value:e.name}),u.__tjs=n,u.__tjs.schema=()=>It(n),u}function xr(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 _r(){let e={...D},n=e.maxStackSize??Ze,t=new Array(n).fill(""),r=0,s=0,o=e.maxErrors??mt,i=new Array(o).fill(null),a=0,c=0,l=0,d=0;function f(v){e={...e,...v}}function u(){return{...e}}function p(v){(e.callStacks||e.debug)&&v&&(t[r]=v,r=(r+1)%n,s<n&&s++)}function y(){(e.callStacks||e.debug)&&s>0&&(r=(r-1+n)%n,s--)}function x(){if(s===0)return[];let v=[],M=(r-s+n)%n;for(let P=0;P<s;P++)v.push(t[(M+P)%n]);return v}function _(){e={...nn},r=0,s=0,a=0,c=0,l=0,d=0}function w(){d++}function $(){d>0&&d--}function h(){return d>0}let g=new Map;function S(v,M,P){g.has(v)||g.set(v,new Map),g.get(v).set(M,P)}function b(v,M){let P=typeof v,V;if(v==null)return;if(P==="string")V="String";else if(P==="number")V="Number";else if(P==="boolean")V="Boolean";else if(Array.isArray(v))V="Array";else if(P==="object")V=v.constructor?.name||"Object";else return;let J=V;for(;J;){let Te=g.get(J);if(Te?.has(M))return Te.get(M);if(P==="object"&&!Array.isArray(v)){if(J=Object.getPrototypeOf(J===V?v:Object.getPrototypeOf(v))?.constructor?.name,J==="Object"||J===V)break}else break}let K=g.get("Object");if(K?.has(M))return K.get(M)}function E(v,M,P){let V=P===null?"null":typeof P,J=e.callStacks||e.debug?x():void 0,K=new Ne(`Expected ${M} for '${v}', got ${V}`,v,M,V,J);if(e.trackErrors!==!1&&(i[a]=K,a=(a+1)%o,c<o&&c++,l++),e.logTypeErrors&&console.error(`[TJS TypeError] ${K.message}`),e.throwTypeErrors)throw K;return K}function k(){if(e.trackErrors===!1||c===0)return[];let v=[],M=(a-c+o)%o;for(let P=0;P<c;P++)v.push(i[(M+P)%o]);return v}function j(){let v=k();return a=0,c=0,l=0,v}function R(){return l}function C(v,M){let P={$error:!0,message:v,...M};if((e.callStacks||e.debug)&&s>0){let V=M?.path?[...x(),M.path]:x();P.stack=V}return P}function N(v,M){return v==null?E(`bang.${M}`,"non-null",v):Xt(v)?v:v[M]}return{version:ce,MonadicError:Ne,typeError:E,isMonadicError:Xt,bang:N,isError:le,error:C,composeErrors:on,typeOf:Ce,isNativeType:br,checkType:we,validateArgs:an,wrap:cn,wrapClass:xr,compareVersions:en,versionsCompatible:tn,createRuntime:_r,configure:f,getConfig:u,pushStack:p,popStack:y,getStack:x,errors:k,clearErrors:j,getErrorCount:R,resetRuntime:_,enterUnsafe:w,exitUnsafe:$,isUnsafeMode:h,validate:ur,infer:ft.infer.bind(ft),Type:z,isRuntimeType:he,Union:Gt,Generic:Ve,Enum:Qt,FunctionPredicate:lt,Nullable:zt,Optional:Zt,TArray:Kt,TString:Bt,TNumber:Dt,TBoolean:Ft,TInteger:qt,TPositiveInt:Ut,TNonEmptyString:Wt,TEmail:Lt,TUrl:Jt,TUuid:Vt,TPair:Yt,TRecord:Ht,Is:Re,IsNot:yr,Eq:sn,NotEq:hr,TypeOf:gr,tjsEquals:ze,registerExtension:S,resolveExtension:b}}var be={version:ce,MonadicError:Ne,typeError:As,isMonadicError:Xt,isError:le,error:ae,composeErrors:on,typeOf:Ce,isNativeType:br,checkType:we,validateArgs:an,wrap:cn,wrapClass:xr,compareVersions:en,versionsCompatible:tn,configure:Ms,getConfig:Ps,pushStack:mr,popStack:ut,getStack:rn,errors:dr,clearErrors:Is,getErrorCount:Os,resetRuntime:Bs,enterUnsafe:Rs,exitUnsafe:Cs,isUnsafeMode:Ns,createRuntime:_r,validate:ur,infer:ft.infer.bind(ft),Type:z,isRuntimeType:he,Union:Gt,Generic:Ve,Enum:Qt,FunctionPredicate:lt,Nullable:zt,Optional:Zt,TArray:Kt,TString:Bt,TNumber:Dt,TBoolean:Ft,TInteger:qt,TPositiveInt:Ut,TNonEmptyString:Wt,TEmail:Lt,TUrl:Jt,TUuid:Vt,Timestamp:ar,LegalDate:cr,TPair:Yt,TRecord:Ht,Is:Re,IsNot:yr,Eq:sn,NotEq:hr,TypeOf:gr};function ln(){let e=globalThis;if(e.__tjs){let n=e.__tjs.version;if(typeof n!="string")return e.__tjs=be,be;let t=en(ce,n);return t===0||(tn(ce,n)?t>0?(console.info(`TJS runtime: upgrading ${n} \u2192 ${ce}`),e.__tjs=be):console.info(`TJS runtime: keeping ${n} (newer than ${ce})`):(console.warn(`TJS runtime version conflict: ${n} vs ${ce} (major version mismatch)`),t>0&&(console.warn(`Upgrading to ${ce} - check for breaking changes`),e.__tjs=be))),e.__tjs}return e.__tjs=be,be}function Ds(e){return`
|
|
174
|
+
`,Ds=ur+`
|
|
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`
|
|
174
176
|
// TJS runtime wrapper (skips unsafe functions)
|
|
175
177
|
if (typeof ${e}.__tjs === 'object' && !${e}.__tjs.unsafe && typeof globalThis.__tjs?.wrap === 'function') {
|
|
176
178
|
${e} = globalThis.__tjs.wrap(${e}, ${e}.__tjs)
|
|
177
179
|
}
|
|
178
|
-
`.trim()}function
|
|
180
|
+
`.trim()}function ri(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 yn(e,n){if(e===n||typeof e=="number"&&typeof n=="number"&&Number.isNaN(e)&&Number.isNaN(n)||ri(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)=>yn(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=>yn(e[s],n[s]))}function gn(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=gn(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=gn(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,p])=>`${r(l)}: ${He(p,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(`,
|
|
179
181
|
`),a=t.length>8?`,
|
|
180
182
|
${s}...`:"";return`{
|
|
181
183
|
${i}${a}
|
|
182
|
-
${o}}`}return String(e)}function
|
|
184
|
+
${o}}`}return String(e)}function si(e){let n=e.replace(/\/\*[\s\S]*?\*\//g,t=>{let r=t.split(`
|
|
183
185
|
`).length-1;return`
|
|
184
|
-
`.repeat(r)});return n=n.replace(/\/\/[^\n]*/g,""),n}function
|
|
185
|
-
`)}function
|
|
186
|
-
`).length;if(
|
|
187
|
-
`).length,
|
|
188
|
-
`),u="const { Is, IsNot, Eq, NotEq, TypeOf } = globalThis.__tjs ?? {};",
|
|
189
|
-
// Test ${
|
|
186
|
+
`.repeat(r)});return n=n.replace(/\/\/[^\n]*/g,""),n}function Mr(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 ii(e){if(Object.keys(e).length===0)return"";let n=[];for(let[t,r]of Object.entries(e)){let s=Mr(r);n.push(`// Resolved import: ${t}`),n.push(s)}return n.join(`
|
|
187
|
+
`)}function Nr(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 p=o+1;for(;p<t.length&&/\s/.test(t[p]);)p++;let f="",u=0;for(;p<t.length;){let m=t[p];if(m==="{"||m==="["||m==="(")u++;else if(m==="}"||m==="]"||m===")"){if(u===0)break;u--}else if(m===","&&u===0)break;f+=m,p++}try{n[l[1]]=new Function(`return ${f.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 Pr(e){let n=[],t=si(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],p=s[4],f=t.slice(0,s.index).split(`
|
|
188
|
+
`).length;if(p===":!")continue;let u=t.slice(s.index+s[0].length),m=xt(u);if(!m)continue;let y=dn(l);if(!(l.trim()&&y.length===0))try{let g=Nr(m);if(!g)continue;let _=y.map($=>new Function(`return ${$}`)());n.push({funcName:c,args:_,expected:g.pattern,defaults:Object.keys(g.defaults).length>0?g.defaults:void 0,line:f,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,p=c;for(let h=c;h<t.length;h++)if(t[h]==="{")l++;else if(t[h]==="}"&&(l--,l===0)){p=h;break}let f=t.slice(c,p),m=/constructor\s*\(([^)]*)\)/.exec(f);if(!m)continue;let y=m[1],g=dn(y);if(y.trim()&&g.length===0)continue;let _;try{_=g.map(h=>new Function(`return ${h}`)())}catch{continue}let $=/(async\s+)?(\w+)\s*\(([^)]*)\)\s*(:[?!]?)\s*/g,S;for(;(S=$.exec(f))!==null;){let h=S[2];if(h==="constructor")continue;let b=!!S[1],E=S[3];if(S[4]===":!")continue;let w=c+S.index,k=t.slice(0,w).split(`
|
|
189
|
+
`).length,A=f.slice(S.index+S[0].length),R=xt(A);if(!R)continue;let C=dn(E);if(!(E.trim()&&C.length===0))try{let N=Nr(R);if(!N)continue;let j=C.map(M=>new Function(`return ${M}`)());n.push({funcName:h,args:j,expected:N.pattern,defaults:Object.keys(N.defaults).length>0?N.defaults:void 0,line:k,isAsync:b,className:a,constructorArgs:_})}catch{}}}return n}function Ir(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(b=>{let E=b.match(/from\s+['"]([^'"]+)['"]/);return E&&!(E[1]in s)}),l=Mr(r),p=ii(s),f=n.map(b=>b.body).join(`
|
|
190
|
+
`),u="const { Is, IsNot, Eq, NotEq, TypeOf } = globalThis.__tjs ?? {};",m=e.map((b,E)=>{let x=o.size>0?We(b.body,o):b.body;return`
|
|
191
|
+
// Test ${E}: ${b.description}
|
|
190
192
|
try {
|
|
191
193
|
${u}
|
|
192
|
-
${
|
|
193
|
-
__testResults.push({ idx: ${
|
|
194
|
+
${x}
|
|
195
|
+
__testResults.push({ idx: ${E}, passed: true });
|
|
194
196
|
} catch (e) {
|
|
195
|
-
__testResults.push({ idx: ${
|
|
197
|
+
__testResults.push({ idx: ${E}, passed: false, error: e.message || String(e) });
|
|
196
198
|
}
|
|
197
199
|
`}).join(`
|
|
198
|
-
`),y=t.filter(
|
|
199
|
-
// Signature test ${
|
|
200
|
+
`),y=t.filter(b=>!b.isAsync),g=t.filter(b=>b.isAsync),_=y.map((b,E)=>{let x=b.className?`${b.className}.${b.funcName}`:b.funcName,w=b.className?`new ${b.className}(${(b.constructorArgs||[]).map(k=>JSON.stringify(k)).join(", ")}).${b.funcName}(${b.args.map(k=>JSON.stringify(k)).join(", ")})`:`${b.funcName}(${b.args.map(k=>JSON.stringify(k)).join(", ")})`;return`
|
|
201
|
+
// Signature test ${E}: ${x}
|
|
200
202
|
try {
|
|
201
|
-
let __actual = ${
|
|
202
|
-
const __expected = ${JSON.stringify(
|
|
203
|
-
const __defaults = ${JSON.stringify(
|
|
203
|
+
let __actual = ${w};
|
|
204
|
+
const __expected = ${JSON.stringify(b.expected)};${b.defaults?`
|
|
205
|
+
const __defaults = ${JSON.stringify(b.defaults)};
|
|
204
206
|
if (typeof __actual === 'object' && __actual !== null) __actual = Object.assign({}, __defaults, __actual);`:""}
|
|
205
207
|
if (__deepEqual(__actual, __expected)) {
|
|
206
|
-
__sigTestResults.push({ idx: ${
|
|
208
|
+
__sigTestResults.push({ idx: ${E}, passed: true });
|
|
207
209
|
} else {
|
|
208
|
-
__sigTestResults.push({ idx: ${
|
|
210
|
+
__sigTestResults.push({ idx: ${E}, passed: false, error: 'Expected ' + __format(__expected) + ' at \\'${x}\\', got ' + __format(__actual) });
|
|
209
211
|
}
|
|
210
212
|
} catch (e) {
|
|
211
|
-
__sigTestResults.push({ idx: ${
|
|
213
|
+
__sigTestResults.push({ idx: ${E}, passed: false, error: e.message || String(e) });
|
|
212
214
|
}
|
|
213
215
|
`}).join(`
|
|
214
|
-
`);
|
|
216
|
+
`);mn();let h=`
|
|
215
217
|
|
|
216
218
|
const __saved_tjs = globalThis.__tjs;
|
|
217
219
|
|
|
@@ -279,14 +281,14 @@ ${o}}`}return String(e)}function qs(e){let n=e.replace(/\/\*[\s\S]*?\*\//g,t=>{l
|
|
|
279
281
|
}
|
|
280
282
|
|
|
281
283
|
// Inject resolved imports first (they may be dependencies)
|
|
282
|
-
${
|
|
284
|
+
${p}
|
|
283
285
|
|
|
284
286
|
// Execute the module code ONCE
|
|
285
287
|
${l}
|
|
286
288
|
${f}
|
|
287
289
|
|
|
288
290
|
// Run explicit test blocks
|
|
289
|
-
${
|
|
291
|
+
${m}
|
|
290
292
|
|
|
291
293
|
// Run signature tests
|
|
292
294
|
${_}
|
|
@@ -295,8 +297,8 @@ ${o}}`}return String(e)}function qs(e){let n=e.replace(/\/\*[\s\S]*?\*\//g,t=>{l
|
|
|
295
297
|
globalThis.__tjs = __saved_tjs;
|
|
296
298
|
}
|
|
297
299
|
return { testResults: __testResults, sigTestResults: __sigTestResults };
|
|
298
|
-
`;try{let
|
|
299
|
-
`)}var ht={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:m.i32_load8_s,storeOp:m.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:m.i32_load8_u,storeOp:m.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:m.i32_load8_u,storeOp:m.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:m.i32_load16_s,storeOp:m.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:m.i32_load16_u,storeOp:m.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:m.i32_load,storeOp:m.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:m.i32_load,storeOp:m.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:m.f32_load,storeOp:m.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:m.f64_load,storeOp:m.f64_store}};function Zs(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 gt(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 $e(e,n){return e.locals.get(n)}function Pe(e,n){switch(e.type){case"ExpressionStatement":{let t=e.expression;return[...B(t,n),m.drop]}case"ReturnStatement":{let t=e;if(n.hasReturn=!0,!t.argument)return[m.return];let r=B(t.argument,n),s=L(t.argument,n);return s==="i32"?r.push(m.f64_convert_i32_s):s==="f32"&&r.push(m.f64_promote_f32),r.push(m.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=L(s.init,n));let a=gt(n,o,i);s.init&&(r.push(...B(s.init,n)),r.push(m.local_set,...I(a)))}return r}case"ForStatement":return Gs(e,n);case"IfStatement":return Ks(e,n);case"BlockStatement":{let t=e,r=[];for(let s of t.body)r.push(...Pe(s,n));return r}default:return n.errors.push(`Unsupported statement type: ${e.type}`),[]}}function Gs(e,n){let t=[];return e.init&&(e.init.type==="VariableDeclaration"?t.push(...Pe(e.init,n)):t.push(...B(e.init,n))),t.push(m.block,se.void),t.push(m.loop,se.void),e.test&&(t.push(...B(e.test,n)),t.push(m.i32_eqz),t.push(m.br_if,1)),n.loopDepth++,e.body&&t.push(...Pe(e.body,n)),n.loopDepth--,e.update&&(t.push(...B(e.update,n)),t.push(m.drop)),t.push(m.br,0),t.push(m.end),t.push(m.end),t}function Ks(e,n){let t=[];return t.push(...B(e.test,n)),t.push(m.if,se.void),t.push(...Pe(e.consequent,n)),e.alternate&&(t.push(m.else),t.push(...Pe(e.alternate,n))),t.push(m.end),t}function L(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 $e(n,e.name)?.type??"f64";case"BinaryExpression":case"AssignmentExpression":{let t=e;if(["<",">","<=",">=","==","!=","===","!=="].includes(t.operator)||["|","&","^","<<",">>",">>>"].includes(t.operator))return"i32";let r=L(t.left,n),s=L(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":L(t.argument,n)}case"MemberExpression":{let t=e;if(t.object.type==="Identifier"&&$e(n,t.object.name)){let s=n.params.find(o=>o.name===t.object.name);if(s?.arrayType){let o=ht[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 B(e,n){switch(e.type){case"Literal":{let t=e;if(typeof t.value=="number"){let r=L(e,n);return r==="i32"?[m.i32_const,...Qe(t.value|0)]:r==="f32"?[m.f32_const,...yn(t.value)]:[m.f64_const,...te(t.value)]}return n.errors.push(`Unsupported literal type: ${typeof t.value}`),[m.f64_const,...te(0)]}case"Identifier":{let t=e.name,r=$e(n,t);return r?[m.local_get,...I(r.index)]:(n.errors.push(`Unknown identifier: ${t}`),[m.f64_const,...te(0)])}case"BinaryExpression":return Ys(e,n);case"UnaryExpression":return Hs(e,n);case"AssignmentExpression":return Qs(e,n);case"UpdateExpression":return Xs(e,n);case"MemberExpression":return ei(e,n);case"CallExpression":return ni(e,n);case"SequenceExpression":{let t=e,r=[];for(let s=0;s<t.expressions.length;s++)r.push(...B(t.expressions[s],n)),s<t.expressions.length-1&&r.push(m.drop);return r}default:return n.errors.push(`Unsupported expression type: ${e.type}`),[m.f64_const,...te(0)]}}function Ys(e,n){let t=B(e.left,n),r=B(e.right,n),s=L(e,n),o=L(e.left,n),i=L(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,d=r;c==="f64"?(o==="i32"?l=[...t,m.f64_convert_i32_s]:o==="f32"&&(l=[...t,m.f64_promote_f32]),i==="i32"?d=[...r,m.f64_convert_i32_s]:i==="f32"&&(d=[...r,m.f64_promote_f32])):c==="f32"&&(o==="i32"&&(l=[...t,m.f32_convert_i32_s]),i==="i32"&&(d=[...r,m.f32_convert_i32_s]));let u={"+":{i32:m.i32_add,f32:m.f32_add,f64:m.f64_add},"-":{i32:m.i32_sub,f32:m.f32_sub,f64:m.f64_sub},"*":{i32:m.i32_mul,f32:m.f32_mul,f64:m.f64_mul},"/":{i32:m.i32_div_s,f32:m.f32_div,f64:m.f64_div},"%":{i32:m.i32_rem_s},"<":{i32:m.i32_lt_s,f32:m.f32_lt,f64:m.f64_lt},">":{i32:m.i32_gt_s,f32:m.f32_gt,f64:m.f64_gt},"<=":{i32:m.i32_le_s,f32:m.f32_le,f64:m.f64_le},">=":{i32:m.i32_ge_s,f32:m.f32_ge,f64:m.f64_ge},"==":{i32:m.i32_eq,f32:m.f32_eq,f64:m.f64_eq},"===":{i32:m.i32_eq,f32:m.f32_eq,f64:m.f64_eq},"!=":{i32:m.i32_ne,f32:m.f32_ne,f64:m.f64_ne},"!==":{i32:m.i32_ne,f32:m.f32_ne,f64:m.f64_ne},"|":{i32:m.i32_or},"&":{i32:m.i32_and},"^":{i32:m.i32_xor},"<<":{i32:m.i32_shl},">>":{i32:m.i32_shr_s},">>>":{i32:m.i32_shr_u}}[e.operator];if(!u)return n.errors.push(`Unsupported operator: ${e.operator}`),[m.f64_const,...te(0)];let p=u[c]??u.f64??u.i32;return p===void 0?(n.errors.push(`Operator ${e.operator} not supported for type ${c}`),[m.f64_const,...te(0)]):[...l,...d,p]}function Hs(e,n){let t=B(e.argument,n),r=L(e.argument,n);switch(e.operator){case"-":return r==="i32"?[m.i32_const,0,...t,m.i32_sub]:r==="f32"?[...t,m.f32_neg]:[...t,m.f64_neg];case"!":return[...t,m.i32_eqz];case"~":return[...t,m.i32_const,...Qe(-1),m.i32_xor];default:return n.errors.push(`Unsupported unary operator: ${e.operator}`),t}}function Qs(e,n){if(e.left.type==="MemberExpression")return ti(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=$e(n,t);if(!r)return n.errors.push(`Unknown variable: ${t}`),[];let s=[];if(e.operator==="="){s.push(...B(e.right,n));let o=L(e.right,n);r.type==="f64"&&o==="i32"?s.push(m.f64_convert_i32_s):r.type==="f64"&&o==="f32"?s.push(m.f64_promote_f32):r.type==="i32"&&o==="f64"?s.push(m.i32_trunc_f64_s):r.type==="i32"&&o==="f32"?s.push(m.i32_trunc_f32_s):r.type==="f32"&&o==="i32"?s.push(m.f32_convert_i32_s):r.type==="f32"&&o==="f64"&&s.push(m.f32_demote_f64)}else{let o=L(e.right,n),i=r.type;o==="f64"||r.type==="f64"?i="f64":(o==="f32"||r.type==="f32")&&(i="f32"),s.push(m.local_get,...I(r.index)),i==="f64"&&r.type==="i32"?s.push(m.f64_convert_i32_s):i==="f64"&&r.type==="f32"?s.push(m.f64_promote_f32):i==="f32"&&r.type==="i32"&&s.push(m.f32_convert_i32_s),s.push(...B(e.right,n)),i==="f64"&&o==="i32"?s.push(m.f64_convert_i32_s):i==="f64"&&o==="f32"?s.push(m.f64_promote_f32):i==="f32"&&o==="i32"&&s.push(m.f32_convert_i32_s);let a=e.operator.slice(0,-1),l={"+":{i32:m.i32_add,f32:m.f32_add,f64:m.f64_add},"-":{i32:m.i32_sub,f32:m.f32_sub,f64:m.f64_sub},"*":{i32:m.i32_mul,f32:m.f32_mul,f64:m.f64_mul},"/":{i32:m.i32_div_s,f32:m.f32_div,f64:m.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(m.i32_trunc_f64_s):r.type==="i32"&&i==="f32"?s.push(m.i32_trunc_f32_s):r.type==="f32"&&i==="f64"&&s.push(m.f32_demote_f64)}return s.push(m.local_tee,...I(r.index)),s}function Xs(e,n){if(e.argument.type!=="Identifier")return n.errors.push("Update expression argument must be identifier"),[];let t=e.argument.name,r=$e(n,t);if(!r)return n.errors.push(`Unknown variable: ${t}`),[];let s=[],o=r.type==="i32";return e.prefix?(s.push(m.local_get,...I(r.index)),o?(s.push(m.i32_const,1),s.push(e.operator==="++"?m.i32_add:m.i32_sub)):(s.push(m.f64_const,...te(1)),s.push(e.operator==="++"?m.f64_add:m.f64_sub)),s.push(m.local_tee,...I(r.index))):(s.push(m.local_get,...I(r.index)),s.push(m.local_get,...I(r.index)),o?(s.push(m.i32_const,1),s.push(e.operator==="++"?m.i32_add:m.i32_sub)):(s.push(m.f64_const,...te(1)),s.push(e.operator==="++"?m.f64_add:m.f64_sub)),s.push(m.local_set,...I(r.index))),s}function ei(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=ht[r.arrayType];if(!s)return n.errors.push(`Unknown array type: ${r.arrayType}`),[];n.needsMemory=!0;let o=[],i=$e(n,t);if(!i)return n.errors.push(`Unknown array: ${t}`),[];if(o.push(m.local_get,...I(i.index)),!e.computed||!e.property)return n.errors.push("Array access requires computed index"),[];let a=B(e.property,n),c=L(e.property,n);return o.push(...a),c==="f64"&&o.push(m.i32_trunc_f64_s),s.bytesPerElement>1&&(o.push(m.i32_const,...Qe(s.bytesPerElement)),o.push(m.i32_mul)),o.push(m.i32_add),o.push(s.loadOp,0,0),o}function ti(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=ht[o.arrayType];if(!i)return r.errors.push(`Unknown array type: ${o.arrayType}`),[];r.needsMemory=!0;let a=[],c=$e(r,s);if(!c)return[];if(!e.computed||!e.property)return r.errors.push("Array store requires computed index"),[];let l=B(e.property,r),d=L(e.property,r),f=()=>{let y=[];return y.push(m.local_get,...I(c.index)),y.push(...l),d==="f64"&&y.push(m.i32_trunc_f64_s),i.bytesPerElement>1&&(y.push(m.i32_const,...Qe(i.bytesPerElement)),y.push(m.i32_mul)),y.push(m.i32_add),y};if(t==="=")a.push(...B(n,r));else{let y=gt(r,`__addr_${r.nextLocalIndex}`,"i32");a.push(...f()),a.push(m.local_tee,...I(y)),a.push(i.loadOp,0,0),a.push(...B(n,r));let x=L(n,r);i.elementType==="f32"&&x==="f64"?a.push(m.f32_demote_f64):i.elementType==="f64"&&x==="f32"?a.push(m.f64_promote_f32):i.elementType==="f32"&&x==="i32"?a.push(m.f32_convert_i32_s):i.elementType==="f64"&&x==="i32"?a.push(m.f64_convert_i32_s):i.elementType==="i32"&&x==="f64"?a.push(m.i32_trunc_f64_s):i.elementType==="i32"&&x==="f32"&&a.push(m.i32_trunc_f32_s);let _=t.slice(0,-1),w={"+":i.elementType==="i32"?m.i32_add:i.elementType==="f32"?m.f32_add:m.f64_add,"-":i.elementType==="i32"?m.i32_sub:i.elementType==="f32"?m.f32_sub:m.f64_sub,"*":i.elementType==="i32"?m.i32_mul:i.elementType==="f32"?m.f32_mul:m.f64_mul};a.push(w[_]??m.f64_add);let $=gt(r,`__val_${r.nextLocalIndex}`,i.elementType);return a.push(m.local_set,...I($)),a.push(m.local_get,...I(y)),a.push(m.local_get,...I($)),a.push(i.storeOp,0,0),a.push(m.local_get,...I($)),a}let u=L(n,r);i.elementType==="f32"&&u==="f64"?a.push(m.f32_demote_f64):i.elementType==="f64"&&u==="f32"?a.push(m.f64_promote_f32):i.elementType==="i32"&&u==="f64"&&a.push(m.i32_trunc_f64_s);let p=gt(r,`__tmp_${r.nextLocalIndex}`,i.elementType);return a.push(m.local_set,...I(p)),a.push(m.local_get,...I(c.index)),a.push(...l),d==="f64"&&a.push(m.i32_trunc_f64_s),i.bytesPerElement>1&&(a.push(m.i32_const,...Qe(i.bytesPerElement)),a.push(m.i32_mul)),a.push(m.i32_add),a.push(m.local_get,...I(p)),a.push(i.storeOp,0,0),a.push(m.local_get,...I(p)),a}function ni(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 ri(t,e.arguments,n)}return n.errors.push(`Unsupported function call: ${e.callee.type}`),[m.f64_const,...te(0)]}function ri(e,n,t){t.needsMemory=!0;let r=[];switch(e){case"v128_load":case"f32x4_load":{r.push(...B(n[0],t)),L(n[0],t)==="f64"&&r.push(m.i32_trunc_f64_s),r.push(...B(n[1],t));let o=L(n[1],t);return o==="f64"?r.push(m.i32_trunc_f64_s):o==="f32"&&r.push(m.i32_trunc_f32_s),r.push(m.i32_add),r.push(...Tr(G.v128_load,2,0)),r}case"v128_store":case"f32x4_store":{r.push(...B(n[0],t)),L(n[0],t)==="f64"&&r.push(m.i32_trunc_f64_s),r.push(...B(n[1],t));let o=L(n[1],t);return o==="f64"?r.push(m.i32_trunc_f64_s):o==="f32"&&r.push(m.i32_trunc_f32_s),r.push(m.i32_add),r.push(...B(n[2],t)),r.push(...Tr(G.v128_store,2,0)),r.push(m.i32_const,0),r}case"f32x4_splat":{r.push(...B(n[0],t));let s=L(n[0],t);return s==="i32"?r.push(m.f32_convert_i32_s):s==="f64"&&r.push(m.f32_demote_f64),r.push(...mn(G.f32x4_splat)),r}case"f32x4_extract_lane":{r.push(...B(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}`),[m.f32_const,...yn(0)]):(r.push(He,...I(G.f32x4_extract_lane),s),r)}case"f32x4_replace_lane":{r.push(...B(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}`),[m.f32_const,...yn(0)];r.push(...B(n[2],t));let o=L(n[2],t);return o==="i32"?r.push(m.f32_convert_i32_s):o==="f64"&&r.push(m.f32_demote_f64),r.push(He,...I(G.f32x4_replace_lane),s),r}case"f32x4_add":case"f32x4_sub":case"f32x4_mul":case"f32x4_div":{r.push(...B(n[0],t)),r.push(...B(n[1],t));let s={f32x4_add:G.f32x4_add,f32x4_sub:G.f32x4_sub,f32x4_mul:G.f32x4_mul,f32x4_div:G.f32x4_div};return r.push(...mn(s[e])),r}case"f32x4_neg":case"f32x4_sqrt":{r.push(...B(n[0],t));let s={f32x4_neg:G.f32x4_neg,f32x4_sqrt:G.f32x4_sqrt};return r.push(...mn(s[e])),r}default:return t.errors.push(`Unknown SIMD intrinsic: ${e}`),[m.f64_const,...te(0)]}}function si(e,n,t){let r=[];for(let a of n){r.push(...B(a,t));let c=L(a,t);c==="i32"?r.push(m.f64_convert_i32_s):c==="f32"&&r.push(m.f64_promote_f32)}let o={abs:m.f64_abs,ceil:m.f64_ceil,floor:m.f64_floor,trunc:m.f64_trunc,sqrt:m.f64_sqrt,min:m.f64_min,max:m.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)`),[m.f64_const,...te(0)]):(t.errors.push(`Unknown Math method: ${e}`),[m.f64_const,...te(0)])}function ii(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 ht[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 oi(e,n,t,r,s){let o=[0,97,115,109,1,0,0,0],i=e.map($=>se[$.type]),a=s?[1,se.f64]:[0],c=Ye(Ke.type,[1,96,...I(e.length),...i,...a]),l=[],d=[];r&&(d=Ye(Ke.import,[1,...dn("env"),...dn("memory"),2,0,1]));let f=Ye(Ke.function,[1,0]),u=Ye(Ke.export,[1,...dn("compute"),0,0]),p=[];if(t.length>0){let $=t[0],h=1;for(let g=1;g<t.length;g++)t[g]===$?h++:(p.push([...I(h),se[$]]),$=t[g],h=1);p.push([...I(h),se[$]])}let x=[...[...I(p.length),...p.flat()],...n,m.end],_=Ye(Ke.code,[1,...I(x.length),...x]),w=[...o,...c];return d.length>0&&w.push(...d),w.push(...f,...u,..._),w}function jr(e){try{let n=e.captures.map(ii),t;try{let l=`function __wasm__(${n.map(d=>d.name).join(", ")}) { ${e.body} }`;t=kr.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=Zs(n),i=[];for(let l of s)i.push(...Pe(l,o));if(o.errors.length>0)return{bytes:new Uint8Array,warnings:o.warnings,success:!1,error:o.errors.join("; ")};let a=oi(n,i,o.localTypes,o.needsMemory,o.hasReturn),c=zs(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 vr(e){let n=[],t=[];for(let a of e){let c=jr(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(`
|
|
300
|
+
`;try{let b=new Function("__deepEqual","__format","__typeMatches",h),{testResults:E,sigTestResults:x}=b(yn,He,gn);for(let w of E){let k=e[w.idx],A=c&&!w.passed&&w.error&&/is not defined$/.test(w.error);i.push({description:k.description,passed:A?!0:w.passed,error:A?void 0:w.error,line:k.line})}for(let w of x){let k=y[w.idx],A=c&&!w.passed&&w.error&&/is not defined$/.test(w.error),R=k.className?`${k.className}.${k.funcName}`:k.funcName;i.push({description:`${R} signature example`,passed:A?!0:w.passed,error:A?void 0:w.error,isSignatureTest:!0,line:k.line})}}catch(b){let E=c&&b instanceof ReferenceError;for(let x of e)i.push({description:x.description,passed:E,error:E?void 0:`Module execution failed: ${b.message}`});for(let x of y){let w=x.className?`${x.className}.${x.funcName}`:x.funcName;i.push({description:`${w} signature example`,passed:E,error:E?void 0:`Module execution failed: ${b.message}`,isSignatureTest:!0})}}for(let b of g){let E=b.className?`${b.className}.${b.funcName}`:b.funcName;i.push({description:`${E} signature example`,passed:!0,isSignatureTest:!0,line:b.line})}return i}function xt(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 dn(e){if(!e.trim())return[];let n=[],t=oi(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 oi(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 Br 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},ai=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},ci=Object.fromEntries(Object.entries(K).map(([e,n])=>[n,e.replace(/_/g,".")]));function hn(e){return[et,...O(e)]}function Or(e,n,t){return[et,...O(e),...O(n),...O(t)]}function O(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 xn(e){let n=new ArrayBuffer(4);return new Float32Array(n)[0]=e,[...new Uint8Array(n)]}function re(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[...O(n.length),...n]}function Xe(e,n){return[e,...O(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 li(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 ui(e,n,t){let r=[],s=1,o=()=>" ".repeat(s),i=n.map((l,p)=>`(param $${l.name} ${l.type})`).join(" "),a=t.map((l,p)=>`(local $L${n.length+p} ${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],p=ai[l]||`unknown(0x${l.toString(16)})`;if(c++,l===d.local_get||l===d.local_set||l===d.local_tee){let[f,u]=he(e,c);c+=u;let m=f<n.length?`$${n[f].name}`:`$L${f}`;r.push(`${o()}${p} ${m}`)}else if(l===d.br||l===d.br_if){let[f,u]=he(e,c);c+=u,r.push(`${o()}${p} ${f}`)}else if(l===d.i32_const){let[f,u]=he(e,c);c+=u,r.push(`${o()}i32.const ${f}`)}else if(l===d.f32_const){let f=new ArrayBuffer(4),u=new Uint8Array(f);for(let y=0;y<4;y++)u[y]=e[c+y];let m=new Float32Array(f)[0];c+=4,r.push(`${o()}f32.const ${m}`)}else if(l===d.f64_const){let f=li(e,c);c+=8,r.push(`${o()}f64.const ${f}`)}else if(l===d.block||l===d.loop){let f=e[c];c++,r.push(`${o()}${p}${f===ie.void?"":` (result ${f===ie.f64?"f64":"i32"})`}`),s++}else if(l===d.if){let f=e[c];c++,r.push(`${o()}if${f===ie.void?"":` (result ${f===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[f,u]=he(e,c);c+=u;let[m,y]=he(e,c);c+=y,r.push(`${o()}${p}${m?` offset=${m}`:""}`)}else if(l===et){let[f,u]=he(e,c);c+=u;let m=ci[f]||`simd.unknown(0x${f.toString(16)})`;if(f===K.v128_load||f===K.v128_store){let[y,g]=he(e,c);c+=g;let[_,$]=he(e,c);c+=$,r.push(`${o()}${m}${_?` offset=${_}`:""}`)}else if(f===K.v128_const){let y=e.slice(c,c+16);c+=16,r.push(`${o()}v128.const ${y.map(g=>"0x"+g.toString(16).padStart(2,"0")).join(" ")}`)}else if(f===K.f32x4_extract_lane||f===K.f32x4_replace_lane){let y=e[c];c++,r.push(`${o()}${m} ${y}`)}else r.push(`${o()}${m}`)}else r.push(`${o()}${p}`)}return r.push(")"),r.join(`
|
|
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(`
|
|
300
302
|
`).map(l=>` * ${l}`);return`/**
|
|
301
303
|
* WASM: ${a.id}
|
|
302
304
|
${c.join(`
|
|
@@ -333,21 +335,21 @@ for(const{id,b64,c,m}of __wasmBlocks){
|
|
|
333
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}}
|
|
334
336
|
return r};
|
|
335
337
|
}})();
|
|
336
|
-
`.trim(),results:n}}function
|
|
337
|
-
`),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}
|
|
338
|
-
`),suffix:"__tjs.popStack();"})}function
|
|
339
|
-
${
|
|
338
|
+
`.trim(),results:n}}import*as qr from"acorn";function wn(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}}Ti(o,s)}}return s(e),ki(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=Ur(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 Ti(e,n){for(let t of Ur(e))n(t)}function Ur(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 ki(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 Sn(e){let n;try{n=qr.parse(`function __wrap__(){${e}}`,{ecmaVersion:2022,sourceType:"module",locations:!1})}catch{return e}let t=`function __wrap__(){${e}}`,r=wn(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 ji(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 vi(e,n,t,r,s){let o=[],i=Ve(n,e),a={},c=!1,l,p;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,g=ye(y,t);if(g.type.kind==="object"&&g.type.destructuredParams){l={},p=new Set;for(let[_,$]of Object.entries(g.type.destructuredParams))a[_]={...$,description:i.params[_]},l[_]=$.type,$.required&&p.add(_)}}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),g=ji(s||"",e.id?.name||"",m.left.name);a[m.left.name]={...y,required:g,default:g?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[g,_]of Object.entries(y.type.destructuredParams))a[g]={..._,description:i.params[g]}}else if(m.type==="RestElement"&&m.argument?.type==="Identifier"){let y=m.argument.name,g=n.match(new RegExp(`\\.\\.\\.${y}\\s*:\\s*([^)]+?)\\s*\\)`));if(g)try{let _=Lr(g[1].trim(),0,{ecmaVersion:2022}),$=Y(_);a[y]={name:y,type:$,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 f;if(r)try{let m=r.includes("=")?Jr(r):r,y=Lr(m,0,{ecmaVersion:2022});f=Y(y)}catch{f={kind:"any"},o.push(`Could not parse return type: ${r}`)}return{types:{name:e.id?.name||"anonymous",params:a,returns:f,description:i.description,isDestructuredParam:c,destructuredShape:l,destructuredRequired:p},warnings:o}}function Ai(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 p of l)r.push(`if (${p} instanceof Error) return ${p};`);for(let[p,f]of Object.entries(a)){let u=c.has(p),m=`${s}${e}.${p}`,y=St(p,f);if(y){let g=f.kind;u?r.push(`if (${y}) return __tjs.typeError('${m}', '${g}', ${p});`):r.push(`if (${p} !== undefined && ${y}) return __tjs.typeError('${m}', '${g}', ${p});`)}}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 p=St(a,c.type);if(p){let f=c.type.kind==="union"?c.type.members.map(u=>u.kind).join(" | "):c.type.kind;c.required?r.push(`if (${p}) return __tjs.typeError('${l}', '${f}', ${a});`):r.push(`if (${a} !== undefined && ${p}) return __tjs.typeError('${l}', '${f}', ${a});`)}if(c.type.kind==="function"){let f=Oi(a,c.type,l);f&&(r.push(f),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 Jr(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 Ri(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 xt(s)}function Ci(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 Ni(e){let n=e.match(/^\/\*\s*tjs\s*<-\s*([^*]+?)\s*\*\//);return n?n[1].trim():void 0}function Mi(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 $t(e,n={}){let{filename:t="<source>",runTests:r=!0,debug:s=!1,resolvedImports:o={}}=n,i=[];e=Pt(e);let c=Ni(e)||t,{code:l,tests:p,mocks:f,testRunner:u}=Dt(e),{ast:m,originalSource:y,requiredParams:g,unsafeFunctions:_}=be(l,{filename:t,colonShorthand:!0}),$=Pi(m),S=ut(l);for(let v of p)v.body=Ue(v.body),S.tjsModes.tjsEquals&&(v.body=Le(v.body)),S.tjsModes.tjsStandard&&(v.body=Sn(v.body));for(let v of f)v.body=Ue(v.body),S.tjsModes.tjsEquals&&(v.body=Le(v.body)),S.tjsModes.tjsStandard&&(v.body=Sn(v.body));let h={},b=[],E=[];for(let v of $){let B=v.id?.name||"anonymous",I=Ri(l,B),se;if(I&&I.includes("="))try{let z=I.matchAll(/(\w+)\s*=\s*/g),X=Jr(I),ue=new Function(`return ${X}`)(),ee={};for(let Rt of z){let Fe=Rt[1];Fe in ue&&(ee[Fe]=ue[Fe])}Object.keys(ee).length>0&&(se=ee)}catch{}let{types:le,warnings:Yr}=vi(v,y,g,I,l);i.push(...Yr),h[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=h[ue];if(ee&&le.params[X]){let Rt=Object.entries(ee.params).map(([ts,ns])=>({name:ts,type:ns.type})),Fe=ee.returns??{kind:"any"};le.params[X].type={kind:"function",params:Rt,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)E.push({start:z.left.end,end:z.right.end});else{let ee=z.right;ee.type==="BinaryExpression"&&ee.operator==="|"&&E.push({start:ee.left.end,end:ee.end})}}let jn=S.moduleSafety==="none"||_.has(B),Hr=S.safeFunctions.has(B),Qr=Ci(l,B),Xr=Mi(e,B),Re={file:c,line:Xr??v.loc?.start.line??0,column:v.loc?.start.column??0},es={unsafe:jn,safe:Hr,returnSafety:Qr},vn=S.polymorphicNames.has(B),At;if(vn){let z=[];for(let ue of $){let ee=ue.id?.name||"";ee.startsWith(B+"$")&&z.push(ee)}let X={polymorphic:!0,variants:z};Re&&(X.source=`${Re.file}:${Re.line}`),At=`${B}.__tjs = ${JSON.stringify(X,null,2)}`}else At=Ii(B,le,es,{debug:s,source:Re,returnDefaults:se});if(b.push({position:v.end,text:`
|
|
341
|
+
${At}`}),!jn&&!vn){let z=`${Re.file}:${Re.line}`,X=Ai(B,le,z);X&&v.body&&v.body.start!==void 0&&(b.push({position:v.body.start+1,text:`
|
|
340
342
|
${X.preamble}
|
|
341
|
-
`}),X.suffix&&
|
|
343
|
+
`}),X.suffix&&b.push({position:v.body.end-1,text:`
|
|
342
344
|
${X.suffix}
|
|
343
|
-
`}))}}S.sort((
|
|
345
|
+
`}))}}if(S.tjsModes.tjsStandard){let v=wn(m,S.source);for(let B of v)E.push({start:B.start,end:B.end}),b.push({position:B.start,text:B.newText})}E.sort((v,B)=>B.start-v.start);let x=S.source;for(let{start:v,end:B}of E)x=x.slice(0,v)+x.slice(B);for(let v of b){let B=0;for(let I of E)I.start<v.position&&(B+=I.end-I.start);v.position-=B}b.sort((v,B)=>B.position-v.position);for(let{position:v,text:B}of b)x=x.slice(0,v)+B+x.slice(v);let w=x.includes("__tjs.typeError("),k=x.includes("__tjs.pushStack("),A=x.includes("Is("),R=x.includes("IsNot("),C=x.includes("Eq("),N=x.includes("NotEq("),j=x.includes("TypeOf("),M=/\bType\(/.test(x),P=/\bGeneric\(/.test(x),L=/\bFunctionPredicate\(/.test(x),V=/\bEnum\(/.test(x),Q=/\bUnion\(/.test(x),Ae=x.includes("__tjs.bang("),rt=x.includes("__tjs.toBool("),jt=x.includes("__tjs.checkFnShape("),kn=S.tjsModes.tjsSafeEval;if(w||k||A||R||C||N||j||M||P||L||V||Q||Ae||rt||jt||kn){let v=[];w&&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]}"),C&&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)}"),j&&v.push("function TypeOf(v){return v===null?'null':typeof v}"),A&&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]))}"),R&&v.push("function IsNot(a,b){return!Is(a,b)}"),M&&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}"),P&&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&&(w||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&&(w||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(`;
|
|
344
346
|
`)+`;
|
|
345
|
-
`:"",
|
|
346
|
-
`+
|
|
347
|
-
`+
|
|
348
|
-
${
|
|
349
|
-
${
|
|
350
|
-
${
|
|
351
|
-
`)}`)}}if(r==="only")return{code:"",types:h,metadata:h,testResults:
|
|
352
|
-
`+b),Et=A.results}return{code:b,types:h,metadata:h,warnings:i.length>0?i:void 0,testRunner:d.length>0?u:void 0,testCount:d.length>0?d.length:void 0,testResults:Ie,wasmCompiled:Et}}function di(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 Xe(e){let n={kind:e.kind};return e.nullable&&(n.nullable=!0),e.items&&(n.items=Xe(e.items)),e.shape&&(n.shape=Object.fromEntries(Object.entries(e.shape).map(([t,r])=>[t,Xe(r)]))),e.members&&(n.members=e.members.map(Xe)),n}function yi(e,n,t={},r={}){let s={};for(let[i,a]of Object.entries(n.params))s[i]={type:Xe(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:Xe(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 gn(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":t=`!Array.isArray(${e})`;break;case"object":t=`(typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e}))`;break;case"union":{let r=n.members.map(s=>gn(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}function _t(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=ye(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),i=Kn(t,n.filename),{ast:a,signature:c,warnings:l}=Nt(i,s,r,n,o);return{ast:a,signature:c,warnings:l}}function gi(e,...n){if(typeof e=="string")return _t(e).ast;let t=e.reduce((r,s,o)=>r+s+(n[o]!==void 0?String(n[o]):""),"");return _t(t).ast}function hi(e,n,t){let{ast:r,signature:s}=_t(e),o=async i=>(await n.run(r,i,t)).result;return o.signature=s,o.ast=r,o}function xt(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?xt(e.items):{}};case"object":return e.shape?{type:"object",properties:Object.fromEntries(Object.entries(e.shape).map(([n,t])=>[n,xt(t)]))}:{type:"object"};case"union":return e.members?{anyOf:e.members.map(xt)}:{};default:return{}}}function bi(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]=xt(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 xi(e,n,...t){if(typeof e=="string")return bt(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 bt(s)}import{s as Cr}from"tosijs-schema";function Nr(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}function wt(e){return Cr.infer(e)}function hn(e){return wt(e)}hn.type=Nr;hn.infer=wt;var _i=new Proxy(hn,{get(e,n){return n==="type"?Nr:n==="infer"?wt:Cr[n]},apply(e,n,t){return wt(t[0])}});function St(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 Mr(e,n,t,r,s){var o=[];t||(t=T),(function i(a,c,l){var d=l||a.type,f=a!==o[o.length-1];f&&o.push(a),t[d](a,c,i),n[d]&&n[d](a,c||o,o),f&&o.pop()})(e,r,s)}function bn(e,n,t){t(e,n)}function Ee(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=bn;T.EmptyStatement=Ee;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=Ee;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=Ee;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=Ee;T.MemberPattern=bn;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=bn;T.ThisExpression=T.Super=T.MetaProperty=Ee;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=Ee;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=Ee;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 Si={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function $i(e,n={}){let t={...Si,...n},r=[],s;try{s=ye(e,{filename:t.filename,colonShorthand:!0}).ast}catch(i){return{diagnostics:[{severity:"error",message:i.message,line:i.loc?.line,column:i.loc?.column,rule:"parse-error"}],valid:!1}}let o=[Pr()];if(Mr(s,{FunctionDeclaration(i,a,c){let l=Pr();o.push(l);for(let d of i.params)Ei(l,d,"parameter");i.id&&(o[o.length-2]||o[0]).declarations.set(i.id.name,{node:i.id,kind:"function",used:!1})},VariableDeclaration(i){let a=o[o.length-1];for(let c of i.declarations)c.id.type==="Identifier"&&a.declarations.set(c.id.name,{node:c.id,kind:i.kind,used:!1})}}),St(s,{Identifier(i){for(let a=o.length-1;a>=0;a--){let c=o[a].declarations.get(i.name);if(c){c.used=!0;break}}}}),t.unusedVariables)for(let i of o)for(let[a,c]of i.declarations)a.startsWith("_")||!c.used&&c.kind!=="function"&&r.push({severity:"warning",message:`'${a}' is declared but never used`,line:c.node.loc?.start?.line,column:c.node.loc?.start?.column,rule:"no-unused-vars"});return t.unreachableCode&&St(s,{BlockStatement(i){let a=!1;for(let c of i.body){if(a){r.push({severity:"warning",message:"Unreachable code after return statement",line:c.loc?.start?.line,column:c.loc?.start?.column,rule:"no-unreachable"});break}c.type==="ReturnStatement"&&(a=!0)}}}),t.noExplicitNew&&St(s,{NewExpression(i){let a="class";i.callee.type==="Identifier"?a=i.callee.name:i.callee.type==="MemberExpression"&&i.callee.property.type==="Identifier"&&(a=i.callee.property.name),r.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${a}(...) instead of new ${a}(...)`,line:i.loc?.start?.line,column:i.loc?.start?.column,rule:"no-explicit-new"})}}),{diagnostics:r,valid:r.filter(i=>i.severity==="error").length===0}}function Pr(){return{declarations:new Map}}function Ei(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{_i as Schema,ce as TJS_VERSION,gi as ajs,tr as assertFunction,we as checkType,hi as createAgent,Ds as emitRuntimeWrapper,ae as error,nr as expectFunction,ie as extractLiteralValue,We as extractTDoc,Pt as extractTests,bi as getToolDefinitions,H as inferTypeFromValue,ln as installRuntime,le as isError,$i as lint,ye as parse,fe as parseParameter,Yn as parseReturnType,ot as preprocess,be as runtime,_s as testUtils,xi as tjs,Nt as transformFunction,_t as transpile,bt as transpileToJS,Ce as typeOf,Ct as typeToString,an as validateArgs,cn as wrap};
|
|
347
|
+
`:"",I=[];w&&I.push("typeError","isMonadicError"),k&&I.push("pushStack","popStack","getStack"),C&&I.push("Eq"),N&&I.push("NotEq"),j&&I.push("TypeOf"),A&&I.push("Is","tjsEquals"),R&&I.push("IsNot"),M&&I.push("Type"),P&&I.push("Generic"),L&&I.push("FunctionPredicate"),V&&I.push("Enum"),Q&&I.push("Union"),rt&&I.push("toBool"),jt&&(I.push("checkFnShape"),w||I.push("typeError","isMonadicError")),Ae&&(I.push("bang"),w||I.push("typeError","isMonadicError"));let se=I.length>0?`{${I.join(",")}}`:"undefined";x=B+`const __tjs = globalThis.__tjs?.createRuntime?.() ?? ${se};
|
|
348
|
+
`+x}kn&&(x=`import { Eval, SafeFunction } from 'tjs-lang';
|
|
349
|
+
`+x);let De;if(r){let v=Pr(e);De=Ir(p,f,v,x,o,S.extensions);let B=De.filter(I=>!I.passed);if(B.length>0&&r===!0){let I=B.map(se=>{if(se.isSignatureTest)return` Function signature example is inconsistent:
|
|
350
|
+
${se.error}`;let le=se.line?` (line ${se.line})`:"";return` Test '${se.description}'${le} failed:
|
|
351
|
+
${se.error}`});throw new Error(`Transpile-time test failures:
|
|
352
|
+
${I.join(`
|
|
353
|
+
`)}`)}}if(r==="only")return{code:"",types:h,metadata:h,testResults:De,testCount:De?.length};let vt;if(S.wasmBlocks.length>0){vt=[];let v=Fr(S.wasmBlocks);v.code&&(x=v.code+`
|
|
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};
|
|
353
355
|
//# sourceMappingURL=tjs-lang.js.map
|