tjs-lang 0.7.6 → 0.7.7
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 +33 -15
- package/demo/docs.json +3 -3
- package/dist/index.js +110 -106
- package/dist/index.js.map +3 -3
- package/dist/src/lang/parser.d.ts +6 -0
- package/dist/tjs-eval.js +37 -34
- package/dist/tjs-eval.js.map +3 -3
- package/dist/tjs-from-ts.js +1 -1
- package/dist/tjs-from-ts.js.map +1 -1
- package/dist/tjs-lang.js +76 -72
- package/dist/tjs-lang.js.map +3 -3
- package/dist/tjs-vm.js +44 -41
- package/dist/tjs-vm.js.map +3 -3
- package/package.json +1 -1
- package/src/lang/codegen.test.ts +40 -0
- package/src/lang/emitters/js-tests.ts +7 -0
- package/src/lang/emitters/js.ts +26 -0
- package/src/lang/features.test.ts +22 -0
- package/src/lang/parser-transforms.ts +235 -6
- package/src/lang/parser.ts +51 -0
- package/src/lang/tests.ts +21 -8
package/dist/tjs-lang.js
CHANGED
|
@@ -1,52 +1,55 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ur=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var lr=Ur((Ki,js)=>{js.exports={name:"tjs-lang",version:"0.7.7",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"],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 Gn 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}},Y=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
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),d=c===r?">":" ";if(i.push(`${d} ${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 ee(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
|
|
4
|
-
`&&(i="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&
|
|
5
|
-
`})()
|
|
6
|
-
`){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
|
|
7
|
-
`),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 d=c.indexOf("/*"),f=c.indexOf("*/");if(d!==-1&&(f===-1||f<d)){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
|
|
8
|
-
`)}function
|
|
9
|
-
`&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let c=t-1;for(;c>=0&&/\s/.test(e[c]);)c--;let l=c>=0?e[c]:"";if(!l||/[=(!,;:{[&|?+\-*%<>~^]/.test(l)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){t++,r="regex";continue}}if(i==="
|
|
10
|
-
|
|
11
|
-
|
|
3
|
+
`)}};function ee(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 rt(e,n){let t="",r=0,s,o,i="normal",a=[],c=[{type:"top-level",braceDepth:0}],l=0,d=()=>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],p=e[r+1];switch(i){case"single-string":if(t+=u,u==="\\"&&r+1<e.length){t+=p,r+=2;continue}u==="'"&&(i="normal"),r++;continue;case"double-string":if(t+=u,u==="\\"&&r+1<e.length){t+=p,r+=2;continue}u==='"'&&(i="normal"),r++;continue;case"template-string":if(t+=u,u==="\\"&&r+1<e.length){t+=p,r+=2;continue}if(u==="$"&&p==="{"){t+=p,r+=2,a.push(1),i="normal";continue}u==="`"&&(i="normal"),r++;continue;case"line-comment":t+=u,u===`
|
|
4
|
+
`&&(i="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&p==="/"){t+=p,r+=2,i="normal";continue}r++;continue;case"regex":if(t+=u,u==="\\"&&r+1<e.length){t+=p,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==="/"&&p==="/"){t+=u+p,r+=2,i="line-comment";continue}if(u==="/"&&p==="*"){t+=u+p,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 x=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(x){let h=x[1],g=x[0].length,S=e[r+g],b=null,E=r+g;(S==="?"||S==="!")&&(b=S,E++,b==="!"?n.unsafeFunctions.add(h):n.safeFunctions.add(h)),t+=`function ${h}(`,r=E;let k=et(e,r,"(",")");if(!k){t+=e[r],r++;continue}let{content:j,endPos:R}=k;r=R;let C=vt(j,n,!0);t+=C+")";let N=r;for(;N<e.length&&/\s/.test(e[N]);)N++;if(e[N]===":"){let v=e.slice(N,N+2),M;for(v===":?"||v===":!"?(N+=2,M=v===":?"?"safe":"unsafe"):N+=1;N<e.length&&/\s/.test(e[N]);)N++;let P=jt(e,N);P&&(s===void 0&&(s=P.type,M&&(o=M)),r=P.endPos)}continue}let _=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),w=(()=>{for(let h=t.length-1;h>=0;h--)if(!/\s/.test(t[h]))return t[h];return`
|
|
5
|
+
`})(),$=w!=="="&&w!==","&&w!=="("&&w!=="["&&w!==">";if(_&&f()&&!$){let h=_[1].length;t+=e.slice(r,r+h),r+=h;continue}if(_&&f()&&$){let h=_[1],g=_[0].length,S=r+g;t+=h+"(",r=S;let b=et(e,r,"(",")");if(!b){t+=e[r],r++;continue}let{content:E,endPos:k}=b;r=k;let j=vt(E,n,!0);t+=j+")";let R=r;for(;R<e.length&&/\s/.test(e[R]);)R++;if(e[R]===":"){let C=e.slice(R,R+2);for(C===":?"||C===":!"?R+=2:R++;R<e.length&&/\s/.test(e[R]);)R++;let N=jt(e,R);N&&(r=N.endPos)}continue}if(e[r]==="("){let h=et(e,r+1,"(",")");if(!h){t+=e[r],r++;continue}let g=h.content,S=h.endPos,b=S;for(;b<e.length&&/\s/.test(e[b]);)b++;let E;if(e[b]===":"){let k=e.slice(b,b+2);for(k===":?"||k===":!"?b+=2:b++;b<e.length&&/\s/.test(e[b]);)b++;let j=jt(e,b);if(j)for(E=j.type,b=j.endPos;b<e.length&&/\s/.test(e[b]);)b++}if(e.slice(b,b+2)==="=>"){let k=null,j=g,R=g.trimStart();R.startsWith("?")&&(R.length===1||/\s/.test(R[1]))?(k="?",j=R.slice(1)):R.startsWith("!")&&(R.length===1||/\s/.test(R[1]))&&(k="!",j=R.slice(1));let C=vt(j,n,!1);for(t+=`(${k==="?"?"/* safe */ ":k==="!"?"/* unsafe */ ":""}${C})`,r=S;r<b&&/\s/.test(e[r]);)t+=e[r],r++;E&&(r=b)}else{let k=rt(g,n);t+=`(${k.source})`,r=S}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:o}}function et(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 $n(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=et(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 Oe(e){return e.replace(/(?<!\|)\|(?!\|)/g," || ")}function jt(e,n){let t=n,r=0,s=!1,o="",i=!1,a=c=>({type:Oe(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:Oe(e.slice(n,l).trim()),endPos:l};if(e[t]!=="|"&&e[t]!=="&")return{type:Oe(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:Oe(e.slice(n,f).trim()),endPos:l}}if(e[t]!=="|"&&e[t]!=="&")return{type:Oe(e.slice(n,l).trim()),endPos:l};continue}t++}return i?a(t):null}function st(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===`
|
|
6
|
+
`){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 vt(e,n,t){let r=rt(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=st(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 d=l.trim();if(!d)return l;if(t&&d.startsWith("{")&&d.endsWith("}")){let p=d.slice(1,-1);return`{ ${wn(p,n)} }`}if(t&&d.startsWith("[")&&d.endsWith("]")){let p=d.slice(1,-1);return`[ ${wn(p,n)} ]`}if(d.startsWith("...")){let p=Sn(d);return p!==-1?d.slice(0,p).trim():l}let f=d.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(f){let[,p,y]=f;return a(p),o=!0,`${p} = ${y}`}if(!Wr(d)){let p=d.match(/^(\w+)\s*=/);return p&&a(p[1]),o=!0,l}let u=Sn(d);if(u!==-1){let p=d.slice(0,u).trim(),y=d.slice(u+1).trim();return a(p),o&&t&&/^\w+$/.test(p),t&&/^\w+$/.test(p)&&n.requiredParams.add(p),`${p} = ${y}`}return l}).join(",")}function wn(e,n){return st(e).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,l,d]=i;n.requiredParams.add(l);let f=tt(d);return`${l} = ${f}`}let a=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,l,d]=a;n.requiredParams.add(l);let f=nt(d);return`${l} = ${f}`}let c=o.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(c){let[,l,d]=c;return n.requiredParams.add(l),`${l} = ${d}`}return s}).join(", ")}function tt(e){let n=e.slice(1,-1).trim();return`{ ${st(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}: ${tt(u)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,f,u]=a;return`${f}: ${tt(u)}`}let c=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(c){let[,f,u]=c;return`${f}: ${nt(u)}`}let l=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(l){let[,f,u]=l;return`${f}: ${nt(u)}`}let d=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(d){let[,f,u]=d;return`${f}: ${u}`}return s}).join(", ")} }`}function nt(e){let n=e.slice(1,-1).trim();return`[ ${st(n).map(s=>{let o=s.trim();return o?o.startsWith("{")&&o.endsWith("}")?tt(o):o.startsWith("[")&&o.endsWith("]")?nt(o):s:s}).join(", ")} ]`}function Wr(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 Sn(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 Lr(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 vn(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 An(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 b=e[l];b==="{"?c++:b==="}"&&c--,l++}if(c!==0){t+=e[r],r++;continue}let d=e.slice(a,l-1),f,u=l,p=e.slice(l).match(/^\s*fallback\s*\{/);if(p){let b=l+p[0].length;c=1;let E=b;for(;E<e.length&&c>0;){let k=e[E];k==="{"?c++:k==="}"&&c--,E++}c===0&&(f=e.slice(b,E-1),u=E)}let x=Vr(d).map(b=>{let E=zr(e,i,b);return E?`${b}: ${E}`:b}),_={id:`__tjs_wasm_${s}`,body:d,fallback:f,captures:x,start:i,end:u};n.push(_);let w=f??d,$=x.map(b=>b.split(":")[0].trim()),h=$.length>0?$.join(", "):"",g=$.length>0?`globalThis.${_.id}(${h})`:`globalThis.${_.id}()`,S=`(globalThis.${_.id} ? ${g} : (() => {${w}})())`;t+=S,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function Jr(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function Vr(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 p=new RegExp(`(?<!\\.)\\b${u}\\b`,"g"),y=new RegExp(`\\.${u}\\b`,"g"),x=n.match(p)?.length||0,_=n.match(y)?.length||0;x<=_&&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 d=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)&&!d.has(u)&&!Jr(u)&&f.push(u);return f.sort()}function zr(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?En(a[1],t):void 0}return En(o[1],t)}function En(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 Fe(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 Rn(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(`
|
|
7
|
+
`),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 d=c.indexOf("/*"),f=c.indexOf("*/");if(d!==-1&&(f===-1||f<d)){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 p=c.match(/^(\s*)/),y=p?p[1]:"",x=c.slice(y.length);o.push(y+";"+x);continue}}o.push(c)}return o.join(`
|
|
8
|
+
`)}function Zr(e){let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
|
|
9
|
+
`&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let c=t-1;for(;c>=0&&/\s/.test(e[c]);)c--;let l=c>=0?e[c]:"";if(!l||/[=(!,;:{[&|?+\-*%<>~^]/.test(l)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){t++,r="regex";continue}}if(i==="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 qe(e){e=Zr(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===`
|
|
10
|
+
`&&(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",d=Gr(o,a),f=Kr(o,a+2),u=o.slice(d,a).trim(),p=o.slice(a+2,f).trim();if(u&&p){let y=o.slice(0,d),x=o.slice(f),w=/[a-zA-Z0-9_$]$/.test(y)?" ":"";o=`${y}${w}${l}(${u}, ${p})${x}`}}return o}function Gr(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 d=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(d))return c;if(d==="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 Kr(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 Cn(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,p=e[u],y=p===void 0||u>=e.length||p!=="="&&p!=="{";if(p==="="||p==="{")i=c[2],a=!0,o=u;else if(y){let x=c[0].trim(),_=c[0].slice(x.length);n+=`const ${s} = Type('${s}', ${x})${_}`,t=u;continue}}let l,d=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,d=o;let p=e.slice(o).match(/^\s*/);p&&(o+=p[0].length)}}if(e[o]==="{"){let u=o+1,p=1,y=u;for(;y<e.length&&p>0;){let S=e[y];S==="{"?p++:S==="}"&&p--,y++}if(p!==0){n+=e[t],t++;continue}let x=e.slice(u,y-1).trim(),_=y,w=x.match(/description\s*:\s*(['"`])([^]*?)\1/);w&&!a&&(i=w[2]);let $,h=x.match(/example\s*:\s*/);if(h){let S=h.index+h[0].length,b=$n(x,S);b&&($=b.value.trim())}let g=x.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(g&&$){let S=g[1].trim(),b=g[2].trim(),E=l?`, ${l}`:"";n+=`const ${s} = Type('${i}', (${S}) => { if (!globalThis.__tjs?.validate(${S}, globalThis.__tjs?.infer(${$}))) return false; ${b} }, ${$}${E})`}else if(g){let S=g[1].trim(),b=g[2].trim(),E=l?`, undefined, ${l}`:"";n+=`const ${s} = Type('${i}', (${S}) => { ${b} }${E})`}else if($){let S=l?`, ${l}`:"";n+=`const ${s} = Type('${i}', undefined, ${$}${S})`}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=d;continue}else if(!c){let u=e.slice(o).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(u){let p=u[0];n+=`const ${s} = Type('${s}', ${p})`,t=o+u[0].length;continue}}}n+=e[t],t++}return n}function Nn(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(),d=Lr(l,/params\s*:\s*\{/),f=l.match(/returns\s*:\s*(.+?)(?:\n|$)/),u=l.match(/returnContract\s*:\s*['"](\w+)['"]/),p=l.match(/description\s*:\s*(['"])([^]*?)\1/),y=[];d&&y.push(`params: ${d[1]}`),f&&y.push(`returns: ${f[1].trim()}`),u&&y.push(`returnContract: '${u[1]}'`);let x=p?p[2]:s;if(o){let _=o.split(",").map($=>{let h=$.trim().split("=").map(g=>g.trim());if(h.length===2){let g=h[1]==="any"||h[1]==="undefined"?"null":h[1];return`['${h[0]}', ${g}]`}return`'${h[0]}'`}),w=o.split(",").map($=>$.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${x}', [${_.join(", ")}], (${w.join(", ")}) => ({ ${y.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${x}', { ${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(),d=l.indexOf(",");if(d!==-1){let f=l.slice(0,d).trim(),u=l.slice(d+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 Mn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(r){let s=r[1],o=r[2],a=t+r[0].length-1+1,c=1,l=a;for(;l<e.length&&c>0;){let $=e[l];$==="{"?c++:$==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let d=e.slice(a,l-1).trim(),f=l,u=o.split(",").map($=>{let h=$.trim().split("=").map(g=>g.trim());if(h.length===2){let g=h[1]==="any"||h[1]==="undefined"?"null":h[1];return`['${h[0]}', ${g}]`}return`'${h[0]}'`}),p=d,y=p.search(/\bdeclaration\s*\{/);if(y!==-1){let $=p.indexOf("{",y),h=1,g=$+1;for(;g<p.length&&h>0;)p[g]==="{"?h++:p[g]==="}"&&h--,g++;p=p.slice(0,y)+p.slice(g)}let x=p.match(/description\s*:\s*(['"`])([^]*?)\1/),_=p.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),w=x?x[2]:s;if(_){let $=_[1].trim().split(",").map(E=>E.trim()),h=_[2].trim(),g=$[0]||"x",S=$.slice(1),b=S.map(E=>`check${E}`);S.forEach((E,k)=>{h=h.replace(new RegExp(`\\b${E}\\s*\\(`,"g"),`${b[k]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${g}, ${b.join(", ")}) => { ${h} }, '${w}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${w}')`;t=f;continue}n+=e[t],t++}return n}function Pn(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 p=e[l];p==="{"?c++:p==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let d=e.slice(a,l-1).trim(),f=l,u=Tn(d);n+=`const ${s} = Union('${o}', [${u.join(", ")}])`,t=f;continue}else{let a=e.indexOf(`
|
|
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(`,
|
|
12
13
|
`),w;y?w=`${i}const __ext_${a} = {
|
|
13
14
|
${_}
|
|
14
15
|
${i}}
|
|
15
16
|
`:w=`${i}Object.assign(__ext_${a}, {
|
|
16
17
|
${_}
|
|
17
18
|
${i}})
|
|
18
|
-
`;for(let
|
|
19
|
-
`;t+=w,r=l}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function
|
|
20
|
-
`?(t++,r=0):r++;return{line:t,column:r}}function
|
|
21
|
-
`&&(o=!1),r++;continue}if(i){if(a==="*"&&c==="/"){i=!1,r+=2;continue}r++;continue}if(s){if(a==="\\"){r+=2;continue}a===s&&(s=!1),r++;continue}if(a==="/"&&c==="/"){o=!0,r+=2;continue}if(a==="/"&&c==="*"){i=!0,r+=2;continue}if(a==="'"||a==='"'||a==="`"){s=a,r++;continue}a==="{"&&t++,a==="}"&&t--,r++}return r}function
|
|
22
|
-
${_}${
|
|
23
|
-
${
|
|
19
|
+
`;for(let $ of f)w+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${$.name}', __ext_${a}.${$.name}) }
|
|
20
|
+
`;t+=w,r=l}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function Ue(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,d,f,u)=>u?`__ext_String.${f}.call(${d})`:`__ext_String.${f}.call(${d}, `);let a=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${s})\\((\\))?`,"g");r=r.replace(a,(l,d,f,u)=>u?`__ext_String.${f}.call(${d})`:`__ext_String.${f}.call(${d}, `);let c=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+s+"\\((\\))?","g");r=r.replace(c,(l,d,f)=>f?`__ext_String.${s}.call(${d})`:`__ext_String.${s}.call(${d}, `)}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,d=c-1,f=!1;for(;d>=0&&l>0;){let u=r[d];f?u===f&&(d===0||r[d-1]!=="\\")&&(f=!1):(u==="]"&&l++,u==="["&&l--,(u==="'"||u==='"'||u==="`")&&(f=u)),d--}if(l===0){let u=r.slice(d+1,c+1),p=r.slice(0,d+1),y=r.slice(c+i.length);y[0]===")"?r=`${p}__ext_Array.${s}.call(${u})${y.slice(1)}`:r=`${p}__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,d)=>d?`__ext_Number.${l}.call(${c})`:`__ext_Number.${l}.call(${c}, `)}return r}function Be(e,n){let t=1,r=0;for(let s=0;s<n&&s<e.length;s++)e[s]===`
|
|
21
|
+
`?(t++,r=0):r++;return{line:t,column:r}}function Bn(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 it(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 At(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=kn(s.trim(),n);l&&t.push(l),s="";continue}s+=c}let i=s.trim();if(i){let a=kn(i,n);a&&t.push(a)}return t}function kn(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 De(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===`
|
|
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 Dn(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],p=o[3],y=o.index,x=y,w=o[0].indexOf("function");w>=0&&(x=y+w),i.push({name:p,fullMatchStart:y,funcKeywordStart:x,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 p=1,y=u+1;for(;y<e.length&&p>0;)e[y]==="("&&p++,e[y]===")"&&p--,y++;let x=y-1,_=e.slice(u+1,x),w=y;for(;w<e.length&&e[w]!=="{";)w++;if(w>=e.length)continue;let $=De(e,w),h=f.fullMatchStart;for(;h>0&&e[h-1]===" ";)h--;let g=s.get(f.name),S=At(_,n);if(_.includes("...")){let E=Be(e,f.funcKeywordStart);throw new Y(`Rest parameters are not supported in polymorphic function '${f.name}'. Use separate function names instead.`,E)}g.push({index:g.length+1,start:h,end:$,text:e.slice(h,$),exported:f.exported,isAsync:f.isAsync,params:S})}for(let[f,u]of s){if(u.length<2)continue;let p=u.filter(y=>y.isAsync).length;if(p>0&&p<u.length){let y=Be(e,u[0].start);throw new Y(`Polymorphic function '${f}': all variants must be either sync or async, not mixed.`,y)}for(let y=0;y<u.length;y++)for(let x=y+1;x<u.length;x++){let _=u[y],w=u[x];if(_.params.length!==w.params.length)continue;let $=!0;for(let h=0;h<_.params.length;h++){let g=_.params[h].defaultValue?it(_.params[h].defaultValue):"any",S=w.params[h].defaultValue?it(w.params[h].defaultValue):"any";if(g!==S){$=!1;break}}if($){let h=Be(e,w.start);throw new Y(`Polymorphic function '${f}': variants ${y+1} and ${x+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 p of u)l.push({name:f,variant:p});l.sort((f,u)=>u.variant.start-f.variant.start);let d=e;for(let{name:f,variant:u}of l){let p=u.isAsync?"async ":"",y=u.text.replace(new RegExp(`(?:export\\s+)?${p?p.replace(/\s+$/,"\\s+"):""}function\\s+${f}\\s*\\(`),`${p}function ${f}$$${u.index}(`);d=d.slice(0,u.start)+y+d.slice(u.end)}for(let[f,u]of s){if(u.length<2)continue;t.add(f);let p=u[0].isAsync,y=u.some(g=>g.exported),x=p?"async ":"",_=y?"export ":"",w=[...u].sort((g,S)=>{if(g.params.length!==S.params.length)return 0;let b=0,E=0;for(let k of g.params){let j=k.defaultValue?it(k.defaultValue):"any";j==="non-negative-integer"?b+=3:j==="integer"?b+=2:j!=="any"&&(b+=1)}for(let k of S.params){let j=k.defaultValue?it(k.defaultValue):"any";j==="non-negative-integer"?E+=3:j==="integer"?E+=2:j!=="any"&&(E+=1)}return E-b}),$=[];for(let g of w){let S=[`__args.length === ${g.params.length}`],b=[];for(let E=0;E<g.params.length;E++){let k=g.params[E];if(b.push(`__args[${E}]`),k.defaultValue){let j=Bn(`__args[${E}]`,k.defaultValue);j!=="true"&&S.push(j)}}$.push(` if (${S.join(" && ")}) return ${f}$${g.index}(${b.join(", ")})`)}let h=`
|
|
23
|
+
${_}${x}function ${f}(...__args) {
|
|
24
|
+
${$.join(`
|
|
24
25
|
`)}
|
|
25
26
|
return __tjs.typeError('${f}', 'no matching overload', __args)
|
|
26
27
|
}
|
|
27
|
-
`;d+=
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
28
|
+
`;d+=h}return{source:d,polymorphicNames:t}}function Fn(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function qn(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,d=e.slice(c).match(/^(['"`])([^]*?)\1\s*/);if(d&&(l=d[2],c+=d[0].length),e[c]==="{"){let f=c+1,u=1,p=f,y=null,x=!1;for(;p<e.length&&u>0;){let _=e[p];if(x){x=!1,p++;continue}if(_==="\\"&&y){x=!0,p++;continue}if(y){_===y&&(y=null),p++;continue}if(_==="/"&&e[p+1]==="/"){let w=e.indexOf(`
|
|
29
|
+
`,p);p=w===-1?e.length:w+1;continue}if(_==="/"&&e[p+1]==="*"){let w=e.indexOf("*/",p+2);p=w===-1?e.length:w+2;continue}if(_==="'"||_==='"'||_==="`"){y=_,p++;continue}_==="{"?u++:_==="}"&&u--,p++}if(u===0){let _=e.slice(f,p-1).trim(),w=p,$=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:l,body:_,start:a,end:w,line:$}),!n)try{new Function(_)()}catch(S){let b=l||`test at line ${$}`;r.push(`Test failed: ${b} (line ${$})
|
|
30
|
+
${S.message||S}`)}let g=(e.slice(a,w).match(/\n/g)||[]).length;s+=`
|
|
31
|
+
`.repeat(g),o=w;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function Un(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,d=De(e,l),f=e.slice(l,d);o.push({className:a,extendsClause:c,bodyStart:l,bodyEnd:d,body:f})}let i=e;for(let a=o.length-1;a>=0;a--){let{className:c,extendsClause:l,bodyStart:d,bodyEnd:f,body:u}=o[a],p=/\bconstructor\s*\(/g,y,x=[];for(;(y=p.exec(u))!==null;)x.push(y.index);if(x.length<2)continue;t.add(c);let _=[];for(let E=0;E<x.length;E++){let k=x[E],j=u.indexOf("(",k),R=1,C=j+1;for(;C<u.length&&R>0;)u[C]==="("&&R++,u[C]===")"&&R--,C++;let N=u.slice(j+1,C-1),v=C;for(;v<u.length&&u[v]!=="{";)v++;let M=De(u,v),P=u.slice(v+1,M-1);_.push({index:E+1,paramStr:N,bodyText:P,fullStart:k,fullEnd:M})}let w=u.slice(0,_[0].fullEnd),$=_[_.length-1].fullEnd;w+=u.slice($);let h=u;for(let E=_.length-1;E>=1;E--){let k=_[E],j=k.fullStart;for(;j>0&&h[j-1]===" ";)j--;j>0&&h[j-1]===`
|
|
32
|
+
`&&j--,h=h.slice(0,j)+h.slice(k.fullEnd)}let g="";for(let E=1;E<_.length;E++){let k=_[E],j=At(k.paramStr,n);if(k.paramStr.includes("...")){let C=Be(e,d+k.fullStart);throw new Y(`Rest parameters are not supported in polymorphic constructors for '${c}'.`,C)}g+=`
|
|
33
|
+
function ${c}$ctor$${k.index}(${k.paramStr}) {`,g+=`
|
|
34
|
+
const __obj = Object.create(${c}.prototype)`,g+=`
|
|
35
|
+
;(function() {${k.bodyText}}).call(__obj)`,g+=`
|
|
36
|
+
return __obj`,g+=`
|
|
35
37
|
}
|
|
36
|
-
`}let
|
|
38
|
+
`}let S=[];for(let E=0;E<_.length;E++){let k=_[E],j=At(k.paramStr,n),R=[`a.length === ${j.length}`];for(let C=0;C<j.length;C++){let N=j[C];if(N.defaultValue){let v=Bn(`a[${C}]`,N.defaultValue);v!=="true"&&R.push(v)}}if(E===0)S.push(` if (${R.join(" && ")}) return Reflect.construct(t, a)`);else{let C=j.map((N,v)=>`a[${v}]`).join(", ");S.push(` if (${R.join(" && ")}) return ${c}$ctor$${k.index}(${C})`)}}g+=`
|
|
37
39
|
function ${c}$dispatch(t, a) {
|
|
38
|
-
`,
|
|
40
|
+
`,g+=S.join(`
|
|
39
41
|
`)+`
|
|
40
|
-
`,
|
|
41
|
-
`,
|
|
42
|
-
`,i=i.slice(0,d)+
|
|
43
|
-
`&&(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
|
|
44
|
-
|
|
45
|
-
`)),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 Yr}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 Kn(e){try{let n=Yr(e,0,{ecmaVersion:2022});return H(n)}catch{return{kind:"any"}}}function vt(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?vt(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}: ${vt(r)}`).join(", ");return e.nullable?`{ ${n} } | null`:`{ ${n} }`}case"union":return e.members?.map(vt).join(" | ")||"any";default:return"any"}}function it(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?it(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=it(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(it)}:{};default:return{}}}function Hr(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=it(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function At(e,n,t,r={},s){let o=qe(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[S,g]of Object.entries(w.type.destructuredParams))i.set(S,{...g,description:o.params[S]});else w.description=o.params[w.name],i.set(w.name,w)}let a;t&&(a=Kn(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 m=Object.fromEntries(i),y={name:e.id?.name||"anonymous",description:o.description,parameters:m,returns:a},b=Hr(m);return{ast:{op:"seq",steps:d,inputSchema:b},signature:y,warnings:c.warnings}}function oe(e,n){let t=[];for(let r of e.body){let s=Ue(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function Ue(e,n){switch(e.type){case"VariableDeclaration":return Qr(e,n);case"ExpressionStatement":return Xr(e,n);case"IfStatement":return ts(e,n);case"WhileStatement":return ns(e,n);case"ForOfStatement":return rs(e,n);case"TryStatement":return ss(e,n);case"ReturnStatement":return is(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 Qr(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 Xr(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return es(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 es(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 ts(e,n){let t=q(e.test,n),r=e.consequent.type==="BlockStatement"?oe(e.consequent,ee(n)):[Ue(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?oe(e.alternate,ee(n)):[Ue(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function ns(e,n){let t=q(e.test,n),r=e.body.type==="BlockStatement"?oe(e.body,ee(n)):[Ue(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function rs(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):[Ue(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function ss(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 is(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 Hn=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),os=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),We=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),as=new Set(["toUpperCase","toLowerCase","trim","trimStart","trimEnd","charAt","charCodeAt","codePointAt","concat","includes","indexOf","lastIndexOf","startsWith","endsWith","slice","substring","substr","replace","replaceAll","match","search","padStart","padEnd","repeat","normalize","localeCompare","toString","valueOf","at","reverse","sort","fill","copyWithin","flat","flatMap","every","some","forEach","add","remove","has","clear","toArray","union","intersection","diff","format","isBefore","isAfter"]);function cs(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return os.has(n)||We.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Hn.has(t)||We.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(as.has(t))return!0}}return!1}function ls(e){if(e.object.type==="Identifier"){let n=e.object.name;return Hn.has(n)||We.has(n)}return!1}var Yn={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 us(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(We.has(n))return Yn[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(We.has(t))return Yn[t]||`${t} is not available in AsyncJS.`}}return null}function Qn(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=Qn(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=us(e);if(i)throw new U(i,W(e),n.source,n.filename)}if(e.type==="CallExpression"&&cs(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"&&ls(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 fs(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=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 fs(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 ps(s,i,e.arguments,n,t,r);s==="console"&&e.callee.type;let a=ds(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function ps(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:b}=ge(i.body,f,"result");u=y?[y]:[{op:"varSet",key:"result",value:b}]}let m=Z(t[1],r);return{step:{op:"reduce",items:n,as:d,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: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 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]=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=Qn(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 ds(e,n){if(e.arguments.length===1&&e.arguments[0].type==="ObjectExpression"){let t=e.arguments[0],r={};for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r[o]=Z(s.value,n)}return r}return{args:e.arguments.map(t=>Z(t,n))}}import{parseExpressionAt as vr}from"acorn";function ys(e,n){let t=n;for(;t>0&&e[t-1]!==`
|
|
46
|
-
`;)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 gs(e){let n=[],t=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{([\s\S]*?)\}\s*\*\/|\/\*test\s*\{([\s\S]*?)\}\s*\*\//g,r;for(;(r=t.exec(e))!==null;){let s=r[2]||`embedded test ${n.length+1}`,o=(r[3]||r[4]||"").trim();n.push({description:s,body:o,line:Rt(e,r.index)})}return n}function Ct(e){let n=[],t=[],r=gs(e);n.push(...r);let s=/test\s+(['"`])([^'"`]*)\1\s*\{|test\s*\(\s*(['"`])([^'"`]*)\3\s*\)\s*\{|test\s*\{/g,o=/mock\s*\{/g,i=e,a,c=[];for(;(a=s.exec(e))!==null;){let u=a.index;if(ys(e,u))continue;let m=a[2]||a[4]||`test ${n.length+1}`,y=a.index+a[0].length,b=Xn(e,y-1);if(b===-1)continue;let _=e.slice(y,b).trim();n.push({description:m,body:_,line:Rt(e,u)}),c.push({start:u,end:b+1,desc:m})}let l=[];for(;(a=o.exec(e))!==null;){let u=a.index,m=a.index+a[0].length,y=Xn(e,m-1);if(y===-1)continue;let b=e.slice(m,y).trim();t.push({body:b,line:Rt(e,u)}),l.push({start:u,end:y+1})}let d=[...c,...l].sort((u,m)=>m.start-u.start);for(let u of d)i=i.slice(0,u.start)+i.slice(u.end);i=i.replace(/\n\s*\n\s*\n/g,`
|
|
42
|
+
`,g+=` return __tjs.typeError('${c}', 'no matching constructor', a)
|
|
43
|
+
`,g+=`}
|
|
44
|
+
`,i=i.slice(0,d)+h+i.slice(f);let b=d+h.length;i=i.slice(0,b)+g+i.slice(b)}return{source:i,polyCtorClasses:t}}function Wn(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,d=1,f=l+1;for(;f<e.length&&d>0;){let u=e[f];u==="{"?d++:u==="}"&&d--,f++}if(d===0){let u=f,p=e.slice(l,u);r+=e.slice(s,c),r+=`let ${i} = class ${i}${a} ${p}; `,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 Ln(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 Jn(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 Vn(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 zn(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 Zn(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=Hr(n);if(c<a){let l=n.slice(c);n=n.slice(0,c);let d=t+2;for(;d<e.length&&/[\w$]/.test(e[d]);)d++;let f=e.slice(t+2,d);n+=`__tjs.bang(${l},'${f}')`,t=d;continue}}n+=o,t++}else r==="line-comment"?(n+=o,o===`
|
|
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 Hr(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=jn(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=jn(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 jn(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 Rt(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(`
|
|
46
|
+
`,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function ot(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}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0};c&&(r="none");let d=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);d&&(r=d[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)\b/,u;for(;u=e.match(f);){let S=u[2];S==="TjsStrict"?(l.tjsEquals=!0,l.tjsClass=!0,l.tjsDate=!0,l.tjsNoeval=!0,l.tjsNoVar=!0,l.tjsStandard=!0):S==="TjsCompat"?(l.tjsEquals=!1,l.tjsClass=!1,l.tjsDate=!1,l.tjsNoeval=!1,l.tjsNoVar=!1,l.tjsStandard=!1,l.tjsSafeEval=!1):S==="TjsEquals"?l.tjsEquals=!0:S==="TjsClass"?l.tjsClass=!0:S==="TjsDate"?l.tjsDate=!0:S==="TjsNoeval"?l.tjsNoeval=!0:S==="TjsNoVar"?l.tjsNoVar=!0:S==="TjsStandard"?l.tjsStandard=!0:S==="TjsSafeEval"&&(l.tjsSafeEval=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${S}\\s*`),"$1")}e=Rt(e),l.tjsStandard&&(e=Rn(e)),e=Jn(e),e=Zn(e),e=Fe(e),l.tjsEquals&&!n.vmTarget&&(e=qe(e)),e=Cn(e),e=Mn(e),e=Nn(e),e=Pn(e),e=In(e),e=Fn(e);let{source:p,returnType:y,returnSafety:x}=rt(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=p;let _=On(e);e=_.source,e=vn(e);let w=Dn(e,s);e=w.source;let $=An(e);e=$.source;let h=qn(e,n.dangerouslySkipTests);e=h.source;let g=Un(e,s);e=g.source;for(let S of g.polyCtorClasses)o.add(`${S}$dispatch`);return l.tjsClass&&(e=Wn(e,g.polyCtorClasses)),l.tjsDate&&(e=Ln(e)),l.tjsNoeval&&(e=zn(e)),l.tjsNoVar&&(e=Vn(e)),e=Ue(e,_.extensions),{source:e,returnType:y,returnSafety:x,moduleSafety:r,tjsModes:l,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:$.blocks,tests:h.tests,testErrors:h.errors,polymorphicNames:w.polymorphicNames,extensions:_.extensions}}function ye(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1}=n,{source:o,returnType:i,returnSafety:a,moduleSafety:c,originalSource:l,requiredParams:d,unsafeFunctions:f,safeFunctions:u,wasmBlocks:p,tests:y,testErrors:x}=r?ot(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:[]};try{return{ast:Gn.parse(o,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:i,returnSafety:a,moduleSafety:c,originalSource:l,requiredParams:d,unsafeFunctions:f,safeFunctions:u,wasmBlocks:p,tests:y,testErrors:x}}catch(_){let w=_.loc||{line:1,column:0};throw new Y(_.message.replace(/\s*\(\d+:\d+\)$/,""),w,l,t)}}function Kn(e,n){for(let r of e.body){if(r.type==="ImportDeclaration")throw new Y("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 Y("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 Y("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 Y("Source must contain a function declaration",{line:1,column:0},void 0,n);if(t.length>1){let r=t[1];throw new Y("Only a single function per agent is allowed",r.loc?.start||{line:1,column:0},void 0,n)}return t[0]}function We(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 d=s[s.length-1],f=r.substring(d.index+d[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(f)){let u=d[1],p=u.split(`
|
|
47
|
+
`),y=p.filter(x=>x.trim().length>0).reduce((x,_)=>{let w=_.match(/^(\s*)/)?.[1].length||0;return Math.min(x,w)},1/0);return y>0&&y<1/0&&(u=p.map(x=>x.slice(y)).join(`
|
|
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
|
+
`;)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 bs(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:Mt(e,r.index)})}return n}function Pt(e){let n=[],t=[],r=bs(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(hs(e,u))continue;let p=a[1]||a[2]||a[3]||a[4]||a[5]||a[6]||`test ${n.length+1}`,y=a.index+a[0].length,x=er(e,y-1);if(x===-1)continue;let _=e.slice(y,x).trim();n.push({description:p,body:_,line:Mt(e,u)}),c.push({start:u,end:x+1,desc:p})}let l=[];for(;(a=o.exec(e))!==null;){let u=a.index,p=a.index+a[0].length,y=er(e,p-1);if(y===-1)continue;let x=e.slice(p,y).trim();t.push({body:x,line:Mt(e,u)}),l.push({start:u,end:y+1})}let d=[...c,...l].sort((u,p)=>p.start-u.start);for(let u of d)i=i.slice(0,u.start)+i.slice(u.end);i=i.replace(/\n\s*\n\s*\n/g,`
|
|
47
50
|
|
|
48
|
-
`).trim();let f=
|
|
49
|
-
`).length}function
|
|
51
|
+
`).trim();let f=xs(n,t);return{code:i,tests:n,mocks:t,testRunner:f}}function er(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 Mt(e,n){return e.slice(0,n).split(`
|
|
52
|
+
`).length}function xs(e,n){if(e.length===0)return"// No tests defined";let t=n.map(s=>s.body).join(`
|
|
50
53
|
`);return`(async () => {
|
|
51
54
|
const __results = []
|
|
52
55
|
|
|
@@ -69,13 +72,13 @@ const __failed = __results.filter(r => !r.passed).length
|
|
|
69
72
|
|
|
70
73
|
// Return summary
|
|
71
74
|
return { passed: __passed, failed: __failed, results: __results }
|
|
72
|
-
})()`.trim()}var
|
|
75
|
+
})()`.trim()}var tr=`
|
|
73
76
|
function assert(condition, message) {
|
|
74
77
|
if (!condition) {
|
|
75
78
|
throw new Error(message || 'Assertion failed')
|
|
76
79
|
}
|
|
77
80
|
}
|
|
78
|
-
`,
|
|
81
|
+
`,nr=`
|
|
79
82
|
function expect(actual) {
|
|
80
83
|
const deepEqual = (a, b) => {
|
|
81
84
|
if (a === b) return true
|
|
@@ -166,48 +169,49 @@ function expect(actual) {
|
|
|
166
169
|
}
|
|
167
170
|
}
|
|
168
171
|
}
|
|
169
|
-
`,
|
|
170
|
-
`+tr;import{validate as lr,s as lt}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 Nt(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 Mt,filter as xs,s as ot}from"tosijs-schema";function he(e){return e!==null&&typeof e=="object"&&"__runtimeType"in e&&e.__runtimeType===!0}function nr(e){return e!==null&&typeof e=="object"&&"schema"in e&&typeof e.schema=="object"}function _s(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=ot.infer(a));else if(n===void 0&&a!==void 0)i=ot.infer(a);else if(nr(n))i=n;else if(_s(n))i=n;else if(n!==void 0)a=n,c=a,i=ot.infer(a);else throw new Error("Type(description) requires a predicate, schema, or example");else nr(e),i=e,s=ws(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?Mt(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?xs(f,i):f},__runtimeType:!0}}function ws(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 Pt=z("string",e=>typeof e=="string"?!0:`expected string, got ${e===null?"null":typeof e}`),It=z("number",e=>typeof e=="number"?!0:`expected number, got ${e===null?"null":typeof e}`),Ot=z("boolean",e=>typeof e=="boolean"?!0:`expected boolean, got ${e===null?"null":typeof e}`),Bt=z("integer",e=>typeof e!="number"?`expected integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?!0:`${e} is not an integer`),Dt=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`),Ft=z("non-empty string",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:e.length===0?"string is empty":!0),qt=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`),rr=e=>{try{return new URL(e),!0}catch{return!1}},Ut=z("URL",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:rr(e)?!0:`"${e}" is not a valid URL`),Wt=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`),sr=e=>{let n=new Date(e);return!isNaN(n.getTime())&&e.includes("T")},ir=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let n=new Date(e+"T00:00:00Z");return!isNaN(n.getTime())},or=z("ISO 8601 timestamp",e=>typeof e=="string"&&sr(e)),ar=z("date (YYYY-MM-DD)",e=>typeof e=="string"&&ir(e));function Jt(e){return z(`${e.description} or null`,n=>n===null||e.check(n)===!0)}function Lt(e){return z(`${e.description} (optional)`,n=>n==null||e.check(n)===!0)}function Vt(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 zt(e){return z(`array of ${e.description}`,n=>Array.isArray(n)&&n.every(t=>e.check(t)===!0))}function Ss(e){if(he(e))return t=>e.check(t)===!0;if(e&&typeof e=="object"&&"schema"in e)return t=>Mt(t,e);let n=ot.infer(e);return t=>Mt(t,n)}function Je(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:Ss(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 Zt=Je(["T","U"],(e,n,t)=>Array.isArray(e)&&e.length===2&&n(e[0])&&t(e[1]),"Pair<T, U>"),Gt=Je(["V"],(e,n)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(n),"Record<string, V>");function Kt(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 $s(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 at(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 at(e,l)});return Object.defineProperties(i,{typeParamNames:{value:s,enumerable:!0},description:{value:e,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),i}return Es(e,n)}function Es(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 m=0;m<f.length;m++){let y=l.params[u[m]],b=t[f[m]];if(y?.type?.kind&&b!==void 0){let _=$s(b);if(_&&y.type.kind!==_&&y.type.kind!=="any")return`param '${f[m]}' expected ${_}, got ${y.type.kind}`}}}}return!0},__runtimeType:!0}}var ks=cr(),ce=ks.version,Le=Symbol.for("tjs.equals");function ut(e){let[n=0,t=0,r=0]=e.split(".").map(Number);return{major:n,minor:t,patch:r}}function Ht(e,n){let t=ut(e),r=ut(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 Qt(e,n){let t=ut(e),r=ut(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 js(e,n,t,r){let s=t===null?"null":typeof t,o=D.callStacks||D.debug?en():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??ft;fr[Ae]=a,Ae=(Ae+1)%c,_e<c&&_e++,pt++}if(D.logTypeErrors&&console.error(`[TJS TypeError] ${a.message}`),D.throwTypeErrors)throw a;return a}function Yt(e){return e instanceof Error&&e.name==="MonadicError"&&"path"in e}var Xt={debug:!1,safety:"inputs",requireReturnTypes:!1,callStacks:!1,maxStackSize:64,trackErrors:!0,maxErrors:64},D={...Xt},Ve=64,ur=new Array(Ve).fill(""),xe=0,ue=0,ft=64,fr=new Array(ft).fill(null),Ae=0,_e=0,pt=0,Me=0;function vs(){Me++}function As(){Me>0&&Me--}function Rs(){return Me>0}function Cs(e){D={...D,...e}}function Ns(){return{...D}}function pr(e){if((D.callStacks||D.debug)&&e){let n=D.maxStackSize??Ve;ur[xe]=e,xe=(xe+1)%n,ue<n&&ue++}}function ct(){if((D.callStacks||D.debug)&&ue>0){let e=D.maxStackSize??Ve;xe=(xe-1+e)%e,ue--}}function en(){if(ue===0)return[];let e=D.maxStackSize??Ve,n=[],t=(xe-ue+e)%e;for(let r=0;r<ue;r++)n.push(ur[(t+r)%e]);return n}function mr(){if(D.trackErrors===!1||_e===0)return[];let e=D.maxErrors??ft,n=[],t=(Ae-_e+e)%e;for(let r=0;r<_e;r++)n.push(fr[(t+r)%e]);return n}function Ms(){let e=mr();return Ae=0,_e=0,pt=0,e}function Ps(){return pt}function Is(){D={...Xt},xe=0,ue=0,Ae=0,_e=0,pt=0,Me=0}function Re(e,n){if(e!==null&&typeof e=="object"&&typeof e[Le]=="function")return e[Le](n);if(n!==null&&typeof n=="object"&&typeof n[Le]=="function")return n[Le](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 dr(e,n){return!Re(e,n)}function yr(e){return e===null?"null":typeof e}function tn(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 gr(e,n){return!tn(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=en(),s=n?.path?[...r,n.path]:r;t.stack=s}return t}function nn(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 hr(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 rn(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 sn(e,n){if(e.__tjs=n,e.__tjs.schema=()=>Nt(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(...m){if(Me>0)return e.apply(this,m);let y=o||!s&&D.safety!=="none",b=r&&(a||!i&&D.safety==="all");if(!y&&!b)return e.apply(this,m);if(m.length>0&&le(m[0]))return m[0];if(y){let w=m.length===1&&typeof m[0]=="object"&&m[0]!==null&&!Array.isArray(m[0]),S=[];if(w){let g=m[0];for(let x=0;x<d;x++){let[$,h]=l[x],E=g[$];if(le(E)){S.push(E);continue}if(h.required&&E===void 0){S.push(ae(`Missing required parameter '${$}'`,{path:`${f}.${$}`,expected:typeof h.type=="string"?h.type:h.type?.description||"value",actual:"undefined",loc:h.loc}));continue}if(E!==void 0){let k=we(E,h.type,`${f}.${$}`);k&&(h.loc&&(k.loc=h.loc),S.push(k))}}}else for(let g=0;g<d;g++){let[x,$]=l[g],h=m[g];if(le(h)){S.push(h);continue}if($.required&&h===void 0){S.push(ae(`Missing required parameter '${x}'`,{path:`${f}.${x}`,expected:typeof $.type=="string"?$.type:$.type?.description||"value",actual:"undefined",loc:$.loc}));continue}if(h!==void 0){let E=we(h,$.type,`${f}.${x}`);E&&($.loc&&(E.loc=$.loc),S.push(E))}}if(S.length>0)return nn(S,f)}let _=D.callStacks||D.debug;_&&pr(f);try{let w=e.apply(this,m);if(b&&n.returns&&!le(w)){let S=c&&typeof w=="object"&&w!==null?Object.assign({},c,w):w,g=we(S,n.returns.type,`${f}()`);if(g)return _&&ct(),g}return _&&ct(),w}catch(w){return _&&ct(),ae(w.message||String(w),{path:f,cause:w})}};return Object.defineProperty(u,"name",{value:e.name}),u.__tjs=n,u.__tjs.schema=()=>Nt(n),u}function br(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 xr(){let e={...D},n=e.maxStackSize??Ve,t=new Array(n).fill(""),r=0,s=0,o=e.maxErrors??ft,i=new Array(o).fill(null),a=0,c=0,l=0,d=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 b(){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={...Xt},r=0,s=0,a=0,c=0,l=0,d=0}function w(){d++}function S(){d>0&&d--}function g(){return d>0}let x=new Map;function $(j,M,P){x.has(j)||x.set(j,new Map),x.get(j).set(M,P)}function h(j,M){let P=typeof j,V;if(j==null)return;if(P==="string")V="String";else if(P==="number")V="Number";else if(P==="boolean")V="Boolean";else if(Array.isArray(j))V="Array";else if(P==="object")V=j.constructor?.name||"Object";else return;let L=V;for(;L;){let Te=x.get(L);if(Te?.has(M))return Te.get(M);if(P==="object"&&!Array.isArray(j)){if(L=Object.getPrototypeOf(L===V?j:Object.getPrototypeOf(j))?.constructor?.name,L==="Object"||L===V)break}else break}let K=x.get("Object");if(K?.has(M))return K.get(M)}function E(j,M,P){let V=P===null?"null":typeof P,L=e.callStacks||e.debug?b():void 0,K=new Ne(`Expected ${M} for '${j}', got ${V}`,j,M,V,L);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 j=[],M=(a-c+o)%o;for(let P=0;P<c;P++)j.push(i[(M+P)%o]);return j}function v(){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 V=M?.path?[...b(),M.path]:b();P.stack=V}return P}function N(j,M){return j==null?E(`bang.${M}`,"non-null",j):Yt(j)?j:j[M]}return{version:ce,MonadicError:Ne,typeError:E,isMonadicError:Yt,bang:N,isError:le,error:C,composeErrors:nn,typeOf:Ce,isNativeType:hr,checkType:we,validateArgs:rn,wrap:sn,wrapClass:br,compareVersions:Ht,versionsCompatible:Qt,createRuntime:xr,configure:f,getConfig:u,pushStack:m,popStack:y,getStack:b,errors:k,clearErrors:v,getErrorCount:R,resetRuntime:_,enterUnsafe:w,exitUnsafe:S,isUnsafeMode:g,validate:lr,infer:lt.infer.bind(lt),Type:z,isRuntimeType:he,Union:Vt,Generic:Je,Enum:Kt,FunctionPredicate:at,Nullable:Jt,Optional:Lt,TArray:zt,TString:Pt,TNumber:It,TBoolean:Ot,TInteger:Bt,TPositiveInt:Dt,TNonEmptyString:Ft,TEmail:qt,TUrl:Ut,TUuid:Wt,TPair:Zt,TRecord:Gt,Is:Re,IsNot:dr,Eq:tn,NotEq:gr,TypeOf:yr,tjsEquals:Le,registerExtension:$,resolveExtension:h}}var be={version:ce,MonadicError:Ne,typeError:js,isMonadicError:Yt,isError:le,error:ae,composeErrors:nn,typeOf:Ce,isNativeType:hr,checkType:we,validateArgs:rn,wrap:sn,wrapClass:br,compareVersions:Ht,versionsCompatible:Qt,configure:Cs,getConfig:Ns,pushStack:pr,popStack:ct,getStack:en,errors:mr,clearErrors:Ms,getErrorCount:Ps,resetRuntime:Is,enterUnsafe:vs,exitUnsafe:As,isUnsafeMode:Rs,createRuntime:xr,validate:lr,infer:lt.infer.bind(lt),Type:z,isRuntimeType:he,Union:Vt,Generic:Je,Enum:Kt,FunctionPredicate:at,Nullable:Jt,Optional:Lt,TArray:zt,TString:Pt,TNumber:It,TBoolean:Ot,TInteger:Bt,TPositiveInt:Dt,TNonEmptyString:Ft,TEmail:qt,TUrl:Ut,TUuid:Wt,Timestamp:or,LegalDate:ar,TPair:Zt,TRecord:Gt,Is:Re,IsNot:dr,Eq:tn,NotEq:gr,TypeOf:yr};function on(){let e=globalThis;if(e.__tjs){let n=e.__tjs.version;if(typeof n!="string")return e.__tjs=be,be;let t=Ht(ce,n);return t===0||(Qt(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 Os(e){return`
|
|
172
|
+
`,_s=tr+`
|
|
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`
|
|
171
174
|
// TJS runtime wrapper (skips unsafe functions)
|
|
172
175
|
if (typeof ${e}.__tjs === 'object' && !${e}.__tjs.unsafe && typeof globalThis.__tjs?.wrap === 'function') {
|
|
173
176
|
${e} = globalThis.__tjs.wrap(${e}, ${e}.__tjs)
|
|
174
177
|
}
|
|
175
|
-
`.trim()}function
|
|
178
|
+
`.trim()}function Fs(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 fn(e,n){if(e===n||typeof e=="number"&&typeof n=="number"&&Number.isNaN(e)&&Number.isNaN(n)||Fs(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)=>fn(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=>fn(e[s],n[s]))}function pn(e,n,t=""){if(n===null)return e===null?{matches:!0}:{matches:!1,error:`Expected null at '${t}', got ${Se(e)}`};if(n===void 0)return e===void 0?{matches:!0}:{matches:!1,error:`Expected undefined at '${t}', got ${Se(e)}`};if(typeof n=="number")return typeof e=="number"?{matches:!0}:{matches:!1,error:`Expected number at '${t}', got ${Se(e)}`};if(typeof n=="string")return typeof e=="string"?{matches:!0}:{matches:!1,error:`Expected string at '${t}', got ${Se(e)}`};if(typeof n=="boolean")return typeof e=="boolean"?{matches:!0}:{matches:!1,error:`Expected boolean at '${t}', got ${Se(e)}`};if(Array.isArray(n)){if(!Array.isArray(e))return{matches:!1,error:`Expected array at '${t}', got ${Se(e)}`};if(n.length===0)return{matches:!0};let r=n[0];for(let s=0;s<e.length;s++){let o=pn(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 ${Se(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=pn(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 Se(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}function Ge(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=>Ge(t,n)).join(", ")}]`:`[${e.slice(0,3).map(t=>Ge(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,d])=>`${r(l)}: ${Ge(d,n)}`).join(", ")}}`;let s=" ".repeat(n+1),o=" ".repeat(n),i=t.slice(0,8).map(([c,l])=>`${s}${r(c)}: ${Ge(l,n+1)}`).join(`,
|
|
176
179
|
`),a=t.length>8?`,
|
|
177
180
|
${s}...`:"";return`{
|
|
178
181
|
${i}${a}
|
|
179
|
-
${o}}`}return String(e)}function
|
|
182
|
+
${o}}`}return String(e)}function qs(e){let n=e.replace(/\/\*[\s\S]*?\*\//g,t=>{let r=t.split(`
|
|
180
183
|
`).length-1;return`
|
|
181
|
-
`.repeat(r)});return n=n.replace(/\/\/[^\n]*/g,""),n}function
|
|
182
|
-
`)}function
|
|
183
|
-
`).length;if(d===":!")continue;let u=t.slice(s.index+s[0].length),
|
|
184
|
-
`).length,
|
|
185
|
-
`),u=e.map((g,
|
|
186
|
-
// Test ${
|
|
184
|
+
`.repeat(r)});return n=n.replace(/\/\/[^\n]*/g,""),n}function Sr(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 Us(e){if(Object.keys(e).length===0)return"";let n=[];for(let[t,r]of Object.entries(e)){let s=Sr(r);n.push(`// Resolved import: ${t}`),n.push(s)}return n.join(`
|
|
185
|
+
`)}function wr(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 d=o+1;for(;d<t.length&&/\s/.test(t[d]);)d++;let f="",u=0;for(;d<t.length;){let p=t[d];if(p==="{"||p==="["||p==="(")u++;else if(p==="}"||p==="]"||p===")"){if(u===0)break;u--}else if(p===","&&u===0)break;f+=p,d++}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 $r(e){let n=[],t=qs(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],d=s[4],f=t.slice(0,s.index).split(`
|
|
186
|
+
`).length;if(d===":!")continue;let u=t.slice(s.index+s[0].length),p=yt(u);if(!p)continue;let y=un(l);if(!(l.trim()&&y.length===0))try{let x=wr(p);if(!x)continue;let _=y.map(w=>new Function(`return ${w}`)());n.push({funcName:c,args:_,expected:x.pattern,defaults:Object.keys(x.defaults).length>0?x.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,d=c;for(let h=c;h<t.length;h++)if(t[h]==="{")l++;else if(t[h]==="}"&&(l--,l===0)){d=h;break}let f=t.slice(c,d),p=/constructor\s*\(([^)]*)\)/.exec(f);if(!p)continue;let y=p[1],x=un(y);if(y.trim()&&x.length===0)continue;let _;try{_=x.map(h=>new Function(`return ${h}`)())}catch{continue}let w=/(async\s+)?(\w+)\s*\(([^)]*)\)\s*(:[?!]?)\s*/g,$;for(;($=w.exec(f))!==null;){let h=$[2];if(h==="constructor")continue;let g=!!$[1],S=$[3];if($[4]===":!")continue;let E=c+$.index,k=t.slice(0,E).split(`
|
|
187
|
+
`).length,j=f.slice($.index+$[0].length),R=yt(j);if(!R)continue;let C=un(S);if(!(S.trim()&&C.length===0))try{let N=wr(R);if(!N)continue;let v=C.map(M=>new Function(`return ${M}`)());n.push({funcName:h,args:v,expected:N.pattern,defaults:Object.keys(N.defaults).length>0?N.defaults:void 0,line:k,isAsync:g,className:a,constructorArgs:_})}catch{}}}return n}function Er(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(g=>{let S=g.match(/from\s+['"]([^'"]+)['"]/);return S&&!(S[1]in s)}),l=Sr(r),d=Us(s),f=n.map(g=>g.body).join(`
|
|
188
|
+
`),u="const { Is, IsNot, Eq, NotEq, TypeOf } = globalThis.__tjs ?? {};",p=e.map((g,S)=>{let b=o.size>0?Ue(g.body,o):g.body;return`
|
|
189
|
+
// Test ${S}: ${g.description}
|
|
187
190
|
try {
|
|
188
|
-
${
|
|
189
|
-
|
|
191
|
+
${u}
|
|
192
|
+
${b}
|
|
193
|
+
__testResults.push({ idx: ${S}, passed: true });
|
|
190
194
|
} catch (e) {
|
|
191
|
-
__testResults.push({ idx: ${
|
|
195
|
+
__testResults.push({ idx: ${S}, passed: false, error: e.message || String(e) });
|
|
192
196
|
}
|
|
193
197
|
`}).join(`
|
|
194
|
-
`),
|
|
195
|
-
// Signature test ${
|
|
198
|
+
`),y=t.filter(g=>!g.isAsync),x=t.filter(g=>g.isAsync),_=y.map((g,S)=>{let b=g.className?`${g.className}.${g.funcName}`:g.funcName,E=g.className?`new ${g.className}(${(g.constructorArgs||[]).map(k=>JSON.stringify(k)).join(", ")}).${g.funcName}(${g.args.map(k=>JSON.stringify(k)).join(", ")})`:`${g.funcName}(${g.args.map(k=>JSON.stringify(k)).join(", ")})`;return`
|
|
199
|
+
// Signature test ${S}: ${b}
|
|
196
200
|
try {
|
|
197
|
-
let __actual = ${
|
|
201
|
+
let __actual = ${E};
|
|
198
202
|
const __expected = ${JSON.stringify(g.expected)};${g.defaults?`
|
|
199
203
|
const __defaults = ${JSON.stringify(g.defaults)};
|
|
200
204
|
if (typeof __actual === 'object' && __actual !== null) __actual = Object.assign({}, __defaults, __actual);`:""}
|
|
201
205
|
if (__deepEqual(__actual, __expected)) {
|
|
202
|
-
__sigTestResults.push({ idx: ${
|
|
206
|
+
__sigTestResults.push({ idx: ${S}, passed: true });
|
|
203
207
|
} else {
|
|
204
|
-
__sigTestResults.push({ idx: ${
|
|
208
|
+
__sigTestResults.push({ idx: ${S}, passed: false, error: 'Expected ' + __format(__expected) + ' at \\'${b}\\', got ' + __format(__actual) });
|
|
205
209
|
}
|
|
206
210
|
} catch (e) {
|
|
207
|
-
__sigTestResults.push({ idx: ${
|
|
211
|
+
__sigTestResults.push({ idx: ${S}, passed: false, error: e.message || String(e) });
|
|
208
212
|
}
|
|
209
213
|
`}).join(`
|
|
210
|
-
`);
|
|
214
|
+
`);ln();let h=`
|
|
211
215
|
|
|
212
216
|
const __saved_tjs = globalThis.__tjs;
|
|
213
217
|
|
|
@@ -282,17 +286,17 @@ ${o}}`}return String(e)}function Ds(e){let n=e.replace(/\/\*[\s\S]*?\*\//g,t=>{l
|
|
|
282
286
|
${f}
|
|
283
287
|
|
|
284
288
|
// Run explicit test blocks
|
|
285
|
-
${
|
|
289
|
+
${p}
|
|
286
290
|
|
|
287
291
|
// Run signature tests
|
|
288
|
-
${
|
|
292
|
+
${_}
|
|
289
293
|
|
|
290
294
|
} finally {
|
|
291
295
|
globalThis.__tjs = __saved_tjs;
|
|
292
296
|
}
|
|
293
297
|
return { testResults: __testResults, sigTestResults: __sigTestResults };
|
|
294
|
-
`;try{let g=new Function("__deepEqual","__format","__typeMatches",
|
|
295
|
-
`)}var yt={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:p.i32_load8_s,storeOp:p.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:p.i32_load8_u,storeOp:p.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:p.i32_load8_u,storeOp:p.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:p.i32_load16_s,storeOp:p.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:p.i32_load16_u,storeOp:p.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:p.i32_load,storeOp:p.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:p.i32_load,storeOp:p.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:p.f32_load,storeOp:p.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:p.f64_load,storeOp:p.f64_store}};function Vs(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 dt(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),p.drop]}case"ReturnStatement":{let t=e;if(n.hasReturn=!0,!t.argument)return[p.return];let r=B(t.argument,n),s=J(t.argument,n);return s==="i32"?r.push(p.f64_convert_i32_s):s==="f32"&&r.push(p.f64_promote_f32),r.push(p.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=dt(n,o,i);s.init&&(r.push(...B(s.init,n)),r.push(p.local_set,...I(a)))}return r}case"ForStatement":return zs(e,n);case"IfStatement":return Zs(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 zs(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(p.block,se.void),t.push(p.loop,se.void),e.test&&(t.push(...B(e.test,n)),t.push(p.i32_eqz),t.push(p.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(p.drop)),t.push(p.br,0),t.push(p.end),t.push(p.end),t}function Zs(e,n){let t=[];return t.push(...B(e.test,n)),t.push(p.if,se.void),t.push(...Pe(e.consequent,n)),e.alternate&&(t.push(p.else),t.push(...Pe(e.alternate,n))),t.push(p.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 $e(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"&&$e(n,t.object.name)){let s=n.params.find(o=>o.name===t.object.name);if(s?.arrayType){let o=yt[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=J(e,n);return r==="i32"?[p.i32_const,...Ye(t.value|0)]:r==="f32"?[p.f32_const,...pn(t.value)]:[p.f64_const,...te(t.value)]}return n.errors.push(`Unsupported literal type: ${typeof t.value}`),[p.f64_const,...te(0)]}case"Identifier":{let t=e.name,r=$e(n,t);return r?[p.local_get,...I(r.index)]:(n.errors.push(`Unknown identifier: ${t}`),[p.f64_const,...te(0)])}case"BinaryExpression":return Gs(e,n);case"UnaryExpression":return Ks(e,n);case"AssignmentExpression":return Ys(e,n);case"UpdateExpression":return Hs(e,n);case"MemberExpression":return Qs(e,n);case"CallExpression":return ei(e,n);case"SequenceExpression":{let t=e,r=[];for(let s=0;s<t.expressions.length;s++)r.push(...B(t.expressions[s],n)),s<t.expressions.length-1&&r.push(p.drop);return r}default:return n.errors.push(`Unsupported expression type: ${e.type}`),[p.f64_const,...te(0)]}}function Gs(e,n){let t=B(e.left,n),r=B(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,d=r;c==="f64"?(o==="i32"?l=[...t,p.f64_convert_i32_s]:o==="f32"&&(l=[...t,p.f64_promote_f32]),i==="i32"?d=[...r,p.f64_convert_i32_s]:i==="f32"&&(d=[...r,p.f64_promote_f32])):c==="f32"&&(o==="i32"&&(l=[...t,p.f32_convert_i32_s]),i==="i32"&&(d=[...r,p.f32_convert_i32_s]));let u={"+":{i32:p.i32_add,f32:p.f32_add,f64:p.f64_add},"-":{i32:p.i32_sub,f32:p.f32_sub,f64:p.f64_sub},"*":{i32:p.i32_mul,f32:p.f32_mul,f64:p.f64_mul},"/":{i32:p.i32_div_s,f32:p.f32_div,f64:p.f64_div},"%":{i32:p.i32_rem_s},"<":{i32:p.i32_lt_s,f32:p.f32_lt,f64:p.f64_lt},">":{i32:p.i32_gt_s,f32:p.f32_gt,f64:p.f64_gt},"<=":{i32:p.i32_le_s,f32:p.f32_le,f64:p.f64_le},">=":{i32:p.i32_ge_s,f32:p.f32_ge,f64:p.f64_ge},"==":{i32:p.i32_eq,f32:p.f32_eq,f64:p.f64_eq},"===":{i32:p.i32_eq,f32:p.f32_eq,f64:p.f64_eq},"!=":{i32:p.i32_ne,f32:p.f32_ne,f64:p.f64_ne},"!==":{i32:p.i32_ne,f32:p.f32_ne,f64:p.f64_ne},"|":{i32:p.i32_or},"&":{i32:p.i32_and},"^":{i32:p.i32_xor},"<<":{i32:p.i32_shl},">>":{i32:p.i32_shr_s},">>>":{i32:p.i32_shr_u}}[e.operator];if(!u)return n.errors.push(`Unsupported operator: ${e.operator}`),[p.f64_const,...te(0)];let m=u[c]??u.f64??u.i32;return m===void 0?(n.errors.push(`Operator ${e.operator} not supported for type ${c}`),[p.f64_const,...te(0)]):[...l,...d,m]}function Ks(e,n){let t=B(e.argument,n),r=J(e.argument,n);switch(e.operator){case"-":return r==="i32"?[p.i32_const,0,...t,p.i32_sub]:r==="f32"?[...t,p.f32_neg]:[...t,p.f64_neg];case"!":return[...t,p.i32_eqz];case"~":return[...t,p.i32_const,...Ye(-1),p.i32_xor];default:return n.errors.push(`Unsupported unary operator: ${e.operator}`),t}}function Ys(e,n){if(e.left.type==="MemberExpression")return Xs(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=J(e.right,n);r.type==="f64"&&o==="i32"?s.push(p.f64_convert_i32_s):r.type==="f64"&&o==="f32"?s.push(p.f64_promote_f32):r.type==="i32"&&o==="f64"?s.push(p.i32_trunc_f64_s):r.type==="i32"&&o==="f32"?s.push(p.i32_trunc_f32_s):r.type==="f32"&&o==="i32"?s.push(p.f32_convert_i32_s):r.type==="f32"&&o==="f64"&&s.push(p.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(p.local_get,...I(r.index)),i==="f64"&&r.type==="i32"?s.push(p.f64_convert_i32_s):i==="f64"&&r.type==="f32"?s.push(p.f64_promote_f32):i==="f32"&&r.type==="i32"&&s.push(p.f32_convert_i32_s),s.push(...B(e.right,n)),i==="f64"&&o==="i32"?s.push(p.f64_convert_i32_s):i==="f64"&&o==="f32"?s.push(p.f64_promote_f32):i==="f32"&&o==="i32"&&s.push(p.f32_convert_i32_s);let a=e.operator.slice(0,-1),l={"+":{i32:p.i32_add,f32:p.f32_add,f64:p.f64_add},"-":{i32:p.i32_sub,f32:p.f32_sub,f64:p.f64_sub},"*":{i32:p.i32_mul,f32:p.f32_mul,f64:p.f64_mul},"/":{i32:p.i32_div_s,f32:p.f32_div,f64:p.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(p.i32_trunc_f64_s):r.type==="i32"&&i==="f32"?s.push(p.i32_trunc_f32_s):r.type==="f32"&&i==="f64"&&s.push(p.f32_demote_f64)}return s.push(p.local_tee,...I(r.index)),s}function Hs(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(p.local_get,...I(r.index)),o?(s.push(p.i32_const,1),s.push(e.operator==="++"?p.i32_add:p.i32_sub)):(s.push(p.f64_const,...te(1)),s.push(e.operator==="++"?p.f64_add:p.f64_sub)),s.push(p.local_tee,...I(r.index))):(s.push(p.local_get,...I(r.index)),s.push(p.local_get,...I(r.index)),o?(s.push(p.i32_const,1),s.push(e.operator==="++"?p.i32_add:p.i32_sub)):(s.push(p.f64_const,...te(1)),s.push(e.operator==="++"?p.f64_add:p.f64_sub)),s.push(p.local_set,...I(r.index))),s}function Qs(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=yt[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(p.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=J(e.property,n);return o.push(...a),c==="f64"&&o.push(p.i32_trunc_f64_s),s.bytesPerElement>1&&(o.push(p.i32_const,...Ye(s.bytesPerElement)),o.push(p.i32_mul)),o.push(p.i32_add),o.push(s.loadOp,0,0),o}function Xs(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=yt[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=J(e.property,r),f=()=>{let y=[];return y.push(p.local_get,...I(c.index)),y.push(...l),d==="f64"&&y.push(p.i32_trunc_f64_s),i.bytesPerElement>1&&(y.push(p.i32_const,...Ye(i.bytesPerElement)),y.push(p.i32_mul)),y.push(p.i32_add),y};if(t==="=")a.push(...B(n,r));else{let y=dt(r,`__addr_${r.nextLocalIndex}`,"i32");a.push(...f()),a.push(p.local_tee,...I(y)),a.push(i.loadOp,0,0),a.push(...B(n,r));let b=J(n,r);i.elementType==="f32"&&b==="f64"?a.push(p.f32_demote_f64):i.elementType==="f64"&&b==="f32"?a.push(p.f64_promote_f32):i.elementType==="f32"&&b==="i32"?a.push(p.f32_convert_i32_s):i.elementType==="f64"&&b==="i32"?a.push(p.f64_convert_i32_s):i.elementType==="i32"&&b==="f64"?a.push(p.i32_trunc_f64_s):i.elementType==="i32"&&b==="f32"&&a.push(p.i32_trunc_f32_s);let _=t.slice(0,-1),w={"+":i.elementType==="i32"?p.i32_add:i.elementType==="f32"?p.f32_add:p.f64_add,"-":i.elementType==="i32"?p.i32_sub:i.elementType==="f32"?p.f32_sub:p.f64_sub,"*":i.elementType==="i32"?p.i32_mul:i.elementType==="f32"?p.f32_mul:p.f64_mul};a.push(w[_]??p.f64_add);let S=dt(r,`__val_${r.nextLocalIndex}`,i.elementType);return a.push(p.local_set,...I(S)),a.push(p.local_get,...I(y)),a.push(p.local_get,...I(S)),a.push(i.storeOp,0,0),a.push(p.local_get,...I(S)),a}let u=J(n,r);i.elementType==="f32"&&u==="f64"?a.push(p.f32_demote_f64):i.elementType==="f64"&&u==="f32"?a.push(p.f64_promote_f32):i.elementType==="i32"&&u==="f64"&&a.push(p.i32_trunc_f64_s);let m=dt(r,`__tmp_${r.nextLocalIndex}`,i.elementType);return a.push(p.local_set,...I(m)),a.push(p.local_get,...I(c.index)),a.push(...l),d==="f64"&&a.push(p.i32_trunc_f64_s),i.bytesPerElement>1&&(a.push(p.i32_const,...Ye(i.bytesPerElement)),a.push(p.i32_mul)),a.push(p.i32_add),a.push(p.local_get,...I(m)),a.push(i.storeOp,0,0),a.push(p.local_get,...I(m)),a}function ei(e,n){if(e.callee.type==="MemberExpression"){let t=e.callee;if(t.object.type==="Identifier"&&t.object.name==="Math"&&t.property.type==="Identifier"){let r=t.property.name;return ni(r,e.arguments,n)}}if(e.callee.type==="Identifier"){let t=e.callee.name;if(t.startsWith("f32x4_")||t.startsWith("v128_"))return ti(t,e.arguments,n)}return n.errors.push(`Unsupported function call: ${e.callee.type}`),[p.f64_const,...te(0)]}function ti(e,n,t){t.needsMemory=!0;let r=[];switch(e){case"v128_load":case"f32x4_load":{r.push(...B(n[0],t)),J(n[0],t)==="f64"&&r.push(p.i32_trunc_f64_s),r.push(...B(n[1],t));let o=J(n[1],t);return o==="f64"?r.push(p.i32_trunc_f64_s):o==="f32"&&r.push(p.i32_trunc_f32_s),r.push(p.i32_add),r.push(...Er(G.v128_load,2,0)),r}case"v128_store":case"f32x4_store":{r.push(...B(n[0],t)),J(n[0],t)==="f64"&&r.push(p.i32_trunc_f64_s),r.push(...B(n[1],t));let o=J(n[1],t);return o==="f64"?r.push(p.i32_trunc_f64_s):o==="f32"&&r.push(p.i32_trunc_f32_s),r.push(p.i32_add),r.push(...B(n[2],t)),r.push(...Er(G.v128_store,2,0)),r.push(p.i32_const,0),r}case"f32x4_splat":{r.push(...B(n[0],t));let s=J(n[0],t);return s==="i32"?r.push(p.f32_convert_i32_s):s==="f64"&&r.push(p.f32_demote_f64),r.push(...un(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}`),[p.f32_const,...pn(0)]):(r.push(Ke,...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}`),[p.f32_const,...pn(0)];r.push(...B(n[2],t));let o=J(n[2],t);return o==="i32"?r.push(p.f32_convert_i32_s):o==="f64"&&r.push(p.f32_demote_f64),r.push(Ke,...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(...un(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(...un(s[e])),r}default:return t.errors.push(`Unknown SIMD intrinsic: ${e}`),[p.f64_const,...te(0)]}}function ni(e,n,t){let r=[];for(let a of n){r.push(...B(a,t));let c=J(a,t);c==="i32"?r.push(p.f64_convert_i32_s):c==="f32"&&r.push(p.f64_promote_f32)}let o={abs:p.f64_abs,ceil:p.f64_ceil,floor:p.f64_floor,trunc:p.f64_trunc,sqrt:p.f64_sqrt,min:p.f64_min,max:p.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)`),[p.f64_const,...te(0)]):(t.errors.push(`Unknown Math method: ${e}`),[p.f64_const,...te(0)])}function ri(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 yt[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 si(e,n,t,r,s){let o=[0,97,115,109,1,0,0,0],i=e.map(S=>se[S.type]),a=s?[1,se.f64]:[0],c=Ge(Ze.type,[1,96,...I(e.length),...i,...a]),l=[],d=[];r&&(d=Ge(Ze.import,[1,...fn("env"),...fn("memory"),2,0,1]));let f=Ge(Ze.function,[1,0]),u=Ge(Ze.export,[1,...fn("compute"),0,0]),m=[];if(t.length>0){let S=t[0],g=1;for(let x=1;x<t.length;x++)t[x]===S?g++:(m.push([...I(g),se[S]]),S=t[x],g=1);m.push([...I(g),se[S]])}let b=[...[...I(m.length),...m.flat()],...n,p.end],_=Ge(Ze.code,[1,...I(b.length),...b]),w=[...o,...c];return d.length>0&&w.push(...d),w.push(...f,...u,..._),w}function kr(e){try{let n=e.captures.map(ri),t;try{let l=`function __wasm__(${n.map(d=>d.name).join(", ")}) { ${e.body} }`;t=Tr.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=Vs(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=si(n,i,o.localTypes,o.needsMemory,o.hasReturn),c=Ls(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 jr(e){let n=[],t=[];for(let a of e){let c=kr(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(`
|
|
298
|
+
`;try{let g=new Function("__deepEqual","__format","__typeMatches",h),{testResults:S,sigTestResults:b}=g(fn,Ge,pn);for(let E of S){let k=e[E.idx],j=c&&!E.passed&&E.error&&/is not defined$/.test(E.error);i.push({description:k.description,passed:j?!0:E.passed,error:j?void 0:E.error,line:k.line})}for(let E of b){let k=y[E.idx],j=c&&!E.passed&&E.error&&/is not defined$/.test(E.error),R=k.className?`${k.className}.${k.funcName}`:k.funcName;i.push({description:`${R} signature example`,passed:j?!0:E.passed,error:j?void 0:E.error,isSignatureTest:!0,line:k.line})}}catch(g){let S=c&&g instanceof ReferenceError;for(let b of e)i.push({description:b.description,passed:S,error:S?void 0:`Module execution failed: ${g.message}`,line:b.line});for(let b of y){let E=b.className?`${b.className}.${b.funcName}`:b.funcName;i.push({description:`${E} signature example`,passed:S,error:S?void 0:`Module execution failed: ${g.message}`,isSignatureTest:!0,line:b.line})}}for(let g of x){let S=g.className?`${g.className}.${g.funcName}`:g.funcName;i.push({description:`${S} signature example`,passed:!0,isSignatureTest:!0,line:g.line})}return i}function yt(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 un(e){if(!e.trim())return[];let n=[],t=Ws(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 Ws(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 kr from"acorn";var se={i32:127,i64:126,f32:125,f64:124,v128:123,funcref:112,externref:111,void:64},Ke={custom:0,type:1,import:2,function:3,table:4,memory:5,global:6,export:7,start:8,element:9,code:10,data:11},m={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},Ls=Object.fromEntries(Object.entries(m).map(([e,n])=>[n,e.replace(/_/g,".")])),He=253,G={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},Js=Object.fromEntries(Object.entries(G).map(([e,n])=>[n,e.replace(/_/g,".")]));function mn(e){return[He,...I(e)]}function Tr(e,n,t){return[He,...I(e),...I(n),...I(t)]}function I(e){let n=[];do{let t=e&127;e>>>=7,e!==0&&(t|=128),n.push(t)}while(e!==0);return n}function Qe(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 yn(e){let n=new ArrayBuffer(4);return new Float32Array(n)[0]=e,[...new Uint8Array(n)]}function te(e){let n=new ArrayBuffer(8);return new Float64Array(n)[0]=e,[...new Uint8Array(n)]}function dn(e){let n=new TextEncoder().encode(e);return[...I(n.length),...n]}function Ye(e,n){return[e,...I(n.length),...n]}function pe(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 Vs(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 zs(e,n,t){let r=[],s=1,o=()=>" ".repeat(s),i=n.map((l,d)=>`(param $${l.name} ${l.type})`).join(" "),a=t.map((l,d)=>`(local $L${n.length+d} ${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],d=Ls[l]||`unknown(0x${l.toString(16)})`;if(c++,l===m.local_get||l===m.local_set||l===m.local_tee){let[f,u]=pe(e,c);c+=u;let p=f<n.length?`$${n[f].name}`:`$L${f}`;r.push(`${o()}${d} ${p}`)}else if(l===m.br||l===m.br_if){let[f,u]=pe(e,c);c+=u,r.push(`${o()}${d} ${f}`)}else if(l===m.i32_const){let[f,u]=pe(e,c);c+=u,r.push(`${o()}i32.const ${f}`)}else if(l===m.f32_const){let f=new ArrayBuffer(4),u=new Uint8Array(f);for(let y=0;y<4;y++)u[y]=e[c+y];let p=new Float32Array(f)[0];c+=4,r.push(`${o()}f32.const ${p}`)}else if(l===m.f64_const){let f=Vs(e,c);c+=8,r.push(`${o()}f64.const ${f}`)}else if(l===m.block||l===m.loop){let f=e[c];c++,r.push(`${o()}${d}${f===se.void?"":` (result ${f===se.f64?"f64":"i32"})`}`),s++}else if(l===m.if){let f=e[c];c++,r.push(`${o()}if${f===se.void?"":` (result ${f===se.f64?"f64":"i32"})`}`),s++}else if(l===m.else)s--,r.push(`${o()}else`),s++;else if(l===m.end)s=Math.max(1,s-1),r.push(`${o()}end`);else if(l===m.f64_load||l===m.f64_store||l===m.f32_load||l===m.f32_store||l===m.i32_load||l===m.i32_store){let[f,u]=pe(e,c);c+=u;let[p,y]=pe(e,c);c+=y,r.push(`${o()}${d}${p?` offset=${p}`:""}`)}else if(l===He){let[f,u]=pe(e,c);c+=u;let p=Js[f]||`simd.unknown(0x${f.toString(16)})`;if(f===G.v128_load||f===G.v128_store){let[y,x]=pe(e,c);c+=x;let[_,w]=pe(e,c);c+=w,r.push(`${o()}${p}${_?` offset=${_}`:""}`)}else if(f===G.v128_const){let y=e.slice(c,c+16);c+=16,r.push(`${o()}v128.const ${y.map(x=>"0x"+x.toString(16).padStart(2,"0")).join(" ")}`)}else if(f===G.f32x4_extract_lane||f===G.f32x4_replace_lane){let y=e[c];c++,r.push(`${o()}${p} ${y}`)}else r.push(`${o()}${p}`)}else r.push(`${o()}${d}`)}return r.push(")"),r.join(`
|
|
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(`
|
|
296
300
|
`).map(l=>` * ${l}`);return`/**
|
|
297
301
|
* WASM: ${a.id}
|
|
298
302
|
${c.join(`
|
|
@@ -329,21 +333,21 @@ for(const{id,b64,c,m}of __wasmBlocks){
|
|
|
329
333
|
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}}
|
|
330
334
|
return r};
|
|
331
335
|
}})();
|
|
332
|
-
`.trim(),results:n}}function
|
|
333
|
-
`),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}`,d=
|
|
334
|
-
`),suffix:"__tjs.popStack();"})}function
|
|
335
|
-
${
|
|
336
|
+
`.trim(),results:n}}function ai(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 ci(e,n,t,r,s){let o=[],i=We(n,e),a={},c=!1,l,d;if(e.params.length===1&&(e.params[0].type==="ObjectPattern"||e.params[0].type==="AssignmentPattern"&&e.params[0].left.type==="ObjectPattern")){c=!0;let p=e.params[0],y=p.type==="ObjectPattern"?p:p.left,x=fe(y,t);if(x.type.kind==="object"&&x.type.destructuredParams){l={},d=new Set;for(let[_,w]of Object.entries(x.type.destructuredParams))a[_]={...w,description:i.params[_]},l[_]=w.type,w.required&&d.add(_)}}else for(let p of e.params)if(p.type==="Identifier"){let y=fe(p,t);a[p.name]={...y,required:t.has(p.name),description:i.params[p.name]}}else if(p.type==="AssignmentPattern"&&p.left.type==="Identifier"){let y=fe(p,t),x=ai(s||"",e.id?.name||"",p.left.name);a[p.left.name]={...y,required:x,default:x?null:y.example??y.default,description:i.params[p.left.name]}}else if(p.type==="ObjectPattern"){let y=fe(p,t);if(y.type.kind==="object"&&y.type.destructuredParams)for(let[x,_]of Object.entries(y.type.destructuredParams))a[x]={..._,description:i.params[x]}}else if(p.type==="RestElement"&&p.argument?.type==="Identifier"){let y=p.argument.name,x=n.match(new RegExp(`\\.\\.\\.${y}\\s*:\\s*([^)]+?)\\s*\\)`));if(x)try{let _=Ar(x[1].trim(),0,{ecmaVersion:2022}),w=H(_);a[y]={name:y,type:w,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 p=r.includes("=")?Rr(r):r,y=Ar(p,0,{ecmaVersion:2022});f=H(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:d},warnings:o}}function li(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 d of l)r.push(`if (${d} instanceof Error) return ${d};`);for(let[d,f]of Object.entries(a)){let u=c.has(d),p=`${s}${e}.${d}`,y=gn(d,f);if(y){let x=f.kind;u?r.push(`if (${y}) return __tjs.typeError('${p}', '${x}', ${d});`):r.push(`if (${d} !== undefined && ${y}) return __tjs.typeError('${p}', '${x}', ${d});`)}}return r.length===0?null:(r.unshift(`__tjs.pushStack('${o}');`),{preamble:r.join(`
|
|
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}`,d=gn(a,c.type);if(d){let f=c.type.kind==="union"?c.type.members.map(u=>u.kind).join(" | "):c.type.kind;c.required?r.push(`if (${d}) return __tjs.typeError('${l}', '${f}', ${a});`):r.push(`if (${a} !== undefined && ${d}) return __tjs.typeError('${l}', '${f}', ${a});`)}}return r.length===0?null:(r.unshift(`__tjs.pushStack('${o}');`),{preamble:r.join(`
|
|
338
|
+
`),suffix:"__tjs.popStack();"})}function Rr(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 ui(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 yt(s)}function fi(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 pi(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 bt(e,n={}){let{filename:t="<source>",runTests:r=!0,debug:s=!1,resolvedImports:o={}}=n,i=[];e=Rt(e);let c=pi(e)||t,{code:l,tests:d,mocks:f,testRunner:u}=Pt(e),{ast:p,originalSource:y,requiredParams:x,unsafeFunctions:_}=ye(l,{filename:t,colonShorthand:!0}),w=di(p),$=ot(l);for(let A of d)A.body=Fe(A.body),$.tjsModes.tjsEquals&&(A.body=qe(A.body));for(let A of f)A.body=Fe(A.body),$.tjsModes.tjsEquals&&(A.body=qe(A.body));let h={},g=[],S=[];for(let A of w){let F=A.id?.name||"anonymous",O=ui(l,F),ne;if(O&&O.includes("="))try{let Q=O.matchAll(/(\w+)\s*=\s*/g),X=Rr(O),de=new Function(`return ${X}`)(),re={};for(let qr of Q){let kt=qr[1];kt in de&&(re[kt]=de[kt])}Object.keys(re).length>0&&(ne=re)}catch{}let{types:me,warnings:Ir}=ci(A,y,x,O,l);i.push(...Ir),h[F]=me;for(let Q of A.params)if(Q.type==="AssignmentPattern"){let X=Q.left?.name||Q.left?.value,de=X?me.params[X]:null;if(de?.required&&de.default===null)S.push({start:Q.left.end,end:Q.right.end});else{let re=Q.right;re.type==="BinaryExpression"&&re.operator==="|"&&S.push({start:re.left.end,end:re.end})}}let xn=$.moduleSafety==="none"||_.has(F),Or=$.safeFunctions.has(F),Br=fi(l,F),Dr=mi(e,F),ke={file:c,line:Dr??A.loc?.start.line??0,column:A.loc?.start.column??0},Fr={unsafe:xn,safe:Or,returnSafety:Br},_n=$.polymorphicNames.has(F),Tt;if(_n){let Q=[];for(let de of w){let re=de.id?.name||"";re.startsWith(F+"$")&&Q.push(re)}let X={polymorphic:!0,variants:Q};ke&&(X.source=`${ke.file}:${ke.line}`),Tt=`${F}.__tjs = ${JSON.stringify(X,null,2)}`}else Tt=yi(F,me,Fr,{debug:s,source:ke,returnDefaults:ne});if(g.push({position:A.end,text:`
|
|
339
|
+
${Tt}`}),!xn&&!_n){let Q=`${ke.file}:${ke.line}`,X=li(F,me,Q);X&&A.body&&A.body.start!==void 0&&(g.push({position:A.body.start+1,text:`
|
|
336
340
|
${X.preamble}
|
|
337
|
-
`}),X.suffix&&
|
|
341
|
+
`}),X.suffix&&g.push({position:A.body.end-1,text:`
|
|
338
342
|
${X.suffix}
|
|
339
|
-
`}))}}
|
|
343
|
+
`}))}}S.sort((A,F)=>F.start-A.start);let b=$.source;for(let{start:A,end:F}of S)b=b.slice(0,A)+b.slice(F);for(let A of g){let F=0;for(let O of S)O.start<A.position&&(F+=O.end-O.start);A.position-=F}g.sort((A,F)=>F.position-A.position);for(let{position:A,text:F}of g)b=b.slice(0,A)+F+b.slice(A);let E=b.includes("__tjs.typeError("),k=b.includes("__tjs.pushStack("),j=b.includes("Is("),R=b.includes("IsNot("),C=b.includes("Eq("),N=b.includes("NotEq("),v=b.includes("TypeOf("),M=/\bType\(/.test(b),P=/\bGeneric\(/.test(b),V=/\bFunctionPredicate\(/.test(b),J=/\bEnum\(/.test(b),K=/\bUnion\(/.test(b),Te=b.includes("__tjs.bang("),$t=$.tjsModes.tjsSafeEval;if(E||k||j||R||C||N||v||M||P||V||J||K||Te||$t){let A=[];E&&A.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&&A.push("const __stack=[];function pushStack(n){__stack.push(n)}function popStack(){__stack.pop()}function getStack(){return[...__stack]}"),C&&A.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&&A.push("function NotEq(a,b){return!Eq(a,b)}"),v&&A.push("function TypeOf(v){return v===null?'null':typeof v}"),j&&A.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&&A.push("function IsNot(a,b){return!Is(a,b)}"),M&&A.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&&A.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}"),V&&A.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}}"),J&&A.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}}"),K&&A.push("function Union(d,...v){const vals=v.flat();return{description:d,check:x=>vals.includes(x),values:vals,__runtimeType:true}}"),Te&&(E||A.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}"),A.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 F=A.length>0?A.join(`;
|
|
340
344
|
`)+`;
|
|
341
|
-
`:"",O=[];E&&O.push("typeError","isMonadicError"),k&&O.push("pushStack","popStack","getStack"),C&&O.push("Eq"),N&&O.push("NotEq"),
|
|
342
|
-
`+
|
|
343
|
-
`+
|
|
345
|
+
`:"",O=[];E&&O.push("typeError","isMonadicError"),k&&O.push("pushStack","popStack","getStack"),C&&O.push("Eq"),N&&O.push("NotEq"),v&&O.push("TypeOf"),j&&O.push("Is","tjsEquals"),R&&O.push("IsNot"),M&&O.push("Type"),P&&O.push("Generic"),V&&O.push("FunctionPredicate"),J&&O.push("Enum"),K&&O.push("Union"),Te&&(O.push("bang"),E||O.push("typeError","isMonadicError"));let ne=O.length>0?`{${O.join(",")}}`:"undefined";b=F+`const __tjs = globalThis.__tjs?.createRuntime?.() ?? ${ne};
|
|
346
|
+
`+b}$t&&(b=`import { Eval, SafeFunction } from 'tjs-lang';
|
|
347
|
+
`+b);let Ie;if(r){let A=$r(e);Ie=Er(d,f,A,b,o,$.extensions);let F=Ie.filter(O=>!O.passed);if(F.length>0&&r===!0){let O=F.map(ne=>{if(ne.isSignatureTest)return` Function signature example is inconsistent:
|
|
344
348
|
${ne.error}`;let me=ne.line?` (line ${ne.line})`:"";return` Test '${ne.description}'${me} failed:
|
|
345
349
|
${ne.error}`});throw new Error(`Transpile-time test failures:
|
|
346
350
|
${O.join(`
|
|
347
|
-
`)}`)}}if(r==="only")return{code:"",types:
|
|
348
|
-
`+h),St=A.results}return{code:h,types:g,metadata:g,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:St}}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 He(e){let n={kind:e.kind};return e.nullable&&(n.nullable=!0),e.items&&(n.items=He(e.items)),e.shape&&(n.shape=Object.fromEntries(Object.entries(e.shape).map(([t,r])=>[t,He(r)]))),e.members&&(n.members=e.members.map(He)),n}function mi(e,n,t={},r={}){let s={};for(let[i,a]of Object.entries(n.params))s[i]={type:He(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:He(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 mn(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=>mn(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 bt(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=ye(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),i=Gn(t,n.filename),{ast:a,signature:c,warnings:l}=At(i,s,r,n,o);return{ast:a,signature:c,warnings:l}}function di(e,...n){if(typeof e=="string")return bt(e).ast;let t=e.reduce((r,s,o)=>r+s+(n[o]!==void 0?String(n[o]):""),"");return bt(t).ast}function yi(e,n,t){let{ast:r,signature:s}=bt(e),o=async i=>(await n.run(r,i,t)).result;return o.signature=s,o.ast=r,o}function ht(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?ht(e.items):{}};case"object":return e.shape?{type:"object",properties:Object.fromEntries(Object.entries(e.shape).map(([n,t])=>[n,ht(t)]))}:{type:"object"};case"union":return e.members?{anyOf:e.members.map(ht)}:{};default:return{}}}function gi(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]=ht(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 hi(e,n,...t){if(typeof e=="string")return gt(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 gt(s)}import{s as Rr}from"tosijs-schema";function Cr(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}function xt(e){return Rr.infer(e)}function dn(e){return xt(e)}dn.type=Cr;dn.infer=xt;var bi=new Proxy(dn,{get(e,n){return n==="type"?Cr:n==="infer"?xt:Rr[n]},apply(e,n,t){return xt(t[0])}});function _t(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 Nr(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 yn(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=yn;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=yn;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=yn;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 _i={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function wi(e,n={}){let t={..._i,...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=[Mr()];if(Nr(s,{FunctionDeclaration(i,a,c){let l=Mr();o.push(l);for(let d of i.params)Si(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})}}),_t(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&&_t(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&&_t(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 Mr(){return{declarations:new Map}}function Si(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{bi as Schema,ce as TJS_VERSION,di as ajs,er as assertFunction,we as checkType,yi as createAgent,Os as emitRuntimeWrapper,ae as error,tr as expectFunction,ie as extractLiteralValue,qe as extractTDoc,Ct as extractTests,gi as getToolDefinitions,H as inferTypeFromValue,on as installRuntime,le as isError,wi as lint,ye as parse,fe as parseParameter,Kn as parseReturnType,st as preprocess,be as runtime,bs as testUtils,hi as tjs,At as transformFunction,bt as transpile,gt as transpileToJS,Ce as typeOf,vt as typeToString,rn as validateArgs,sn as wrap};
|
|
351
|
+
`)}`)}}if(r==="only")return{code:"",types:h,metadata:h,testResults:Ie,testCount:Ie?.length};let Et;if($.wasmBlocks.length>0){Et=[];let A=vr($.wasmBlocks);A.code&&(b=A.code+`
|
|
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};
|
|
349
353
|
//# sourceMappingURL=tjs-lang.js.map
|