tjs-lang 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,349 @@
1
+ var qr=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var cr=qr((Zi,Ts)=>{Ts.exports={name:"tjs-lang",version:"0.7.5",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 Zn 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
+ `),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 tt(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],m=e[r+1];switch(i){case"single-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}u==="'"&&(i="normal"),r++;continue;case"double-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}u==='"'&&(i="normal"),r++;continue;case"template-string":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}if(u==="$"&&m==="{"){t+=m,r+=2,a.push(1),i="normal";continue}u==="`"&&(i="normal"),r++;continue;case"line-comment":t+=u,u===`
4
+ `&&(i="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&m==="/"){t+=m,r+=2,i="normal";continue}r++;continue;case"regex":if(t+=u,u==="\\"&&r+1<e.length){t+=m,r+=2;continue}if(u==="["){for(r++;r<e.length&&e[r]!=="]";)t+=e[r],e[r]==="\\"&&r+1<e.length?(t+=e[r+1],r+=2):r++;r<e.length&&(t+=e[r],r++);continue}if(u==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)t+=e[r],r++;i="normal";continue}r++;continue;case"normal":if(a.length>0){if(u==="{")a[a.length-1]++;else if(u==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),t+=u,r++,i="template-string";continue}}if(u==="'"){t+=u,r++,i="single-string";continue}if(u==='"'){t+=u,r++,i="double-string";continue}if(u==="`"){t+=u,r++,i="template-string";continue}if(u==="/"&&m==="/"){t+=u+m,r+=2,i="line-comment";continue}if(u==="/"&&m==="*"){t+=u+m,r+=2,i="block-comment";continue}if(u==="/"){let g=t.trimEnd();if(!g[g.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(g)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(g)){t+=u,r++,i="regex";continue}}break}if(u==="{"){l++,t+=u,r++;continue}if(u==="}"){l--;let g=c[c.length-1];g&&l===g.braceDepth&&c.pop(),t+=u,r++;continue}let y=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(y){let g=y[0].slice(0,-1);t+=g,r+=g.length,c.push({type:"class-body",braceDepth:l});continue}let b=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(b){let g=b[1],x=b[0].length,$=e[r+x],h=null,E=r+x;($==="?"||$==="!")&&(h=$,E++,h==="!"?n.unsafeFunctions.add(g):n.safeFunctions.add(g)),t+=`function ${g}(`,r=E;let k=Qe(e,r,"(",")");if(!k){t+=e[r],r++;continue}let{content:v,endPos:R}=k;r=R;let C=kt(v,n,!0);t+=C+")";let N=r;for(;N<e.length&&/\s/.test(e[N]);)N++;if(e[N]===":"){let j=e.slice(N,N+2),M;for(j===":?"||j===":!"?(N+=2,M=j===":?"?"safe":"unsafe"):N+=1;N<e.length&&/\s/.test(e[N]);)N++;let P=Tt(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 g=t.length-1;g>=0;g--)if(!/\s/.test(t[g]))return t[g];return`
5
+ `})(),S=w!=="="&&w!==","&&w!=="("&&w!=="["&&w!==">";if(_&&f()&&!S){let g=_[1].length;t+=e.slice(r,r+g),r+=g;continue}if(_&&f()&&S){let g=_[1],x=_[0].length,$=r+x;t+=g+"(",r=$;let h=Qe(e,r,"(",")");if(!h){t+=e[r],r++;continue}let{content:E,endPos:k}=h;r=k;let v=kt(E,n,!0);t+=v+")";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=Tt(e,R);N&&(r=N.endPos)}continue}if(e[r]==="("){let g=Qe(e,r+1,"(",")");if(!g){t+=e[r],r++;continue}let x=g.content,$=g.endPos,h=$;for(;h<e.length&&/\s/.test(e[h]);)h++;let E;if(e[h]===":"){let k=e.slice(h,h+2);for(k===":?"||k===":!"?h+=2:h++;h<e.length&&/\s/.test(e[h]);)h++;let v=Tt(e,h);if(v)for(E=v.type,h=v.endPos;h<e.length&&/\s/.test(e[h]);)h++}if(e.slice(h,h+2)==="=>"){let k=null,v=x,R=x.trimStart();R.startsWith("?")&&(R.length===1||/\s/.test(R[1]))?(k="?",v=R.slice(1)):R.startsWith("!")&&(R.length===1||/\s/.test(R[1]))&&(k="!",v=R.slice(1));let C=kt(v,n,!1);for(t+=`(${k==="?"?"/* safe */ ":k==="!"?"/* unsafe */ ":""}${C})`,r=$;r<h&&/\s/.test(e[r]);)t+=e[r],r++;E&&(r=h)}else{let k=tt(x,n);t+=`(${k.source})`,r=$}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:o}}function Qe(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=Qe(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 Tt(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 nt(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 kt(e,n,t){let r=tt(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=nt(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 m=d.slice(1,-1);return`{ ${bn(m,n)} }`}if(t&&d.startsWith("[")&&d.endsWith("]")){let m=d.slice(1,-1);return`[ ${bn(m,n)} ]`}if(d.startsWith("...")){let m=xn(d);return m!==-1?d.slice(0,m).trim():l}let f=d.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(f){let[,m,y]=f;return a(m),o=!0,`${m} = ${y}`}if(!Ur(d)){let m=d.match(/^(\w+)\s*=/);return m&&a(m[1]),o=!0,l}let u=xn(d);if(u!==-1){let m=d.slice(0,u).trim(),y=d.slice(u+1).trim();return a(m),o&&t&&/^\w+$/.test(m),t&&/^\w+$/.test(m)&&n.requiredParams.add(m),`${m} = ${y}`}return l}).join(",")}function bn(e,n){return nt(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=Xe(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=et(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 Xe(e){let n=e.slice(1,-1).trim();return`{ ${nt(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}: ${Xe(u)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,f,u]=a;return`${f}: ${Xe(u)}`}let c=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(c){let[,f,u]=c;return`${f}: ${et(u)}`}let l=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(l){let[,f,u]=l;return`${f}: ${et(u)}`}let d=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(d){let[,f,u]=d;return`${f}: ${u}`}return s}).join(", ")} }`}function et(e){let n=e.slice(1,-1).trim();return`[ ${nt(n).map(s=>{let o=s.trim();return o?o.startsWith("{")&&o.endsWith("}")?Xe(o):o.startsWith("[")&&o.endsWith("]")?et(o):s:s}).join(", ")} ]`}function Ur(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 xn(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 Wr(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 Tn(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 kn(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 h=e[l];h==="{"?c++:h==="}"&&c--,l++}if(c!==0){t+=e[r],r++;continue}let d=e.slice(a,l-1),f,u=l,m=e.slice(l).match(/^\s*fallback\s*\{/);if(m){let h=l+m[0].length;c=1;let E=h;for(;E<e.length&&c>0;){let k=e[E];k==="{"?c++:k==="}"&&c--,E++}c===0&&(f=e.slice(h,E-1),u=E)}let b=Lr(d).map(h=>{let E=Vr(e,i,h);return E?`${h}: ${E}`:h}),_={id:`__tjs_wasm_${s}`,body:d,fallback:f,captures:b,start:i,end:u};n.push(_);let w=f??d,S=b.map(h=>h.split(":")[0].trim()),g=S.length>0?S.join(", "):"",x=S.length>0?`globalThis.${_.id}(${g})`:`globalThis.${_.id}()`,$=`(globalThis.${_.id} ? ${x} : (() => {${w}})())`;t+=$,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function Jr(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function Lr(e){let n=e.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),t=new Set,r=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,s;for(;(s=r.exec(n))!==null;)t.add(s[1]);let o=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,i=new Set;for(;(s=o.exec(n))!==null;)i.add(s[1]);for(let u of t){if(!i.has(u))continue;let m=new RegExp(`(?<!\\.)\\b${u}\\b`,"g"),y=new RegExp(`\\.${u}\\b`,"g"),b=n.match(m)?.length||0,_=n.match(y)?.length||0;b<=_&&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 Vr(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?wn(a[1],t):void 0}return wn(o[1],t)}function wn(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 jn(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 vn(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 m=c.match(/^(\s*)/),y=m?m[1]:"",b=c.slice(y.length);o.push(y+";"+b);continue}}o.push(c)}return o.join(`
8
+ `)}function An(e){e=e.replace(/\btypeof\s+([a-zA-Z_$][\w$.]*(?:\?\.[\w$]+)*)/g,"TypeOf($1)");let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
9
+ `&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let c=t-1;for(;c>=0&&/\s/.test(e[c]);)c--;let l=c>=0?e[c]:"";if(!l||/[=(!,;:{[&|?+\-*%<>~^]/.test(l)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){t++,r="regex";continue}}if(i==="="&&a==="="&&e[t+2]!=="="&&e[t-1]!=="!"){n.push({pos:t,op:"=="}),t+=2;continue}if(i==="!"&&a==="="&&e[t+2]!=="="){n.push({pos:t,op:"!="}),t+=2;continue}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let{pos:a,op:c}=n[i],l=c==="=="?"Eq":"NotEq",d=zr(o,a),f=Zr(o,a+2),u=o.slice(d,a).trim(),m=o.slice(a+2,f).trim();if(u&&m){let y=o.slice(0,d),b=o.slice(f),w=/[a-zA-Z0-9_$]$/.test(y)?" ":"";o=`${y}${w}${l}(${u}, ${m})${b}`}}return o}function zr(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 Zr(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 Rn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(r){let s=r[1],o=t+r[0].length,i=s,a=!1,c=e.slice(o).match(/^(['"`])([^]*?)\1\s*/);if(c){let u=o+c[0].length,m=e[u],y=m===void 0||u>=e.length||m!=="="&&m!=="{";if(m==="="||m==="{")i=c[2],a=!0,o=u;else if(y){let b=c[0].trim(),_=c[0].slice(b.length);n+=`const ${s} = Type('${s}', ${b})${_}`,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 m=e.slice(o).match(/^\s*/);m&&(o+=m[0].length)}}if(e[o]==="{"){let u=o+1,m=1,y=u;for(;y<e.length&&m>0;){let $=e[y];$==="{"?m++:$==="}"&&m--,y++}if(m!==0){n+=e[t],t++;continue}let b=e.slice(u,y-1).trim(),_=y,w=b.match(/description\s*:\s*(['"`])([^]*?)\1/);w&&!a&&(i=w[2]);let S,g=b.match(/example\s*:\s*/);if(g){let $=g.index+g[0].length,h=_n(b,$);h&&(S=h.value.trim())}let x=b.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(x&&S){let $=x[1].trim(),h=x[2].trim(),E=l?`, ${l}`:"";n+=`const ${s} = Type('${i}', (${$}) => { if (!globalThis.__tjs?.validate(${$}, globalThis.__tjs?.infer(${S}))) return false; ${h} }, ${S}${E})`}else if(x){let $=x[1].trim(),h=x[2].trim(),E=l?`, undefined, ${l}`:"";n+=`const ${s} = Type('${i}', (${$}) => { ${h} }${E})`}else if(S){let $=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 m=u[0];n+=`const ${s} = Type('${s}', ${m})`,t=o+u[0].length;continue}}}n+=e[t],t++}return n}function Cn(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=Wr(l,/params\s*:\s*\{/),f=l.match(/returns\s*:\s*(.+?)(?:\n|$)/),u=l.match(/returnContract\s*:\s*['"](\w+)['"]/),m=l.match(/description\s*:\s*(['"])([^]*?)\1/),y=[];d&&y.push(`params: ${d[1]}`),f&&y.push(`returns: ${f[1].trim()}`),u&&y.push(`returnContract: '${u[1]}'`);let b=m?m[2]:s;if(o){let _=o.split(",").map(S=>{let g=S.trim().split("=").map(x=>x.trim());if(g.length===2){let x=g[1]==="any"||g[1]==="undefined"?"null":g[1];return`['${g[0]}', ${x}]`}return`'${g[0]}'`}),w=o.split(",").map(S=>S.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${b}', [${_.join(", ")}], (${w.join(", ")}) => ({ ${y.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${b}', { ${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 Nn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(r){let s=r[1],o=r[2],a=t+r[0].length-1+1,c=1,l=a;for(;l<e.length&&c>0;){let S=e[l];S==="{"?c++:S==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let d=e.slice(a,l-1).trim(),f=l,u=o.split(",").map(S=>{let g=S.trim().split("=").map(x=>x.trim());if(g.length===2){let x=g[1]==="any"||g[1]==="undefined"?"null":g[1];return`['${g[0]}', ${x}]`}return`'${g[0]}'`}),m=d,y=m.search(/\bdeclaration\s*\{/);if(y!==-1){let S=m.indexOf("{",y),g=1,x=S+1;for(;x<m.length&&g>0;)m[x]==="{"?g++:m[x]==="}"&&g--,x++;m=m.slice(0,y)+m.slice(x)}let b=m.match(/description\s*:\s*(['"`])([^]*?)\1/),_=m.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),w=b?b[2]:s;if(_){let S=_[1].trim().split(",").map(E=>E.trim()),g=_[2].trim(),x=S[0]||"x",$=S.slice(1),h=$.map(E=>`check${E}`);$.forEach((E,k)=>{g=g.replace(new RegExp(`\\b${E}\\s*\\(`,"g"),`${h[k]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${x}, ${h.join(", ")}) => { ${g} }, '${w}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${w}')`;t=f;continue}n+=e[t],t++}return n}function Mn(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(r){let s=r[1],o=r[3],i=t+r[0].length;if(e[i]==="{"){let a=i+1,c=1,l=a;for(;l<e.length&&c>0;){let m=e[l];m==="{"?c++:m==="}"&&c--,l++}if(c!==0){n+=e[t],t++;continue}let d=e.slice(a,l-1).trim(),f=l,u=Sn(d);n+=`const ${s} = Union('${o}', [${u.join(", ")}])`,t=f;continue}else{let a=e.indexOf(`
10
+ `,i);a===-1&&(a=e.length);let c=e.slice(i,a).trim();if(c){let l=Sn(c);n+=`const ${s} = Union('${o}', [${l.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function Sn(e){let n=[],t=e.split("|").map(r=>r.trim());for(let r of t)r&&n.push(r);return n}function Pn(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,m=Gr(d).map(([y,b])=>`${y}: ${b}`).join(", ");n+=`const ${s} = Enum('${o}', { ${m} })`,t=f;continue}n+=e[t],t++}return n}function Gr(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 In(e){let n=new Map,t="",r=0;for(;r<e.length;){let s=e.slice(r),o=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/);if(!o){if(r===0||e[r-1]===`
11
+ `||e[r-1]===";"||e[r-1]==="}"){let g=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,m=e.slice(c+1,l-1);for(;u<m.length;){let g=m.slice(u).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!g){u++;continue}let x=g[1],$=!!g[2],h=g[3],E=u+g[0].length-1,k=1,v=E+1;for(;v<m.length&&k>0;)m[v]==="("&&k++,m[v]===")"&&k--,v++;let R=m.slice(E+1,v-1),C=v;for(;C<m.length&&/\s/.test(m[C]);)C++;if(m[C]==="="&&m[C+1]===">"){let L=Be(e,c+1+u);throw new Y(`Arrow functions are not allowed in extend blocks (method '${h}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,L)}if(m[C]!=="{"){u++;continue}let N=De(m,C),j=m.slice(u,N).trim(),M=R.split(",").map(L=>L.trim()).filter(L=>L.length>0).map(L=>{let K=L.match(/^(\w+)\s*:\s*(.+)$/);return K?`${K[1]} = ${K[2]}`:L}).join(", "),P=$?"async ":"",V=m.slice(C+1,N-1);f.push({name:h,isAsync:$,fullText:`${h}: ${P}function(${M}) {${V}}`}),u=N}let y=!n.has(a);y&&n.set(a,new Set);let b=n.get(a);for(let S of f)b.add(S.name);let _=f.map(S=>` ${S.fullText}`).join(`,
12
+ `),w;y?w=`${i}const __ext_${a} = {
13
+ ${_}
14
+ ${i}}
15
+ `:w=`${i}Object.assign(__ext_${a}, {
16
+ ${_}
17
+ ${i}})
18
+ `;for(let S of f)w+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${S.name}', __ext_${a}.${S.name}) }
19
+ `;t+=w,r=l}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function Fe(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),m=r.slice(0,d+1),y=r.slice(c+i.length);y[0]===")"?r=`${m}__ext_Array.${s}.call(${u})${y.slice(1)}`:r=`${m}__ext_Array.${s}.call(${u}, ${y}`}a=c+1}}for(let[s,o]of t){if(!o.includes("Number"))continue;let i=new RegExp(`(\\d+(?:\\.\\d+)?)\\.(${s})\\((\\))?`,"g");r=r.replace(i,(a,c,l,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]===`
20
+ `?(t++,r=0):r++;return{line:t,column:r}}function On(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 rt(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 jt(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=$n(s.trim(),n);l&&t.push(l),s="";continue}s+=c}let i=s.trim();if(i){let a=$n(i,n);a&&t.push(a)}return t}function $n(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===`
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 Bn(e,n){let t=new Set,r=/(?:^|(?<=[\n;{}]))\s*(export\s+)?(async\s+)?function\s+(\w+)\s*\(/gm,s=new Map,o,i=[];for(;(o=r.exec(e))!==null;){let f=!!o[1],u=!!o[2],m=o[3],y=o.index,b=y,w=o[0].indexOf("function");w>=0&&(b=y+w),i.push({name:m,fullMatchStart:y,funcKeywordStart:b,exported:f,isAsync:u})}for(let f of i)s.has(f.name)||s.set(f.name,[]);let a=new Map;for(let f of i)a.set(f.name,(a.get(f.name)||0)+1);let c=new Set;for(let[f,u]of a)u>1&&c.add(f);if(c.size===0)return{source:e,polymorphicNames:t};for(let f of i){if(!c.has(f.name))continue;let u=e.indexOf("(",f.funcKeywordStart);if(u===-1)continue;let m=1,y=u+1;for(;y<e.length&&m>0;)e[y]==="("&&m++,e[y]===")"&&m--,y++;let b=y-1,_=e.slice(u+1,b),w=y;for(;w<e.length&&e[w]!=="{";)w++;if(w>=e.length)continue;let S=De(e,w),g=f.fullMatchStart;for(;g>0&&e[g-1]===" ";)g--;let x=s.get(f.name),$=jt(_,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)}x.push({index:x.length+1,start:g,end:S,text:e.slice(g,S),exported:f.exported,isAsync:f.isAsync,params:$})}for(let[f,u]of s){if(u.length<2)continue;let m=u.filter(y=>y.isAsync).length;if(m>0&&m<u.length){let y=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 b=y+1;b<u.length;b++){let _=u[y],w=u[b];if(_.params.length!==w.params.length)continue;let S=!0;for(let g=0;g<_.params.length;g++){let x=_.params[g].defaultValue?rt(_.params[g].defaultValue):"any",$=w.params[g].defaultValue?rt(w.params[g].defaultValue):"any";if(x!==$){S=!1;break}}if(S){let g=Be(e,w.start);throw new Y(`Polymorphic function '${f}': variants ${y+1} and ${b+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,g)}}}let l=[];for(let[f,u]of s)if(!(u.length<2))for(let m of u)l.push({name:f,variant:m});l.sort((f,u)=>u.variant.start-f.variant.start);let d=e;for(let{name:f,variant:u}of l){let m=u.isAsync?"async ":"",y=u.text.replace(new RegExp(`(?:export\\s+)?${m?m.replace(/\s+$/,"\\s+"):""}function\\s+${f}\\s*\\(`),`${m}function ${f}$$${u.index}(`);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 m=u[0].isAsync,y=u.some(x=>x.exported),b=m?"async ":"",_=y?"export ":"",w=[...u].sort((x,$)=>{if(x.params.length!==$.params.length)return 0;let h=0,E=0;for(let k of x.params){let v=k.defaultValue?rt(k.defaultValue):"any";v==="non-negative-integer"?h+=3:v==="integer"?h+=2:v!=="any"&&(h+=1)}for(let k of $.params){let v=k.defaultValue?rt(k.defaultValue):"any";v==="non-negative-integer"?E+=3:v==="integer"?E+=2:v!=="any"&&(E+=1)}return E-h}),S=[];for(let x of w){let $=[`__args.length === ${x.params.length}`],h=[];for(let E=0;E<x.params.length;E++){let k=x.params[E];if(h.push(`__args[${E}]`),k.defaultValue){let v=On(`__args[${E}]`,k.defaultValue);v!=="true"&&$.push(v)}}S.push(` if (${$.join(" && ")}) return ${f}$${x.index}(${h.join(", ")})`)}let g=`
22
+ ${_}${b}function ${f}(...__args) {
23
+ ${S.join(`
24
+ `)}
25
+ return __tjs.typeError('${f}', 'no matching overload', __args)
26
+ }
27
+ `;d+=g}return{source:d,polymorphicNames:t}}function Dn(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function Fn(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,m=f;for(;m<e.length&&u>0;){let y=e[m];y==="{"?u++:y==="}"&&u--,m++}if(u===0){let y=e.slice(f,m-1).trim(),b=m,_=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:l,body:y,start:a,end:b,line:_}),!n)try{new Function(y)()}catch(g){let x=l||`test at line ${_}`;r.push(`Test failed: ${x} (line ${_})
28
+ ${g.message||g}`)}let S=(e.slice(a,b).match(/\n/g)||[]).length;s+=`
29
+ `.repeat(S),o=b;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function qn(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],m=/\bconstructor\s*\(/g,y,b=[];for(;(y=m.exec(u))!==null;)b.push(y.index);if(b.length<2)continue;t.add(c);let _=[];for(let E=0;E<b.length;E++){let k=b[E],v=u.indexOf("(",k),R=1,C=v+1;for(;C<u.length&&R>0;)u[C]==="("&&R++,u[C]===")"&&R--,C++;let N=u.slice(v+1,C-1),j=C;for(;j<u.length&&u[j]!=="{";)j++;let M=De(u,j),P=u.slice(j+1,M-1);_.push({index:E+1,paramStr:N,bodyText:P,fullStart:k,fullEnd:M})}let w=u.slice(0,_[0].fullEnd),S=_[_.length-1].fullEnd;w+=u.slice(S);let g=u;for(let E=_.length-1;E>=1;E--){let k=_[E],v=k.fullStart;for(;v>0&&g[v-1]===" ";)v--;v>0&&g[v-1]===`
30
+ `&&v--,g=g.slice(0,v)+g.slice(k.fullEnd)}let x="";for(let E=1;E<_.length;E++){let k=_[E],v=jt(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)}x+=`
31
+ function ${c}$ctor$${k.index}(${k.paramStr}) {`,x+=`
32
+ const __obj = Object.create(${c}.prototype)`,x+=`
33
+ ;(function() {${k.bodyText}}).call(__obj)`,x+=`
34
+ return __obj`,x+=`
35
+ }
36
+ `}let $=[];for(let E=0;E<_.length;E++){let k=_[E],v=jt(k.paramStr,n),R=[`a.length === ${v.length}`];for(let C=0;C<v.length;C++){let N=v[C];if(N.defaultValue){let j=On(`a[${C}]`,N.defaultValue);j!=="true"&&R.push(j)}}if(E===0)$.push(` if (${R.join(" && ")}) return Reflect.construct(t, a)`);else{let C=v.map((N,j)=>`a[${j}]`).join(", ");$.push(` if (${R.join(" && ")}) return ${c}$ctor$${k.index}(${C})`)}}x+=`
37
+ function ${c}$dispatch(t, a) {
38
+ `,x+=$.join(`
39
+ `)+`
40
+ `,x+=` return __tjs.typeError('${c}', 'no matching constructor', a)
41
+ `,x+=`}
42
+ `,i=i.slice(0,d)+g+i.slice(f);let h=d+g.length;i=i.slice(0,h)+x+i.slice(h)}return{source:i,polyCtorClasses:t}}function Un(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,m=e.slice(l,u);r+=e.slice(s,c),r+=`let ${i} = class ${i}${a} ${m}; `,n.has(i)?r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return ${i}$dispatch(t, a) }, construct(t, a) { return ${i}$dispatch(t, a) } });`:r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,s=u}}return r+=e.slice(s),r}function Wn(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 Ln(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 Vn(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=Kr(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===`
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 Kr(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=En(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=En(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 En(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 st(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 $=u[2];$==="TjsStrict"?(l.tjsEquals=!0,l.tjsClass=!0,l.tjsDate=!0,l.tjsNoeval=!0,l.tjsNoVar=!0,l.tjsStandard=!0):$==="TjsCompat"?(l.tjsEquals=!1,l.tjsClass=!1,l.tjsDate=!1,l.tjsNoeval=!1,l.tjsNoVar=!1,l.tjsStandard=!1,l.tjsSafeEval=!1):$==="TjsEquals"?l.tjsEquals=!0:$==="TjsClass"?l.tjsClass=!0:$==="TjsDate"?l.tjsDate=!0:$==="TjsNoeval"?l.tjsNoeval=!0:$==="TjsNoVar"?l.tjsNoVar=!0:$==="TjsStandard"?l.tjsStandard=!0:$==="TjsSafeEval"&&(l.tjsSafeEval=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${$}\\s*`),"$1")}l.tjsStandard&&(e=vn(e)),e=Jn(e),e=zn(e),e=jn(e),l.tjsEquals&&!n.vmTarget&&(e=An(e)),e=Rn(e),e=Nn(e),e=Cn(e),e=Mn(e),e=Pn(e),e=Dn(e);let{source:m,returnType:y,returnSafety:b}=tt(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=m;let _=In(e);e=_.source,e=Tn(e);let w=Bn(e,s);e=w.source;let S=kn(e);e=S.source;let g=Fn(e,n.dangerouslySkipTests);e=g.source;let x=qn(e,s);e=x.source;for(let $ of x.polyCtorClasses)o.add(`${$}$dispatch`);return l.tjsClass&&(e=Un(e,x.polyCtorClasses)),l.tjsDate&&(e=Wn(e)),l.tjsNoeval&&(e=Vn(e)),l.tjsNoVar&&(e=Ln(e)),e=Fe(e,_.extensions),{source:e,returnType:y,returnSafety:b,moduleSafety:r,tjsModes:l,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:S.blocks,tests:g.tests,testErrors:g.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:m,tests:y,testErrors:b}=r?st(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:Zn.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:m,tests:y,testErrors:b}}catch(_){let w=_.loc||{line:1,column:0};throw new Y(_.message.replace(/\s*\(\d+:\d+\)$/,""),w,l,t)}}function Gn(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 qe(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],m=u.split(`
44
+ `),y=m.filter(b=>b.trim().length>0).reduce((b,_)=>{let w=_.match(/^(\s*)/)?.[1].length||0;return Math.min(b,w)},1/0);return y>0&&y<1/0&&(u=m.map(b=>b.slice(y)).join(`
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,`
47
+
48
+ `).trim();let f=hs(n,t);return{code:i,tests:n,mocks:t,testRunner:f}}function Xn(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 Rt(e,n){return e.slice(0,n).split(`
49
+ `).length}function hs(e,n){if(e.length===0)return"// No tests defined";let t=n.map(s=>s.body).join(`
50
+ `);return`(async () => {
51
+ const __results = []
52
+
53
+ ${e.map((s,o)=>`
54
+ // Test ${o+1}: ${s.description}
55
+ try {
56
+ ${t}
57
+ await (async () => {
58
+ ${s.body}
59
+ })()
60
+ __results.push({ description: ${JSON.stringify(s.description)}, passed: true })
61
+ } catch (__e) {
62
+ __results.push({ description: ${JSON.stringify(s.description)}, passed: false, error: __e.message })
63
+ }`).join(`
64
+ `)}
65
+
66
+ // Compute summary (no console output - caller handles reporting)
67
+ const __passed = __results.filter(r => r.passed).length
68
+ const __failed = __results.filter(r => !r.passed).length
69
+
70
+ // Return summary
71
+ return { passed: __passed, failed: __failed, results: __results }
72
+ })()`.trim()}var er=`
73
+ function assert(condition, message) {
74
+ if (!condition) {
75
+ throw new Error(message || 'Assertion failed')
76
+ }
77
+ }
78
+ `,tr=`
79
+ function expect(actual) {
80
+ const deepEqual = (a, b) => {
81
+ if (a === b) return true
82
+ if (a === null || b === null) return a === b
83
+ if (a === undefined || b === undefined) return a === undefined && b === undefined
84
+ if (typeof a !== typeof b) return false
85
+ if (typeof a !== 'object') return a === b
86
+ if (Array.isArray(a) !== Array.isArray(b)) return false
87
+ if (Array.isArray(a)) {
88
+ if (a.length !== b.length) return false
89
+ return a.every((v, i) => deepEqual(v, b[i]))
90
+ }
91
+ const keysA = Object.keys(a)
92
+ const keysB = Object.keys(b)
93
+ if (keysA.length !== keysB.length) return false
94
+ return keysA.every(k => deepEqual(a[k], b[k]))
95
+ }
96
+
97
+ const format = (v) => {
98
+ if (v === null) return 'null'
99
+ if (v === undefined) return 'undefined'
100
+ if (typeof v === 'string') return JSON.stringify(v)
101
+ if (typeof v === 'object') return JSON.stringify(v)
102
+ return String(v)
103
+ }
104
+
105
+ return {
106
+ toBe(expected) {
107
+ if (!deepEqual(actual, expected)) {
108
+ throw new Error(\`Expected \${format(expected)} but got \${format(actual)}\`)
109
+ }
110
+ },
111
+ toEqual(expected) {
112
+ if (!deepEqual(actual, expected)) {
113
+ throw new Error(\`Expected \${format(expected)} but got \${format(actual)}\`)
114
+ }
115
+ },
116
+ toContain(item) {
117
+ if (!Array.isArray(actual) || !actual.some(v => deepEqual(v, item))) {
118
+ throw new Error(\`Expected \${format(actual)} to contain \${format(item)}\`)
119
+ }
120
+ },
121
+ toThrow(message) {
122
+ let threw = false
123
+ let thrownMessage = ''
124
+ try {
125
+ if (typeof actual === 'function') actual()
126
+ } catch (e) {
127
+ threw = true
128
+ thrownMessage = e.message || String(e)
129
+ }
130
+ if (!threw) {
131
+ throw new Error('Expected function to throw but it did not')
132
+ }
133
+ if (message && !thrownMessage.includes(message)) {
134
+ throw new Error(\`Expected error containing "\${message}" but got "\${thrownMessage}"\`)
135
+ }
136
+ },
137
+ toBeTruthy() {
138
+ if (!actual) {
139
+ throw new Error(\`Expected \${format(actual)} to be truthy\`)
140
+ }
141
+ },
142
+ toBeFalsy() {
143
+ if (actual) {
144
+ throw new Error(\`Expected \${format(actual)} to be falsy\`)
145
+ }
146
+ },
147
+ toBeNull() {
148
+ if (actual !== null) {
149
+ throw new Error(\`Expected null but got \${format(actual)}\`)
150
+ }
151
+ },
152
+ toBeUndefined() {
153
+ if (actual !== undefined) {
154
+ throw new Error(\`Expected undefined but got \${format(actual)}\`)
155
+ }
156
+ },
157
+ toBeGreaterThan(n) {
158
+ if (!(actual > n)) {
159
+ throw new Error(\`Expected \${format(actual)} to be greater than \${n}\`)
160
+ }
161
+ },
162
+ toBeLessThan(n) {
163
+ if (!(actual < n)) {
164
+ throw new Error(\`Expected \${format(actual)} to be less than \${n}\`)
165
+ }
166
+ }
167
+ }
168
+ }
169
+ `,bs=er+`
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`
171
+ // TJS runtime wrapper (skips unsafe functions)
172
+ if (typeof ${e}.__tjs === 'object' && !${e}.__tjs.unsafe && typeof globalThis.__tjs?.wrap === 'function') {
173
+ ${e} = globalThis.__tjs.wrap(${e}, ${e}.__tjs)
174
+ }
175
+ `.trim()}function Bs(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 cn(e,n){if(e===n||typeof e=="number"&&typeof n=="number"&&Number.isNaN(e)&&Number.isNaN(n)||Bs(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)=>cn(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=>cn(e[s],n[s]))}function ln(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=ln(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=ln(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 ze(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=>ze(t,n)).join(", ")}]`:`[${e.slice(0,3).map(t=>ze(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)}: ${ze(d,n)}`).join(", ")}}`;let s=" ".repeat(n+1),o=" ".repeat(n),i=t.slice(0,8).map(([c,l])=>`${s}${r(c)}: ${ze(l,n+1)}`).join(`,
176
+ `),a=t.length>8?`,
177
+ ${s}...`:"";return`{
178
+ ${i}${a}
179
+ ${o}}`}return String(e)}function Ds(e){let n=e.replace(/\/\*[\s\S]*?\*\//g,t=>{let r=t.split(`
180
+ `).length-1;return`
181
+ `.repeat(r)});return n=n.replace(/\/\/[^\n]*/g,""),n}function wr(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 Fs(e){if(Object.keys(e).length===0)return"";let n=[];for(let[t,r]of Object.entries(e)){let s=wr(r);n.push(`// Resolved import: ${t}`),n.push(s)}return n.join(`
182
+ `)}function _r(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 m=t[d];if(m==="{"||m==="["||m==="(")u++;else if(m==="}"||m==="]"||m===")"){if(u===0)break;u--}else if(m===","&&u===0)break;f+=m,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 Sr(e){let n=[],t=Ds(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(`
183
+ `).length;if(d===":!")continue;let u=t.slice(s.index+s[0].length),m=mt(u);if(!m)continue;let y=an(l);if(!(l.trim()&&y.length===0))try{let b=_r(m);if(!b)continue;let _=y.map(w=>new Function(`return ${w}`)());n.push({funcName:c,args:_,expected:b.pattern,defaults:Object.keys(b.defaults).length>0?b.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 g=c;g<t.length;g++)if(t[g]==="{")l++;else if(t[g]==="}"&&(l--,l===0)){d=g;break}let f=t.slice(c,d),m=/constructor\s*\(([^)]*)\)/.exec(f);if(!m)continue;let y=m[1],b=an(y);if(y.trim()&&b.length===0)continue;let _;try{_=b.map(g=>new Function(`return ${g}`)())}catch{continue}let w=/(async\s+)?(\w+)\s*\(([^)]*)\)\s*(:[?!]?)\s*/g,S;for(;(S=w.exec(f))!==null;){let g=S[2];if(g==="constructor")continue;let x=!!S[1],$=S[3];if(S[4]===":!")continue;let E=c+S.index,k=t.slice(0,E).split(`
184
+ `).length,v=f.slice(S.index+S[0].length),R=mt(v);if(!R)continue;let C=an($);if(!($.trim()&&C.length===0))try{let N=_r(R);if(!N)continue;let j=C.map(M=>new Function(`return ${M}`)());n.push({funcName:g,args:j,expected:N.pattern,defaults:Object.keys(N.defaults).length>0?N.defaults:void 0,line:k,isAsync:x,className:a,constructorArgs:_})}catch{}}}return n}function $r(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 x=g.match(/from\s+['"]([^'"]+)['"]/);return x&&!(x[1]in s)}),l=wr(r),d=Fs(s),f=n.map(g=>g.body).join(`
185
+ `),u=e.map((g,x)=>{let $=o.size>0?Fe(g.body,o):g.body;return`
186
+ // Test ${x}: ${g.description}
187
+ try {
188
+ ${$}
189
+ __testResults.push({ idx: ${x}, passed: true });
190
+ } catch (e) {
191
+ __testResults.push({ idx: ${x}, passed: false, error: e.message || String(e) });
192
+ }
193
+ `}).join(`
194
+ `),m=t.filter(g=>!g.isAsync),y=t.filter(g=>g.isAsync),b=m.map((g,x)=>{let $=g.className?`${g.className}.${g.funcName}`:g.funcName,h=g.className?`new ${g.className}(${(g.constructorArgs||[]).map(E=>JSON.stringify(E)).join(", ")}).${g.funcName}(${g.args.map(E=>JSON.stringify(E)).join(", ")})`:`${g.funcName}(${g.args.map(E=>JSON.stringify(E)).join(", ")})`;return`
195
+ // Signature test ${x}: ${$}
196
+ try {
197
+ let __actual = ${h};
198
+ const __expected = ${JSON.stringify(g.expected)};${g.defaults?`
199
+ const __defaults = ${JSON.stringify(g.defaults)};
200
+ if (typeof __actual === 'object' && __actual !== null) __actual = Object.assign({}, __defaults, __actual);`:""}
201
+ if (__deepEqual(__actual, __expected)) {
202
+ __sigTestResults.push({ idx: ${x}, passed: true });
203
+ } else {
204
+ __sigTestResults.push({ idx: ${x}, passed: false, error: 'Expected ' + __format(__expected) + ' at \\'${$}\\', got ' + __format(__actual) });
205
+ }
206
+ } catch (e) {
207
+ __sigTestResults.push({ idx: ${x}, passed: false, error: e.message || String(e) });
208
+ }
209
+ `}).join(`
210
+ `);on();let S=`
211
+
212
+ const __saved_tjs = globalThis.__tjs;
213
+
214
+ const __testResults = [];
215
+ const __sigTestResults = [];
216
+ try {
217
+ // Test assertions
218
+ function assert(condition, message) {
219
+ if (!condition) throw new Error(message || 'Assertion failed')
220
+ }
221
+
222
+ function expect(actual) {
223
+ return {
224
+ toBe(expected) {
225
+ if (!__deepEqual(actual, expected)) {
226
+ throw new Error('Expected ' + __format(expected) + ' but got ' + __format(actual))
227
+ }
228
+ },
229
+ toEqual(expected) {
230
+ if (!__deepEqual(actual, expected)) {
231
+ throw new Error('Expected ' + __format(expected) + ' but got ' + __format(actual))
232
+ }
233
+ },
234
+ toContain(item) {
235
+ if (!Array.isArray(actual) || !actual.some(function(v) { return __deepEqual(v, item) })) {
236
+ throw new Error('Expected ' + __format(actual) + ' to contain ' + __format(item))
237
+ }
238
+ },
239
+ toBeTruthy() {
240
+ if (!actual) {
241
+ throw new Error('Expected ' + __format(actual) + ' to be truthy')
242
+ }
243
+ },
244
+ toBeFalsy() {
245
+ if (actual) {
246
+ throw new Error('Expected ' + __format(actual) + ' to be falsy')
247
+ }
248
+ },
249
+ toBeNull() {
250
+ if (actual !== null) {
251
+ throw new Error('Expected null but got ' + __format(actual))
252
+ }
253
+ },
254
+ toBeUndefined() {
255
+ if (actual !== undefined) {
256
+ throw new Error('Expected undefined but got ' + __format(actual))
257
+ }
258
+ },
259
+ toBeGreaterThan(n) {
260
+ if (!(actual > n)) {
261
+ throw new Error('Expected ' + __format(actual) + ' to be greater than ' + n)
262
+ }
263
+ },
264
+ toBeLessThan(n) {
265
+ if (!(actual < n)) {
266
+ throw new Error('Expected ' + __format(actual) + ' to be less than ' + n)
267
+ }
268
+ },
269
+ toBeNaN() {
270
+ if (typeof actual !== 'number' || !Number.isNaN(actual)) {
271
+ throw new Error('Expected NaN but got ' + __format(actual))
272
+ }
273
+ }
274
+ }
275
+ }
276
+
277
+ // Inject resolved imports first (they may be dependencies)
278
+ ${d}
279
+
280
+ // Execute the module code ONCE
281
+ ${l}
282
+ ${f}
283
+
284
+ // Run explicit test blocks
285
+ ${u}
286
+
287
+ // Run signature tests
288
+ ${b}
289
+
290
+ } finally {
291
+ globalThis.__tjs = __saved_tjs;
292
+ }
293
+ return { testResults: __testResults, sigTestResults: __sigTestResults };
294
+ `;try{let g=new Function("__deepEqual","__format","__typeMatches",S),{testResults:x,sigTestResults:$}=g(cn,ze,ln);for(let h of x){let E=e[h.idx],k=c&&!h.passed&&h.error&&/is not defined$/.test(h.error);i.push({description:E.description,passed:k?!0:h.passed,error:k?void 0:h.error,line:E.line})}for(let h of $){let E=m[h.idx],k=c&&!h.passed&&h.error&&/is not defined$/.test(h.error),v=E.className?`${E.className}.${E.funcName}`:E.funcName;i.push({description:`${v} signature example`,passed:k?!0:h.passed,error:k?void 0:h.error,isSignatureTest:!0,line:E.line})}}catch(g){let x=c&&g instanceof ReferenceError;for(let $ of e)i.push({description:$.description,passed:x,error:x?void 0:`Module execution failed: ${g.message}`,line:$.line});for(let $ of m){let h=$.className?`${$.className}.${$.funcName}`:$.funcName;i.push({description:`${h} signature example`,passed:x,error:x?void 0:`Module execution failed: ${g.message}`,isSignatureTest:!0,line:$.line})}}for(let g of y){let x=g.className?`${g.className}.${g.funcName}`:g.funcName;i.push({description:`${x} signature example`,passed:!0,isSignatureTest:!0,line:g.line})}return i}function mt(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 an(e){if(!e.trim())return[];let n=[],t=qs(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 qs(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 Tr from"acorn";var se={i32:127,i64:126,f32:125,f64:124,v128:123,funcref:112,externref:111,void:64},Ze={custom:0,type:1,import:2,function:3,table:4,memory:5,global:6,export:7,start:8,element:9,code:10,data:11},p={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},Us=Object.fromEntries(Object.entries(p).map(([e,n])=>[n,e.replace(/_/g,".")])),Ke=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},Ws=Object.fromEntries(Object.entries(G).map(([e,n])=>[n,e.replace(/_/g,".")]));function un(e){return[Ke,...I(e)]}function Er(e,n,t){return[Ke,...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 Ye(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 pn(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 fn(e){let n=new TextEncoder().encode(e);return[...I(n.length),...n]}function Ge(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 Js(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 Ls(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=Us[l]||`unknown(0x${l.toString(16)})`;if(c++,l===p.local_get||l===p.local_set||l===p.local_tee){let[f,u]=pe(e,c);c+=u;let m=f<n.length?`$${n[f].name}`:`$L${f}`;r.push(`${o()}${d} ${m}`)}else if(l===p.br||l===p.br_if){let[f,u]=pe(e,c);c+=u,r.push(`${o()}${d} ${f}`)}else if(l===p.i32_const){let[f,u]=pe(e,c);c+=u,r.push(`${o()}i32.const ${f}`)}else if(l===p.f32_const){let f=new ArrayBuffer(4),u=new Uint8Array(f);for(let y=0;y<4;y++)u[y]=e[c+y];let m=new Float32Array(f)[0];c+=4,r.push(`${o()}f32.const ${m}`)}else if(l===p.f64_const){let f=Js(e,c);c+=8,r.push(`${o()}f64.const ${f}`)}else if(l===p.block||l===p.loop){let f=e[c];c++,r.push(`${o()}${d}${f===se.void?"":` (result ${f===se.f64?"f64":"i32"})`}`),s++}else if(l===p.if){let f=e[c];c++,r.push(`${o()}if${f===se.void?"":` (result ${f===se.f64?"f64":"i32"})`}`),s++}else if(l===p.else)s--,r.push(`${o()}else`),s++;else if(l===p.end)s=Math.max(1,s-1),r.push(`${o()}end`);else if(l===p.f64_load||l===p.f64_store||l===p.f32_load||l===p.f32_store||l===p.i32_load||l===p.i32_store){let[f,u]=pe(e,c);c+=u;let[m,y]=pe(e,c);c+=y,r.push(`${o()}${d}${m?` offset=${m}`:""}`)}else if(l===Ke){let[f,u]=pe(e,c);c+=u;let m=Ws[f]||`simd.unknown(0x${f.toString(16)})`;if(f===G.v128_load||f===G.v128_store){let[y,b]=pe(e,c);c+=b;let[_,w]=pe(e,c);c+=w,r.push(`${o()}${m}${_?` offset=${_}`:""}`)}else if(f===G.v128_const){let y=e.slice(c,c+16);c+=16,r.push(`${o()}v128.const ${y.map(b=>"0x"+b.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()}${m} ${y}`)}else r.push(`${o()}${m}`)}else r.push(`${o()}${d}`)}return r.push(")"),r.join(`
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(`
296
+ `).map(l=>` * ${l}`);return`/**
297
+ * WASM: ${a.id}
298
+ ${c.join(`
299
+ `)}
300
+ */`}).join(`
301
+ `),s=t.map(a=>`{id:${JSON.stringify(a.id)},b64:${JSON.stringify(a.base64)},c:${JSON.stringify(a.captures)},m:${a.needsMemory}}`).join(","),o=t.some(a=>a.needsMemory);return{code:`${r}
302
+ ;(async()=>{
303
+ const __wasmBlocks=[${s}];
304
+ const __b64ToBytes=s=>{const b=atob(s),a=new Uint8Array(b.length);for(let i=0;i<b.length;i++)a[i]=b.charCodeAt(i);return a};
305
+ const __parseType=c=>{const m=c.match(/^(\\w+)\\s*:\\s*(\\w+)$/);if(!m)return{n:c,t:'f64',a:false};const[,n,ts]=m;const at={Float32Array:'f32',Float64Array:'f64',Int32Array:'i32',Uint8Array:'i32'};if(at[ts])return{n,t:'i32',a:true,at:ts};return{n,t:'f64',a:false}};
306
+ ${o?`const __wasmMem=new WebAssembly.Memory({initial:1024});
307
+ let __woff=0;
308
+ globalThis.wasmBuffer=function(Ctor,len){const bytes=len*Ctor.BYTES_PER_ELEMENT;const align=Math.max(Ctor.BYTES_PER_ELEMENT,16);__woff=(__woff+align-1)&~(align-1);const arr=new Ctor(__wasmMem.buffer,__woff,len);__woff+=bytes;return arr};`:""}
309
+ for(const{id,b64,c,m}of __wasmBlocks){
310
+ const bytes=__b64ToBytes(b64);
311
+ const params=c.map(__parseType);
312
+ const hasArrays=params.some(p=>p.a);
313
+ const mem=m?__wasmMem:null;
314
+ const imp=mem?{env:{memory:mem}}:{};
315
+ const inst=await WebAssembly.instantiate(await WebAssembly.compile(bytes),imp);
316
+ const compute=inst.exports.compute;
317
+ if(!hasArrays){globalThis[id]=compute;continue}
318
+ globalThis[id]=function(...args){
319
+ const mv=new Uint8Array(mem.buffer);let off=__woff;const ptrs=[];
320
+ for(let i=0;i<params.length;i++){const p=params[i],a=args[i];
321
+ if(p.a&&a?.buffer){
322
+ if(a.buffer===mem.buffer){ptrs.push(a.byteOffset)}
323
+ else{const ab=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);off=(off+15)&~15;mv.set(ab,off);ptrs.push(off);off+=ab.length}
324
+ } else ptrs.push(a)}
325
+ const r=compute(...ptrs);off=__woff;
326
+ for(let i=0;i<params.length;i++){const p=params[i],a=args[i];
327
+ if(p.a&&a?.buffer){
328
+ if(a.buffer===mem.buffer) continue;
329
+ 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
+ return r};
331
+ }})();
332
+ `.trim(),results:n}}function ii(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 oi(e,n,t,r,s){let o=[],i=qe(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 m=e.params[0],y=m.type==="ObjectPattern"?m:m.left,b=fe(y,t);if(b.type.kind==="object"&&b.type.destructuredParams){l={},d=new Set;for(let[_,w]of Object.entries(b.type.destructuredParams))a[_]={...w,description:i.params[_]},l[_]=w.type,w.required&&d.add(_)}}else for(let m of e.params)if(m.type==="Identifier"){let y=fe(m,t);a[m.name]={...y,required:t.has(m.name),description:i.params[m.name]}}else if(m.type==="AssignmentPattern"&&m.left.type==="Identifier"){let y=fe(m,t),b=ii(s||"",e.id?.name||"",m.left.name);a[m.left.name]={...y,required:b,default:b?null:y.example??y.default,description:i.params[m.left.name]}}else if(m.type==="ObjectPattern"){let y=fe(m,t);if(y.type.kind==="object"&&y.type.destructuredParams)for(let[b,_]of Object.entries(y.type.destructuredParams))a[b]={..._,description:i.params[b]}}else if(m.type==="RestElement"&&m.argument?.type==="Identifier"){let y=m.argument.name,b=n.match(new RegExp(`\\.\\.\\.${y}\\s*:\\s*([^)]+?)\\s*\\)`));if(b)try{let _=vr(b[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 m=r.includes("=")?Ar(r):r,y=vr(m,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 ai(e,n,t){let r=[],s=t?`${t}:`:"",o=t?`${t}:${e}`:e;if(n.isDestructuredParam&&n.destructuredShape){let a=n.destructuredShape,c=n.destructuredRequired||new Set,l=Object.keys(a);if(l.length===0)return null;for(let d of l)r.push(`if (${d} instanceof Error) return ${d};`);for(let[d,f]of Object.entries(a)){let u=c.has(d),m=`${s}${e}.${d}`,y=mn(d,f);if(y){let b=f.kind;u?r.push(`if (${y}) return __tjs.typeError('${m}', '${b}', ${d});`):r.push(`if (${d} !== undefined && ${y}) return __tjs.typeError('${m}', '${b}', ${d});`)}}return r.length===0?null:(r.unshift(`__tjs.pushStack('${o}');`),{preamble:r.join(`
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=mn(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(`
334
+ `),suffix:"__tjs.popStack();"})}function Ar(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 ci(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 mt(s)}function li(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 ui(e){let n=e.match(/^\/\*\s*tjs\s*<-\s*([^*]+?)\s*\*\//);return n?n[1].trim():void 0}function fi(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 gt(e,n={}){let{filename:t="<source>",runTests:r=!0,debug:s=!1,resolvedImports:o={}}=n,i=[],c=ui(e)||t,{code:l,tests:d,mocks:f,testRunner:u}=Ct(e),{ast:m,originalSource:y,requiredParams:b,unsafeFunctions:_}=ye(l,{filename:t,colonShorthand:!0}),w=pi(m),S=st(l),g={},x=[],$=[];for(let A of w){let F=A.id?.name||"anonymous",O=ci(l,F),ne;if(O&&O.includes("="))try{let Q=O.matchAll(/(\w+)\s*=\s*/g),X=Ar(O),de=new Function(`return ${X}`)(),re={};for(let Fr of Q){let Et=Fr[1];Et in de&&(re[Et]=de[Et])}Object.keys(re).length>0&&(ne=re)}catch{}let{types:me,warnings:Pr}=oi(A,y,b,O,l);i.push(...Pr),g[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)$.push({start:Q.left.end,end:Q.right.end});else{let re=Q.right;re.type==="BinaryExpression"&&re.operator==="|"&&$.push({start:re.left.end,end:re.end})}}let gn=S.moduleSafety==="none"||_.has(F),Ir=S.safeFunctions.has(F),Or=li(l,F),Br=fi(e,F),ke={file:c,line:Br??A.loc?.start.line??0,column:A.loc?.start.column??0},Dr={unsafe:gn,safe:Ir,returnSafety:Or},hn=S.polymorphicNames.has(F),$t;if(hn){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}`),$t=`${F}.__tjs = ${JSON.stringify(X,null,2)}`}else $t=mi(F,me,Dr,{debug:s,source:ke,returnDefaults:ne});if(x.push({position:A.end,text:`
335
+ ${$t}`}),!gn&&!hn){let Q=`${ke.file}:${ke.line}`,X=ai(F,me,Q);X&&A.body&&A.body.start!==void 0&&(x.push({position:A.body.start+1,text:`
336
+ ${X.preamble}
337
+ `}),X.suffix&&x.push({position:A.body.end-1,text:`
338
+ ${X.suffix}
339
+ `}))}}$.sort((A,F)=>F.start-A.start);let h=S.source;for(let{start:A,end:F}of $)h=h.slice(0,A)+h.slice(F);for(let A of x){let F=0;for(let O of $)O.start<A.position&&(F+=O.end-O.start);A.position-=F}x.sort((A,F)=>F.position-A.position);for(let{position:A,text:F}of x)h=h.slice(0,A)+F+h.slice(A);let E=h.includes("__tjs.typeError("),k=h.includes("__tjs.pushStack("),v=h.includes("Is("),R=h.includes("IsNot("),C=h.includes("Eq("),N=h.includes("NotEq("),j=h.includes("TypeOf("),M=/\bType\(/.test(h),P=/\bGeneric\(/.test(h),V=/\bFunctionPredicate\(/.test(h),L=/\bEnum\(/.test(h),K=/\bUnion\(/.test(h),Te=h.includes("__tjs.bang("),wt=S.tjsModes.tjsSafeEval;if(E||k||v||R||C||N||j||M||P||V||L||K||Te||wt){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)}"),j&&A.push("function TypeOf(v){return v===null?'null':typeof v}"),v&&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}}"),L&&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
+ `)+`;
341
+ `:"",O=[];E&&O.push("typeError","isMonadicError"),k&&O.push("pushStack","popStack","getStack"),C&&O.push("Eq"),N&&O.push("NotEq"),j&&O.push("TypeOf"),v&&O.push("Is","tjsEquals"),R&&O.push("IsNot"),M&&O.push("Type"),P&&O.push("Generic"),V&&O.push("FunctionPredicate"),L&&O.push("Enum"),K&&O.push("Union"),Te&&(O.push("bang"),E||O.push("typeError","isMonadicError"));let ne=O.length>0?`{${O.join(",")}}`:"undefined";h=F+`const __tjs = globalThis.__tjs?.createRuntime?.() ?? ${ne};
342
+ `+h}wt&&(h=`import { Eval, SafeFunction } from 'tjs-lang';
343
+ `+h);let Ie;if(r){let A=Sr(e);Ie=$r(d,f,A,h,o,S.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
+ ${ne.error}`;let me=ne.line?` (line ${ne.line})`:"";return` Test '${ne.description}'${me} failed:
345
+ ${ne.error}`});throw new Error(`Transpile-time test failures:
346
+ ${O.join(`
347
+ `)}`)}}if(r==="only")return{code:"",types:g,metadata:g,testResults:Ie,testCount:Ie?.length};let St;if(S.wasmBlocks.length>0){St=[];let A=jr(S.wasmBlocks);A.code&&(h=A.code+`
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};
349
+ //# sourceMappingURL=tjs-lang.js.map