tjs-lang 0.6.43 → 0.6.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,51 +1,51 @@
1
- var h8=Object.defineProperty;var x8=(Z,$)=>()=>($||Z(($={exports:{}}).exports,$),$.exports);var u8=(Z)=>Z;function d8(Z,$){this[Z]=u8.bind(null,$)}var l8=(Z,$)=>{for(var X in $)h8(Z,X,{get:$[X],enumerable:!0,configurable:!0,set:d8.bind($,X)})};var m8=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var S4=((Z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(Z,{get:($,X)=>(typeof require<"u"?require:$)[X]}):Z)(function(Z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+Z+'" is not supported')});var _7=x8((qH,NZ)=>{NZ.exports={name:"tjs-lang",version:"0.6.43",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",exports:{".":{bun:"./src/index.ts",default:"./dist/index.js"},"./eval":{bun:"./src/lang/eval.ts",default:"./dist/lang/eval.js"},"./lang":{bun:"./src/lang/index.ts",default:"./dist/lang/index.js"},"./lang/eval":{bun:"./src/lang/eval.ts",default:"./dist/lang/eval.js"},"./lang/from-ts":{bun:"./src/lang/emitters/from-ts.ts",default:"./dist/lang/emitters/from-ts.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",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.2.0","tosijs-ui":"^1.2.0",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.2.0"}}});var D6={};l8(D6,{sep:()=>w8,resolve:()=>F4,relative:()=>U8,posix:()=>M8,parse:()=>B8,normalize:()=>q6,join:()=>L8,isAbsolute:()=>_8,format:()=>R8,extname:()=>I8,dirname:()=>D8,delimiter:()=>j8,default:()=>VX,basename:()=>A8,_makeLong:()=>q8});function M1(Z){if(typeof Z!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(Z))}function W8(Z,$){var X="",Q=0,H=-1,K=0,Y;for(var z=0;z<=Z.length;++z){if(z<Z.length)Y=Z.charCodeAt(z);else if(Y===47)break;else Y=47;if(Y===47){if(H===z-1||K===1);else if(H!==z-1&&K===2){if(X.length<2||Q!==2||X.charCodeAt(X.length-1)!==46||X.charCodeAt(X.length-2)!==46){if(X.length>2){var G=X.lastIndexOf("/");if(G!==X.length-1){if(G===-1)X="",Q=0;else X=X.slice(0,G),Q=X.length-1-X.lastIndexOf("/");H=z,K=0;continue}}else if(X.length===2||X.length===1){X="",Q=0,H=z,K=0;continue}}if($){if(X.length>0)X+="/..";else X="..";Q=2}}else{if(X.length>0)X+="/"+Z.slice(H+1,z);else X=Z.slice(H+1,z);Q=z-H-1}H=z,K=0}else if(Y===46&&K!==-1)++K;else K=-1}return X}function PX(Z,$){var X=$.dir||$.root,Q=$.base||($.name||"")+($.ext||"");if(!X)return Q;if(X===$.root)return X+Q;return X+Z+Q}function F4(){var Z="",$=!1,X;for(var Q=arguments.length-1;Q>=-1&&!$;Q--){var H;if(Q>=0)H=arguments[Q];else{if(X===void 0)X=process.cwd();H=X}if(M1(H),H.length===0)continue;Z=H+"/"+Z,$=H.charCodeAt(0)===47}if(Z=W8(Z,!$),$)if(Z.length>0)return"/"+Z;else return"/";else if(Z.length>0)return Z;else return"."}function q6(Z){if(M1(Z),Z.length===0)return".";var $=Z.charCodeAt(0)===47,X=Z.charCodeAt(Z.length-1)===47;if(Z=W8(Z,!$),Z.length===0&&!$)Z=".";if(Z.length>0&&X)Z+="/";if($)return"/"+Z;return Z}function _8(Z){return M1(Z),Z.length>0&&Z.charCodeAt(0)===47}function L8(){if(arguments.length===0)return".";var Z;for(var $=0;$<arguments.length;++$){var X=arguments[$];if(M1(X),X.length>0)if(Z===void 0)Z=X;else Z+="/"+X}if(Z===void 0)return".";return q6(Z)}function U8(Z,$){if(M1(Z),M1($),Z===$)return"";if(Z=F4(Z),$=F4($),Z===$)return"";var X=1;for(;X<Z.length;++X)if(Z.charCodeAt(X)!==47)break;var Q=Z.length,H=Q-X,K=1;for(;K<$.length;++K)if($.charCodeAt(K)!==47)break;var Y=$.length,z=Y-K,G=H<z?H:z,J=-1,W=0;for(;W<=G;++W){if(W===G){if(z>G){if($.charCodeAt(K+W)===47)return $.slice(K+W+1);else if(W===0)return $.slice(K+W)}else if(H>G){if(Z.charCodeAt(X+W)===47)J=W;else if(W===0)J=0}break}var L=Z.charCodeAt(X+W),_=$.charCodeAt(K+W);if(L!==_)break;else if(L===47)J=W}var U="";for(W=X+J+1;W<=Q;++W)if(W===Q||Z.charCodeAt(W)===47)if(U.length===0)U+="..";else U+="/..";if(U.length>0)return U+$.slice(K+J);else{if(K+=J,$.charCodeAt(K)===47)++K;return $.slice(K)}}function q8(Z){return Z}function D8(Z){if(M1(Z),Z.length===0)return".";var $=Z.charCodeAt(0),X=$===47,Q=-1,H=!0;for(var K=Z.length-1;K>=1;--K)if($=Z.charCodeAt(K),$===47){if(!H){Q=K;break}}else H=!1;if(Q===-1)return X?"/":".";if(X&&Q===1)return"//";return Z.slice(0,Q)}function A8(Z,$){if($!==void 0&&typeof $!=="string")throw TypeError('"ext" argument must be a string');M1(Z);var X=0,Q=-1,H=!0,K;if($!==void 0&&$.length>0&&$.length<=Z.length){if($.length===Z.length&&$===Z)return"";var Y=$.length-1,z=-1;for(K=Z.length-1;K>=0;--K){var G=Z.charCodeAt(K);if(G===47){if(!H){X=K+1;break}}else{if(z===-1)H=!1,z=K+1;if(Y>=0)if(G===$.charCodeAt(Y)){if(--Y===-1)Q=K}else Y=-1,Q=z}}if(X===Q)Q=z;else if(Q===-1)Q=Z.length;return Z.slice(X,Q)}else{for(K=Z.length-1;K>=0;--K)if(Z.charCodeAt(K)===47){if(!H){X=K+1;break}}else if(Q===-1)H=!1,Q=K+1;if(Q===-1)return"";return Z.slice(X,Q)}}function I8(Z){M1(Z);var $=-1,X=0,Q=-1,H=!0,K=0;for(var Y=Z.length-1;Y>=0;--Y){var z=Z.charCodeAt(Y);if(z===47){if(!H){X=Y+1;break}continue}if(Q===-1)H=!1,Q=Y+1;if(z===46){if($===-1)$=Y;else if(K!==1)K=1}else if($!==-1)K=-1}if($===-1||Q===-1||K===0||K===1&&$===Q-1&&$===X+1)return"";return Z.slice($,Q)}function R8(Z){if(Z===null||typeof Z!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof Z);return PX("/",Z)}function B8(Z){M1(Z);var $={root:"",dir:"",base:"",ext:"",name:""};if(Z.length===0)return $;var X=Z.charCodeAt(0),Q=X===47,H;if(Q)$.root="/",H=1;else H=0;var K=-1,Y=0,z=-1,G=!0,J=Z.length-1,W=0;for(;J>=H;--J){if(X=Z.charCodeAt(J),X===47){if(!G){Y=J+1;break}continue}if(z===-1)G=!1,z=J+1;if(X===46){if(K===-1)K=J;else if(W!==1)W=1}else if(K!==-1)W=-1}if(K===-1||z===-1||W===0||W===1&&K===z-1&&K===Y+1){if(z!==-1)if(Y===0&&Q)$.base=$.name=Z.slice(1,z);else $.base=$.name=Z.slice(Y,z)}else{if(Y===0&&Q)$.name=Z.slice(1,K),$.base=Z.slice(1,z);else $.name=Z.slice(Y,K),$.base=Z.slice(Y,z);$.ext=Z.slice(K,z)}if(Y>0)$.dir=Z.slice(0,Y-1);else if(Q)$.dir="/";return $}var w8="/",j8=":",M8,VX;var A6=m8(()=>{M8=((Z)=>(Z.posix=Z,Z))({resolve:F4,normalize:q6,isAbsolute:_8,join:L8,relative:U8,_makeLong:q8,dirname:D8,basename:A8,extname:I8,format:R8,parse:B8,sep:w8,delimiter:j8,win32:null,posix:null}),VX=M8});import*as X7 from"acorn";class c extends Error{line;column;source;filename;constructor(Z,$,X,Q){let H=`${Q||"<source>"}:${$.line}:${$.column}`;super(`${Z} at ${H}`);this.name="TranspileError",this.line=$.line,this.column=$.column,this.source=X,this.filename=Q}}class z1 extends c{constructor(Z,$,X,Q){super(Z,$,X,Q);this.name="SyntaxError"}formatWithContext(Z=2){if(!this.source)return this.message;let $=this.source.split(`
1
+ var u8=Object.defineProperty;var d8=(Z,$)=>()=>($||Z(($={exports:{}}).exports,$),$.exports);var l8=(Z)=>Z;function m8(Z,$){this[Z]=l8.bind(null,$)}var i8=(Z,$)=>{for(var X in $)u8(Z,X,{get:$[X],enumerable:!0,configurable:!0,set:m8.bind($,X)})};var p8=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var T4=((Z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(Z,{get:($,X)=>(typeof require<"u"?require:$)[X]}):Z)(function(Z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+Z+'" is not supported')});var L7=d8((AH,SZ)=>{SZ.exports={name:"tjs-lang",version:"0.6.45",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",exports:{".":{bun:"./src/index.ts",default:"./dist/index.js"},"./eval":{bun:"./src/lang/eval.ts",default:"./dist/lang/eval.js"},"./lang":{bun:"./src/lang/index.ts",default:"./dist/lang/index.js"},"./lang/eval":{bun:"./src/lang/eval.ts",default:"./dist/lang/eval.js"},"./lang/from-ts":{bun:"./src/lang/emitters/from-ts.ts",default:"./dist/lang/emitters/from-ts.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",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.2.0","tosijs-ui":"^1.2.0",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.2.0"}}});var A6={};i8(A6,{sep:()=>M8,resolve:()=>F4,relative:()=>D8,posix:()=>P8,parse:()=>j8,normalize:()=>D6,join:()=>q8,isAbsolute:()=>U8,format:()=>w8,extname:()=>B8,dirname:()=>I8,delimiter:()=>F8,default:()=>OX,basename:()=>R8,_makeLong:()=>A8});function M1(Z){if(typeof Z!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(Z))}function L8(Z,$){var X="",Q=0,H=-1,K=0,Y;for(var z=0;z<=Z.length;++z){if(z<Z.length)Y=Z.charCodeAt(z);else if(Y===47)break;else Y=47;if(Y===47){if(H===z-1||K===1);else if(H!==z-1&&K===2){if(X.length<2||Q!==2||X.charCodeAt(X.length-1)!==46||X.charCodeAt(X.length-2)!==46){if(X.length>2){var G=X.lastIndexOf("/");if(G!==X.length-1){if(G===-1)X="",Q=0;else X=X.slice(0,G),Q=X.length-1-X.lastIndexOf("/");H=z,K=0;continue}}else if(X.length===2||X.length===1){X="",Q=0,H=z,K=0;continue}}if($){if(X.length>0)X+="/..";else X="..";Q=2}}else{if(X.length>0)X+="/"+Z.slice(H+1,z);else X=Z.slice(H+1,z);Q=z-H-1}H=z,K=0}else if(Y===46&&K!==-1)++K;else K=-1}return X}function CX(Z,$){var X=$.dir||$.root,Q=$.base||($.name||"")+($.ext||"");if(!X)return Q;if(X===$.root)return X+Q;return X+Z+Q}function F4(){var Z="",$=!1,X;for(var Q=arguments.length-1;Q>=-1&&!$;Q--){var H;if(Q>=0)H=arguments[Q];else{if(X===void 0)X=process.cwd();H=X}if(M1(H),H.length===0)continue;Z=H+"/"+Z,$=H.charCodeAt(0)===47}if(Z=L8(Z,!$),$)if(Z.length>0)return"/"+Z;else return"/";else if(Z.length>0)return Z;else return"."}function D6(Z){if(M1(Z),Z.length===0)return".";var $=Z.charCodeAt(0)===47,X=Z.charCodeAt(Z.length-1)===47;if(Z=L8(Z,!$),Z.length===0&&!$)Z=".";if(Z.length>0&&X)Z+="/";if($)return"/"+Z;return Z}function U8(Z){return M1(Z),Z.length>0&&Z.charCodeAt(0)===47}function q8(){if(arguments.length===0)return".";var Z;for(var $=0;$<arguments.length;++$){var X=arguments[$];if(M1(X),X.length>0)if(Z===void 0)Z=X;else Z+="/"+X}if(Z===void 0)return".";return D6(Z)}function D8(Z,$){if(M1(Z),M1($),Z===$)return"";if(Z=F4(Z),$=F4($),Z===$)return"";var X=1;for(;X<Z.length;++X)if(Z.charCodeAt(X)!==47)break;var Q=Z.length,H=Q-X,K=1;for(;K<$.length;++K)if($.charCodeAt(K)!==47)break;var Y=$.length,z=Y-K,G=H<z?H:z,J=-1,W=0;for(;W<=G;++W){if(W===G){if(z>G){if($.charCodeAt(K+W)===47)return $.slice(K+W+1);else if(W===0)return $.slice(K+W)}else if(H>G){if(Z.charCodeAt(X+W)===47)J=W;else if(W===0)J=0}break}var U=Z.charCodeAt(X+W),_=$.charCodeAt(K+W);if(U!==_)break;else if(U===47)J=W}var L="";for(W=X+J+1;W<=Q;++W)if(W===Q||Z.charCodeAt(W)===47)if(L.length===0)L+="..";else L+="/..";if(L.length>0)return L+$.slice(K+J);else{if(K+=J,$.charCodeAt(K)===47)++K;return $.slice(K)}}function A8(Z){return Z}function I8(Z){if(M1(Z),Z.length===0)return".";var $=Z.charCodeAt(0),X=$===47,Q=-1,H=!0;for(var K=Z.length-1;K>=1;--K)if($=Z.charCodeAt(K),$===47){if(!H){Q=K;break}}else H=!1;if(Q===-1)return X?"/":".";if(X&&Q===1)return"//";return Z.slice(0,Q)}function R8(Z,$){if($!==void 0&&typeof $!=="string")throw TypeError('"ext" argument must be a string');M1(Z);var X=0,Q=-1,H=!0,K;if($!==void 0&&$.length>0&&$.length<=Z.length){if($.length===Z.length&&$===Z)return"";var Y=$.length-1,z=-1;for(K=Z.length-1;K>=0;--K){var G=Z.charCodeAt(K);if(G===47){if(!H){X=K+1;break}}else{if(z===-1)H=!1,z=K+1;if(Y>=0)if(G===$.charCodeAt(Y)){if(--Y===-1)Q=K}else Y=-1,Q=z}}if(X===Q)Q=z;else if(Q===-1)Q=Z.length;return Z.slice(X,Q)}else{for(K=Z.length-1;K>=0;--K)if(Z.charCodeAt(K)===47){if(!H){X=K+1;break}}else if(Q===-1)H=!1,Q=K+1;if(Q===-1)return"";return Z.slice(X,Q)}}function B8(Z){M1(Z);var $=-1,X=0,Q=-1,H=!0,K=0;for(var Y=Z.length-1;Y>=0;--Y){var z=Z.charCodeAt(Y);if(z===47){if(!H){X=Y+1;break}continue}if(Q===-1)H=!1,Q=Y+1;if(z===46){if($===-1)$=Y;else if(K!==1)K=1}else if($!==-1)K=-1}if($===-1||Q===-1||K===0||K===1&&$===Q-1&&$===X+1)return"";return Z.slice($,Q)}function w8(Z){if(Z===null||typeof Z!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof Z);return CX("/",Z)}function j8(Z){M1(Z);var $={root:"",dir:"",base:"",ext:"",name:""};if(Z.length===0)return $;var X=Z.charCodeAt(0),Q=X===47,H;if(Q)$.root="/",H=1;else H=0;var K=-1,Y=0,z=-1,G=!0,J=Z.length-1,W=0;for(;J>=H;--J){if(X=Z.charCodeAt(J),X===47){if(!G){Y=J+1;break}continue}if(z===-1)G=!1,z=J+1;if(X===46){if(K===-1)K=J;else if(W!==1)W=1}else if(K!==-1)W=-1}if(K===-1||z===-1||W===0||W===1&&K===z-1&&K===Y+1){if(z!==-1)if(Y===0&&Q)$.base=$.name=Z.slice(1,z);else $.base=$.name=Z.slice(Y,z)}else{if(Y===0&&Q)$.name=Z.slice(1,K),$.base=Z.slice(1,z);else $.name=Z.slice(Y,K),$.base=Z.slice(Y,z);$.ext=Z.slice(K,z)}if(Y>0)$.dir=Z.slice(0,Y-1);else if(Q)$.dir="/";return $}var M8="/",F8=":",P8,OX;var I6=p8(()=>{P8=((Z)=>(Z.posix=Z,Z))({resolve:F4,normalize:D6,isAbsolute:U8,join:q8,relative:D8,_makeLong:A8,dirname:I8,basename:R8,extname:B8,format:w8,parse:j8,sep:M8,delimiter:F8,win32:null,posix:null}),OX=P8});import*as Q7 from"acorn";class c extends Error{line;column;source;filename;constructor(Z,$,X,Q){let H=`${Q||"<source>"}:${$.line}:${$.column}`;super(`${Z} at ${H}`);this.name="TranspileError",this.line=$.line,this.column=$.column,this.source=X,this.filename=Q}}class z1 extends c{constructor(Z,$,X,Q){super(Z,$,X,Q);this.name="SyntaxError"}formatWithContext(Z=2){if(!this.source)return this.message;let $=this.source.split(`
2
2
  `),X=this.line-1,Q=Math.max(0,X-Z),H=Math.min($.length-1,X+Z),K=[],Y=String(H+1).length;for(let z=Q;z<=H;z++){let G=String(z+1).padStart(Y),J=z===X?">":" ";if(K.push(`${J} ${G} | ${$[z]}`),z===X){let W=" ".repeat(Y+4+this.column);K.push(`${W}^ ${this.message.split(" at ")[0]}`)}}return K.join(`
3
- `)}}class i8 extends c{expected;received;suggestion;constructor(Z,$,X){super(Z,$,X?.source,X?.filename);this.name="TypeError",this.expected=X?.expected,this.received=X?.received,this.suggestion=X?.suggestion}}function _1(Z){return{depth:Z.depth+1,locals:new Map,parent:Z,parameters:Z.parameters,atoms:Z.atoms,warnings:Z.warnings,source:Z.source,filename:Z.filename,options:Z.options}}function p8(Z,$){if($.locals.has(Z))return $.locals.get(Z);if($.parameters.has(Z))return $.parameters.get(Z)?.type;if($.parent)return p8(Z,$.parent);return}function o(Z){if(Z.loc)return{line:Z.loc.start.line,column:Z.loc.start.column};return{line:1,column:0}}function b0(Z,$){let X="",Q=0,H,K,Y="normal",z=[],G=[{type:"top-level",braceDepth:0}],J=0,W=()=>G[G.length-1]?.type||"top-level",L=()=>{let _=G[G.length-1];return _?.type==="class-body"&&J===_.braceDepth+1};while(Q<Z.length){let _=Z[Q],U=Z[Q+1];switch(Y){case"single-string":if(X+=_,_==="\\"&&Q+1<Z.length){X+=U,Q+=2;continue}if(_==="'")Y="normal";Q++;continue;case"double-string":if(X+=_,_==="\\"&&Q+1<Z.length){X+=U,Q+=2;continue}if(_==='"')Y="normal";Q++;continue;case"template-string":if(X+=_,_==="\\"&&Q+1<Z.length){X+=U,Q+=2;continue}if(_==="$"&&U==="{"){X+=U,Q+=2,z.push(1),Y="normal";continue}if(_==="`")Y="normal";Q++;continue;case"line-comment":if(X+=_,_===`
4
- `)Y="normal";Q++;continue;case"block-comment":if(X+=_,_==="*"&&U==="/"){X+=U,Q+=2,Y="normal";continue}Q++;continue;case"regex":if(X+=_,_==="\\"&&Q+1<Z.length){X+=U,Q+=2;continue}if(_==="["){Q++;while(Q<Z.length&&Z[Q]!=="]")if(X+=Z[Q],Z[Q]==="\\"&&Q+1<Z.length)X+=Z[Q+1],Q+=2;else Q++;if(Q<Z.length)X+=Z[Q],Q++;continue}if(_==="/"){Q++;while(Q<Z.length&&/[gimsuy]/.test(Z[Q]))X+=Z[Q],Q++;Y="normal";continue}Q++;continue;case"normal":if(z.length>0){if(_==="{")z[z.length-1]++;else if(_==="}"){if(z[z.length-1]--,z[z.length-1]===0){z.pop(),X+=_,Q++,Y="template-string";continue}}}if(_==="'"){X+=_,Q++,Y="single-string";continue}if(_==='"'){X+=_,Q++,Y="double-string";continue}if(_==="`"){X+=_,Q++,Y="template-string";continue}if(_==="/"&&U==="/"){X+=_+U,Q+=2,Y="line-comment";continue}if(_==="/"&&U==="*"){X+=_+U,Q+=2,Y="block-comment";continue}if(_==="/"){let R=X.trimEnd();if(!R[R.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(R)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(R)){X+=_,Q++,Y="regex";continue}}break}if(_==="{"){J++,X+=_,Q++;continue}if(_==="}"){J--;let R=G[G.length-1];if(R&&J===R.braceDepth)G.pop();X+=_,Q++;continue}let q=Z.slice(Q).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(q){let R=q[0].slice(0,-1);X+=R,Q+=R.length,G.push({type:"class-body",braceDepth:J});continue}let A=Z.slice(Q).match(/^function\s+(\w+)\s*\(/);if(A){let R=A[1],w=A[0].length,C=Z[Q+w],P=null,O=Q+w;if(C==="?"||C==="!")if(P=C,O++,P==="!")$.unsafeFunctions.add(R);else $.safeFunctions.add(R);X+=`function ${R}(`,Q=O;let k=T0(Z,Q,"(",")");if(!k){X+=Z[Q],Q++;continue}let{content:V,endPos:T}=k;Q=T;let N=T4(V,$,!0);X+=N+")";let g=Q;while(g<Z.length&&/\s/.test(Z[g]))g++;let b=Z.slice(g,g+2);if(b==="->"||b==="-?"||b==="-!"){g+=2;while(g<Z.length&&/\s/.test(Z[g]))g++;let f=S0(Z,g);if(f){let{type:n,endPos:m}=f;if(H===void 0){if(H=n,b==="-?")K="safe";else if(b==="-!")K="unsafe"}Q=m}}continue}let B=Z.slice(Q).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),M=(()=>{for(let R=X.length-1;R>=0;R--)if(!/\s/.test(X[R]))return X[R];return`
5
- `})(),F=M!=="="&&M!==","&&M!=="("&&M!=="["&&M!==">";if(B&&L()&&!F){let R=B[1].length;X+=Z.slice(Q,Q+R),Q+=R;continue}if(B&&L()&&F){let R=B[1],w=B[0].length,C=Q+w;X+=R+"(",Q=C;let P=T0(Z,Q,"(",")");if(!P){X+=Z[Q],Q++;continue}let{content:O,endPos:k}=P;Q=k;let V=T4(O,$,!0);X+=V+")";let T=Q;while(T<Z.length&&/\s/.test(Z[T]))T++;let N=Z.slice(T,T+2);if(N==="->"||N==="-!"||N==="-?"){T+=2;while(T<Z.length&&/\s/.test(Z[T]))T++;let g=S0(Z,T);if(g)Q=g.endPos}else if(Z[T]===":"){T++;while(T<Z.length&&/\s/.test(Z[T]))T++;let g=S0(Z,T);if(g)Q=g.endPos}continue}if(Z[Q]==="("){let R=T0(Z,Q+1,"(",")");if(!R){X+=Z[Q],Q++;continue}let{content:w,endPos:C}=R,P=C;while(P<Z.length&&/\s/.test(Z[P]))P++;let O,k=Z.slice(P,P+2);if(k==="->"||k==="-?"||k==="-!"){P+=2;while(P<Z.length&&/\s/.test(Z[P]))P++;let V=S0(Z,P);if(V){O=V.type,P=V.endPos;while(P<Z.length&&/\s/.test(Z[P]))P++}}if(Z.slice(P,P+2)==="=>"){let V=null,T=w,N=w.trimStart();if(N.startsWith("?")&&(N.length===1||/\s/.test(N[1])))V="?",T=N.slice(1);else if(N.startsWith("!")&&(N.length===1||/\s/.test(N[1])))V="!",T=N.slice(1);let g=T4(T,$,!1);X+=`(${V==="?"?"/* safe */ ":V==="!"?"/* unsafe */ ":""}${g})`,Q=C;while(Q<P&&/\s/.test(Z[Q]))X+=Z[Q],Q++;if(O)Q=P}else{let V=b0(w,$);X+=`(${V.source})`,Q=C}continue}X+=Z[Q],Q++}return{source:X,returnType:H,returnSafety:K}}function T0(Z,$,X,Q){let H=1,K=$,Y=!1,z="";while(K<Z.length&&H>0){let G=Z[K];if(!Y&&(G==="'"||G==='"'||G==="`"))Y=!0,z=G;else if(Y&&G===z&&Z[K-1]!=="\\")Y=!1;else if(!Y){if(G===X)H++;else if(G===Q)H--}K++}if(H!==0)return null;return{content:Z.slice($,K-1),endPos:K}}function T6(Z,$){let X=$;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)return null;let Q=X,H=Z[X];if(H==="{"||H==="["){let Y=H==="{"?"}":"]",z=T0(Z,X+1,H,Y);if(!z)return null;return{value:Z.slice(Q,z.endPos),endPos:z.endPos}}if(H==="'"||H==='"'||H==="`"){X++;while(X<Z.length){if(Z[X]===H&&Z[X-1]!=="\\")return X++,{value:Z.slice(Q,X),endPos:X};X++}return null}if(/[-+\d]/.test(H)){while(X<Z.length&&/[\d.eE+-]/.test(Z[X]))X++;return{value:Z.slice(Q,X),endPos:X}}let K=Z.slice(X).match(/^(true|false|null|undefined)\b/);if(K)return{value:K[1],endPos:X+K[1].length};return null}function Y0(Z){return Z.replace(/(?<!\|)\|(?!\|)/g," || ")}function S0(Z,$){let X=$,Q=0,H=!1,K="",Y=!1,z=(G)=>({type:Y0(Z.slice($,G).trim()),endPos:G});while(X<Z.length){let G=Z[X];if(!H&&(G==="'"||G==='"'||G==="`")){H=!0,K=G,Y=!0,X++;continue}if(H){if(G===K&&Z[X-1]!=="\\"){if(H=!1,X++,Q===0){let J=X;while(J<Z.length&&/\s/.test(Z[J]))J++;if(Z[J]==="{"){if(!Z.slice(J+1).match(/^\s*(\w+)\s*:/))return z(X)}if(Z[J]!=="|"&&Z[J]!=="&")return z(X)}continue}X++;continue}if(G==="{"||G==="["||G==="("){Q++,Y=!0,X++;continue}if(G==="}"||G==="]"||G===")"){if(Q--,Q===0){X++;let J=X;while(J<Z.length&&/\s/.test(Z[J]))J++;if(Z[J]==="|"||Z[J]==="&")continue;return z(X)}X++;continue}if(Q===0&&G==="{"){if(Y)return z(X);if(Z.slice(X+1).match(/^\s*(\w+)\s*:/)){Q++,Y=!0,X++;continue}return z(X)}if(Q===0&&(G==="|"||G==="&")){if(X++,X<Z.length&&Z[X]==="|")X++;while(X<Z.length&&/\s/.test(Z[X]))X++;continue}if(Q===0&&(/\d/.test(G)||G==="-"&&/\d/.test(Z[X+1]))){let J=X;if(Z[J]==="-")J++;while(J<Z.length&&/\d/.test(Z[J]))J++;if(J<Z.length&&Z[J]==="."&&/\d/.test(Z[J+1])){J++;while(J<Z.length&&/\d/.test(Z[J]))J++}if(J<Z.length&&(Z[J]==="e"||Z[J]==="E")){if(J++,J<Z.length&&(Z[J]==="+"||Z[J]==="-"))J++;while(J<Z.length&&/\d/.test(Z[J]))J++}Y=!0,X=J;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X<Z.length&&Z[X]==="{")return{type:Y0(Z.slice($,J).trim()),endPos:J};if(Z[X]!=="|"&&Z[X]!=="&")return{type:Y0(Z.slice($,J).trim()),endPos:J};continue}if(Q===0&&/[a-zA-Z_]/.test(G)){let J=X;while(J<Z.length&&/\w/.test(Z[J]))J++;Y=!0,X=J;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X<Z.length&&Z[X]==="("){Q++,X++;continue}if(X<Z.length&&Z[X]==="{"){if(!Z.slice(X+1).match(/^\s*(\w+)\s*:/)){let L=J;while(L>$&&/\s/.test(Z[L-1]))L--;return{type:Y0(Z.slice($,L).trim()),endPos:J}}}if(Z[X]!=="|"&&Z[X]!=="&")return{type:Y0(Z.slice($,J).trim()),endPos:J};continue}X++}if(Y)return z(X);return null}function v0(Z){let $=[],X="",Q=0,H=!1,K=!1,Y=0;while(Y<Z.length){let z=Z[Y],G=Z[Y+1];if(!K&&z==="/"&&G==="/"){H=!0,X+="//",Y+=2;continue}if(!H&&z==="/"&&G==="*"){K=!0,X+="/*",Y+=2;continue}if(H&&z===`
6
- `){H=!1,X+=z,Y++;continue}if(K&&z==="*"&&G==="/"){K=!1,X+="*/",Y+=2;continue}if(H||K){X+=z,Y++;continue}if(z==="("||z==="{"||z==="[")Q++,X+=z;else if(z===")"||z==="}"||z==="]")Q--,X+=z;else if(z===","&&Q===0)$.push(X),X="";else X+=z;Y++}if(X.trim())$.push(X);return $}function T4(Z,$,X){let Q=b0(Z,{originalSource:Z,requiredParams:$.requiredParams,unsafeFunctions:$.unsafeFunctions,safeFunctions:$.safeFunctions}).source,H=v0(Q),K=!1,Y=new Set,z=(J)=>{if(X&&/^\w+$/.test(J)){if(Y.has(J))throw Error(`Duplicate parameter name '${J}'`);Y.add(J)}};return H.map((J)=>{let W=J.trim();if(!W)return J;if(X&&W.startsWith("{")&&W.endsWith("}")){let U=W.slice(1,-1);return`{ ${E6(U,$)} }`}if(X&&W.startsWith("[")&&W.endsWith("]")){let U=W.slice(1,-1);return`[ ${E6(U,$)} ]`}if(W.startsWith("...")){let U=S6(W);if(U!==-1)return W.slice(0,U).trim();return J}let L=W.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(L){let[,U,q]=L;return z(U),K=!0,`${U} = ${q}`}if(!n8(W)){let U=W.match(/^(\w+)\s*=/);if(U)z(U[1]);return K=!0,J}let _=S6(W);if(_!==-1){let U=W.slice(0,_).trim(),q=W.slice(_+1).trim();if(z(U),K&&X&&/^\w+$/.test(U));if(X&&/^\w+$/.test(U))$.requiredParams.add(U);return`${U} = ${q}`}return J}).join(",")}function E6(Z,$){return v0(Z).map((H)=>{let K=H.trim();if(!K)return H;let Y=K.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(Y){let[,J,W]=Y;$.requiredParams.add(J);let L=k0(W);return`${J} = ${L}`}let z=K.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(z){let[,J,W]=z;$.requiredParams.add(J);let L=g0(W);return`${J} = ${L}`}let G=K.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(G){let[,J,W]=G;return $.requiredParams.add(J),`${J} = ${W}`}return H}).join(", ")}function k0(Z){let $=Z.slice(1,-1).trim();return`{ ${v0($).map((H)=>{let K=H.trim();if(!K)return H;let Y=K.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(Y){let[,L,_]=Y;return`${L}: ${k0(_)}`}let z=K.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(z){let[,L,_]=z;return`${L}: ${k0(_)}`}let G=K.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(G){let[,L,_]=G;return`${L}: ${g0(_)}`}let J=K.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(J){let[,L,_]=J;return`${L}: ${g0(_)}`}let W=K.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(W){let[,L,_]=W;return`${L}: ${_}`}return H}).join(", ")} }`}function g0(Z){let $=Z.slice(1,-1).trim();return`[ ${v0($).map((H)=>{let K=H.trim();if(!K)return H;if(K.startsWith("{")&&K.endsWith("}"))return k0(K);if(K.startsWith("[")&&K.endsWith("]"))return g0(K);return H}).join(", ")} ]`}function n8(Z){let $=0,X=!1,Q=!1,H=!1,K="";for(let Y=0;Y<Z.length;Y++){let z=Z[Y];if(!H&&(z==="'"||z==='"'||z==="`")){H=!0,K=z;continue}if(H){if(z===K&&Z[Y-1]!=="\\")H=!1;continue}if(z==="("||z==="{"||z==="[")$++;else if(z===")"||z==="}"||z==="]")$--;else if($===0){if(z===":")X=!0;if(z==="="&&Z[Y+1]!==">")Q=!0}}return X&&!Q}function S6(Z){let $=0,X=!1,Q="";for(let H=0;H<Z.length;H++){let K=Z[H];if(!X&&(K==="'"||K==='"'||K==="`")){X=!0,Q=K;continue}if(X){if(K===Q&&Z[H-1]!=="\\")X=!1;continue}if(K==="("||K==="{"||K==="[")$++;else if(K===")"||K==="}"||K==="]")$--;else if($===0&&K===":")return H}return-1}function c8(Z,$){let X=Z.match($);if(!X)return null;let Q=X.index+X[0].length-1,H=1,K=Q+1;while(K<Z.length&&H>0){if(Z[K]==="{")H++;else if(Z[K]==="}")H--;K++}if(H!==0)return null;let Y=Z.slice(Q,K),z=[X[0].slice(0,-1)+Y,Y];return z.index=X.index,z}function v6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\btry\s*\{/);if(Q){let K=X+Q[0].length-1+1,Y=1,z=K;while(z<Z.length&&Y>0){let J=Z[z];if(J==="{")Y++;else if(J==="}")Y--;z++}if(Y!==0){$+=Z[X],X++;continue}if(Z.slice(z).match(/^\s*(catch|finally)\b/))$+=Z.slice(X,z),X=z;else{let J=Z.slice(K,z-1);$+=`try {${J}} catch (__try_err) { return new (__tjs?.MonadicError ?? Error)(__try_err?.message || String(__try_err), 'try', undefined, undefined, __tjs?.getStack?.()) }`,X=z}}else $+=Z[X],X++}return $}function f6(Z){let $=[],X="",Q=0,H=0;while(Q<Z.length){let K=Z.slice(Q).match(/^\bwasm\s*\{/);if(K){let Y=Q,z=Q+K[0].length,G=1,J=z;while(J<Z.length&&G>0){let P=Z[J];if(P==="{")G++;else if(P==="}")G--;J++}if(G!==0){X+=Z[Q],Q++;continue}let W=Z.slice(z,J-1),L,_=J,U=Z.slice(J).match(/^\s*fallback\s*\{/);if(U){let P=J+U[0].length;G=1;let O=P;while(O<Z.length&&G>0){let k=Z[O];if(k==="{")G++;else if(k==="}")G--;O++}if(G===0)L=Z.slice(P,O-1),_=O}let A=s8(W).map((P)=>{let O=a8(Z,Y,P);return O?`${P}: ${O}`:P}),B={id:`__tjs_wasm_${H}`,body:W,fallback:L,captures:A,start:Y,end:_};$.push(B);let M=L??W,F=A.map((P)=>P.split(":")[0].trim()),R=F.length>0?F.join(", "):"",w=F.length>0?`globalThis.${B.id}(${R})`:`globalThis.${B.id}()`,C=`(globalThis.${B.id} ? ${w} : (() => {${M}})())`;X+=C,Q=_,H++}else X+=Z[Q],Q++}return{source:X,blocks:$}}function o8(Z){return Z.startsWith("f32x4_")||Z.startsWith("v128_")}function s8(Z){let $=Z.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),X=new Set,Q=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,H;while((H=Q.exec($))!==null)X.add(H[1]);let K=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,Y=new Set;while((H=K.exec($))!==null)Y.add(H[1]);for(let _ of X){if(!Y.has(_))continue;let U=new RegExp(`(?<!\\.)\\b${_}\\b`,"g"),q=new RegExp(`\\.${_}\\b`,"g"),A=$.match(U)?.length||0,B=$.match(q)?.length||0;if(A<=B)Y.delete(_)}let z=new Set,G=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((H=G.exec($))!==null)z.add(H[1]);let J=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((H=J.exec($))!==null)z.add(H[1]);let W=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"]),L=[];for(let _ of Y)if(!z.has(_)&&!W.has(_)&&!o8(_))L.push(_);return L.sort()}function a8(Z,$,X){let Q=Z.slice(0,$),H=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,K=Q.match(H);if(!K){let Y=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,z=Q.match(Y);if(!z)return;return k6(z[1],X)}return k6(K[1],X)}function k6(Z,$){let X=Z.split(",").map((Q)=>Q.trim());for(let Q of X){let H=Q.match(new RegExp(`^${$}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(H)return H[1];let K=Q.match(new RegExp(`^${$}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(K)return K[1]}return}function y6(Z){let X=new RegExp(`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")\\s+IsNot\\s+([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,"g");Z=Z.replace(X,"IsNot($1, $2)");let Q=new RegExp(`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")\\s+Is\\s+([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,"g");return Z=Z.replace(Q,"Is($1, $2)"),Z}function h6(Z){let $=/^[\s]*[([/+\-`]/,X=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,Q=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,H=Z.split(`
7
- `),K=[];for(let Y=0;Y<H.length;Y++){let z=H[Y],G=Y>0?H[Y-1]:"";if(Y>0&&$.test(z)){let J=G.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!X.test(J)&&!Q.test(J)){let W=z.match(/^(\s*)/),L=W?W[1]:"",_=z.slice(L.length);K.push(L+";"+_);continue}}K.push(z)}return K.join(`
8
- `)}function x6(Z){Z=Z.replace(/\btypeof\s+([a-zA-Z_$][\w$.]*(?:\?\.[\w$]+)*)/g,"TypeOf($1)");let $=[],X=0,Q="normal",H=[];while(X<Z.length){let Y=Z[X],z=Z[X+1];switch(Q){case"single-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="'")Q="normal";X++;continue;case"double-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==='"')Q="normal";X++;continue;case"template-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="$"&&z==="{"){X+=2,H.push(1),Q="normal";continue}if(Y==="`")Q="normal";X++;continue;case"line-comment":if(Y===`
9
- `)Q="normal";X++;continue;case"block-comment":if(Y==="*"&&z==="/"){X+=2,Q="normal";continue}X++;continue;case"regex":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="["){X++;while(X<Z.length&&Z[X]!=="]")if(Z[X]==="\\"&&X+1<Z.length)X+=2;else X++;if(X<Z.length)X++;continue}if(Y==="/"){X++;while(X<Z.length&&/[gimsuy]/.test(Z[X]))X++;Q="normal";continue}X++;continue;case"normal":if(H.length>0){if(Y==="{")H[H.length-1]++;else if(Y==="}"){if(H[H.length-1]--,H[H.length-1]===0){H.pop(),X++,Q="template-string";continue}}}if(Y==="'"){X++,Q="single-string";continue}if(Y==='"'){X++,Q="double-string";continue}if(Y==="`"){X++,Q="template-string";continue}if(Y==="/"&&z==="/"){X+=2,Q="line-comment";continue}if(Y==="/"&&z==="*"){X+=2,Q="block-comment";continue}if(Y==="/"){let G=X-1;while(G>=0&&/\s/.test(Z[G]))G--;let J=G>=0?Z[G]:"";if(!J||/[=(!,;:{[&|?+\-*%<>~^]/.test(J)||G>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(Z.slice(Math.max(0,G-10),G+1))){X++,Q="regex";continue}}if(Y==="="&&z==="="&&Z[X+2]!=="="&&Z[X-1]!=="!"){$.push({pos:X,op:"=="}),X+=2;continue}if(Y==="!"&&z==="="&&Z[X+2]!=="="){$.push({pos:X,op:"!="}),X+=2;continue}break}X++}if($.length===0)return Z;let K=Z;for(let Y=$.length-1;Y>=0;Y--){let{pos:z,op:G}=$[Y],J=G==="=="?"Eq":"NotEq",W=r8(K,z),L=t8(K,z+2),_=K.slice(W,z).trim(),U=K.slice(z+2,L).trim();if(_&&U){let q=K.slice(0,W),A=K.slice(L),M=/[a-zA-Z0-9_$]$/.test(q)?" ":"";K=`${q}${M}${J}(${_}, ${U})${A}`}}return K}function r8(Z,$){let X=$-1;while(X>=0&&/\s/.test(Z[X]))X--;if(X<0)return 0;let Q=0,H=!1,K="";while(X>=0){let Y=Z[X],z=X>0?Z[X-1]:"";if(H){if(Y===K&&z!=="\\")H=!1;X--;continue}if((Y==='"'||Y==="'"||Y==="`")&&z!=="\\"){H=!0,K=Y,X--;continue}if(Y===")"||Y==="]"||Y==="}"){Q++,X--;continue}if(Y==="("||Y==="["){if(Q>0){Q--,X--;continue}return X+1}if(Y==="{"){if(Q>0){Q--,X--;continue}return X+1}if(Q>0){X--;continue}if(Y===";")return X+1;if(/[a-z]/.test(Y)){let G=X+1,J=X;while(J>0&&/[a-z]/i.test(Z[J-1]))J--;let W=Z.slice(J,G),L=J>0?Z[J-1]:"";if(!/[a-zA-Z0-9_$]/.test(L)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(W))return G;if(W==="new")return J}}if(Y===">"&&z==="=")return X+1;if(Y==="="&&z!=="="&&z!=="!"&&z!=="<"&&z!==">")return X+1;if(Y==="&"&&z==="&")return X+1;if(Y==="|"&&z==="|")return X+1;if(Y==="?"||Y===":")return X+1;if(Y===",")return X+1;X--}return 0}function t8(Z,$){let X=$;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)return Z.length;let Q=0,H=!1,K="";while(X<Z.length){let Y=Z[X],z=X+1<Z.length?Z[X+1]:"";if(H){if(Y===K&&Z[X-1]!=="\\")H=!1;X++;continue}if((Y==='"'||Y==="'"||Y==="`")&&Z[X-1]!=="\\"){H=!0,K=Y,X++;continue}if(Y==="("||Y==="["||Y==="{"){Q++,X++;continue}if(Y===")"||Y==="]"||Y==="}"){if(Q>0){Q--,X++;continue}return X}if(Q>0){X++;continue}if(Y===";")return X;if(Y==="&"&&z==="&")return X;if(Y==="|"&&z==="|")return X;if(Y==="?")return X;if(Y===":")return X;if(Y===",")return X;if((Y==="="||Y==="!")&&z==="="&&Z[X+2]!=="=")return X;X++}return Z.length}function u6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(Q){let H=Q[1],K=X+Q[0].length,Y=H,z=!1,G=Z.slice(K).match(/^(['"`])([^]*?)\1\s*/);if(G){let _=K+G[0].length,U=Z[_],q=U===void 0||_>=Z.length||U!=="="&&U!=="{";if(U==="="||U==="{")Y=G[2],z=!0,K=_;else if(q){let A=G[0].trim(),B=G[0].slice(A.length);$+=`const ${H} = Type('${H}', ${A})${B}`,X=_;continue}}let J,W=K,L=Z.slice(K).match(/^=\s*/);if(L){K+=L[0].length;let _=Z.slice(K).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(_){J=_[0],K+=_[0].length,W=K;let U=Z.slice(K).match(/^\s*/);if(U)K+=U[0].length}}if(Z[K]==="{"){let _=K+1,U=1,q=_;while(q<Z.length&&U>0){let C=Z[q];if(C==="{")U++;else if(C==="}")U--;q++}if(U!==0){$+=Z[X],X++;continue}let A=Z.slice(_,q-1).trim(),B=q,M=A.match(/description\s*:\s*(['"`])([^]*?)\1/);if(M&&!z)Y=M[2];let F,R=A.match(/example\s*:\s*/);if(R){let C=R.index+R[0].length,P=T6(A,C);if(P)F=P.value.trim()}let w=A.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(w&&F){let C=w[1].trim(),P=w[2].trim(),O=J?`, ${J}`:"";$+=`const ${H} = Type('${Y}', (${C}) => { if (!globalThis.__tjs?.validate(${C}, globalThis.__tjs?.infer(${F}))) return false; ${P} }, ${F}${O})`}else if(w){let C=w[1].trim(),P=w[2].trim(),O=J?`, undefined, ${J}`:"";$+=`const ${H} = Type('${Y}', (${C}) => { ${P} }${O})`}else if(F){let C=J?`, ${J}`:"";$+=`const ${H} = Type('${Y}', undefined, ${F}${C})`}else if(J)$+=`const ${H} = Type('${Y}', ${J})`;else $+=`const ${H} = Type('${Y}')`;X=B;continue}else if(J){$+=`const ${H} = Type('${Y}', ${J})`,X=W;continue}else if(!G){let _=Z.slice(K).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(_){let U=_[0];$+=`const ${H} = Type('${H}', ${U})`,X=K+_[0].length;continue}}}$+=Z[X],X++}return $}function d6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bFunctionPredicate\s+([A-Z_][a-zA-Z0-9_]*)\s*(?:<([^>]+)>)?\s*/);if(Q){let H=Q[1],K=Q[2],Y=X+Q[0].length;if(Z[Y]==="{"){let z=1,G=Y+1;while(G<Z.length&&z>0){if(Z[G]==="{")z++;else if(Z[G]==="}")z--;G++}if(z===0){let J=Z.slice(Y+1,G-1).trim(),W=c8(J,/params\s*:\s*\{/),L=J.match(/returns\s*:\s*(.+?)(?:\n|$)/),_=J.match(/returnContract\s*:\s*['"](\w+)['"]/),U=J.match(/description\s*:\s*(['"])([^]*?)\1/),q=[];if(W)q.push(`params: ${W[1]}`);if(L)q.push(`returns: ${L[1].trim()}`);if(_)q.push(`returnContract: '${_[1]}'`);let A=U?U[2]:H;if(K){let B=K.split(",").map((F)=>{let R=F.trim().split("=").map((w)=>w.trim());if(R.length===2){let w=R[1]==="any"||R[1]==="undefined"?"null":R[1];return`['${R[0]}', ${w}]`}return`'${R[0]}'`}),M=K.split(",").map((F)=>F.trim().split("=")[0].trim());$+=`const ${H} = FunctionPredicate('${A}', [${B.join(", ")}], (${M.join(", ")}) => ({ ${q.join(", ")} }))`}else $+=`const ${H} = FunctionPredicate('${A}', { ${q.join(", ")} })`;X=G;continue}}if(Z[Y]==="("){let z=1,G=Y+1;while(G<Z.length&&z>0){if(Z[G]==="(")z++;else if(Z[G]===")")z--;G++}if(z===0){let J=Z.slice(Y+1,G-1).trim(),W=J.indexOf(",");if(W!==-1){let L=J.slice(0,W).trim(),_=J.slice(W+1).trim();$+=`const ${H} = FunctionPredicate(${_}, ${L})`}else $+=`const ${H} = FunctionPredicate('${H}', ${J})`;X=G;continue}}}$+=Z[X],X++}return $}function l6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(Q){let H=Q[1],K=Q[2],z=X+Q[0].length-1+1,G=1,J=z;while(J<Z.length&&G>0){let F=Z[J];if(F==="{")G++;else if(F==="}")G--;J++}if(G!==0){$+=Z[X],X++;continue}let W=Z.slice(z,J-1).trim(),L=J,_=K.split(",").map((F)=>{let R=F.trim().split("=").map((w)=>w.trim());if(R.length===2){let w=R[1]==="any"||R[1]==="undefined"?"null":R[1];return`['${R[0]}', ${w}]`}return`'${R[0]}'`}),U=W,q=U.search(/\bdeclaration\s*\{/);if(q!==-1){let F=U.indexOf("{",q),R=1,w=F+1;while(w<U.length&&R>0){if(U[w]==="{")R++;else if(U[w]==="}")R--;w++}U=U.slice(0,q)+U.slice(w)}let A=U.match(/description\s*:\s*(['"`])([^]*?)\1/),B=U.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),M=A?A[2]:H;if(B){let F=B[1].trim().split(",").map((O)=>O.trim()),R=B[2].trim(),w=F[0]||"x",C=F.slice(1),P=C.map((O)=>`check${O}`);C.forEach((O,k)=>{R=R.replace(new RegExp(`\\b${O}\\s*\\(`,"g"),`${P[k]}(`)}),$+=`const ${H} = Generic([${_.join(", ")}], (${w}, ${P.join(", ")}) => { ${R} }, '${M}')`}else $+=`const ${H} = Generic([${_.join(", ")}], () => true, '${M}')`;X=L;continue}$+=Z[X],X++}return $}function m6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(Q){let H=Q[1],K=Q[3],Y=X+Q[0].length;if(Z[Y]==="{"){let z=Y+1,G=1,J=z;while(J<Z.length&&G>0){let U=Z[J];if(U==="{")G++;else if(U==="}")G--;J++}if(G!==0){$+=Z[X],X++;continue}let W=Z.slice(z,J-1).trim(),L=J,_=g6(W);$+=`const ${H} = Union('${K}', [${_.join(", ")}])`,X=L;continue}else{let z=Z.indexOf(`
10
- `,Y);if(z===-1)z=Z.length;let G=Z.slice(Y,z).trim();if(G){let J=g6(G);$+=`const ${H} = Union('${K}', [${J.join(", ")}])`,X=z;continue}}}$+=Z[X],X++}return $}function g6(Z){let $=[],X=Z.split("|").map((Q)=>Q.trim());for(let Q of X){if(!Q)continue;$.push(Q)}return $}function i6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(Q){let H=Q[1],K=Q[3],z=X+Q[0].length-1+1,G=1,J=z;while(J<Z.length&&G>0){let q=Z[J];if(q==="{")G++;else if(q==="}")G--;J++}if(G!==0){$+=Z[X],X++;continue}let W=Z.slice(z,J-1).trim(),L=J,U=e8(W).map(([q,A])=>`${q}: ${A}`).join(", ");$+=`const ${H} = Enum('${K}', { ${U} })`,X=L;continue}$+=Z[X],X++}return $}function e8(Z){let $=[],X=0,Q=Z.split(/[\n,]/).map((H)=>H.trim()).filter((H)=>H&&!H.startsWith("//"));for(let H of Q){let K=H.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(K){let Y=K[1],z=K[2]?.trim();if(z!==void 0){$.push([Y,z]);let G=Number(z);if(!isNaN(G))X=G+1}else $.push([Y,String(X)]),X++}}return $}function p6(Z){let $=new Map,X="",Q=0;while(Q<Z.length){let H=Z.slice(Q),K=H.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/);if(!K){if(Q===0||Z[Q-1]===`
11
- `||Z[Q-1]===";"||Z[Q-1]==="}"){let R=H.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/)}X+=Z[Q],Q++;continue}let Y=K[1],z=K[2],G=Q+K[0].length-1,J=G0(Z,G),W=Z.slice(G+1,J-1).trim(),L=[],_=0,U=Z.slice(G+1,J-1);while(_<U.length){let R=U.slice(_).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!R){_++;continue}let w=R[1],C=!!R[2],P=R[3],O=_+R[0].length-1,k=1,V=O+1;while(V<U.length&&k>0){if(U[V]==="(")k++;if(U[V]===")")k--;V++}let T=U.slice(O+1,V-1),N=V;while(N<U.length&&/\s/.test(U[N]))N++;if(U[N]==="="&&U[N+1]===">"){let X1=z0(Z,G+1+_);throw new z1(`Arrow functions are not allowed in extend blocks (method '${P}' in extend ${z}). Use regular function syntax instead, as extension methods need 'this' binding.`,X1)}if(U[N]!=="{"){_++;continue}let g=G0(U,N),b=U.slice(_,g).trim(),f=T.split(",").map((X1)=>X1.trim()).filter((X1)=>X1.length>0).map((X1)=>{let b1=X1.match(/^(\w+)\s*:\s*(.+)$/);if(b1)return`${b1[1]} = ${b1[2]}`;return X1}).join(", "),n=C?"async ":"",m=U.slice(N+1,g-1);L.push({name:P,isAsync:C,fullText:`${P}: ${n}function(${f}) {${m}}`}),_=g}let q=!$.has(z);if(q)$.set(z,new Set);let A=$.get(z);for(let F of L)A.add(F.name);let B=L.map((F)=>` ${F.fullText}`).join(`,
3
+ `)}}class n8 extends c{expected;received;suggestion;constructor(Z,$,X){super(Z,$,X?.source,X?.filename);this.name="TypeError",this.expected=X?.expected,this.received=X?.received,this.suggestion=X?.suggestion}}function _1(Z){return{depth:Z.depth+1,locals:new Map,parent:Z,parameters:Z.parameters,atoms:Z.atoms,warnings:Z.warnings,source:Z.source,filename:Z.filename,options:Z.options}}function c8(Z,$){if($.locals.has(Z))return $.locals.get(Z);if($.parameters.has(Z))return $.parameters.get(Z)?.type;if($.parent)return c8(Z,$.parent);return}function o(Z){if(Z.loc)return{line:Z.loc.start.line,column:Z.loc.start.column};return{line:1,column:0}}function b0(Z,$){let X="",Q=0,H,K,Y="normal",z=[],G=[{type:"top-level",braceDepth:0}],J=0,W=()=>G[G.length-1]?.type||"top-level",U=()=>{let _=G[G.length-1];return _?.type==="class-body"&&J===_.braceDepth+1};while(Q<Z.length){let _=Z[Q],L=Z[Q+1];switch(Y){case"single-string":if(X+=_,_==="\\"&&Q+1<Z.length){X+=L,Q+=2;continue}if(_==="'")Y="normal";Q++;continue;case"double-string":if(X+=_,_==="\\"&&Q+1<Z.length){X+=L,Q+=2;continue}if(_==='"')Y="normal";Q++;continue;case"template-string":if(X+=_,_==="\\"&&Q+1<Z.length){X+=L,Q+=2;continue}if(_==="$"&&L==="{"){X+=L,Q+=2,z.push(1),Y="normal";continue}if(_==="`")Y="normal";Q++;continue;case"line-comment":if(X+=_,_===`
4
+ `)Y="normal";Q++;continue;case"block-comment":if(X+=_,_==="*"&&L==="/"){X+=L,Q+=2,Y="normal";continue}Q++;continue;case"regex":if(X+=_,_==="\\"&&Q+1<Z.length){X+=L,Q+=2;continue}if(_==="["){Q++;while(Q<Z.length&&Z[Q]!=="]")if(X+=Z[Q],Z[Q]==="\\"&&Q+1<Z.length)X+=Z[Q+1],Q+=2;else Q++;if(Q<Z.length)X+=Z[Q],Q++;continue}if(_==="/"){Q++;while(Q<Z.length&&/[gimsuy]/.test(Z[Q]))X+=Z[Q],Q++;Y="normal";continue}Q++;continue;case"normal":if(z.length>0){if(_==="{")z[z.length-1]++;else if(_==="}"){if(z[z.length-1]--,z[z.length-1]===0){z.pop(),X+=_,Q++,Y="template-string";continue}}}if(_==="'"){X+=_,Q++,Y="single-string";continue}if(_==='"'){X+=_,Q++,Y="double-string";continue}if(_==="`"){X+=_,Q++,Y="template-string";continue}if(_==="/"&&L==="/"){X+=_+L,Q+=2,Y="line-comment";continue}if(_==="/"&&L==="*"){X+=_+L,Q+=2,Y="block-comment";continue}if(_==="/"){let R=X.trimEnd();if(!R[R.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(R)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(R)){X+=_,Q++,Y="regex";continue}}break}if(_==="{"){J++,X+=_,Q++;continue}if(_==="}"){J--;let R=G[G.length-1];if(R&&J===R.braceDepth)G.pop();X+=_,Q++;continue}let q=Z.slice(Q).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(q){let R=q[0].slice(0,-1);X+=R,Q+=R.length,G.push({type:"class-body",braceDepth:J});continue}let A=Z.slice(Q).match(/^function\s+(\w+)\s*\(/);if(A){let R=A[1],w=A[0].length,C=Z[Q+w],P=null,O=Q+w;if(C==="?"||C==="!")if(P=C,O++,P==="!")$.unsafeFunctions.add(R);else $.safeFunctions.add(R);X+=`function ${R}(`,Q=O;let k=T0(Z,Q,"(",")");if(!k){X+=Z[Q],Q++;continue}let{content:V,endPos:T}=k;Q=T;let N=k4(V,$,!0);X+=N+")";let g=Q;while(g<Z.length&&/\s/.test(Z[g]))g++;let b=Z.slice(g,g+2);if(b==="->"||b==="-?"||b==="-!"){g+=2;while(g<Z.length&&/\s/.test(Z[g]))g++;let y=S0(Z,g);if(y){let{type:n,endPos:m}=y;if(H===void 0){if(H=n,b==="-?")K="safe";else if(b==="-!")K="unsafe"}Q=m}}continue}let B=Z.slice(Q).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),M=(()=>{for(let R=X.length-1;R>=0;R--)if(!/\s/.test(X[R]))return X[R];return`
5
+ `})(),F=M!=="="&&M!==","&&M!=="("&&M!=="["&&M!==">";if(B&&U()&&!F){let R=B[1].length;X+=Z.slice(Q,Q+R),Q+=R;continue}if(B&&U()&&F){let R=B[1],w=B[0].length,C=Q+w;X+=R+"(",Q=C;let P=T0(Z,Q,"(",")");if(!P){X+=Z[Q],Q++;continue}let{content:O,endPos:k}=P;Q=k;let V=k4(O,$,!0);X+=V+")";let T=Q;while(T<Z.length&&/\s/.test(Z[T]))T++;let N=Z.slice(T,T+2);if(N==="->"||N==="-!"||N==="-?"){T+=2;while(T<Z.length&&/\s/.test(Z[T]))T++;let g=S0(Z,T);if(g)Q=g.endPos}else if(Z[T]===":"){T++;while(T<Z.length&&/\s/.test(Z[T]))T++;let g=S0(Z,T);if(g)Q=g.endPos}continue}if(Z[Q]==="("){let R=T0(Z,Q+1,"(",")");if(!R){X+=Z[Q],Q++;continue}let{content:w,endPos:C}=R,P=C;while(P<Z.length&&/\s/.test(Z[P]))P++;let O,k=Z.slice(P,P+2);if(k==="->"||k==="-?"||k==="-!"){P+=2;while(P<Z.length&&/\s/.test(Z[P]))P++;let V=S0(Z,P);if(V){O=V.type,P=V.endPos;while(P<Z.length&&/\s/.test(Z[P]))P++}}if(Z.slice(P,P+2)==="=>"){let V=null,T=w,N=w.trimStart();if(N.startsWith("?")&&(N.length===1||/\s/.test(N[1])))V="?",T=N.slice(1);else if(N.startsWith("!")&&(N.length===1||/\s/.test(N[1])))V="!",T=N.slice(1);let g=k4(T,$,!1);X+=`(${V==="?"?"/* safe */ ":V==="!"?"/* unsafe */ ":""}${g})`,Q=C;while(Q<P&&/\s/.test(Z[Q]))X+=Z[Q],Q++;if(O)Q=P}else{let V=b0(w,$);X+=`(${V.source})`,Q=C}continue}X+=Z[Q],Q++}return{source:X,returnType:H,returnSafety:K}}function T0(Z,$,X,Q){let H=1,K=$,Y=!1,z="";while(K<Z.length&&H>0){let G=Z[K];if(!Y&&(G==="'"||G==='"'||G==="`"))Y=!0,z=G;else if(Y&&G===z&&Z[K-1]!=="\\")Y=!1;else if(!Y){if(G===X)H++;else if(G===Q)H--}K++}if(H!==0)return null;return{content:Z.slice($,K-1),endPos:K}}function k6(Z,$){let X=$;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)return null;let Q=X,H=Z[X];if(H==="{"||H==="["){let Y=H==="{"?"}":"]",z=T0(Z,X+1,H,Y);if(!z)return null;return{value:Z.slice(Q,z.endPos),endPos:z.endPos}}if(H==="'"||H==='"'||H==="`"){X++;while(X<Z.length){if(Z[X]===H&&Z[X-1]!=="\\")return X++,{value:Z.slice(Q,X),endPos:X};X++}return null}if(/[-+\d]/.test(H)){while(X<Z.length&&/[\d.eE+-]/.test(Z[X]))X++;return{value:Z.slice(Q,X),endPos:X}}let K=Z.slice(X).match(/^(true|false|null|undefined)\b/);if(K)return{value:K[1],endPos:X+K[1].length};return null}function Y0(Z){return Z.replace(/(?<!\|)\|(?!\|)/g," || ")}function S0(Z,$){let X=$,Q=0,H=!1,K="",Y=!1,z=(G)=>({type:Y0(Z.slice($,G).trim()),endPos:G});while(X<Z.length){let G=Z[X];if(!H&&(G==="'"||G==='"'||G==="`")){H=!0,K=G,Y=!0,X++;continue}if(H){if(G===K&&Z[X-1]!=="\\"){if(H=!1,X++,Q===0){let J=X;while(J<Z.length&&/\s/.test(Z[J]))J++;if(Z[J]==="{"){if(!Z.slice(J+1).match(/^\s*(\w+)\s*:/))return z(X)}if(Z[J]!=="|"&&Z[J]!=="&")return z(X)}continue}X++;continue}if(G==="{"||G==="["||G==="("){Q++,Y=!0,X++;continue}if(G==="}"||G==="]"||G===")"){if(Q--,Q===0){X++;let J=X;while(J<Z.length&&/\s/.test(Z[J]))J++;if(Z[J]==="|"||Z[J]==="&")continue;return z(X)}X++;continue}if(Q===0&&G==="{"){if(Y)return z(X);if(Z.slice(X+1).match(/^\s*(\w+)\s*:/)){Q++,Y=!0,X++;continue}return z(X)}if(Q===0&&(G==="|"||G==="&")){if(X++,X<Z.length&&Z[X]==="|")X++;while(X<Z.length&&/\s/.test(Z[X]))X++;continue}if(Q===0&&(/\d/.test(G)||G==="-"&&/\d/.test(Z[X+1]))){let J=X;if(Z[J]==="-")J++;while(J<Z.length&&/\d/.test(Z[J]))J++;if(J<Z.length&&Z[J]==="."&&/\d/.test(Z[J+1])){J++;while(J<Z.length&&/\d/.test(Z[J]))J++}if(J<Z.length&&(Z[J]==="e"||Z[J]==="E")){if(J++,J<Z.length&&(Z[J]==="+"||Z[J]==="-"))J++;while(J<Z.length&&/\d/.test(Z[J]))J++}Y=!0,X=J;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X<Z.length&&Z[X]==="{")return{type:Y0(Z.slice($,J).trim()),endPos:J};if(Z[X]!=="|"&&Z[X]!=="&")return{type:Y0(Z.slice($,J).trim()),endPos:J};continue}if(Q===0&&/[a-zA-Z_]/.test(G)){let J=X;while(J<Z.length&&/\w/.test(Z[J]))J++;Y=!0,X=J;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X<Z.length&&Z[X]==="("){Q++,X++;continue}if(X<Z.length&&Z[X]==="{"){if(!Z.slice(X+1).match(/^\s*(\w+)\s*:/)){let U=J;while(U>$&&/\s/.test(Z[U-1]))U--;return{type:Y0(Z.slice($,U).trim()),endPos:J}}}if(Z[X]!=="|"&&Z[X]!=="&")return{type:Y0(Z.slice($,J).trim()),endPos:J};continue}X++}if(Y)return z(X);return null}function v0(Z){let $=[],X="",Q=0,H=!1,K=!1,Y=0;while(Y<Z.length){let z=Z[Y],G=Z[Y+1];if(!K&&z==="/"&&G==="/"){H=!0,X+="//",Y+=2;continue}if(!H&&z==="/"&&G==="*"){K=!0,X+="/*",Y+=2;continue}if(H&&z===`
6
+ `){H=!1,X+=z,Y++;continue}if(K&&z==="*"&&G==="/"){K=!1,X+="*/",Y+=2;continue}if(H||K){X+=z,Y++;continue}if(z==="("||z==="{"||z==="[")Q++,X+=z;else if(z===")"||z==="}"||z==="]")Q--,X+=z;else if(z===","&&Q===0)$.push(X),X="";else X+=z;Y++}if(X.trim())$.push(X);return $}function k4(Z,$,X){let Q=b0(Z,{originalSource:Z,requiredParams:$.requiredParams,unsafeFunctions:$.unsafeFunctions,safeFunctions:$.safeFunctions}).source,H=v0(Q),K=!1,Y=new Set,z=(J)=>{if(X&&/^\w+$/.test(J)){if(Y.has(J))throw Error(`Duplicate parameter name '${J}'`);Y.add(J)}};return H.map((J)=>{let W=J.trim();if(!W)return J;if(X&&W.startsWith("{")&&W.endsWith("}")){let L=W.slice(1,-1);return`{ ${S6(L,$)} }`}if(X&&W.startsWith("[")&&W.endsWith("]")){let L=W.slice(1,-1);return`[ ${S6(L,$)} ]`}if(W.startsWith("...")){let L=T6(W);if(L!==-1)return W.slice(0,L).trim();return J}let U=W.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(U){let[,L,q]=U;return z(L),K=!0,`${L} = ${q}`}if(!o8(W)){let L=W.match(/^(\w+)\s*=/);if(L)z(L[1]);return K=!0,J}let _=T6(W);if(_!==-1){let L=W.slice(0,_).trim(),q=W.slice(_+1).trim();if(z(L),K&&X&&/^\w+$/.test(L));if(X&&/^\w+$/.test(L))$.requiredParams.add(L);return`${L} = ${q}`}return J}).join(",")}function S6(Z,$){return v0(Z).map((H)=>{let K=H.trim();if(!K)return H;let Y=K.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(Y){let[,J,W]=Y;$.requiredParams.add(J);let U=k0(W);return`${J} = ${U}`}let z=K.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(z){let[,J,W]=z;$.requiredParams.add(J);let U=g0(W);return`${J} = ${U}`}let G=K.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(G){let[,J,W]=G;return $.requiredParams.add(J),`${J} = ${W}`}return H}).join(", ")}function k0(Z){let $=Z.slice(1,-1).trim();return`{ ${v0($).map((H)=>{let K=H.trim();if(!K)return H;let Y=K.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(Y){let[,U,_]=Y;return`${U}: ${k0(_)}`}let z=K.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(z){let[,U,_]=z;return`${U}: ${k0(_)}`}let G=K.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(G){let[,U,_]=G;return`${U}: ${g0(_)}`}let J=K.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(J){let[,U,_]=J;return`${U}: ${g0(_)}`}let W=K.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(W){let[,U,_]=W;return`${U}: ${_}`}return H}).join(", ")} }`}function g0(Z){let $=Z.slice(1,-1).trim();return`[ ${v0($).map((H)=>{let K=H.trim();if(!K)return H;if(K.startsWith("{")&&K.endsWith("}"))return k0(K);if(K.startsWith("[")&&K.endsWith("]"))return g0(K);return H}).join(", ")} ]`}function o8(Z){let $=0,X=!1,Q=!1,H=!1,K="";for(let Y=0;Y<Z.length;Y++){let z=Z[Y];if(!H&&(z==="'"||z==='"'||z==="`")){H=!0,K=z;continue}if(H){if(z===K&&Z[Y-1]!=="\\")H=!1;continue}if(z==="("||z==="{"||z==="[")$++;else if(z===")"||z==="}"||z==="]")$--;else if($===0){if(z===":")X=!0;if(z==="="&&Z[Y+1]!==">")Q=!0}}return X&&!Q}function T6(Z){let $=0,X=!1,Q="";for(let H=0;H<Z.length;H++){let K=Z[H];if(!X&&(K==="'"||K==='"'||K==="`")){X=!0,Q=K;continue}if(X){if(K===Q&&Z[H-1]!=="\\")X=!1;continue}if(K==="("||K==="{"||K==="[")$++;else if(K===")"||K==="}"||K==="]")$--;else if($===0&&K===":")return H}return-1}function s8(Z,$){let X=Z.match($);if(!X)return null;let Q=X.index+X[0].length-1,H=1,K=Q+1;while(K<Z.length&&H>0){if(Z[K]==="{")H++;else if(Z[K]==="}")H--;K++}if(H!==0)return null;let Y=Z.slice(Q,K),z=[X[0].slice(0,-1)+Y,Y];return z.index=X.index,z}function f6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\btry\s*\{/);if(Q){let K=X+Q[0].length-1+1,Y=1,z=K;while(z<Z.length&&Y>0){let J=Z[z];if(J==="{")Y++;else if(J==="}")Y--;z++}if(Y!==0){$+=Z[X],X++;continue}if(Z.slice(z).match(/^\s*(catch|finally)\b/))$+=Z.slice(X,z),X=z;else{let J=Z.slice(K,z-1);$+=`try {${J}} catch (__try_err) { return new (__tjs?.MonadicError ?? Error)(__try_err?.message || String(__try_err), 'try', undefined, undefined, __tjs?.getStack?.()) }`,X=z}}else $+=Z[X],X++}return $}function y6(Z){let $=[],X="",Q=0,H=0;while(Q<Z.length){let K=Z.slice(Q).match(/^\bwasm\s*\{/);if(K){let Y=Q,z=Q+K[0].length,G=1,J=z;while(J<Z.length&&G>0){let P=Z[J];if(P==="{")G++;else if(P==="}")G--;J++}if(G!==0){X+=Z[Q],Q++;continue}let W=Z.slice(z,J-1),U,_=J,L=Z.slice(J).match(/^\s*fallback\s*\{/);if(L){let P=J+L[0].length;G=1;let O=P;while(O<Z.length&&G>0){let k=Z[O];if(k==="{")G++;else if(k==="}")G--;O++}if(G===0)U=Z.slice(P,O-1),_=O}let A=r8(W).map((P)=>{let O=t8(Z,Y,P);return O?`${P}: ${O}`:P}),B={id:`__tjs_wasm_${H}`,body:W,fallback:U,captures:A,start:Y,end:_};$.push(B);let M=U??W,F=A.map((P)=>P.split(":")[0].trim()),R=F.length>0?F.join(", "):"",w=F.length>0?`globalThis.${B.id}(${R})`:`globalThis.${B.id}()`,C=`(globalThis.${B.id} ? ${w} : (() => {${M}})())`;X+=C,Q=_,H++}else X+=Z[Q],Q++}return{source:X,blocks:$}}function a8(Z){return Z.startsWith("f32x4_")||Z.startsWith("v128_")}function r8(Z){let $=Z.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),X=new Set,Q=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,H;while((H=Q.exec($))!==null)X.add(H[1]);let K=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,Y=new Set;while((H=K.exec($))!==null)Y.add(H[1]);for(let _ of X){if(!Y.has(_))continue;let L=new RegExp(`(?<!\\.)\\b${_}\\b`,"g"),q=new RegExp(`\\.${_}\\b`,"g"),A=$.match(L)?.length||0,B=$.match(q)?.length||0;if(A<=B)Y.delete(_)}let z=new Set,G=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((H=G.exec($))!==null)z.add(H[1]);let J=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((H=J.exec($))!==null)z.add(H[1]);let W=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"]),U=[];for(let _ of Y)if(!z.has(_)&&!W.has(_)&&!a8(_))U.push(_);return U.sort()}function t8(Z,$,X){let Q=Z.slice(0,$),H=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,K=Q.match(H);if(!K){let Y=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,z=Q.match(Y);if(!z)return;return g6(z[1],X)}return g6(K[1],X)}function g6(Z,$){let X=Z.split(",").map((Q)=>Q.trim());for(let Q of X){let H=Q.match(new RegExp(`^${$}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(H)return H[1];let K=Q.match(new RegExp(`^${$}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(K)return K[1]}return}function h6(Z){let X=new RegExp(`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")\\s+IsNot\\s+([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,"g");Z=Z.replace(X,"IsNot($1, $2)");let Q=new RegExp(`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")\\s+Is\\s+([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,"g");return Z=Z.replace(Q,"Is($1, $2)"),Z}function x6(Z){let $=/^[\s]*[([/+\-`]/,X=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,Q=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,H=Z.split(`
7
+ `),K=[];for(let Y=0;Y<H.length;Y++){let z=H[Y],G=Y>0?H[Y-1]:"";if(Y>0&&$.test(z)){let J=G.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!X.test(J)&&!Q.test(J)){let W=z.match(/^(\s*)/),U=W?W[1]:"",_=z.slice(U.length);K.push(U+";"+_);continue}}K.push(z)}return K.join(`
8
+ `)}function u6(Z){Z=Z.replace(/\btypeof\s+([a-zA-Z_$][\w$.]*(?:\?\.[\w$]+)*)/g,"TypeOf($1)");let $=[],X=0,Q="normal",H=[];while(X<Z.length){let Y=Z[X],z=Z[X+1];switch(Q){case"single-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="'")Q="normal";X++;continue;case"double-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==='"')Q="normal";X++;continue;case"template-string":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="$"&&z==="{"){X+=2,H.push(1),Q="normal";continue}if(Y==="`")Q="normal";X++;continue;case"line-comment":if(Y===`
9
+ `)Q="normal";X++;continue;case"block-comment":if(Y==="*"&&z==="/"){X+=2,Q="normal";continue}X++;continue;case"regex":if(Y==="\\"&&X+1<Z.length){X+=2;continue}if(Y==="["){X++;while(X<Z.length&&Z[X]!=="]")if(Z[X]==="\\"&&X+1<Z.length)X+=2;else X++;if(X<Z.length)X++;continue}if(Y==="/"){X++;while(X<Z.length&&/[gimsuy]/.test(Z[X]))X++;Q="normal";continue}X++;continue;case"normal":if(H.length>0){if(Y==="{")H[H.length-1]++;else if(Y==="}"){if(H[H.length-1]--,H[H.length-1]===0){H.pop(),X++,Q="template-string";continue}}}if(Y==="'"){X++,Q="single-string";continue}if(Y==='"'){X++,Q="double-string";continue}if(Y==="`"){X++,Q="template-string";continue}if(Y==="/"&&z==="/"){X+=2,Q="line-comment";continue}if(Y==="/"&&z==="*"){X+=2,Q="block-comment";continue}if(Y==="/"){let G=X-1;while(G>=0&&/\s/.test(Z[G]))G--;let J=G>=0?Z[G]:"";if(!J||/[=(!,;:{[&|?+\-*%<>~^]/.test(J)||G>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(Z.slice(Math.max(0,G-10),G+1))){X++,Q="regex";continue}}if(Y==="="&&z==="="&&Z[X+2]!=="="&&Z[X-1]!=="!"){$.push({pos:X,op:"=="}),X+=2;continue}if(Y==="!"&&z==="="&&Z[X+2]!=="="){$.push({pos:X,op:"!="}),X+=2;continue}break}X++}if($.length===0)return Z;let K=Z;for(let Y=$.length-1;Y>=0;Y--){let{pos:z,op:G}=$[Y],J=G==="=="?"Eq":"NotEq",W=e8(K,z),U=ZZ(K,z+2),_=K.slice(W,z).trim(),L=K.slice(z+2,U).trim();if(_&&L){let q=K.slice(0,W),A=K.slice(U),M=/[a-zA-Z0-9_$]$/.test(q)?" ":"";K=`${q}${M}${J}(${_}, ${L})${A}`}}return K}function e8(Z,$){let X=$-1;while(X>=0&&/\s/.test(Z[X]))X--;if(X<0)return 0;let Q=0,H=!1,K="";while(X>=0){let Y=Z[X],z=X>0?Z[X-1]:"";if(H){if(Y===K&&z!=="\\")H=!1;X--;continue}if((Y==='"'||Y==="'"||Y==="`")&&z!=="\\"){H=!0,K=Y,X--;continue}if(Y===")"||Y==="]"||Y==="}"){Q++,X--;continue}if(Y==="("||Y==="["){if(Q>0){Q--,X--;continue}return X+1}if(Y==="{"){if(Q>0){Q--,X--;continue}return X+1}if(Q>0){X--;continue}if(Y===";")return X+1;if(/[a-z]/.test(Y)){let G=X+1,J=X;while(J>0&&/[a-z]/i.test(Z[J-1]))J--;let W=Z.slice(J,G),U=J>0?Z[J-1]:"";if(!/[a-zA-Z0-9_$]/.test(U)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(W))return G;if(W==="new")return J}}if(Y===">"&&z==="=")return X+1;if(Y==="="&&z!=="="&&z!=="!"&&z!=="<"&&z!==">")return X+1;if(Y==="&"&&z==="&")return X+1;if(Y==="|"&&z==="|")return X+1;if(Y==="?"||Y===":")return X+1;if(Y===",")return X+1;X--}return 0}function ZZ(Z,$){let X=$;while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)return Z.length;let Q=0,H=!1,K="";while(X<Z.length){let Y=Z[X],z=X+1<Z.length?Z[X+1]:"";if(H){if(Y===K&&Z[X-1]!=="\\")H=!1;X++;continue}if((Y==='"'||Y==="'"||Y==="`")&&Z[X-1]!=="\\"){H=!0,K=Y,X++;continue}if(Y==="("||Y==="["||Y==="{"){Q++,X++;continue}if(Y===")"||Y==="]"||Y==="}"){if(Q>0){Q--,X++;continue}return X}if(Q>0){X++;continue}if(Y===";")return X;if(Y==="&"&&z==="&")return X;if(Y==="|"&&z==="|")return X;if(Y==="?")return X;if(Y===":")return X;if(Y===",")return X;if((Y==="="||Y==="!")&&z==="="&&Z[X+2]!=="=")return X;X++}return Z.length}function d6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(Q){let H=Q[1],K=X+Q[0].length,Y=H,z=!1,G=Z.slice(K).match(/^(['"`])([^]*?)\1\s*/);if(G){let _=K+G[0].length,L=Z[_],q=L===void 0||_>=Z.length||L!=="="&&L!=="{";if(L==="="||L==="{")Y=G[2],z=!0,K=_;else if(q){let A=G[0].trim(),B=G[0].slice(A.length);$+=`const ${H} = Type('${H}', ${A})${B}`,X=_;continue}}let J,W=K,U=Z.slice(K).match(/^=\s*/);if(U){K+=U[0].length;let _=Z.slice(K).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(_){J=_[0],K+=_[0].length,W=K;let L=Z.slice(K).match(/^\s*/);if(L)K+=L[0].length}}if(Z[K]==="{"){let _=K+1,L=1,q=_;while(q<Z.length&&L>0){let C=Z[q];if(C==="{")L++;else if(C==="}")L--;q++}if(L!==0){$+=Z[X],X++;continue}let A=Z.slice(_,q-1).trim(),B=q,M=A.match(/description\s*:\s*(['"`])([^]*?)\1/);if(M&&!z)Y=M[2];let F,R=A.match(/example\s*:\s*/);if(R){let C=R.index+R[0].length,P=k6(A,C);if(P)F=P.value.trim()}let w=A.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(w&&F){let C=w[1].trim(),P=w[2].trim(),O=J?`, ${J}`:"";$+=`const ${H} = Type('${Y}', (${C}) => { if (!globalThis.__tjs?.validate(${C}, globalThis.__tjs?.infer(${F}))) return false; ${P} }, ${F}${O})`}else if(w){let C=w[1].trim(),P=w[2].trim(),O=J?`, undefined, ${J}`:"";$+=`const ${H} = Type('${Y}', (${C}) => { ${P} }${O})`}else if(F){let C=J?`, ${J}`:"";$+=`const ${H} = Type('${Y}', undefined, ${F}${C})`}else if(J)$+=`const ${H} = Type('${Y}', ${J})`;else $+=`const ${H} = Type('${Y}')`;X=B;continue}else if(J){$+=`const ${H} = Type('${Y}', ${J})`,X=W;continue}else if(!G){let _=Z.slice(K).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(_){let L=_[0];$+=`const ${H} = Type('${H}', ${L})`,X=K+_[0].length;continue}}}$+=Z[X],X++}return $}function l6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bFunctionPredicate\s+([A-Z_][a-zA-Z0-9_]*)\s*(?:<([^>]+)>)?\s*/);if(Q){let H=Q[1],K=Q[2],Y=X+Q[0].length;if(Z[Y]==="{"){let z=1,G=Y+1;while(G<Z.length&&z>0){if(Z[G]==="{")z++;else if(Z[G]==="}")z--;G++}if(z===0){let J=Z.slice(Y+1,G-1).trim(),W=s8(J,/params\s*:\s*\{/),U=J.match(/returns\s*:\s*(.+?)(?:\n|$)/),_=J.match(/returnContract\s*:\s*['"](\w+)['"]/),L=J.match(/description\s*:\s*(['"])([^]*?)\1/),q=[];if(W)q.push(`params: ${W[1]}`);if(U)q.push(`returns: ${U[1].trim()}`);if(_)q.push(`returnContract: '${_[1]}'`);let A=L?L[2]:H;if(K){let B=K.split(",").map((F)=>{let R=F.trim().split("=").map((w)=>w.trim());if(R.length===2){let w=R[1]==="any"||R[1]==="undefined"?"null":R[1];return`['${R[0]}', ${w}]`}return`'${R[0]}'`}),M=K.split(",").map((F)=>F.trim().split("=")[0].trim());$+=`const ${H} = FunctionPredicate('${A}', [${B.join(", ")}], (${M.join(", ")}) => ({ ${q.join(", ")} }))`}else $+=`const ${H} = FunctionPredicate('${A}', { ${q.join(", ")} })`;X=G;continue}}if(Z[Y]==="("){let z=1,G=Y+1;while(G<Z.length&&z>0){if(Z[G]==="(")z++;else if(Z[G]===")")z--;G++}if(z===0){let J=Z.slice(Y+1,G-1).trim(),W=J.indexOf(",");if(W!==-1){let U=J.slice(0,W).trim(),_=J.slice(W+1).trim();$+=`const ${H} = FunctionPredicate(${_}, ${U})`}else $+=`const ${H} = FunctionPredicate('${H}', ${J})`;X=G;continue}}}$+=Z[X],X++}return $}function m6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(Q){let H=Q[1],K=Q[2],z=X+Q[0].length-1+1,G=1,J=z;while(J<Z.length&&G>0){let F=Z[J];if(F==="{")G++;else if(F==="}")G--;J++}if(G!==0){$+=Z[X],X++;continue}let W=Z.slice(z,J-1).trim(),U=J,_=K.split(",").map((F)=>{let R=F.trim().split("=").map((w)=>w.trim());if(R.length===2){let w=R[1]==="any"||R[1]==="undefined"?"null":R[1];return`['${R[0]}', ${w}]`}return`'${R[0]}'`}),L=W,q=L.search(/\bdeclaration\s*\{/);if(q!==-1){let F=L.indexOf("{",q),R=1,w=F+1;while(w<L.length&&R>0){if(L[w]==="{")R++;else if(L[w]==="}")R--;w++}L=L.slice(0,q)+L.slice(w)}let A=L.match(/description\s*:\s*(['"`])([^]*?)\1/),B=L.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),M=A?A[2]:H;if(B){let F=B[1].trim().split(",").map((O)=>O.trim()),R=B[2].trim(),w=F[0]||"x",C=F.slice(1),P=C.map((O)=>`check${O}`);C.forEach((O,k)=>{R=R.replace(new RegExp(`\\b${O}\\s*\\(`,"g"),`${P[k]}(`)}),$+=`const ${H} = Generic([${_.join(", ")}], (${w}, ${P.join(", ")}) => { ${R} }, '${M}')`}else $+=`const ${H} = Generic([${_.join(", ")}], () => true, '${M}')`;X=U;continue}$+=Z[X],X++}return $}function i6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(Q){let H=Q[1],K=Q[3],Y=X+Q[0].length;if(Z[Y]==="{"){let z=Y+1,G=1,J=z;while(J<Z.length&&G>0){let L=Z[J];if(L==="{")G++;else if(L==="}")G--;J++}if(G!==0){$+=Z[X],X++;continue}let W=Z.slice(z,J-1).trim(),U=J,_=b6(W);$+=`const ${H} = Union('${K}', [${_.join(", ")}])`,X=U;continue}else{let z=Z.indexOf(`
10
+ `,Y);if(z===-1)z=Z.length;let G=Z.slice(Y,z).trim();if(G){let J=b6(G);$+=`const ${H} = Union('${K}', [${J.join(", ")}])`,X=z;continue}}}$+=Z[X],X++}return $}function b6(Z){let $=[],X=Z.split("|").map((Q)=>Q.trim());for(let Q of X){if(!Q)continue;$.push(Q)}return $}function p6(Z){let $="",X=0;while(X<Z.length){let Q=Z.slice(X).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(Q){let H=Q[1],K=Q[3],z=X+Q[0].length-1+1,G=1,J=z;while(J<Z.length&&G>0){let q=Z[J];if(q==="{")G++;else if(q==="}")G--;J++}if(G!==0){$+=Z[X],X++;continue}let W=Z.slice(z,J-1).trim(),U=J,L=$Z(W).map(([q,A])=>`${q}: ${A}`).join(", ");$+=`const ${H} = Enum('${K}', { ${L} })`,X=U;continue}$+=Z[X],X++}return $}function $Z(Z){let $=[],X=0,Q=Z.split(/[\n,]/).map((H)=>H.trim()).filter((H)=>H&&!H.startsWith("//"));for(let H of Q){let K=H.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(K){let Y=K[1],z=K[2]?.trim();if(z!==void 0){$.push([Y,z]);let G=Number(z);if(!isNaN(G))X=G+1}else $.push([Y,String(X)]),X++}}return $}function n6(Z){let $=new Map,X="",Q=0;while(Q<Z.length){let H=Z.slice(Q),K=H.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/);if(!K){if(Q===0||Z[Q-1]===`
11
+ `||Z[Q-1]===";"||Z[Q-1]==="}"){let R=H.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/)}X+=Z[Q],Q++;continue}let Y=K[1],z=K[2],G=Q+K[0].length-1,J=G0(Z,G),W=Z.slice(G+1,J-1).trim(),U=[],_=0,L=Z.slice(G+1,J-1);while(_<L.length){let R=L.slice(_).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!R){_++;continue}let w=R[1],C=!!R[2],P=R[3],O=_+R[0].length-1,k=1,V=O+1;while(V<L.length&&k>0){if(L[V]==="(")k++;if(L[V]===")")k--;V++}let T=L.slice(O+1,V-1),N=V;while(N<L.length&&/\s/.test(L[N]))N++;if(L[N]==="="&&L[N+1]===">"){let X1=z0(Z,G+1+_);throw new z1(`Arrow functions are not allowed in extend blocks (method '${P}' in extend ${z}). Use regular function syntax instead, as extension methods need 'this' binding.`,X1)}if(L[N]!=="{"){_++;continue}let g=G0(L,N),b=L.slice(_,g).trim(),y=T.split(",").map((X1)=>X1.trim()).filter((X1)=>X1.length>0).map((X1)=>{let b1=X1.match(/^(\w+)\s*:\s*(.+)$/);if(b1)return`${b1[1]} = ${b1[2]}`;return X1}).join(", "),n=C?"async ":"",m=L.slice(N+1,g-1);U.push({name:P,isAsync:C,fullText:`${P}: ${n}function(${y}) {${m}}`}),_=g}let q=!$.has(z);if(q)$.set(z,new Set);let A=$.get(z);for(let F of U)A.add(F.name);let B=U.map((F)=>` ${F.fullText}`).join(`,
12
12
  `),M;if(q)M=`${Y}const __ext_${z} = {
13
13
  ${B}
14
14
  ${Y}}
15
15
  `;else M=`${Y}Object.assign(__ext_${z}, {
16
16
  ${B}
17
17
  ${Y}})
18
- `;for(let F of L)M+=`${Y}if (__tjs?.registerExtension) { __tjs.registerExtension('${z}', '${F.name}', __ext_${z}.${F.name}) }
19
- `;X+=M,Q=J}if(Q<=Z.length&&X.length<Z.length);return{source:X,extensions:$}}function J0(Z,$){if($.size===0)return Z;let X=new Map;for(let[H,K]of $)for(let Y of K){if(!X.has(Y))X.set(Y,[]);X.get(Y).push(H)}let Q=Z;for(let[H,K]of X){if(!K.includes("String"))continue;let Y=new RegExp(`('(?:[^'\\\\]|\\\\.)*')\\.(${H})\\((\\))?`,"g");Q=Q.replace(Y,(J,W,L,_)=>{return _?`__ext_String.${L}.call(${W})`:`__ext_String.${L}.call(${W}, `});let z=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${H})\\((\\))?`,"g");Q=Q.replace(z,(J,W,L,_)=>{return _?`__ext_String.${L}.call(${W})`:`__ext_String.${L}.call(${W}, `});let G=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+H+"\\((\\))?","g");Q=Q.replace(G,(J,W,L)=>{return L?`__ext_String.${H}.call(${W})`:`__ext_String.${H}.call(${W}, `})}for(let[H,K]of X){if(!K.includes("Array"))continue;let Y=`].${H}(`,z=0,G;while((G=Q.indexOf(Y,z))!==-1){let J=1,W=G-1,L=!1;while(W>=0&&J>0){let _=Q[W];if(L){if(_===L&&(W===0||Q[W-1]!=="\\"))L=!1}else{if(_==="]")J++;if(_==="[")J--;if(_==="'"||_==='"'||_==="`")L=_}W--}if(J===0){let _=Q.slice(W+1,G+1),U=Q.slice(0,W+1),q=Q.slice(G+Y.length);if(q[0]===")")Q=`${U}__ext_Array.${H}.call(${_})${q.slice(1)}`;else Q=`${U}__ext_Array.${H}.call(${_}, ${q}`}z=G+1}}for(let[H,K]of X){if(!K.includes("Number"))continue;let Y=new RegExp(`(\\d+(?:\\.\\d+)?)\\.(${H})\\((\\))?`,"g");Q=Q.replace(Y,(z,G,J,W)=>{return W?`__ext_Number.${J}.call(${G})`:`__ext_Number.${J}.call(${G}, `})}return Q}function z0(Z,$){let X=1,Q=0;for(let H=0;H<$&&H<Z.length;H++)if(Z[H]===`
20
- `)X++,Q=0;else Q++;return{line:X,column:Q}}function n6(Z,$){let X=$.trim();if(/^['"`]/.test(X))return`typeof ${Z} === 'string'`;if(X==="true"||X==="false")return`typeof ${Z} === 'boolean'`;if(X==="null")return`${Z} === null`;if(X==="undefined")return`${Z} === undefined`;if(X.startsWith("["))return`Array.isArray(${Z})`;if(X.startsWith("{"))return`(typeof ${Z} === 'object' && ${Z} !== null && !Array.isArray(${Z}))`;if(/^\+\d+/.test(X))return`(typeof ${Z} === 'number' && Number.isInteger(${Z}) && ${Z} >= 0)`;if(/^-?\d+\.\d+/.test(X))return`typeof ${Z} === 'number'`;if(/^-?\d+$/.test(X))return`(typeof ${Z} === 'number' && Number.isInteger(${Z}))`;return"true"}function f0(Z){let $=Z.trim();if(/^['"`]/.test($))return"string";if($==="true"||$==="false")return"boolean";if($==="null")return"null";if($==="undefined")return"undefined";if($.startsWith("["))return"array";if($.startsWith("{"))return"object";if(/^\+\d+/.test($))return"non-negative-integer";if(/^-?\d+\.\d+/.test($))return"number";if(/^-?\d+$/.test($))return"integer";return"any"}function k4(Z,$){let X=[],Q=0,H="",K=!1;for(let z=0;z<Z.length;z++){let G=Z[z];if(!K&&(G==="'"||G==='"'||G==="`")){K=G,H+=G;continue}if(K){if(H+=G,G==="\\"){if(z++,z<Z.length)H+=Z[z];continue}if(G===K)K=!1;continue}if(G==="("||G==="["||G==="{"){Q++,H+=G;continue}if(G===")"||G==="]"||G==="}"){Q--,H+=G;continue}if(G===","&&Q===0){let J=b6(H.trim(),$);if(J)X.push(J);H="";continue}H+=G}let Y=H.trim();if(Y){let z=b6(Y,$);if(z)X.push(z)}return X}function b6(Z,$){let X=Z.replace(/^\/\*\s*unsafe\s*\*\/\s*/,"");if(X.startsWith("..."))return null;let Q=X.indexOf("=");if(Q===-1)return{name:X.trim(),defaultValue:"",required:!0};let H=X.slice(0,Q).trim(),K=X.slice(Q+1).trim();return{name:H,defaultValue:K,required:$.has(H)}}function G0(Z,$){let X=1,Q=$+1,H=!1,K=!1,Y=!1;while(Q<Z.length&&X>0){let z=Z[Q],G=Q+1<Z.length?Z[Q+1]:"";if(K){if(z===`
21
- `)K=!1;Q++;continue}if(Y){if(z==="*"&&G==="/"){Y=!1,Q+=2;continue}Q++;continue}if(H){if(z==="\\"){Q+=2;continue}if(z===H)H=!1;Q++;continue}if(z==="/"&&G==="/"){K=!0,Q+=2;continue}if(z==="/"&&G==="*"){Y=!0,Q+=2;continue}if(z==="'"||z==='"'||z==="`"){H=z,Q++;continue}if(z==="{")X++;if(z==="}")X--;Q++}return Q}function c6(Z,$){let X=new Set,Q=/(?:^|(?<=[\n;{}]))\s*(export\s+)?(async\s+)?function\s+(\w+)\s*\(/gm,H=new Map,K,Y=[];while((K=Q.exec(Z))!==null){let L=!!K[1],_=!!K[2],U=K[3],q=K.index,A=q,M=K[0].indexOf("function");if(M>=0)A=q+M;Y.push({name:U,fullMatchStart:q,funcKeywordStart:A,exported:L,isAsync:_})}for(let L of Y)if(!H.has(L.name))H.set(L.name,[]);let z=new Map;for(let L of Y)z.set(L.name,(z.get(L.name)||0)+1);let G=new Set;for(let[L,_]of z)if(_>1)G.add(L);if(G.size===0)return{source:Z,polymorphicNames:X};for(let L of Y){if(!G.has(L.name))continue;let _=Z.indexOf("(",L.funcKeywordStart);if(_===-1)continue;let U=1,q=_+1;while(q<Z.length&&U>0){if(Z[q]==="(")U++;if(Z[q]===")")U--;q++}let A=q-1,B=Z.slice(_+1,A),M=q;while(M<Z.length&&Z[M]!=="{")M++;if(M>=Z.length)continue;let F=G0(Z,M),R=L.fullMatchStart;while(R>0&&Z[R-1]===" ")R--;let w=H.get(L.name),C=k4(B,$);if(B.includes("...")){let O=z0(Z,L.funcKeywordStart);throw new z1(`Rest parameters are not supported in polymorphic function '${L.name}'. Use separate function names instead.`,O)}w.push({index:w.length+1,start:R,end:F,text:Z.slice(R,F),exported:L.exported,isAsync:L.isAsync,params:C})}for(let[L,_]of H){if(_.length<2)continue;let U=_.filter((q)=>q.isAsync).length;if(U>0&&U<_.length){let q=z0(Z,_[0].start);throw new z1(`Polymorphic function '${L}': all variants must be either sync or async, not mixed.`,q)}for(let q=0;q<_.length;q++)for(let A=q+1;A<_.length;A++){let B=_[q],M=_[A];if(B.params.length!==M.params.length)continue;let F=!0;for(let R=0;R<B.params.length;R++){let w=B.params[R].defaultValue?f0(B.params[R].defaultValue):"any",C=M.params[R].defaultValue?f0(M.params[R].defaultValue):"any";if(w!==C){F=!1;break}}if(F){let R=z0(Z,M.start);throw new z1(`Polymorphic function '${L}': variants ${q+1} and ${A+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,R)}}}let J=[];for(let[L,_]of H){if(_.length<2)continue;for(let U of _)J.push({name:L,variant:U})}J.sort((L,_)=>_.variant.start-L.variant.start);let W=Z;for(let{name:L,variant:_}of J){let U=_.isAsync?"async ":"",q=_.text.replace(new RegExp(`(?:export\\s+)?${U?U.replace(/\s+$/,"\\s+"):""}function\\s+${L}\\s*\\(`),`${U}function ${L}$$${_.index}(`);W=W.slice(0,_.start)+q+W.slice(_.end)}for(let[L,_]of H){if(_.length<2)continue;X.add(L);let U=_[0].isAsync,q=_.some((w)=>w.exported),A=U?"async ":"",B=q?"export ":"",M=[..._].sort((w,C)=>{if(w.params.length!==C.params.length)return 0;let P=0,O=0;for(let k of w.params){let V=k.defaultValue?f0(k.defaultValue):"any";if(V==="non-negative-integer")P+=3;else if(V==="integer")P+=2;else if(V!=="any")P+=1}for(let k of C.params){let V=k.defaultValue?f0(k.defaultValue):"any";if(V==="non-negative-integer")O+=3;else if(V==="integer")O+=2;else if(V!=="any")O+=1}return O-P}),F=[];for(let w of M){let C=[`__args.length === ${w.params.length}`],P=[];for(let O=0;O<w.params.length;O++){let k=w.params[O];if(P.push(`__args[${O}]`),k.defaultValue){let V=n6(`__args[${O}]`,k.defaultValue);if(V!=="true")C.push(V)}}F.push(` if (${C.join(" && ")}) return ${L}$${w.index}(${P.join(", ")})`)}let R=`
22
- ${B}${A}function ${L}(...__args) {
18
+ `;for(let F of U)M+=`${Y}if (__tjs?.registerExtension) { __tjs.registerExtension('${z}', '${F.name}', __ext_${z}.${F.name}) }
19
+ `;X+=M,Q=J}if(Q<=Z.length&&X.length<Z.length);return{source:X,extensions:$}}function J0(Z,$){if($.size===0)return Z;let X=new Map;for(let[H,K]of $)for(let Y of K){if(!X.has(Y))X.set(Y,[]);X.get(Y).push(H)}let Q=Z;for(let[H,K]of X){if(!K.includes("String"))continue;let Y=new RegExp(`('(?:[^'\\\\]|\\\\.)*')\\.(${H})\\((\\))?`,"g");Q=Q.replace(Y,(J,W,U,_)=>{return _?`__ext_String.${U}.call(${W})`:`__ext_String.${U}.call(${W}, `});let z=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${H})\\((\\))?`,"g");Q=Q.replace(z,(J,W,U,_)=>{return _?`__ext_String.${U}.call(${W})`:`__ext_String.${U}.call(${W}, `});let G=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+H+"\\((\\))?","g");Q=Q.replace(G,(J,W,U)=>{return U?`__ext_String.${H}.call(${W})`:`__ext_String.${H}.call(${W}, `})}for(let[H,K]of X){if(!K.includes("Array"))continue;let Y=`].${H}(`,z=0,G;while((G=Q.indexOf(Y,z))!==-1){let J=1,W=G-1,U=!1;while(W>=0&&J>0){let _=Q[W];if(U){if(_===U&&(W===0||Q[W-1]!=="\\"))U=!1}else{if(_==="]")J++;if(_==="[")J--;if(_==="'"||_==='"'||_==="`")U=_}W--}if(J===0){let _=Q.slice(W+1,G+1),L=Q.slice(0,W+1),q=Q.slice(G+Y.length);if(q[0]===")")Q=`${L}__ext_Array.${H}.call(${_})${q.slice(1)}`;else Q=`${L}__ext_Array.${H}.call(${_}, ${q}`}z=G+1}}for(let[H,K]of X){if(!K.includes("Number"))continue;let Y=new RegExp(`(\\d+(?:\\.\\d+)?)\\.(${H})\\((\\))?`,"g");Q=Q.replace(Y,(z,G,J,W)=>{return W?`__ext_Number.${J}.call(${G})`:`__ext_Number.${J}.call(${G}, `})}return Q}function z0(Z,$){let X=1,Q=0;for(let H=0;H<$&&H<Z.length;H++)if(Z[H]===`
20
+ `)X++,Q=0;else Q++;return{line:X,column:Q}}function c6(Z,$){let X=$.trim();if(/^['"`]/.test(X))return`typeof ${Z} === 'string'`;if(X==="true"||X==="false")return`typeof ${Z} === 'boolean'`;if(X==="null")return`${Z} === null`;if(X==="undefined")return`${Z} === undefined`;if(X.startsWith("["))return`Array.isArray(${Z})`;if(X.startsWith("{"))return`(typeof ${Z} === 'object' && ${Z} !== null && !Array.isArray(${Z}))`;if(/^\+\d+/.test(X))return`(typeof ${Z} === 'number' && Number.isInteger(${Z}) && ${Z} >= 0)`;if(/^-?\d+\.\d+/.test(X))return`typeof ${Z} === 'number'`;if(/^-?\d+$/.test(X))return`(typeof ${Z} === 'number' && Number.isInteger(${Z}))`;return"true"}function f0(Z){let $=Z.trim();if(/^['"`]/.test($))return"string";if($==="true"||$==="false")return"boolean";if($==="null")return"null";if($==="undefined")return"undefined";if($.startsWith("["))return"array";if($.startsWith("{"))return"object";if(/^\+\d+/.test($))return"non-negative-integer";if(/^-?\d+\.\d+/.test($))return"number";if(/^-?\d+$/.test($))return"integer";return"any"}function g4(Z,$){let X=[],Q=0,H="",K=!1;for(let z=0;z<Z.length;z++){let G=Z[z];if(!K&&(G==="'"||G==='"'||G==="`")){K=G,H+=G;continue}if(K){if(H+=G,G==="\\"){if(z++,z<Z.length)H+=Z[z];continue}if(G===K)K=!1;continue}if(G==="("||G==="["||G==="{"){Q++,H+=G;continue}if(G===")"||G==="]"||G==="}"){Q--,H+=G;continue}if(G===","&&Q===0){let J=v6(H.trim(),$);if(J)X.push(J);H="";continue}H+=G}let Y=H.trim();if(Y){let z=v6(Y,$);if(z)X.push(z)}return X}function v6(Z,$){let X=Z.replace(/^\/\*\s*unsafe\s*\*\/\s*/,"");if(X.startsWith("..."))return null;let Q=X.indexOf("=");if(Q===-1)return{name:X.trim(),defaultValue:"",required:!0};let H=X.slice(0,Q).trim(),K=X.slice(Q+1).trim();return{name:H,defaultValue:K,required:$.has(H)}}function G0(Z,$){let X=1,Q=$+1,H=!1,K=!1,Y=!1;while(Q<Z.length&&X>0){let z=Z[Q],G=Q+1<Z.length?Z[Q+1]:"";if(K){if(z===`
21
+ `)K=!1;Q++;continue}if(Y){if(z==="*"&&G==="/"){Y=!1,Q+=2;continue}Q++;continue}if(H){if(z==="\\"){Q+=2;continue}if(z===H)H=!1;Q++;continue}if(z==="/"&&G==="/"){K=!0,Q+=2;continue}if(z==="/"&&G==="*"){Y=!0,Q+=2;continue}if(z==="'"||z==='"'||z==="`"){H=z,Q++;continue}if(z==="{")X++;if(z==="}")X--;Q++}return Q}function o6(Z,$){let X=new Set,Q=/(?:^|(?<=[\n;{}]))\s*(export\s+)?(async\s+)?function\s+(\w+)\s*\(/gm,H=new Map,K,Y=[];while((K=Q.exec(Z))!==null){let U=!!K[1],_=!!K[2],L=K[3],q=K.index,A=q,M=K[0].indexOf("function");if(M>=0)A=q+M;Y.push({name:L,fullMatchStart:q,funcKeywordStart:A,exported:U,isAsync:_})}for(let U of Y)if(!H.has(U.name))H.set(U.name,[]);let z=new Map;for(let U of Y)z.set(U.name,(z.get(U.name)||0)+1);let G=new Set;for(let[U,_]of z)if(_>1)G.add(U);if(G.size===0)return{source:Z,polymorphicNames:X};for(let U of Y){if(!G.has(U.name))continue;let _=Z.indexOf("(",U.funcKeywordStart);if(_===-1)continue;let L=1,q=_+1;while(q<Z.length&&L>0){if(Z[q]==="(")L++;if(Z[q]===")")L--;q++}let A=q-1,B=Z.slice(_+1,A),M=q;while(M<Z.length&&Z[M]!=="{")M++;if(M>=Z.length)continue;let F=G0(Z,M),R=U.fullMatchStart;while(R>0&&Z[R-1]===" ")R--;let w=H.get(U.name),C=g4(B,$);if(B.includes("...")){let O=z0(Z,U.funcKeywordStart);throw new z1(`Rest parameters are not supported in polymorphic function '${U.name}'. Use separate function names instead.`,O)}w.push({index:w.length+1,start:R,end:F,text:Z.slice(R,F),exported:U.exported,isAsync:U.isAsync,params:C})}for(let[U,_]of H){if(_.length<2)continue;let L=_.filter((q)=>q.isAsync).length;if(L>0&&L<_.length){let q=z0(Z,_[0].start);throw new z1(`Polymorphic function '${U}': all variants must be either sync or async, not mixed.`,q)}for(let q=0;q<_.length;q++)for(let A=q+1;A<_.length;A++){let B=_[q],M=_[A];if(B.params.length!==M.params.length)continue;let F=!0;for(let R=0;R<B.params.length;R++){let w=B.params[R].defaultValue?f0(B.params[R].defaultValue):"any",C=M.params[R].defaultValue?f0(M.params[R].defaultValue):"any";if(w!==C){F=!1;break}}if(F){let R=z0(Z,M.start);throw new z1(`Polymorphic function '${U}': variants ${q+1} and ${A+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,R)}}}let J=[];for(let[U,_]of H){if(_.length<2)continue;for(let L of _)J.push({name:U,variant:L})}J.sort((U,_)=>_.variant.start-U.variant.start);let W=Z;for(let{name:U,variant:_}of J){let L=_.isAsync?"async ":"",q=_.text.replace(new RegExp(`(?:export\\s+)?${L?L.replace(/\s+$/,"\\s+"):""}function\\s+${U}\\s*\\(`),`${L}function ${U}$$${_.index}(`);W=W.slice(0,_.start)+q+W.slice(_.end)}for(let[U,_]of H){if(_.length<2)continue;X.add(U);let L=_[0].isAsync,q=_.some((w)=>w.exported),A=L?"async ":"",B=q?"export ":"",M=[..._].sort((w,C)=>{if(w.params.length!==C.params.length)return 0;let P=0,O=0;for(let k of w.params){let V=k.defaultValue?f0(k.defaultValue):"any";if(V==="non-negative-integer")P+=3;else if(V==="integer")P+=2;else if(V!=="any")P+=1}for(let k of C.params){let V=k.defaultValue?f0(k.defaultValue):"any";if(V==="non-negative-integer")O+=3;else if(V==="integer")O+=2;else if(V!=="any")O+=1}return O-P}),F=[];for(let w of M){let C=[`__args.length === ${w.params.length}`],P=[];for(let O=0;O<w.params.length;O++){let k=w.params[O];if(P.push(`__args[${O}]`),k.defaultValue){let V=c6(`__args[${O}]`,k.defaultValue);if(V!=="true")C.push(V)}}F.push(` if (${C.join(" && ")}) return ${U}$${w.index}(${P.join(", ")})`)}let R=`
22
+ ${B}${A}function ${U}(...__args) {
23
23
  ${F.join(`
24
24
  `)}
25
- return __tjs.typeError('${L}', 'no matching overload', __args)
25
+ return __tjs.typeError('${U}', 'no matching overload', __args)
26
26
  }
27
- `;W+=R}return{source:W,polymorphicNames:X}}function o6(Z){return Z.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,($,X)=>{return $.replace(X,`const ${X}`)})}function s6(Z,$=!1){let X=[],Q=[],H="",K=0;while(K<Z.length){let Y=Z.slice(K).match(/^\btest\s+/);if(Y){let z=K,G=K+Y[0].length,J,W=Z.slice(G).match(/^(['"`])([^]*?)\1\s*/);if(W)J=W[2],G+=W[0].length;if(Z[G]==="{"){let L=G+1,_=1,U=L;while(U<Z.length&&_>0){let q=Z[U];if(q==="{")_++;else if(q==="}")_--;U++}if(_===0){let q=Z.slice(L,U-1).trim(),A=U,B=(Z.slice(0,z).match(/\n/g)||[]).length+1;if(X.push({description:J,body:q,start:z,end:A,line:B}),!$)try{Function(q)()}catch(R){let w=J||`test at line ${B}`;Q.push(`Test failed: ${w} (line ${B})
27
+ `;W+=R}return{source:W,polymorphicNames:X}}function s6(Z){return Z.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,($,X)=>{return $.replace(X,`const ${X}`)})}function a6(Z,$=!1){let X=[],Q=[],H="",K=0;while(K<Z.length){let Y=Z.slice(K).match(/^\btest\s+/);if(Y){let z=K,G=K+Y[0].length,J,W=Z.slice(G).match(/^(['"`])([^]*?)\1\s*/);if(W)J=W[2],G+=W[0].length;if(Z[G]==="{"){let U=G+1,_=1,L=U;while(L<Z.length&&_>0){let q=Z[L];if(q==="{")_++;else if(q==="}")_--;L++}if(_===0){let q=Z.slice(U,L-1).trim(),A=L,B=(Z.slice(0,z).match(/\n/g)||[]).length+1;if(X.push({description:J,body:q,start:z,end:A,line:B}),!$)try{Function(q)()}catch(R){let w=J||`test at line ${B}`;Q.push(`Test failed: ${w} (line ${B})
28
28
  ${R.message||R}`)}let F=(Z.slice(z,A).match(/\n/g)||[]).length;H+=`
29
- `.repeat(F),K=A;continue}}}H+=Z[K],K++}return{source:H,tests:X,errors:Q}}function a6(Z,$){let X=new Set,Q=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,H,K=[];while((H=Q.exec(Z))!==null){let z=H[1],G=H[2]?.trim()||"",J=H.index+H[0].length-1,W=G0(Z,J),L=Z.slice(J,W);K.push({className:z,extendsClause:G,bodyStart:J,bodyEnd:W,body:L})}let Y=Z;for(let z=K.length-1;z>=0;z--){let{className:G,extendsClause:J,bodyStart:W,bodyEnd:L,body:_}=K[z],U=/\bconstructor\s*\(/g,q,A=[];while((q=U.exec(_))!==null)A.push(q.index);if(A.length<2)continue;X.add(G);let B=[];for(let O=0;O<A.length;O++){let k=A[O],V=_.indexOf("(",k),T=1,N=V+1;while(N<_.length&&T>0){if(_[N]==="(")T++;if(_[N]===")")T--;N++}let g=_.slice(V+1,N-1),b=N;while(b<_.length&&_[b]!=="{")b++;let f=G0(_,b),n=_.slice(b+1,f-1);B.push({index:O+1,paramStr:g,bodyText:n,fullStart:k,fullEnd:f})}let M=_.slice(0,B[0].fullEnd),F=B[B.length-1].fullEnd;M+=_.slice(F);let R=_;for(let O=B.length-1;O>=1;O--){let k=B[O],V=k.fullStart;while(V>0&&R[V-1]===" ")V--;if(V>0&&R[V-1]===`
30
- `)V--;R=R.slice(0,V)+R.slice(k.fullEnd)}let w="";for(let O=1;O<B.length;O++){let k=B[O],V=k4(k.paramStr,$);if(k.paramStr.includes("...")){let N=z0(Z,W+k.fullStart);throw new z1(`Rest parameters are not supported in polymorphic constructors for '${G}'.`,N)}w+=`
29
+ `.repeat(F),K=A;continue}}}H+=Z[K],K++}return{source:H,tests:X,errors:Q}}function r6(Z,$){let X=new Set,Q=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,H,K=[];while((H=Q.exec(Z))!==null){let z=H[1],G=H[2]?.trim()||"",J=H.index+H[0].length-1,W=G0(Z,J),U=Z.slice(J,W);K.push({className:z,extendsClause:G,bodyStart:J,bodyEnd:W,body:U})}let Y=Z;for(let z=K.length-1;z>=0;z--){let{className:G,extendsClause:J,bodyStart:W,bodyEnd:U,body:_}=K[z],L=/\bconstructor\s*\(/g,q,A=[];while((q=L.exec(_))!==null)A.push(q.index);if(A.length<2)continue;X.add(G);let B=[];for(let O=0;O<A.length;O++){let k=A[O],V=_.indexOf("(",k),T=1,N=V+1;while(N<_.length&&T>0){if(_[N]==="(")T++;if(_[N]===")")T--;N++}let g=_.slice(V+1,N-1),b=N;while(b<_.length&&_[b]!=="{")b++;let y=G0(_,b),n=_.slice(b+1,y-1);B.push({index:O+1,paramStr:g,bodyText:n,fullStart:k,fullEnd:y})}let M=_.slice(0,B[0].fullEnd),F=B[B.length-1].fullEnd;M+=_.slice(F);let R=_;for(let O=B.length-1;O>=1;O--){let k=B[O],V=k.fullStart;while(V>0&&R[V-1]===" ")V--;if(V>0&&R[V-1]===`
30
+ `)V--;R=R.slice(0,V)+R.slice(k.fullEnd)}let w="";for(let O=1;O<B.length;O++){let k=B[O],V=g4(k.paramStr,$);if(k.paramStr.includes("...")){let N=z0(Z,W+k.fullStart);throw new z1(`Rest parameters are not supported in polymorphic constructors for '${G}'.`,N)}w+=`
31
31
  function ${G}$ctor$${k.index}(${k.paramStr}) {`,w+=`
32
32
  const __obj = Object.create(${G}.prototype)`,w+=`
33
33
  ;(function() {${k.bodyText}}).call(__obj)`,w+=`
34
34
  return __obj`,w+=`
35
35
  }
36
- `}let C=[];for(let O=0;O<B.length;O++){let k=B[O],V=k4(k.paramStr,$),T=[`a.length === ${V.length}`];for(let N=0;N<V.length;N++){let g=V[N];if(g.defaultValue){let b=n6(`a[${N}]`,g.defaultValue);if(b!=="true")T.push(b)}}if(O===0)C.push(` if (${T.join(" && ")}) return Reflect.construct(t, a)`);else{let N=V.map((g,b)=>`a[${b}]`).join(", ");C.push(` if (${T.join(" && ")}) return ${G}$ctor$${k.index}(${N})`)}}w+=`
36
+ `}let C=[];for(let O=0;O<B.length;O++){let k=B[O],V=g4(k.paramStr,$),T=[`a.length === ${V.length}`];for(let N=0;N<V.length;N++){let g=V[N];if(g.defaultValue){let b=c6(`a[${N}]`,g.defaultValue);if(b!=="true")T.push(b)}}if(O===0)C.push(` if (${T.join(" && ")}) return Reflect.construct(t, a)`);else{let N=V.map((g,b)=>`a[${b}]`).join(", ");C.push(` if (${T.join(" && ")}) return ${G}$ctor$${k.index}(${N})`)}}w+=`
37
37
  function ${G}$dispatch(t, a) {
38
38
  `,w+=C.join(`
39
39
  `)+`
40
40
  `,w+=` return __tjs.typeError('${G}', 'no matching constructor', a)
41
41
  `,w+=`}
42
- `,Y=Y.slice(0,W)+R+Y.slice(L);let P=W+R.length;Y=Y.slice(0,P)+w+Y.slice(P)}return{source:Y,polyCtorClasses:X}}function r6(Z,$=new Set){let X=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,Q="",H=0,K;while((K=X.exec(Z))!==null){let Y=K[1],z=K[2]||"",G=K.index,J=G+K[0].length-1,W=1,L=J+1;while(L<Z.length&&W>0){let _=Z[L];if(_==="{")W++;else if(_==="}")W--;L++}if(W===0){let _=L,U=Z.slice(J,_);if(Q+=Z.slice(H,G),Q+=`let ${Y} = class ${Y}${z} ${U}; `,$.has(Y))Q+=`${Y} = new Proxy(${Y}, { apply(t, _, a) { return ${Y}$dispatch(t, a) }, construct(t, a) { return ${Y}$dispatch(t, a) } });`;else Q+=`${Y} = new Proxy(${Y}, { apply(t, _, a) { return Reflect.construct(t, a) } });`;H=_}}return Q+=Z.slice(H),Q}function t6(Z){let $=[{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:X,message:Q}of $)if(X.test(Z))throw Error(Q);return Z}function e6(Z){let $=new Set,X=/\bconst!\s+(\w+)\b/g,Q;while((Q=X.exec(Z))!==null)$.add(Q[1]);if($.size===0)return Z;Z=Z.replace(/\bconst!\s+/g,"const ");let H=Z.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"");for(let K of $){if(new RegExp(`\\b${K}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])\\s*(?:=(?!=)|\\+\\+|--|\\+=|-=|\\*=|\\/=|%=|&&=|\\|\\|=|\\?\\?=|<<=|>>=|>>>=|\\^=|&=|\\|=)`,"g").test(H))throw Error(`Cannot mutate immutable binding '${K}'. const! bindings are read-only at compile time.`);if(new RegExp(`(?:\\+\\+|--)\\s*${K}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(H))throw Error(`Cannot mutate immutable binding '${K}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\bdelete\\s+${K}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(H))throw Error(`Cannot mutate immutable binding '${K}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\b${K}\\s*\\.\\s*(?:${"push|pop|splice|shift|unshift|sort|reverse|fill|copyWithin|set"})\\s*\\(`,"g").test(H))throw Error(`Cannot call mutating method on immutable binding '${K}'. const! bindings are read-only at compile time.`)}return Z}function Z7(Z){if(/(?<![a-zA-Z_$])\bvar\s+/.test(Z))throw Error("var is not allowed in TjsNoVar mode. Use const or let instead.");return Z}function $7(Z){if(/(?<![A-Za-z_$])\beval\s*\(/.test(Z))throw Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(Z))throw Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return Z}function y0(Z,$={}){let X=Z,Q,H=new Set,K=new Set,Y=new Set,z={tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1},G=Z.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);if(G)Q=G[2],Z=Z.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1");let J=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval)\b/,W;while(W=Z.match(J)){let R=W[2];if(R==="TjsStrict")z.tjsEquals=!0,z.tjsClass=!0,z.tjsDate=!0,z.tjsNoeval=!0,z.tjsNoVar=!0,z.tjsStandard=!0;else if(R==="TjsEquals")z.tjsEquals=!0;else if(R==="TjsClass")z.tjsClass=!0;else if(R==="TjsDate")z.tjsDate=!0;else if(R==="TjsNoeval")z.tjsNoeval=!0;else if(R==="TjsNoVar")z.tjsNoVar=!0;else if(R==="TjsStandard")z.tjsStandard=!0;else if(R==="TjsSafeEval")z.tjsSafeEval=!0;Z=Z.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${R}\\s*`),"$1")}if(z.tjsStandard)Z=h6(Z);if(Z=e6(Z),Z=y6(Z),z.tjsEquals&&!$.vmTarget)Z=x6(Z);Z=u6(Z),Z=l6(Z),Z=d6(Z),Z=m6(Z),Z=i6(Z),Z=o6(Z);let{source:L,returnType:_,returnSafety:U}=b0(Z,{originalSource:X,requiredParams:H,unsafeFunctions:K,safeFunctions:Y});Z=L;let q=p6(Z);Z=q.source,Z=v6(Z);let A=c6(Z,H);Z=A.source;let B=f6(Z);Z=B.source;let M=s6(Z,$.dangerouslySkipTests);Z=M.source;let F=a6(Z,H);Z=F.source;for(let R of F.polyCtorClasses)K.add(`${R}$dispatch`);if(z.tjsClass)Z=r6(Z,F.polyCtorClasses);if(z.tjsDate)Z=t6(Z);if(z.tjsNoeval)Z=$7(Z);if(z.tjsNoVar)Z=Z7(Z);return Z=J0(Z,q.extensions),{source:Z,returnType:_,returnSafety:U,moduleSafety:Q,tjsModes:z,originalSource:X,requiredParams:H,unsafeFunctions:K,safeFunctions:Y,wasmBlocks:B.blocks,tests:M.tests,testErrors:M.errors,polymorphicNames:A.polymorphicNames,extensions:q.extensions}}function F1(Z,$={}){let{filename:X="<source>",colonShorthand:Q=!0,vmTarget:H=!1}=$,{source:K,returnType:Y,returnSafety:z,moduleSafety:G,originalSource:J,requiredParams:W,unsafeFunctions:L,safeFunctions:_,wasmBlocks:U,tests:q,testErrors:A}=Q?y0(Z,{vmTarget:H}):{source:Z,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:Z,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[]};try{return{ast:X7.parse(K,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:Y,returnSafety:z,moduleSafety:G,originalSource:J,requiredParams:W,unsafeFunctions:L,safeFunctions:_,wasmBlocks:U,tests:q,testErrors:A}}catch(B){let M=B.loc||{line:1,column:0};throw new z1(B.message.replace(/\s*\(\d+:\d+\)$/,""),M,J,X)}}function h0(Z,$){for(let Q of Z.body){if(Q.type==="ImportDeclaration")throw new z1("Imports are not supported. All atoms must be registered with the VM.",Q.loc?.start||{line:1,column:0},void 0,$);if(Q.type==="ExportNamedDeclaration"||Q.type==="ExportDefaultDeclaration")throw new z1("Exports are not supported. The function is automatically exported.",Q.loc?.start||{line:1,column:0},void 0,$);if(Q.type==="ClassDeclaration")throw new z1("Classes are not supported. Agent99 uses functional composition.",Q.loc?.start||{line:1,column:0},void 0,$)}let X=Z.body.filter((Q)=>Q.type==="FunctionDeclaration");if(X.length===0)throw new z1("Source must contain a function declaration",{line:1,column:0},void 0,$);if(X.length>1){let Q=X[1];throw new z1("Only a single function per agent is allowed",Q.loc?.start||{line:1,column:0},void 0,$)}return X[0]}function W0(Z,$){let X={params:{}};if(!$.loc)return X;let Q=Z.substring(0,$.start),H=[...Q.matchAll(/\/\*#([\s\S]*?)\*\//g)];if(H.length>0){let W=H[H.length-1],L=Q.substring(W.index+W[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(L)){let _=W[1],U=_.split(`
43
- `),q=U.filter((A)=>A.trim().length>0).reduce((A,B)=>{let M=B.match(/^(\s*)/)?.[1].length||0;return Math.min(A,M)},1/0);if(q>0&&q<1/0)_=U.map((A)=>A.slice(q)).join(`
44
- `);return X.description=_.trim(),X}}let K=Q.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!K)return X;let Y=K[0],z=Y.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);if(z)X.description=z[1].trim();let G=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,J;while((J=G.exec(Y))!==null)X.params[J[1]]=J[2].trim();return X}import{parseExpressionAt as ZZ}from"acorn";function G1(Z){switch(Z.type){case"Literal":{let $=Z.value;if($===null)return{kind:"null"};if(typeof $==="string")return{kind:"string"};if(typeof $==="number"){let X=Z.raw;if(X&&X.includes("."))return{kind:"number"};return{kind:"integer"}}if(typeof $==="boolean")return{kind:"boolean"};return{kind:"any"}}case"ArrayExpression":{let $=Z.elements;if($.length===0)return{kind:"array",items:{kind:"any"}};let X=$.filter((Y)=>Y!=null).map((Y)=>G1(Y));if(X.length===0)return{kind:"array",items:{kind:"any"}};let Q=new Map;for(let Y of X){let z=JSON.stringify(Y);if(!Q.has(z))Q.set(z,Y)}let H=[...Q.values()];return{kind:"array",items:H.length===1?H[0]:{kind:"union",members:H}}}case"ObjectExpression":{let $=Z.properties,X={};for(let Q of $)if(Q.type==="Property"&&Q.key.type==="Identifier"){let H=Q.key.name;X[H]=G1(Q.value)}return{kind:"object",shape:X}}case"LogicalExpression":{let{operator:$,left:X,right:Q}=Z;if($==="||")return G1(X);if($==="&&")return G1(Q);if($==="??")return G1(Q);return{kind:"any"}}case"BinaryExpression":{let{operator:$,left:X,right:Q}=Z;if($==="|"){let H=G1(X),K=G1(Q);if(K.kind==="null")return{...H,nullable:!0};if(H.kind==="null")return{...K,nullable:!0};return{kind:"union",members:[H,K]}}return{kind:"any"}}case"Identifier":{if(Z.name==="undefined")return{kind:"undefined"};return{kind:"any"}}case"UnaryExpression":{let{operator:$,argument:X}=Z;if($==="+"&&X.type==="Literal"){if(typeof X.value==="number")return{kind:"non-negative-integer"}}if($==="-"&&X.type==="Literal"){if(typeof X.value==="number"){let H=X.raw;if(H&&H.includes("."))return{kind:"number"};return{kind:"integer"}}}return{kind:"any"}}default:return{kind:"any"}}}function O1(Z,$){if(Z.type==="Identifier")return{name:Z.name,type:{kind:"any"},required:!0};if(Z.type==="AssignmentPattern"){let{left:X,right:Q}=Z;if(X.type!=="Identifier")throw new c("Only simple parameter names are supported",o(Z));let H=X.name,K=$?.has(H)??!1,Y=G1(Q),z=B1(Q);return{name:H,type:Y,required:K,default:K?null:z,example:z,loc:{start:Z.start,end:Z.end}}}if(Z.type==="ObjectPattern"){let X=Z.properties,Q={},H={};for(let K of X)if(K.type==="Property"){let Y=K.key.type==="Identifier"?K.key.name:String(K.key.value);if(K.value.type==="Identifier")Q[Y]={kind:"any"},H[Y]={name:Y,type:{kind:"any"},required:!0};else if(K.value.type==="AssignmentPattern"){let z=O1(K.value,$),G=$?.has(Y)??!1;Q[Y]=z.type,H[Y]={name:Y,type:z.type,required:G,default:G?null:z.example,example:z.example}}}return{name:"__destructured__",type:{kind:"object",shape:Q,destructuredParams:H},required:!0}}throw new c(`Unsupported parameter pattern: ${Z.type}`,o(Z))}function B1(Z){switch(Z.type){case"Literal":return Z.value;case"ArrayExpression":return Z.elements.map(($)=>$?B1($):null);case"ObjectExpression":{let $={};for(let X of Z.properties)if(X.type==="Property"&&X.key.type==="Identifier")$[X.key.name]=B1(X.value);return $}case"UnaryExpression":if(Z.operator==="-"){let $=B1(Z.argument);return typeof $==="number"?-$:void 0}if(Z.operator==="+"){let $=B1(Z.argument);return typeof $==="number"?+$:void 0}return;case"BinaryExpression":{let{operator:$,left:X}=Z;if($==="|")return B1(X);return}case"LogicalExpression":{let{operator:$,left:X,right:Q}=Z;if($==="&&"){if(X.type==="Literal"&&X.value===null)return null}if($==="||")return B1(X)??B1(Q);if($==="??")return B1(X)??B1(Q);return}default:return}}function Q7(Z){try{let $=ZZ(Z,0,{ecmaVersion:2022});return G1($)}catch{return{kind:"any"}}}function g4(Z){switch(Z.kind){case"string":return Z.nullable?"string | null":"string";case"number":return Z.nullable?"number | null":"number";case"integer":return Z.nullable?"integer | null":"integer";case"non-negative-integer":return Z.nullable?"non-negative integer | null":"non-negative integer";case"boolean":return Z.nullable?"boolean | null":"boolean";case"null":return"null";case"any":return"any";case"array":{let $=Z.items?g4(Z.items):"any";return Z.nullable?`${$}[] | null`:`${$}[]`}case"object":{if(!Z.shape||Object.keys(Z.shape).length===0)return Z.nullable?"object | null":"object";let $=Object.entries(Z.shape).map(([X,Q])=>`${X}: ${g4(Q)}`).join(", ");return Z.nullable?`{ ${$} } | null`:`{ ${$} }`}case"union":return Z.members?.map(g4).join(" | ")||"any";default:return"any"}}function x0(Z){switch(Z.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:Z.items?x0(Z.items):{}};case"object":if(Z.shape){let $={};for(let[X,Q]of Object.entries(Z.shape))$[X]=x0(Q);return{type:"object",properties:$,additionalProperties:!1}}return{type:"object"};case"union":if(Z.members)return{oneOf:Z.members.map(x0)};return{};default:return{}}}function $Z(Z){let $={},X=[];for(let[Q,H]of Object.entries(Z))if($[Q]=x0(H.type),H.required)X.push(Q);return{type:"object",properties:$,required:X.length>0?X:void 0,additionalProperties:!1}}function U0(Z,$,X,Q={},H){let K=W0($,Z),Y=new Map;for(let B of Z.params){let M=O1(B,H);if(M.name==="__destructured__"&&M.type.kind==="object"&&M.type.destructuredParams)for(let[F,R]of Object.entries(M.type.destructuredParams))Y.set(F,{...R,description:K.params[F]});else M.description=K.params[M.name],Y.set(M.name,M)}let z;if(X)z=Q7(X);let G={depth:0,locals:new Map,parameters:Y,atoms:new Set(Object.keys(Q.atoms||{})),warnings:[],source:$,filename:Q.filename||"<source>",options:Q},J=w1(Z.body,G),W=[],L=[],_=[];for(let[B,M]of Y.entries())if(M.required)L.push(B);else if(M.default!==void 0)_.push({name:B,defaultValue:M.default});else L.push(B);if(L.length>0)W.push({op:"varsImport",keys:L});for(let{name:B,defaultValue:M}of _)W.push({op:"varsImport",keys:[B]}),W.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:B},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:B,value:M}]});W.push(...J);let U=Object.fromEntries(Y),q={name:Z.id?.name||"anonymous",description:K.description,parameters:U,returns:z},A=$Z(U);return{ast:{op:"seq",steps:W,inputSchema:A},signature:q,warnings:G.warnings}}function w1(Z,$){let X=[];for(let Q of Z.body){let H=_0(Q,$);if(H)if(Array.isArray(H))X.push(...H);else X.push(H)}return X}function _0(Z,$){switch(Z.type){case"VariableDeclaration":return XZ(Z,$);case"ExpressionStatement":return QZ(Z,$);case"IfStatement":return KZ(Z,$);case"WhileStatement":return YZ(Z,$);case"ForOfStatement":return zZ(Z,$);case"TryStatement":return GZ(Z,$);case"ReturnStatement":return JZ(Z,$);case"ThrowStatement":throw new c("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",o(Z),$.source,$.filename);case"BlockStatement":return{op:"scope",steps:w1(Z,_1($))};case"EmptyStatement":return null;default:throw new c(`Unsupported statement type: ${Z.type}`,o(Z),$.source,$.filename)}}function XZ(Z,$){let X=[],Q=Z.kind==="const",H=Q?"constSet":"varSet";for(let K of Z.declarations){if(K.id.type!=="Identifier")throw new c("Only simple variable names are supported",o(K),$.source,$.filename);let Y=K.id.name;if(K.init){let{step:z,resultVar:G}=y1(K.init,$,Y,Q);if(z)X.push(z);else if(G!==Y)X.push({op:H,key:Y,value:G});let J=G1(K.init);$.locals.set(Y,J)}else{if(Q)throw new c("const declarations must be initialized",o(K),$.source,$.filename);X.push({op:"varSet",key:Y,value:null}),$.locals.set(Y,{kind:"any",nullable:!0})}}return X}function QZ(Z,$){let X=Z.expression;if(X.type==="AssignmentExpression")return HZ(X,$);if(X.type==="CallExpression"){let{step:Q,resultVar:H}=y1(X,$);if(Q)return Q;if(H)return{op:"varSet",key:"_",value:H};return null}return $.warnings.push({message:"Expression statement has no effect",line:o(Z).line,column:o(Z).column}),null}function HZ(Z,$){if(Z.left.type!=="Identifier")throw new c("Only simple variable assignment is supported",o(Z),$.source,$.filename);let X=Z.left.name,{step:Q,resultVar:H}=y1(Z.right,$,X);if(Q)return Q;return{op:"varSet",key:X,value:H}}function KZ(Z,$){let X=p(Z.test,$),Q=Z.consequent.type==="BlockStatement"?w1(Z.consequent,_1($)):[_0(Z.consequent,$)].filter(Boolean),H;if(Z.alternate)H=Z.alternate.type==="BlockStatement"?w1(Z.alternate,_1($)):[_0(Z.alternate,$)].filter(Boolean);return{op:"if",condition:X,then:Q,...H&&{else:H}}}function YZ(Z,$){let X=p(Z.test,$),Q=Z.body.type==="BlockStatement"?w1(Z.body,_1($)):[_0(Z.body,$)].filter(Boolean);return{op:"while",condition:X,body:Q}}function zZ(Z,$){let X;if(Z.left.type==="VariableDeclaration"){let Y=Z.left.declarations[0];if(Y.id.type!=="Identifier")throw new c("Only simple variable names are supported in for...of",o(Z.left),$.source,$.filename);X=Y.id.name}else if(Z.left.type==="Identifier")X=Z.left.name;else throw new c("Unsupported for...of left-hand side",o(Z.left),$.source,$.filename);let Q=Z1(Z.right,$),H=_1($);H.locals.set(X,{kind:"any"});let K=Z.body.type==="BlockStatement"?w1(Z.body,H):[_0(Z.body,H)].filter(Boolean);return{op:"map",items:Q,as:X,steps:K}}function GZ(Z,$){let X=w1(Z.block,_1($)),Q,H;if(Z.handler){let K=_1($);if(Z.handler.param?.type==="Identifier")H=Z.handler.param.name,K.locals.set(H,{kind:"any"});Q=w1(Z.handler.body,K)}return{op:"try",try:X,...Q&&{catch:Q},...H&&{catchParam:H}}}function JZ(Z,$){if(!Z.argument)return{op:"return",value:{}};let{step:X,resultVar:Q}=y1(Z.argument,$,"__returnVal__");if(X)return[X,{op:"return",value:Q}];return{op:"return",value:Z1(Z.argument,$)}}var K7=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),WZ=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),L0=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),_Z=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 LZ(Z){if(Z.callee.type==="Identifier"){let $=Z.callee.name;return WZ.has($)||L0.has($)}if(Z.callee.type==="MemberExpression"){let $=Z.callee;if($.object.type==="Identifier"){let X=$.object.name;if(K7.has(X)||L0.has(X))return!0}if($.property.type==="Identifier"){let X=$.property.name;if(_Z.has(X))return!0}}return!1}function UZ(Z){if(Z.object.type==="Identifier"){let $=Z.object.name;return K7.has($)||L0.has($)}return!1}var H7={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 qZ(Z){if(Z.callee.type==="Identifier"){let $=Z.callee.name;if(L0.has($))return H7[$]||`${$} is not available in AsyncJS.`}if(Z.callee.type==="MemberExpression"){let $=Z.callee;if($.object.type==="Identifier"){let X=$.object.name;if(L0.has(X))return H7[X]||`${X} is not available in AsyncJS.`}}return null}function Y7(Z){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."}[Z]||" Use factory functions or object literals instead."}function y1(Z,$,X,Q){let H=Q?"constSet":"varSet";if(Z.type==="ChainExpression")return y1(Z.expression,$,X,Q);if(Z.type==="NewExpression"){let Y=Z,z="constructor";if(Y.callee.type==="Identifier")z=Y.callee.name;let G=Y7(z);throw new c(`The 'new' keyword is not supported in AsyncJS.${G}`,o(Z),$.source,$.filename)}if(Z.type==="CallExpression"){let Y=qZ(Z);if(Y)throw new c(Y,o(Z),$.source,$.filename)}if(Z.type==="CallExpression"&&LZ(Z)){let Y=p(Z,$);if(X)return{step:{op:H,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}if(Z.type==="MemberExpression"&&UZ(Z)){let Y=p(Z,$);if(X)return{step:{op:H,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}if(Z.type==="CallExpression")return DZ(Z,$,X,Q);if(Z.type==="TemplateLiteral")return IZ(Z,$,X,Q);if(Z.type==="BinaryExpression"||Z.type==="LogicalExpression"||Z.type==="UnaryExpression"){let Y=p(Z,$);if(X)return{step:{op:H,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}return{step:null,resultVar:Z1(Z,$)}}function DZ(Z,$,X,Q){let H,K=!1,Y;if(Z.callee.type==="Identifier")H=Z.callee.name;else if(Z.callee.type==="MemberExpression"){let G=Z.callee;if(G.property.type==="Identifier")H=G.property.name,K=!0,Y=Z1(G.object,$);else throw new c("Computed method names are not supported",o(Z),$.source,$.filename)}else throw new c("Only named function calls are supported",o(Z),$.source,$.filename);if(K)return AZ(H,Y,Z.arguments,$,X,Q);if(H==="console"&&Z.callee.type==="MemberExpression");let z=RZ(Z,$);return{step:{op:H,...z,...X&&{result:X},...X&&Q&&{resultConst:!0}},resultVar:X}}function AZ(Z,$,X,Q,H,K){switch(Z){case"map":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],G=z?.type==="Identifier"?z.name:"item",J=_1(Q);J.locals.set(G,{kind:"any"});let W;if(Y.body.type==="BlockStatement")W=w1(Y.body,J);else{let{step:L,resultVar:_}=y1(Y.body,J,"result");W=L?[L]:[{op:"varSet",key:"result",value:_}]}return{step:{op:"map",items:$,as:G,steps:W,...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}break;case"filter":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],G=z?.type==="Identifier"?z.name:"item",J=_1(Q);J.locals.set(G,{kind:"any"});let W;if(Y.body.type==="BlockStatement")throw new c("filter callback must be an expression, not a block",o(X[0]),Q.source,Q.filename);else W=p(Y.body,J);return{step:{op:"filter",items:$,as:G,condition:W,...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}break;case"find":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],G=z?.type==="Identifier"?z.name:"item",J=_1(Q);J.locals.set(G,{kind:"any"});let W;if(Y.body.type==="BlockStatement")throw new c("find callback must be an expression, not a block",o(X[0]),Q.source,Q.filename);else W=p(Y.body,J);return{step:{op:"find",items:$,as:G,condition:W,...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}break;case"reduce":if(X.length>=2&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],G=Y.params[1],J=z?.type==="Identifier"?z.name:"acc",W=G?.type==="Identifier"?G.name:"item",L=_1(Q);L.locals.set(J,{kind:"any"}),L.locals.set(W,{kind:"any"});let _;if(Y.body.type==="BlockStatement")_=w1(Y.body,L);else{let{step:q,resultVar:A}=y1(Y.body,L,"result");_=q?[q]:[{op:"varSet",key:"result",value:A}]}let U=Z1(X[1],Q);return{step:{op:"reduce",items:$,as:W,accumulator:J,initial:U,steps:_,...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}break;case"slice":break;case"push":return{step:{op:"push",list:$,item:Z1(X[0],Q),...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H};case"join":return{step:{op:"join",list:$,sep:X.length>0?Z1(X[0],Q):"",...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H};case"split":return{step:{op:"split",str:$,sep:X.length>0?Z1(X[0],Q):"",...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}return Q.warnings.push({message:`Unknown method '${Z}' - treating as atom call`,line:0,column:0}),{step:{op:Z,receiver:$,args:X.map((Y)=>Z1(Y,Q)),...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}function IZ(Z,$,X,Q){let H="",K={};for(let Y=0;Y<Z.quasis.length;Y++)if(H+=Z.quasis[Y].value.cooked||Z.quasis[Y].value.raw,Y<Z.expressions.length){let z=Z.expressions[Y],G=`_${Y}`;K[G]=Z1(z,$),H+=`{{${G}}}`}return{step:{op:"template",tmpl:H,vars:K,...X&&{result:X},...X&&Q&&{resultConst:!0}},resultVar:X}}function p(Z,$){switch(Z.type){case"Literal":return{$expr:"literal",value:Z.value};case"Identifier":return{$expr:"ident",name:Z.name};case"MemberExpression":{let X=Z,Q=p(X.object,$),H=X.optional===!0;if(X.computed){let Y=X.property;if(Y.type==="Literal")return{$expr:"member",object:Q,property:String(Y.value),computed:!0,...H&&{optional:!0}};throw new c("Computed member access with variables not yet supported",o(Z),$.source,$.filename)}let K=X.property.name;return{$expr:"member",object:Q,property:K,...H&&{optional:!0}}}case"ChainExpression":return p(Z.expression,$);case"BinaryExpression":{let X=Z;return{$expr:"binary",op:X.operator,left:p(X.left,$),right:p(X.right,$)}}case"LogicalExpression":{let X=Z;return{$expr:"logical",op:X.operator,left:p(X.left,$),right:p(X.right,$)}}case"UnaryExpression":{let X=Z;return{$expr:"unary",op:X.operator,argument:p(X.argument,$)}}case"ConditionalExpression":{let X=Z;return{$expr:"conditional",test:p(X.test,$),consequent:p(X.consequent,$),alternate:p(X.alternate,$)}}case"ArrayExpression":return{$expr:"array",elements:Z.elements.filter((Q)=>Q!==null).map((Q)=>p(Q,$))};case"ObjectExpression":{let X=Z,Q=[];for(let H of X.properties)if(H.type==="Property"){let K=H.key.type==="Identifier"?H.key.name:String(H.key.value);Q.push({key:K,value:p(H.value,$)})}return{$expr:"object",properties:Q}}case"CallExpression":{let X=Z;if(X.callee.type==="MemberExpression"){let Q=X.callee,H=Q.property.type==="Identifier"?Q.property.name:String(Q.property.value),K=Q.optional===!0||X.optional===!0;return{$expr:"methodCall",object:p(Q.object,$),method:H,arguments:X.arguments.map((Y)=>p(Y,$)),...K&&{optional:!0}}}if(X.callee.type==="Identifier")return{$expr:"call",callee:X.callee.name,arguments:X.arguments.map((H)=>p(H,$))};throw new c("Complex function calls in expressions should be lifted to statements",o(Z),$.source,$.filename)}case"NewExpression":{let X=Z,Q="constructor";if(X.callee.type==="Identifier")Q=X.callee.name;let H=Y7(Q);throw new c(`The 'new' keyword is not supported in AsyncJS.${H}`,o(Z),$.source,$.filename)}case"TemplateLiteral":throw new c("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",o(Z),$.source,$.filename);default:throw new c(`Unsupported expression type in condition: ${Z.type}`,o(Z),$.source,$.filename)}}function Z1(Z,$){switch(Z.type){case"Literal":return Z.value;case"Identifier":return Z.name;case"MemberExpression":{let X=Z;if(X.optional===!0)return p(Z,$);let H=Z1(X.object,$);if(H&&typeof H==="object"&&H.$expr){let Y=X.computed?String(X.property.value):X.property.name;return{$expr:"member",object:H,property:Y,...X.computed&&{computed:!0}}}if(X.computed)return`${H}[${Z1(X.property,$)}]`;let K=X.property.name;if(typeof H==="string")return`${H}.${K}`;if(H&&H.$kind==="arg")return{$kind:"arg",path:`${H.path}.${K}`};return`${H}.${K}`}case"ChainExpression":return Z1(Z.expression,$);case"ArrayExpression":return Z.elements.map((X)=>X?Z1(X,$):null);case"ObjectExpression":{let X={};for(let Q of Z.properties)if(Q.type==="Property"){let H=Q.key.type==="Identifier"?Q.key.name:String(Q.key.value);X[H]=Z1(Q.value,$)}return X}case"TemplateLiteral":return p(Z,$);case"CallExpression":return p(Z,$);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return p(Z,$);default:return null}}function RZ(Z,$){if(Z.arguments.length===1&&Z.arguments[0].type==="ObjectExpression"){let X=Z.arguments[0],Q={};for(let H of X.properties)if(H.type==="Property"){let K=H.key.type==="Identifier"?H.key.name:String(H.key.value);Q[K]=Z1(H.value,$)}return Q}return{args:Z.arguments.map((X)=>Z1(X,$))}}import{parseExpressionAt as T7}from"acorn";function BZ(Z,$){let X=$;while(X>0&&Z[X-1]!==`
45
- `)X--;if(Z.slice(X,$).includes("//"))return!0;let H=0,K=!1;while(H<$)if(!K&&Z.slice(H,H+2)==="/*")K=!0,H+=2;else if(K&&Z.slice(H,H+2)==="*/")K=!1,H+=2;else H++;return K}function wZ(Z){let $=[],X=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{([\s\S]*?)\}\s*\*\/|\/\*test\s*\{([\s\S]*?)\}\s*\*\//g,Q;while((Q=X.exec(Z))!==null){let H=Q[2]||`embedded test ${$.length+1}`,K=(Q[3]||Q[4]||"").trim();$.push({description:H,body:K,line:b4(Z,Q.index)})}return $}function v4(Z){let $=[],X=[],Q=wZ(Z);$.push(...Q);let H=/test\s+(['"`])([^'"`]*)\1\s*\{|test\s*\(\s*(['"`])([^'"`]*)\3\s*\)\s*\{|test\s*\{/g,K=/mock\s*\{/g,Y=Z,z,G=[];while((z=H.exec(Z))!==null){let _=z.index;if(BZ(Z,_))continue;let U=z[2]||z[4]||`test ${$.length+1}`,q=z.index+z[0].length,A=z7(Z,q-1);if(A===-1)continue;let B=Z.slice(q,A).trim();$.push({description:U,body:B,line:b4(Z,_)}),G.push({start:_,end:A+1,desc:U})}let J=[];while((z=K.exec(Z))!==null){let _=z.index,U=z.index+z[0].length,q=z7(Z,U-1);if(q===-1)continue;let A=Z.slice(U,q).trim();X.push({body:A,line:b4(Z,_)}),J.push({start:_,end:q+1})}let W=[...G,...J].sort((_,U)=>U.start-_.start);for(let _ of W)Y=Y.slice(0,_.start)+Y.slice(_.end);Y=Y.replace(/\n\s*\n\s*\n/g,`
42
+ `,Y=Y.slice(0,W)+R+Y.slice(U);let P=W+R.length;Y=Y.slice(0,P)+w+Y.slice(P)}return{source:Y,polyCtorClasses:X}}function t6(Z,$=new Set){let X=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,Q="",H=0,K;while((K=X.exec(Z))!==null){let Y=K[1],z=K[2]||"",G=K.index,J=G+K[0].length-1,W=1,U=J+1;while(U<Z.length&&W>0){let _=Z[U];if(_==="{")W++;else if(_==="}")W--;U++}if(W===0){let _=U,L=Z.slice(J,_);if(Q+=Z.slice(H,G),Q+=`let ${Y} = class ${Y}${z} ${L}; `,$.has(Y))Q+=`${Y} = new Proxy(${Y}, { apply(t, _, a) { return ${Y}$dispatch(t, a) }, construct(t, a) { return ${Y}$dispatch(t, a) } });`;else Q+=`${Y} = new Proxy(${Y}, { apply(t, _, a) { return Reflect.construct(t, a) } });`;H=_}}return Q+=Z.slice(H),Q}function e6(Z){let $=[{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:X,message:Q}of $)if(X.test(Z))throw Error(Q);return Z}function Z7(Z){let $=new Set,X=/\bconst!\s+(\w+)\b/g,Q;while((Q=X.exec(Z))!==null)$.add(Q[1]);if($.size===0)return Z;Z=Z.replace(/\bconst!\s+/g,"const ");let H=Z.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"");for(let K of $){if(new RegExp(`\\b${K}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])\\s*(?:=(?!=)|\\+\\+|--|\\+=|-=|\\*=|\\/=|%=|&&=|\\|\\|=|\\?\\?=|<<=|>>=|>>>=|\\^=|&=|\\|=)`,"g").test(H))throw Error(`Cannot mutate immutable binding '${K}'. const! bindings are read-only at compile time.`);if(new RegExp(`(?:\\+\\+|--)\\s*${K}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(H))throw Error(`Cannot mutate immutable binding '${K}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\bdelete\\s+${K}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(H))throw Error(`Cannot mutate immutable binding '${K}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\b${K}\\s*\\.\\s*(?:${"push|pop|splice|shift|unshift|sort|reverse|fill|copyWithin|set"})\\s*\\(`,"g").test(H))throw Error(`Cannot call mutating method on immutable binding '${K}'. const! bindings are read-only at compile time.`)}return Z}function $7(Z){if(/(?<![a-zA-Z_$])\bvar\s+/.test(Z))throw Error("var is not allowed in TjsNoVar mode. Use const or let instead.");return Z}function X7(Z){if(/(?<![A-Za-z_$])\beval\s*\(/.test(Z))throw Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(Z))throw Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return Z}function y0(Z,$={}){let X=Z,Q,H=new Set,K=new Set,Y=new Set,z={tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1},G=Z.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);if(G)Q=G[2],Z=Z.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1");let J=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval)\b/,W;while(W=Z.match(J)){let R=W[2];if(R==="TjsStrict")z.tjsEquals=!0,z.tjsClass=!0,z.tjsDate=!0,z.tjsNoeval=!0,z.tjsNoVar=!0,z.tjsStandard=!0;else if(R==="TjsEquals")z.tjsEquals=!0;else if(R==="TjsClass")z.tjsClass=!0;else if(R==="TjsDate")z.tjsDate=!0;else if(R==="TjsNoeval")z.tjsNoeval=!0;else if(R==="TjsNoVar")z.tjsNoVar=!0;else if(R==="TjsStandard")z.tjsStandard=!0;else if(R==="TjsSafeEval")z.tjsSafeEval=!0;Z=Z.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${R}\\s*`),"$1")}if(z.tjsStandard)Z=x6(Z);if(Z=Z7(Z),Z=h6(Z),z.tjsEquals&&!$.vmTarget)Z=u6(Z);Z=d6(Z),Z=m6(Z),Z=l6(Z),Z=i6(Z),Z=p6(Z),Z=s6(Z);let{source:U,returnType:_,returnSafety:L}=b0(Z,{originalSource:X,requiredParams:H,unsafeFunctions:K,safeFunctions:Y});Z=U;let q=n6(Z);Z=q.source,Z=f6(Z);let A=o6(Z,H);Z=A.source;let B=y6(Z);Z=B.source;let M=a6(Z,$.dangerouslySkipTests);Z=M.source;let F=r6(Z,H);Z=F.source;for(let R of F.polyCtorClasses)K.add(`${R}$dispatch`);if(z.tjsClass)Z=t6(Z,F.polyCtorClasses);if(z.tjsDate)Z=e6(Z);if(z.tjsNoeval)Z=X7(Z);if(z.tjsNoVar)Z=$7(Z);return Z=J0(Z,q.extensions),{source:Z,returnType:_,returnSafety:L,moduleSafety:Q,tjsModes:z,originalSource:X,requiredParams:H,unsafeFunctions:K,safeFunctions:Y,wasmBlocks:B.blocks,tests:M.tests,testErrors:M.errors,polymorphicNames:A.polymorphicNames,extensions:q.extensions}}function F1(Z,$={}){let{filename:X="<source>",colonShorthand:Q=!0,vmTarget:H=!1}=$,{source:K,returnType:Y,returnSafety:z,moduleSafety:G,originalSource:J,requiredParams:W,unsafeFunctions:U,safeFunctions:_,wasmBlocks:L,tests:q,testErrors:A}=Q?y0(Z,{vmTarget:H}):{source:Z,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:Z,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[]};try{return{ast:Q7.parse(K,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:Y,returnSafety:z,moduleSafety:G,originalSource:J,requiredParams:W,unsafeFunctions:U,safeFunctions:_,wasmBlocks:L,tests:q,testErrors:A}}catch(B){let M=B.loc||{line:1,column:0};throw new z1(B.message.replace(/\s*\(\d+:\d+\)$/,""),M,J,X)}}function h0(Z,$){for(let Q of Z.body){if(Q.type==="ImportDeclaration")throw new z1("Imports are not supported. All atoms must be registered with the VM.",Q.loc?.start||{line:1,column:0},void 0,$);if(Q.type==="ExportNamedDeclaration"||Q.type==="ExportDefaultDeclaration")throw new z1("Exports are not supported. The function is automatically exported.",Q.loc?.start||{line:1,column:0},void 0,$);if(Q.type==="ClassDeclaration")throw new z1("Classes are not supported. Agent99 uses functional composition.",Q.loc?.start||{line:1,column:0},void 0,$)}let X=Z.body.filter((Q)=>Q.type==="FunctionDeclaration");if(X.length===0)throw new z1("Source must contain a function declaration",{line:1,column:0},void 0,$);if(X.length>1){let Q=X[1];throw new z1("Only a single function per agent is allowed",Q.loc?.start||{line:1,column:0},void 0,$)}return X[0]}function W0(Z,$){let X={params:{}};if(!$.loc)return X;let Q=Z.substring(0,$.start),H=[...Q.matchAll(/\/\*#([\s\S]*?)\*\//g)];if(H.length>0){let W=H[H.length-1],U=Q.substring(W.index+W[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(U)){let _=W[1],L=_.split(`
43
+ `),q=L.filter((A)=>A.trim().length>0).reduce((A,B)=>{let M=B.match(/^(\s*)/)?.[1].length||0;return Math.min(A,M)},1/0);if(q>0&&q<1/0)_=L.map((A)=>A.slice(q)).join(`
44
+ `);return X.description=_.trim(),X}}let K=Q.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!K)return X;let Y=K[0],z=Y.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);if(z)X.description=z[1].trim();let G=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,J;while((J=G.exec(Y))!==null)X.params[J[1]]=J[2].trim();return X}import{parseExpressionAt as XZ}from"acorn";function G1(Z){switch(Z.type){case"Literal":{let $=Z.value;if($===null)return{kind:"null"};if(typeof $==="string")return{kind:"string"};if(typeof $==="number"){let X=Z.raw;if(X&&X.includes("."))return{kind:"number"};return{kind:"integer"}}if(typeof $==="boolean")return{kind:"boolean"};return{kind:"any"}}case"ArrayExpression":{let $=Z.elements;if($.length===0)return{kind:"array",items:{kind:"any"}};let X=$.filter((Y)=>Y!=null).map((Y)=>G1(Y));if(X.length===0)return{kind:"array",items:{kind:"any"}};let Q=new Map;for(let Y of X){let z=JSON.stringify(Y);if(!Q.has(z))Q.set(z,Y)}let H=[...Q.values()];return{kind:"array",items:H.length===1?H[0]:{kind:"union",members:H}}}case"ObjectExpression":{let $=Z.properties,X={};for(let Q of $)if(Q.type==="Property"&&Q.key.type==="Identifier"){let H=Q.key.name;X[H]=G1(Q.value)}return{kind:"object",shape:X}}case"LogicalExpression":{let{operator:$,left:X,right:Q}=Z;if($==="||")return G1(X);if($==="&&")return G1(Q);if($==="??")return G1(Q);return{kind:"any"}}case"BinaryExpression":{let{operator:$,left:X,right:Q}=Z;if($==="|"){let H=G1(X),K=G1(Q);if(K.kind==="null")return{...H,nullable:!0};if(H.kind==="null")return{...K,nullable:!0};return{kind:"union",members:[H,K]}}return{kind:"any"}}case"Identifier":{if(Z.name==="undefined")return{kind:"undefined"};return{kind:"any"}}case"UnaryExpression":{let{operator:$,argument:X}=Z;if($==="+"&&X.type==="Literal"){if(typeof X.value==="number")return{kind:"non-negative-integer"}}if($==="-"&&X.type==="Literal"){if(typeof X.value==="number"){let H=X.raw;if(H&&H.includes("."))return{kind:"number"};return{kind:"integer"}}}return{kind:"any"}}default:return{kind:"any"}}}function O1(Z,$){if(Z.type==="Identifier")return{name:Z.name,type:{kind:"any"},required:!0};if(Z.type==="AssignmentPattern"){let{left:X,right:Q}=Z;if(X.type!=="Identifier")throw new c("Only simple parameter names are supported",o(Z));let H=X.name,K=$?.has(H)??!1,Y=G1(Q),z=B1(Q);return{name:H,type:Y,required:K,default:K?null:z,example:z,loc:{start:Z.start,end:Z.end}}}if(Z.type==="ObjectPattern"){let X=Z.properties,Q={},H={};for(let K of X)if(K.type==="Property"){let Y=K.key.type==="Identifier"?K.key.name:String(K.key.value);if(K.value.type==="Identifier")Q[Y]={kind:"any"},H[Y]={name:Y,type:{kind:"any"},required:!0};else if(K.value.type==="AssignmentPattern"){let z=O1(K.value,$),G=$?.has(Y)??!1;Q[Y]=z.type,H[Y]={name:Y,type:z.type,required:G,default:G?null:z.example,example:z.example}}}return{name:"__destructured__",type:{kind:"object",shape:Q,destructuredParams:H},required:!0}}throw new c(`Unsupported parameter pattern: ${Z.type}`,o(Z))}function B1(Z){switch(Z.type){case"Literal":return Z.value;case"ArrayExpression":return Z.elements.map(($)=>$?B1($):null);case"ObjectExpression":{let $={};for(let X of Z.properties)if(X.type==="Property"&&X.key.type==="Identifier")$[X.key.name]=B1(X.value);return $}case"UnaryExpression":if(Z.operator==="-"){let $=B1(Z.argument);return typeof $==="number"?-$:void 0}if(Z.operator==="+"){let $=B1(Z.argument);return typeof $==="number"?+$:void 0}return;case"BinaryExpression":{let{operator:$,left:X}=Z;if($==="|")return B1(X);return}case"LogicalExpression":{let{operator:$,left:X,right:Q}=Z;if($==="&&"){if(X.type==="Literal"&&X.value===null)return null}if($==="||")return B1(X)??B1(Q);if($==="??")return B1(X)??B1(Q);return}default:return}}function H7(Z){try{let $=XZ(Z,0,{ecmaVersion:2022});return G1($)}catch{return{kind:"any"}}}function b4(Z){switch(Z.kind){case"string":return Z.nullable?"string | null":"string";case"number":return Z.nullable?"number | null":"number";case"integer":return Z.nullable?"integer | null":"integer";case"non-negative-integer":return Z.nullable?"non-negative integer | null":"non-negative integer";case"boolean":return Z.nullable?"boolean | null":"boolean";case"null":return"null";case"any":return"any";case"array":{let $=Z.items?b4(Z.items):"any";return Z.nullable?`${$}[] | null`:`${$}[]`}case"object":{if(!Z.shape||Object.keys(Z.shape).length===0)return Z.nullable?"object | null":"object";let $=Object.entries(Z.shape).map(([X,Q])=>`${X}: ${b4(Q)}`).join(", ");return Z.nullable?`{ ${$} } | null`:`{ ${$} }`}case"union":return Z.members?.map(b4).join(" | ")||"any";default:return"any"}}function x0(Z){switch(Z.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:Z.items?x0(Z.items):{}};case"object":if(Z.shape){let $={};for(let[X,Q]of Object.entries(Z.shape))$[X]=x0(Q);return{type:"object",properties:$,additionalProperties:!1}}return{type:"object"};case"union":if(Z.members)return{oneOf:Z.members.map(x0)};return{};default:return{}}}function QZ(Z){let $={},X=[];for(let[Q,H]of Object.entries(Z))if($[Q]=x0(H.type),H.required)X.push(Q);return{type:"object",properties:$,required:X.length>0?X:void 0,additionalProperties:!1}}function U0(Z,$,X,Q={},H){let K=W0($,Z),Y=new Map;for(let B of Z.params){let M=O1(B,H);if(M.name==="__destructured__"&&M.type.kind==="object"&&M.type.destructuredParams)for(let[F,R]of Object.entries(M.type.destructuredParams))Y.set(F,{...R,description:K.params[F]});else M.description=K.params[M.name],Y.set(M.name,M)}let z;if(X)z=H7(X);let G={depth:0,locals:new Map,parameters:Y,atoms:new Set(Object.keys(Q.atoms||{})),warnings:[],source:$,filename:Q.filename||"<source>",options:Q},J=w1(Z.body,G),W=[],U=[],_=[];for(let[B,M]of Y.entries())if(M.required)U.push(B);else if(M.default!==void 0)_.push({name:B,defaultValue:M.default});else U.push(B);if(U.length>0)W.push({op:"varsImport",keys:U});for(let{name:B,defaultValue:M}of _)W.push({op:"varsImport",keys:[B]}),W.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:B},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:B,value:M}]});W.push(...J);let L=Object.fromEntries(Y),q={name:Z.id?.name||"anonymous",description:K.description,parameters:L,returns:z},A=QZ(L);return{ast:{op:"seq",steps:W,inputSchema:A},signature:q,warnings:G.warnings}}function w1(Z,$){let X=[];for(let Q of Z.body){let H=_0(Q,$);if(H)if(Array.isArray(H))X.push(...H);else X.push(H)}return X}function _0(Z,$){switch(Z.type){case"VariableDeclaration":return HZ(Z,$);case"ExpressionStatement":return KZ(Z,$);case"IfStatement":return zZ(Z,$);case"WhileStatement":return GZ(Z,$);case"ForOfStatement":return JZ(Z,$);case"TryStatement":return WZ(Z,$);case"ReturnStatement":return _Z(Z,$);case"ThrowStatement":throw new c("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",o(Z),$.source,$.filename);case"BlockStatement":return{op:"scope",steps:w1(Z,_1($))};case"EmptyStatement":return null;default:throw new c(`Unsupported statement type: ${Z.type}`,o(Z),$.source,$.filename)}}function HZ(Z,$){let X=[],Q=Z.kind==="const",H=Q?"constSet":"varSet";for(let K of Z.declarations){if(K.id.type!=="Identifier")throw new c("Only simple variable names are supported",o(K),$.source,$.filename);let Y=K.id.name;if(K.init){let{step:z,resultVar:G}=y1(K.init,$,Y,Q);if(z)X.push(z);else if(G!==Y)X.push({op:H,key:Y,value:G});let J=G1(K.init);$.locals.set(Y,J)}else{if(Q)throw new c("const declarations must be initialized",o(K),$.source,$.filename);X.push({op:"varSet",key:Y,value:null}),$.locals.set(Y,{kind:"any",nullable:!0})}}return X}function KZ(Z,$){let X=Z.expression;if(X.type==="AssignmentExpression")return YZ(X,$);if(X.type==="CallExpression"){let{step:Q,resultVar:H}=y1(X,$);if(Q)return Q;if(H)return{op:"varSet",key:"_",value:H};return null}return $.warnings.push({message:"Expression statement has no effect",line:o(Z).line,column:o(Z).column}),null}function YZ(Z,$){if(Z.left.type!=="Identifier")throw new c("Only simple variable assignment is supported",o(Z),$.source,$.filename);let X=Z.left.name,{step:Q,resultVar:H}=y1(Z.right,$,X);if(Q)return Q;return{op:"varSet",key:X,value:H}}function zZ(Z,$){let X=p(Z.test,$),Q=Z.consequent.type==="BlockStatement"?w1(Z.consequent,_1($)):[_0(Z.consequent,$)].filter(Boolean),H;if(Z.alternate)H=Z.alternate.type==="BlockStatement"?w1(Z.alternate,_1($)):[_0(Z.alternate,$)].filter(Boolean);return{op:"if",condition:X,then:Q,...H&&{else:H}}}function GZ(Z,$){let X=p(Z.test,$),Q=Z.body.type==="BlockStatement"?w1(Z.body,_1($)):[_0(Z.body,$)].filter(Boolean);return{op:"while",condition:X,body:Q}}function JZ(Z,$){let X;if(Z.left.type==="VariableDeclaration"){let Y=Z.left.declarations[0];if(Y.id.type!=="Identifier")throw new c("Only simple variable names are supported in for...of",o(Z.left),$.source,$.filename);X=Y.id.name}else if(Z.left.type==="Identifier")X=Z.left.name;else throw new c("Unsupported for...of left-hand side",o(Z.left),$.source,$.filename);let Q=Z1(Z.right,$),H=_1($);H.locals.set(X,{kind:"any"});let K=Z.body.type==="BlockStatement"?w1(Z.body,H):[_0(Z.body,H)].filter(Boolean);return{op:"map",items:Q,as:X,steps:K}}function WZ(Z,$){let X=w1(Z.block,_1($)),Q,H;if(Z.handler){let K=_1($);if(Z.handler.param?.type==="Identifier")H=Z.handler.param.name,K.locals.set(H,{kind:"any"});Q=w1(Z.handler.body,K)}return{op:"try",try:X,...Q&&{catch:Q},...H&&{catchParam:H}}}function _Z(Z,$){if(!Z.argument)return{op:"return",value:{}};let{step:X,resultVar:Q}=y1(Z.argument,$,"__returnVal__");if(X)return[X,{op:"return",value:Q}];return{op:"return",value:Z1(Z.argument,$)}}var Y7=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),LZ=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),L0=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),UZ=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 qZ(Z){if(Z.callee.type==="Identifier"){let $=Z.callee.name;return LZ.has($)||L0.has($)}if(Z.callee.type==="MemberExpression"){let $=Z.callee;if($.object.type==="Identifier"){let X=$.object.name;if(Y7.has(X)||L0.has(X))return!0}if($.property.type==="Identifier"){let X=$.property.name;if(UZ.has(X))return!0}}return!1}function DZ(Z){if(Z.object.type==="Identifier"){let $=Z.object.name;return Y7.has($)||L0.has($)}return!1}var K7={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 AZ(Z){if(Z.callee.type==="Identifier"){let $=Z.callee.name;if(L0.has($))return K7[$]||`${$} is not available in AsyncJS.`}if(Z.callee.type==="MemberExpression"){let $=Z.callee;if($.object.type==="Identifier"){let X=$.object.name;if(L0.has(X))return K7[X]||`${X} is not available in AsyncJS.`}}return null}function z7(Z){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."}[Z]||" Use factory functions or object literals instead."}function y1(Z,$,X,Q){let H=Q?"constSet":"varSet";if(Z.type==="ChainExpression")return y1(Z.expression,$,X,Q);if(Z.type==="NewExpression"){let Y=Z,z="constructor";if(Y.callee.type==="Identifier")z=Y.callee.name;let G=z7(z);throw new c(`The 'new' keyword is not supported in AsyncJS.${G}`,o(Z),$.source,$.filename)}if(Z.type==="CallExpression"){let Y=AZ(Z);if(Y)throw new c(Y,o(Z),$.source,$.filename)}if(Z.type==="CallExpression"&&qZ(Z)){let Y=p(Z,$);if(X)return{step:{op:H,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}if(Z.type==="MemberExpression"&&DZ(Z)){let Y=p(Z,$);if(X)return{step:{op:H,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}if(Z.type==="CallExpression")return IZ(Z,$,X,Q);if(Z.type==="TemplateLiteral")return BZ(Z,$,X,Q);if(Z.type==="BinaryExpression"||Z.type==="LogicalExpression"||Z.type==="UnaryExpression"){let Y=p(Z,$);if(X)return{step:{op:H,key:X,value:Y},resultVar:X};return{step:null,resultVar:Y}}return{step:null,resultVar:Z1(Z,$)}}function IZ(Z,$,X,Q){let H,K=!1,Y;if(Z.callee.type==="Identifier")H=Z.callee.name;else if(Z.callee.type==="MemberExpression"){let G=Z.callee;if(G.property.type==="Identifier")H=G.property.name,K=!0,Y=Z1(G.object,$);else throw new c("Computed method names are not supported",o(Z),$.source,$.filename)}else throw new c("Only named function calls are supported",o(Z),$.source,$.filename);if(K)return RZ(H,Y,Z.arguments,$,X,Q);if(H==="console"&&Z.callee.type==="MemberExpression");let z=wZ(Z,$);return{step:{op:H,...z,...X&&{result:X},...X&&Q&&{resultConst:!0}},resultVar:X}}function RZ(Z,$,X,Q,H,K){switch(Z){case"map":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],G=z?.type==="Identifier"?z.name:"item",J=_1(Q);J.locals.set(G,{kind:"any"});let W;if(Y.body.type==="BlockStatement")W=w1(Y.body,J);else{let{step:U,resultVar:_}=y1(Y.body,J,"result");W=U?[U]:[{op:"varSet",key:"result",value:_}]}return{step:{op:"map",items:$,as:G,steps:W,...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}break;case"filter":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],G=z?.type==="Identifier"?z.name:"item",J=_1(Q);J.locals.set(G,{kind:"any"});let W;if(Y.body.type==="BlockStatement")throw new c("filter callback must be an expression, not a block",o(X[0]),Q.source,Q.filename);else W=p(Y.body,J);return{step:{op:"filter",items:$,as:G,condition:W,...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}break;case"find":if(X.length>0&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],G=z?.type==="Identifier"?z.name:"item",J=_1(Q);J.locals.set(G,{kind:"any"});let W;if(Y.body.type==="BlockStatement")throw new c("find callback must be an expression, not a block",o(X[0]),Q.source,Q.filename);else W=p(Y.body,J);return{step:{op:"find",items:$,as:G,condition:W,...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}break;case"reduce":if(X.length>=2&&(X[0].type==="ArrowFunctionExpression"||X[0].type==="FunctionExpression")){let Y=X[0],z=Y.params[0],G=Y.params[1],J=z?.type==="Identifier"?z.name:"acc",W=G?.type==="Identifier"?G.name:"item",U=_1(Q);U.locals.set(J,{kind:"any"}),U.locals.set(W,{kind:"any"});let _;if(Y.body.type==="BlockStatement")_=w1(Y.body,U);else{let{step:q,resultVar:A}=y1(Y.body,U,"result");_=q?[q]:[{op:"varSet",key:"result",value:A}]}let L=Z1(X[1],Q);return{step:{op:"reduce",items:$,as:W,accumulator:J,initial:L,steps:_,...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}break;case"slice":break;case"push":return{step:{op:"push",list:$,item:Z1(X[0],Q),...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H};case"join":return{step:{op:"join",list:$,sep:X.length>0?Z1(X[0],Q):"",...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H};case"split":return{step:{op:"split",str:$,sep:X.length>0?Z1(X[0],Q):"",...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}return Q.warnings.push({message:`Unknown method '${Z}' - treating as atom call`,line:0,column:0}),{step:{op:Z,receiver:$,args:X.map((Y)=>Z1(Y,Q)),...H&&{result:H},...H&&K&&{resultConst:!0}},resultVar:H}}function BZ(Z,$,X,Q){let H="",K={};for(let Y=0;Y<Z.quasis.length;Y++)if(H+=Z.quasis[Y].value.cooked||Z.quasis[Y].value.raw,Y<Z.expressions.length){let z=Z.expressions[Y],G=`_${Y}`;K[G]=Z1(z,$),H+=`{{${G}}}`}return{step:{op:"template",tmpl:H,vars:K,...X&&{result:X},...X&&Q&&{resultConst:!0}},resultVar:X}}function p(Z,$){switch(Z.type){case"Literal":return{$expr:"literal",value:Z.value};case"Identifier":return{$expr:"ident",name:Z.name};case"MemberExpression":{let X=Z,Q=p(X.object,$),H=X.optional===!0;if(X.computed){let Y=X.property;if(Y.type==="Literal")return{$expr:"member",object:Q,property:String(Y.value),computed:!0,...H&&{optional:!0}};throw new c("Computed member access with variables not yet supported",o(Z),$.source,$.filename)}let K=X.property.name;return{$expr:"member",object:Q,property:K,...H&&{optional:!0}}}case"ChainExpression":return p(Z.expression,$);case"BinaryExpression":{let X=Z;return{$expr:"binary",op:X.operator,left:p(X.left,$),right:p(X.right,$)}}case"LogicalExpression":{let X=Z;return{$expr:"logical",op:X.operator,left:p(X.left,$),right:p(X.right,$)}}case"UnaryExpression":{let X=Z;return{$expr:"unary",op:X.operator,argument:p(X.argument,$)}}case"ConditionalExpression":{let X=Z;return{$expr:"conditional",test:p(X.test,$),consequent:p(X.consequent,$),alternate:p(X.alternate,$)}}case"ArrayExpression":return{$expr:"array",elements:Z.elements.filter((Q)=>Q!==null).map((Q)=>p(Q,$))};case"ObjectExpression":{let X=Z,Q=[];for(let H of X.properties)if(H.type==="Property"){let K=H.key.type==="Identifier"?H.key.name:String(H.key.value);Q.push({key:K,value:p(H.value,$)})}return{$expr:"object",properties:Q}}case"CallExpression":{let X=Z;if(X.callee.type==="MemberExpression"){let Q=X.callee,H=Q.property.type==="Identifier"?Q.property.name:String(Q.property.value),K=Q.optional===!0||X.optional===!0;return{$expr:"methodCall",object:p(Q.object,$),method:H,arguments:X.arguments.map((Y)=>p(Y,$)),...K&&{optional:!0}}}if(X.callee.type==="Identifier")return{$expr:"call",callee:X.callee.name,arguments:X.arguments.map((H)=>p(H,$))};throw new c("Complex function calls in expressions should be lifted to statements",o(Z),$.source,$.filename)}case"NewExpression":{let X=Z,Q="constructor";if(X.callee.type==="Identifier")Q=X.callee.name;let H=z7(Q);throw new c(`The 'new' keyword is not supported in AsyncJS.${H}`,o(Z),$.source,$.filename)}case"TemplateLiteral":throw new c("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",o(Z),$.source,$.filename);default:throw new c(`Unsupported expression type in condition: ${Z.type}`,o(Z),$.source,$.filename)}}function Z1(Z,$){switch(Z.type){case"Literal":return Z.value;case"Identifier":return Z.name;case"MemberExpression":{let X=Z;if(X.optional===!0)return p(Z,$);let H=Z1(X.object,$);if(H&&typeof H==="object"&&H.$expr){let Y=X.computed?String(X.property.value):X.property.name;return{$expr:"member",object:H,property:Y,...X.computed&&{computed:!0}}}if(X.computed)return`${H}[${Z1(X.property,$)}]`;let K=X.property.name;if(typeof H==="string")return`${H}.${K}`;if(H&&H.$kind==="arg")return{$kind:"arg",path:`${H.path}.${K}`};return`${H}.${K}`}case"ChainExpression":return Z1(Z.expression,$);case"ArrayExpression":return Z.elements.map((X)=>X?Z1(X,$):null);case"ObjectExpression":{let X={};for(let Q of Z.properties)if(Q.type==="Property"){let H=Q.key.type==="Identifier"?Q.key.name:String(Q.key.value);X[H]=Z1(Q.value,$)}return X}case"TemplateLiteral":return p(Z,$);case"CallExpression":return p(Z,$);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return p(Z,$);default:return null}}function wZ(Z,$){if(Z.arguments.length===1&&Z.arguments[0].type==="ObjectExpression"){let X=Z.arguments[0],Q={};for(let H of X.properties)if(H.type==="Property"){let K=H.key.type==="Identifier"?H.key.name:String(H.key.value);Q[K]=Z1(H.value,$)}return Q}return{args:Z.arguments.map((X)=>Z1(X,$))}}import{parseExpressionAt as g7}from"acorn";function jZ(Z,$){let X=$;while(X>0&&Z[X-1]!==`
45
+ `)X--;if(Z.slice(X,$).includes("//"))return!0;let H=0,K=!1;while(H<$)if(!K&&Z.slice(H,H+2)==="/*")K=!0,H+=2;else if(K&&Z.slice(H,H+2)==="*/")K=!1,H+=2;else H++;return K}function MZ(Z){let $=[],X=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{([\s\S]*?)\}\s*\*\/|\/\*test\s*\{([\s\S]*?)\}\s*\*\//g,Q;while((Q=X.exec(Z))!==null){let H=Q[2]||`embedded test ${$.length+1}`,K=(Q[3]||Q[4]||"").trim();$.push({description:H,body:K,line:v4(Z,Q.index)})}return $}function f4(Z){let $=[],X=[],Q=MZ(Z);$.push(...Q);let H=/test\s+(['"`])([^'"`]*)\1\s*\{|test\s*\(\s*(['"`])([^'"`]*)\3\s*\)\s*\{|test\s*\{/g,K=/mock\s*\{/g,Y=Z,z,G=[];while((z=H.exec(Z))!==null){let _=z.index;if(jZ(Z,_))continue;let L=z[2]||z[4]||`test ${$.length+1}`,q=z.index+z[0].length,A=G7(Z,q-1);if(A===-1)continue;let B=Z.slice(q,A).trim();$.push({description:L,body:B,line:v4(Z,_)}),G.push({start:_,end:A+1,desc:L})}let J=[];while((z=K.exec(Z))!==null){let _=z.index,L=z.index+z[0].length,q=G7(Z,L-1);if(q===-1)continue;let A=Z.slice(L,q).trim();X.push({body:A,line:v4(Z,_)}),J.push({start:_,end:q+1})}let W=[...G,...J].sort((_,L)=>L.start-_.start);for(let _ of W)Y=Y.slice(0,_.start)+Y.slice(_.end);Y=Y.replace(/\n\s*\n\s*\n/g,`
46
46
 
47
- `).trim();let L=jZ($,X);return{code:Y,tests:$,mocks:X,testRunner:L}}function z7(Z,$){let X=0,Q=null,H=!1;for(let K=$;K<Z.length;K++){let Y=Z[K];if(H){H=!1;continue}if(Y==="\\"){H=!0;continue}if(!Q&&(Y==='"'||Y==="'"||Y==="`")){Q=Y;continue}if(Q===Y){Q=null;continue}if(Q)continue;if(Y==="{")X++;if(Y==="}"){if(X--,X===0)return K}}return-1}function b4(Z,$){return Z.slice(0,$).split(`
48
- `).length}function jZ(Z,$){if(Z.length===0)return"// No tests defined";let X=$.map((H)=>H.body).join(`
47
+ `).trim();let U=FZ($,X);return{code:Y,tests:$,mocks:X,testRunner:U}}function G7(Z,$){let X=0,Q=null,H=!1;for(let K=$;K<Z.length;K++){let Y=Z[K];if(H){H=!1;continue}if(Y==="\\"){H=!0;continue}if(!Q&&(Y==='"'||Y==="'"||Y==="`")){Q=Y;continue}if(Q===Y){Q=null;continue}if(Q)continue;if(Y==="{")X++;if(Y==="}"){if(X--,X===0)return K}}return-1}function v4(Z,$){return Z.slice(0,$).split(`
48
+ `).length}function FZ(Z,$){if(Z.length===0)return"// No tests defined";let X=$.map((H)=>H.body).join(`
49
49
  `);return`(async () => {
50
50
  const __results = []
51
51
 
@@ -68,13 +68,13 @@ const __failed = __results.filter(r => !r.passed).length
68
68
 
69
69
  // Return summary
70
70
  return { passed: __passed, failed: __failed, results: __results }
71
- })()`.trim()}var G7=`
71
+ })()`.trim()}var J7=`
72
72
  function assert(condition, message) {
73
73
  if (!condition) {
74
74
  throw new Error(message || 'Assertion failed')
75
75
  }
76
76
  }
77
- `,J7=`
77
+ `,W7=`
78
78
  function expect(actual) {
79
79
  const deepEqual = (a, b) => {
80
80
  if (a === b) return true
@@ -165,24 +165,24 @@ function expect(actual) {
165
165
  }
166
166
  }
167
167
  }
168
- `,MZ=G7+`
169
- `+J7;import{validate as L7,s as H4}from"tosijs-schema";import{validate as f4,s as u0}from"tosijs-schema";function N1(Z){return Z!==null&&typeof Z==="object"&&"__runtimeType"in Z&&Z.__runtimeType===!0}function W7(Z){return Z!==null&&typeof Z==="object"&&"schema"in Z&&typeof Z.schema==="object"}function FZ(Z){return Z!==null&&typeof Z==="object"&&"type"in Z&&typeof Z.type==="string"}function t(Z,$,X,Q){let H,K,Y,z=X,G=Q;if(typeof Z==="string")if(H=Z,typeof $==="function"){if(K=$,z!==void 0)Y=u0.infer(z)}else if($===void 0&&z!==void 0)Y=u0.infer(z);else if(W7($))Y=$;else if(FZ($))Y=$;else if($!==void 0)z=$,G=z,Y=u0.infer(z);else throw Error("Type(description) requires a predicate, schema, or example");else{if(W7(Z))Y=Z;else Y=Z;H=PZ(Y)}let J;if(Y){let L=Y?.schema??Y;if(L&&typeof L==="object"&&Array.isArray(L.examples))J=L.examples}if(z===void 0&&J&&J.length>0)z=J[0];return{description:H,check:(L)=>{if(K)return K(L);if(Y)return f4(L,Y);return!1},schema:Y,predicate:K,example:z,examples:J,default:G,__runtimeType:!0}}function PZ(Z){let $=Z?.schema??Z;if($&&typeof $==="object"&&"type"in $){let X=$;switch(X.type){case"string":if(X.format)return`string (${X.format})`;if(X.pattern)return`string matching ${X.pattern}`;if(X.minLength!==void 0&&X.maxLength!==void 0)return`string (${X.minLength}-${X.maxLength} chars)`;return"string";case"number":case"integer":if(X.minimum!==void 0&&X.maximum!==void 0)return`${X.type} (${X.minimum}-${X.maximum})`;if(X.minimum!==void 0)return`${X.type} >= ${X.minimum}`;if(X.maximum!==void 0)return`${X.type} <= ${X.maximum}`;return X.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var d0=t("string",(Z)=>typeof Z==="string"),l0=t("number",(Z)=>typeof Z==="number"),m0=t("boolean",(Z)=>typeof Z==="boolean"),i0=t("integer",(Z)=>typeof Z==="number"&&Number.isInteger(Z)),p0=t("positive integer",(Z)=>typeof Z==="number"&&Number.isInteger(Z)&&Z>0),n0=t("non-empty string",(Z)=>typeof Z==="string"&&Z.length>0),c0=t("email address",(Z)=>typeof Z==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Z)),y4=(Z)=>{try{return new URL(Z),!0}catch{return!1}},o0=t("URL",(Z)=>typeof Z==="string"&&y4(Z)),s0=t("UUID",(Z)=>typeof Z==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(Z)),h4=(Z)=>{let $=new Date(Z);return!isNaN($.getTime())&&Z.includes("T")},x4=(Z)=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(Z))return!1;let $=new Date(Z+"T00:00:00Z");return!isNaN($.getTime())},u4=t("ISO 8601 timestamp",(Z)=>typeof Z==="string"&&h4(Z)),d4=t("date (YYYY-MM-DD)",(Z)=>typeof Z==="string"&&x4(Z));function a0(Z){return t(`${Z.description} or null`,($)=>$===null||Z.check($))}function r0(Z){return t(`${Z.description} (optional)`,($)=>$===null||$===void 0||Z.check($))}function t0(Z,$,...X){if(typeof Z==="string"&&Array.isArray($)){let K=Z,Y=$,z=new Set(Y);return{description:K,check:(J)=>z.has(J),__runtimeType:!0,values:Y}}let Q=[];if(N1(Z))Q.push(Z);if(N1($))Q.push($);Q.push(...X);let H=Q.map((K)=>K.description).join(" | ");return t(H,(K)=>Q.some((Y)=>Y.check(K)))}function e0(Z){return t(`array of ${Z.description}`,($)=>Array.isArray($)&&$.every((X)=>Z.check(X)))}function VZ(Z){if(N1(Z))return(X)=>Z.check(X);if(Z&&typeof Z==="object"&&"schema"in Z)return(X)=>f4(X,Z);let $=u0.infer(Z);return(X)=>f4(X,$)}function n1(Z,$,X){let Q=[],H=[];for(let Y of Z)if(typeof Y==="string")Q.push(Y),H.push(void 0);else Q.push(Y[0]),H.push(Y[1]);let K=(...Y)=>{let z=Q.map((J,W)=>{let L=W<Y.length?Y[W]:H[W];if(L===void 0)return()=>!0;return VZ(L)}),G=X;return Q.forEach((J,W)=>{let L=W<Y.length?Y[W]:H[W],_="any";if(N1(L))_=L.description;else if(L!==void 0)_=typeof L==="string"?"string":JSON.stringify(L);G=G.replace(new RegExp(`\\b${J}\\b`,"g"),_)}),t(G,(J)=>$(J,...z))};return K.params=Q,K.description=X,K}var Z4=n1(["T","U"],(Z,$,X)=>Array.isArray(Z)&&Z.length===2&&$(Z[0])&&X(Z[1]),"Pair<T, U>"),$4=n1(["V"],(Z,$)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z)&&Object.values(Z).every($),"Record<string, V>");function X4(Z,$){let X=Object.values($),Q=new Set(X),H=Object.keys($),K={};for(let[z,G]of Object.entries($))K[G]=z;return{description:Z,check:(z)=>Q.has(z),__runtimeType:!0,members:$,names:K,values:X,keys:H}}function CZ(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";switch(typeof Z){case"string":return"string";case"boolean":return"boolean";case"number":return Number.isInteger(Z)?"integer":"number";case"object":return Array.isArray(Z)?"array":"object";default:return null}}function q0(Z,$,X){if(Array.isArray($)&&X){let Q=$,H=[],K=[];for(let z of Q)if(Array.isArray(z))H.push(z[0]),K.push(z[1]);else H.push(z),K.push(void 0);let Y=(...z)=>{let G=H.map((W,L)=>L<z.length?z[L]:K[L]),J=X(...G);return q0(Z,J)};return Object.defineProperties(Y,{typeParamNames:{value:H,enumerable:!0},description:{value:Z,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),Y}return OZ(Z,$)}function OZ(Z,$){let X={},Q=void 0,H="assertReturns";if(typeof $==="function"){let Y=$.__tjs;if(Y){if(Y.params)for(let[z,G]of Object.entries(Y.params))X[z]=G?.example??null;if(Y.returns)Q=Y.returns?.example??null;if(Y.safeReturn)H="checkedReturns";else if(Y.unsafe)H="assertReturns";else H="returns"}}else X=$.params??{},Q=$.returns,H=$.returnContract??"assertReturns";return{description:Z,params:X,returns:Q,returnContract:H,check:(Y)=>{if(typeof Y!=="function")return!1;let z=Object.keys(X).length;if(z>0){let J=Y.__tjs;if(J?.params){if(Object.keys(J.params).length!==z)return!1;let L=Object.keys(X),_=Object.keys(J.params);for(let U=0;U<L.length;U++){let q=J.params[_[U]],A=X[L[U]];if(q?.type?.kind&&A!==void 0){let B=CZ(A);if(B&&q.type.kind!==B&&q.type.kind!=="any")return!1}}}}return!0},__runtimeType:!0}}var EZ=_7(),K1=EZ.version,D0=Symbol.for("tjs.equals");function K4(Z){let[$=0,X=0,Q=0]=Z.split(".").map(Number);return{major:$,minor:X,patch:Q}}function l4(Z,$){let X=K4(Z),Q=K4($);if(X.major!==Q.major)return X.major<Q.major?-1:1;if(X.minor!==Q.minor)return X.minor<Q.minor?-1:1;if(X.patch!==Q.patch)return X.patch<Q.patch?-1:1;return 0}function m4(Z,$){let X=K4(Z),Q=K4($);return X.major===Q.major}class s1 extends Error{path;expected;actual;callStack;constructor(Z,$,X,Q,H){super(Z);if(this.name="MonadicError",this.path=$,this.expected=X,this.actual=Q,this.callStack=H,Error.captureStackTrace)Error.captureStackTrace(this,s1)}}function SZ(Z,$,X){let Q=X===null?"null":typeof X,H=Q1.debug?D7():void 0,K=new s1(`Expected ${$} for '${Z}', got ${Q}`,Z,$,Q,H);if(Q1.logTypeErrors)console.error(`[TJS TypeError] ${K.message}`);if(Q1.throwTypeErrors)throw K;return K}function U7(Z){return Z instanceof Error&&Z.name==="MonadicError"&&"path"in Z}var i4={debug:!1,safety:"inputs",requireReturnTypes:!1,maxStackSize:100},Q1={...i4},V1=[],a1=0;function TZ(){a1++}function kZ(){if(a1>0)a1--}function gZ(){return a1>0}function bZ(Z){Q1={...Q1,...Z}}function vZ(){return{...Q1}}function q7(Z){if(Q1.debug&&Z){V1.push(Z);let $=Q1.maxStackSize??100;while(V1.length>$)V1.shift()}}function Q4(){if(Q1.debug)V1.pop()}function D7(){return[...V1]}function fZ(){Q1={...i4},V1.length=0,a1=0}function c1(Z,$){if(Z!==null&&typeof Z==="object"&&typeof Z[D0]==="function")return Z[D0]($);if($!==null&&typeof $==="object"&&typeof $[D0]==="function")return $[D0](Z);if(Z!==null&&typeof Z==="object"&&typeof Z.Equals==="function")return Z.Equals($);if($!==null&&typeof $==="object"&&typeof $.Equals==="function")return $.Equals(Z);if(Z instanceof String||Z instanceof Number||Z instanceof Boolean)Z=Z.valueOf();if($ instanceof String||$ instanceof Number||$ instanceof Boolean)$=$.valueOf();if(Z===$)return!0;if((Z===null||Z===void 0)&&($===null||$===void 0))return!0;if(Z===null||Z===void 0||$===null||$===void 0)return!1;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Z instanceof Set&&$ instanceof Set){if(Z.size!==$.size)return!1;for(let H of Z)if(!$.has(H))return!1;return!0}if(Z instanceof Map&&$ instanceof Map){if(Z.size!==$.size)return!1;for(let[H,K]of Z){if(!$.has(H))return!1;if(!c1(K,$.get(H)))return!1}return!0}if(Z instanceof Date&&$ instanceof Date)return Z.getTime()===$.getTime();if(Z instanceof RegExp&&$ instanceof RegExp)return Z.toString()===$.toString();if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((H,K)=>c1(H,$[K]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),Q=Object.keys($);if(X.length!==Q.length)return!1;return X.every((H)=>c1(Z[H],$[H]))}function A7(Z,$){return!c1(Z,$)}function I7(Z){if(Z===null)return"null";return typeof Z}function p4(Z,$){if(Z instanceof String||Z instanceof Number||Z instanceof Boolean)Z=Z.valueOf();if($ instanceof String||$ instanceof Number||$ instanceof Boolean)$=$.valueOf();if(Z===$)return!0;if((Z===null||Z===void 0)&&($===null||$===void 0))return!0;return!1}function R7(Z,$){return!p4(Z,$)}function P1(Z){return Z!==null&&typeof Z==="object"&&Z.$error===!0}function j1(Z,$){let X={$error:!0,message:Z,...$};if(Q1.debug&&V1.length>0){let Q=$?.path?[...V1,$.path]:[...V1];X.stack=Q}return X}function n4(Z,$){if(Z.length===0)return j1("Unknown error");if(Z.length===1)return Z[0];let X=Z.map((H)=>{if(H.path){let K=H.path.split(".");return K[K.length-1]}return"unknown"}).join(", "),Q=`Multiple parameter errors in ${$||"function"}: ${X}`;return j1(Q,{path:$,errors:Z})}function o1(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";let $=typeof Z;if($!=="object")return $;let X=Z.constructor?.name;if(X&&X!=="Object")return X;return"object"}function B7(Z,$){if(Z===null||Z===void 0)return!1;if(typeof Z!=="object"&&typeof Z!=="function")return!1;let X=Z;while(X!==null){if(X.constructor?.name===$)return!0;X=Object.getPrototypeOf(X)}return!1}function x1(Z,$,X){if(P1(Z))return Z;if(typeof $==="object"&&$!==null&&"check"in $){if($.check(Z))return null;return j1(`Expected ${$.description} but got ${o1(Z)}`,{path:X,expected:$.description,actual:o1(Z)})}let Q=o1(Z);if($==="any")return null;if($===Q)return null;if($==="number"&&Q==="number")return null;if($==="integer"&&Q==="number"&&Number.isInteger(Z))return null;if($==="non-negative-integer"&&Q==="number"&&Number.isInteger(Z)&&Z>=0)return null;if($==="object"&&Q==="object")return null;return j1(`Expected ${$} but got ${Q}`,{path:X,expected:$,actual:Q})}function c4(Z,$,X){for(let[Q,H]of Object.entries($.params)){let K=Z[Q];if(P1(K))return K;if(H.required&&K===void 0){let z=typeof H.type==="string"?H.type:H.type.description;return j1(`Missing required parameter '${Q}'`,{path:X?`${X}.${Q}`:Q,expected:z,actual:"undefined",loc:H.loc})}if(K===void 0)continue;let Y=x1(K,H.type,X?`${X}.${Q}`:Q);if(Y){if(H.loc)Y.loc=H.loc;return Y}}return null}function o4(Z,$){if(Z.__tjs=$,!(!$.polymorphic&&($.safe||$.safeReturn||Q1.safety!=="none"&&!$.unsafe||$.returns&&Q1.safety==="all"&&!$.unsafeReturn)))return Z;let Q=!!$.returns,H=!!$.unsafe,K=!!$.safe,Y=!!$.unsafeReturn,z=!!$.safeReturn,G=$.returns?.defaults,J=Object.entries($.params),W=J.length,L=Z.name||$.name||"anonymous",_=function(...U){if(a1>0)return Z.apply(this,U);let q=K||!H&&Q1.safety!=="none",A=Q&&(z||!Y&&Q1.safety==="all");if(!q&&!A)return Z.apply(this,U);if(U.length>0&&P1(U[0]))return U[0];if(q){let B=U.length===1&&typeof U[0]==="object"&&U[0]!==null&&!Array.isArray(U[0]),M=[];if(!B)for(let F=0;F<W;F++){let[R,w]=J[F],C=U[F];if(P1(C)){M.push(C);continue}if(w.required&&C===void 0){M.push(j1(`Missing required parameter '${R}'`,{path:`${L}.${R}`,expected:typeof w.type==="string"?w.type:w.type?.description||"value",actual:"undefined",loc:w.loc}));continue}if(C!==void 0){let P=x1(C,w.type,`${L}.${R}`);if(P){if(w.loc)P.loc=w.loc;M.push(P)}}}else{let F=U[0];for(let R=0;R<W;R++){let[w,C]=J[R],P=F[w];if(P1(P)){M.push(P);continue}if(C.required&&P===void 0){M.push(j1(`Missing required parameter '${w}'`,{path:`${L}.${w}`,expected:typeof C.type==="string"?C.type:C.type?.description||"value",actual:"undefined",loc:C.loc}));continue}if(P!==void 0){let O=x1(P,C.type,`${L}.${w}`);if(O){if(C.loc)O.loc=C.loc;M.push(O)}}}}if(M.length>0)return n4(M,L)}q7(L);try{let B=Z.apply(this,U);if(A&&$.returns&&!P1(B)){let M=G&&typeof B==="object"&&B!==null?Object.assign({},G,B):B,F=x1(M,$.returns.type,`${L}()`);if(F)return Q4(),F}return Q4(),B}catch(B){return Q4(),j1(B.message||String(B),{path:L,cause:B})}};return Object.defineProperty(_,"name",{value:Z.name}),_.__tjs=$,_}function w7(Z){let $=new Proxy(Z,{construct(X,Q,H){return Reflect.construct(X,Q,H)},apply(X,Q,H){return Reflect.construct(X,H)}});Object.defineProperty($,"name",{value:Z.name});for(let X of Object.getOwnPropertyNames(Z))if(X!=="length"&&X!=="name"&&X!=="prototype")Object.defineProperty($,X,Object.getOwnPropertyDescriptor(Z,X));return $}function yZ(){let Z={...Q1},$=[],X=0;function Q(M){Z={...Z,...M}}function H(){return{...Z}}function K(M){if(Z.debug&&M){$.push(M);let F=Z.maxStackSize??100;while($.length>F)$.shift()}}function Y(){if(Z.debug)$.pop()}function z(){return[...$]}function G(){Z={...i4},$.length=0,X=0}function J(){X++}function W(){if(X>0)X--}function L(){return X>0}let _=new Map;function U(M,F,R){if(!_.has(M))_.set(M,new Map);_.get(M).set(F,R)}function q(M,F){let R=typeof M,w;if(M===null||M===void 0)return;if(R==="string")w="String";else if(R==="number")w="Number";else if(R==="boolean")w="Boolean";else if(Array.isArray(M))w="Array";else if(R==="object")w=M.constructor?.name||"Object";else return;let C=w;while(C){let O=_.get(C);if(O?.has(F))return O.get(F);if(R==="object"&&!Array.isArray(M)){if(C=Object.getPrototypeOf(C===w?M:Object.getPrototypeOf(M))?.constructor?.name,C==="Object"||C===w)break}else break}let P=_.get("Object");if(P?.has(F))return P.get(F);return}function A(M,F,R){let w=R===null?"null":typeof R,C=Z.debug?z():void 0,P=new s1(`Expected ${F} for '${M}', got ${w}`,M,F,w,C);if(Z.logTypeErrors)console.error(`[TJS TypeError] ${P.message}`);if(Z.throwTypeErrors)throw P;return P}function B(M,F){let R={$error:!0,message:M,...F};if(Z.debug&&$.length>0){let w=F?.path?[...$,F.path]:[...$];R.stack=w}return R}return{version:K1,MonadicError:s1,typeError:A,isMonadicError:U7,isError:P1,error:B,composeErrors:n4,typeOf:o1,isNativeType:B7,checkType:x1,validateArgs:c4,wrap:o4,wrapClass:w7,compareVersions:l4,versionsCompatible:m4,configure:Q,getConfig:H,pushStack:K,popStack:Y,getStack:z,resetRuntime:G,enterUnsafe:J,exitUnsafe:W,isUnsafeMode:L,validate:L7,infer:H4.infer.bind(H4),Type:t,isRuntimeType:N1,Union:t0,Generic:n1,Enum:X4,FunctionPredicate:q0,Nullable:a0,Optional:r0,TArray:e0,TString:d0,TNumber:l0,TBoolean:m0,TInteger:i0,TPositiveInt:p0,TNonEmptyString:n0,TEmail:c0,TUrl:o0,TUuid:s0,TPair:Z4,TRecord:$4,Is:c1,IsNot:A7,Eq:p4,NotEq:R7,TypeOf:I7,tjsEquals:D0,registerExtension:U,resolveExtension:q}}var h1={version:K1,MonadicError:s1,typeError:SZ,isMonadicError:U7,isError:P1,error:j1,composeErrors:n4,typeOf:o1,isNativeType:B7,checkType:x1,validateArgs:c4,wrap:o4,wrapClass:w7,compareVersions:l4,versionsCompatible:m4,configure:bZ,getConfig:vZ,pushStack:q7,popStack:Q4,getStack:D7,resetRuntime:fZ,enterUnsafe:TZ,exitUnsafe:kZ,isUnsafeMode:gZ,createRuntime:yZ,validate:L7,infer:H4.infer.bind(H4),Type:t,isRuntimeType:N1,Union:t0,Generic:n1,Enum:X4,FunctionPredicate:q0,Nullable:a0,Optional:r0,TArray:e0,TString:d0,TNumber:l0,TBoolean:m0,TInteger:i0,TPositiveInt:p0,TNonEmptyString:n0,TEmail:c0,TUrl:o0,TUuid:s0,Timestamp:u4,LegalDate:d4,TPair:Z4,TRecord:$4,Is:c1,IsNot:A7,Eq:p4,NotEq:R7,TypeOf:I7};function s4(){let Z=globalThis;if(Z.__tjs){let $=Z.__tjs.version;if(typeof $!=="string")return Z.__tjs=h1,h1;let X=l4(K1,$);if(X===0)return Z.__tjs;if(m4(K1,$))if(X>0)console.info(`TJS runtime: upgrading ${$} → ${K1}`),Z.__tjs=h1;else console.info(`TJS runtime: keeping ${$} (newer than ${K1})`);else if(console.warn(`TJS runtime version conflict: ${$} vs ${K1} (major version mismatch)`),X>0)console.warn(`Upgrading to ${K1} - check for breaking changes`),Z.__tjs=h1;return Z.__tjs}return Z.__tjs=h1,h1}function hZ(Z){return`
168
+ `,PZ=J7+`
169
+ `+W7;import{validate as U7,s as H4}from"tosijs-schema";import{validate as y4,s as u0}from"tosijs-schema";function N1(Z){return Z!==null&&typeof Z==="object"&&"__runtimeType"in Z&&Z.__runtimeType===!0}function _7(Z){return Z!==null&&typeof Z==="object"&&"schema"in Z&&typeof Z.schema==="object"}function VZ(Z){return Z!==null&&typeof Z==="object"&&"type"in Z&&typeof Z.type==="string"}function t(Z,$,X,Q){let H,K,Y,z=X,G=Q;if(typeof Z==="string")if(H=Z,typeof $==="function"){if(K=$,z!==void 0)Y=u0.infer(z)}else if($===void 0&&z!==void 0)Y=u0.infer(z);else if(_7($))Y=$;else if(VZ($))Y=$;else if($!==void 0)z=$,G=z,Y=u0.infer(z);else throw Error("Type(description) requires a predicate, schema, or example");else{if(_7(Z))Y=Z;else Y=Z;H=CZ(Y)}let J;if(Y){let U=Y?.schema??Y;if(U&&typeof U==="object"&&Array.isArray(U.examples))J=U.examples}if(z===void 0&&J&&J.length>0)z=J[0];return{description:H,check:(U)=>{if(K)return K(U);if(Y)return y4(U,Y);return!1},schema:Y,predicate:K,example:z,examples:J,default:G,__runtimeType:!0}}function CZ(Z){let $=Z?.schema??Z;if($&&typeof $==="object"&&"type"in $){let X=$;switch(X.type){case"string":if(X.format)return`string (${X.format})`;if(X.pattern)return`string matching ${X.pattern}`;if(X.minLength!==void 0&&X.maxLength!==void 0)return`string (${X.minLength}-${X.maxLength} chars)`;return"string";case"number":case"integer":if(X.minimum!==void 0&&X.maximum!==void 0)return`${X.type} (${X.minimum}-${X.maximum})`;if(X.minimum!==void 0)return`${X.type} >= ${X.minimum}`;if(X.maximum!==void 0)return`${X.type} <= ${X.maximum}`;return X.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var d0=t("string",(Z)=>typeof Z==="string"),l0=t("number",(Z)=>typeof Z==="number"),m0=t("boolean",(Z)=>typeof Z==="boolean"),i0=t("integer",(Z)=>typeof Z==="number"&&Number.isInteger(Z)),p0=t("positive integer",(Z)=>typeof Z==="number"&&Number.isInteger(Z)&&Z>0),n0=t("non-empty string",(Z)=>typeof Z==="string"&&Z.length>0),c0=t("email address",(Z)=>typeof Z==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Z)),h4=(Z)=>{try{return new URL(Z),!0}catch{return!1}},o0=t("URL",(Z)=>typeof Z==="string"&&h4(Z)),s0=t("UUID",(Z)=>typeof Z==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(Z)),x4=(Z)=>{let $=new Date(Z);return!isNaN($.getTime())&&Z.includes("T")},u4=(Z)=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(Z))return!1;let $=new Date(Z+"T00:00:00Z");return!isNaN($.getTime())},d4=t("ISO 8601 timestamp",(Z)=>typeof Z==="string"&&x4(Z)),l4=t("date (YYYY-MM-DD)",(Z)=>typeof Z==="string"&&u4(Z));function a0(Z){return t(`${Z.description} or null`,($)=>$===null||Z.check($))}function r0(Z){return t(`${Z.description} (optional)`,($)=>$===null||$===void 0||Z.check($))}function t0(Z,$,...X){if(typeof Z==="string"&&Array.isArray($)){let K=Z,Y=$,z=new Set(Y);return{description:K,check:(J)=>z.has(J),__runtimeType:!0,values:Y}}let Q=[];if(N1(Z))Q.push(Z);if(N1($))Q.push($);Q.push(...X);let H=Q.map((K)=>K.description).join(" | ");return t(H,(K)=>Q.some((Y)=>Y.check(K)))}function e0(Z){return t(`array of ${Z.description}`,($)=>Array.isArray($)&&$.every((X)=>Z.check(X)))}function OZ(Z){if(N1(Z))return(X)=>Z.check(X);if(Z&&typeof Z==="object"&&"schema"in Z)return(X)=>y4(X,Z);let $=u0.infer(Z);return(X)=>y4(X,$)}function n1(Z,$,X){let Q=[],H=[];for(let Y of Z)if(typeof Y==="string")Q.push(Y),H.push(void 0);else Q.push(Y[0]),H.push(Y[1]);let K=(...Y)=>{let z=Q.map((J,W)=>{let U=W<Y.length?Y[W]:H[W];if(U===void 0)return()=>!0;return OZ(U)}),G=X;return Q.forEach((J,W)=>{let U=W<Y.length?Y[W]:H[W],_="any";if(N1(U))_=U.description;else if(U!==void 0)_=typeof U==="string"?"string":JSON.stringify(U);G=G.replace(new RegExp(`\\b${J}\\b`,"g"),_)}),t(G,(J)=>$(J,...z))};return K.params=Q,K.description=X,K}var Z4=n1(["T","U"],(Z,$,X)=>Array.isArray(Z)&&Z.length===2&&$(Z[0])&&X(Z[1]),"Pair<T, U>"),$4=n1(["V"],(Z,$)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z)&&Object.values(Z).every($),"Record<string, V>");function X4(Z,$){let X=Object.values($),Q=new Set(X),H=Object.keys($),K={};for(let[z,G]of Object.entries($))K[G]=z;return{description:Z,check:(z)=>Q.has(z),__runtimeType:!0,members:$,names:K,values:X,keys:H}}function NZ(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";switch(typeof Z){case"string":return"string";case"boolean":return"boolean";case"number":return Number.isInteger(Z)?"integer":"number";case"object":return Array.isArray(Z)?"array":"object";default:return null}}function q0(Z,$,X){if(Array.isArray($)&&X){let Q=$,H=[],K=[];for(let z of Q)if(Array.isArray(z))H.push(z[0]),K.push(z[1]);else H.push(z),K.push(void 0);let Y=(...z)=>{let G=H.map((W,U)=>U<z.length?z[U]:K[U]),J=X(...G);return q0(Z,J)};return Object.defineProperties(Y,{typeParamNames:{value:H,enumerable:!0},description:{value:Z,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),Y}return EZ(Z,$)}function EZ(Z,$){let X={},Q=void 0,H="assertReturns";if(typeof $==="function"){let Y=$.__tjs;if(Y){if(Y.params)for(let[z,G]of Object.entries(Y.params))X[z]=G?.example??null;if(Y.returns)Q=Y.returns?.example??null;if(Y.safeReturn)H="checkedReturns";else if(Y.unsafe)H="assertReturns";else H="returns"}}else X=$.params??{},Q=$.returns,H=$.returnContract??"assertReturns";return{description:Z,params:X,returns:Q,returnContract:H,check:(Y)=>{if(typeof Y!=="function")return!1;let z=Object.keys(X).length;if(z>0){let J=Y.__tjs;if(J?.params){if(Object.keys(J.params).length!==z)return!1;let U=Object.keys(X),_=Object.keys(J.params);for(let L=0;L<U.length;L++){let q=J.params[_[L]],A=X[U[L]];if(q?.type?.kind&&A!==void 0){let B=NZ(A);if(B&&q.type.kind!==B&&q.type.kind!=="any")return!1}}}}return!0},__runtimeType:!0}}var TZ=L7(),K1=TZ.version,D0=Symbol.for("tjs.equals");function K4(Z){let[$=0,X=0,Q=0]=Z.split(".").map(Number);return{major:$,minor:X,patch:Q}}function m4(Z,$){let X=K4(Z),Q=K4($);if(X.major!==Q.major)return X.major<Q.major?-1:1;if(X.minor!==Q.minor)return X.minor<Q.minor?-1:1;if(X.patch!==Q.patch)return X.patch<Q.patch?-1:1;return 0}function i4(Z,$){let X=K4(Z),Q=K4($);return X.major===Q.major}class s1 extends Error{path;expected;actual;callStack;constructor(Z,$,X,Q,H){super(Z);if(this.name="MonadicError",this.path=$,this.expected=X,this.actual=Q,this.callStack=H,Error.captureStackTrace)Error.captureStackTrace(this,s1)}}function kZ(Z,$,X){let Q=X===null?"null":typeof X,H=Q1.debug?A7():void 0,K=new s1(`Expected ${$} for '${Z}', got ${Q}`,Z,$,Q,H);if(Q1.logTypeErrors)console.error(`[TJS TypeError] ${K.message}`);if(Q1.throwTypeErrors)throw K;return K}function q7(Z){return Z instanceof Error&&Z.name==="MonadicError"&&"path"in Z}var p4={debug:!1,safety:"inputs",requireReturnTypes:!1,maxStackSize:100},Q1={...p4},V1=[],a1=0;function gZ(){a1++}function bZ(){if(a1>0)a1--}function vZ(){return a1>0}function fZ(Z){Q1={...Q1,...Z}}function yZ(){return{...Q1}}function D7(Z){if(Q1.debug&&Z){V1.push(Z);let $=Q1.maxStackSize??100;while(V1.length>$)V1.shift()}}function Q4(){if(Q1.debug)V1.pop()}function A7(){return[...V1]}function hZ(){Q1={...p4},V1.length=0,a1=0}function c1(Z,$){if(Z!==null&&typeof Z==="object"&&typeof Z[D0]==="function")return Z[D0]($);if($!==null&&typeof $==="object"&&typeof $[D0]==="function")return $[D0](Z);if(Z!==null&&typeof Z==="object"&&typeof Z.Equals==="function")return Z.Equals($);if($!==null&&typeof $==="object"&&typeof $.Equals==="function")return $.Equals(Z);if(Z instanceof String||Z instanceof Number||Z instanceof Boolean)Z=Z.valueOf();if($ instanceof String||$ instanceof Number||$ instanceof Boolean)$=$.valueOf();if(Z===$)return!0;if(typeof Z==="number"&&typeof $==="number"&&isNaN(Z)&&isNaN($))return!0;if((Z===null||Z===void 0)&&($===null||$===void 0))return!0;if(Z===null||Z===void 0||$===null||$===void 0)return!1;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Z instanceof Set&&$ instanceof Set){if(Z.size!==$.size)return!1;for(let H of Z)if(!$.has(H))return!1;return!0}if(Z instanceof Map&&$ instanceof Map){if(Z.size!==$.size)return!1;for(let[H,K]of Z){if(!$.has(H))return!1;if(!c1(K,$.get(H)))return!1}return!0}if(Z instanceof Date&&$ instanceof Date)return Z.getTime()===$.getTime();if(Z instanceof RegExp&&$ instanceof RegExp)return Z.toString()===$.toString();if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((H,K)=>c1(H,$[K]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),Q=Object.keys($);if(X.length!==Q.length)return!1;return X.every((H)=>c1(Z[H],$[H]))}function I7(Z,$){return!c1(Z,$)}function R7(Z){if(Z===null)return"null";return typeof Z}function B7(Z){return typeof Z==="number"&&isFinite(Z)&&!isNaN(Z)}function n4(Z,$){if(Z instanceof String||Z instanceof Number||Z instanceof Boolean)Z=Z.valueOf();if($ instanceof String||$ instanceof Number||$ instanceof Boolean)$=$.valueOf();if(Z===$)return!0;if(typeof Z==="number"&&typeof $==="number"&&isNaN(Z)&&isNaN($))return!0;if((Z===null||Z===void 0)&&($===null||$===void 0))return!0;return!1}function w7(Z,$){return!n4(Z,$)}function P1(Z){return Z!==null&&typeof Z==="object"&&Z.$error===!0}function j1(Z,$){let X={$error:!0,message:Z,...$};if(Q1.debug&&V1.length>0){let Q=$?.path?[...V1,$.path]:[...V1];X.stack=Q}return X}function c4(Z,$){if(Z.length===0)return j1("Unknown error");if(Z.length===1)return Z[0];let X=Z.map((H)=>{if(H.path){let K=H.path.split(".");return K[K.length-1]}return"unknown"}).join(", "),Q=`Multiple parameter errors in ${$||"function"}: ${X}`;return j1(Q,{path:$,errors:Z})}function o1(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";let $=typeof Z;if($!=="object")return $;let X=Z.constructor?.name;if(X&&X!=="Object")return X;return"object"}function j7(Z,$){if(Z===null||Z===void 0)return!1;if(typeof Z!=="object"&&typeof Z!=="function")return!1;let X=Z;while(X!==null){if(X.constructor?.name===$)return!0;X=Object.getPrototypeOf(X)}return!1}function x1(Z,$,X){if(P1(Z))return Z;if(typeof $==="object"&&$!==null&&"check"in $){if($.check(Z))return null;return j1(`Expected ${$.description} but got ${o1(Z)}`,{path:X,expected:$.description,actual:o1(Z)})}let Q=o1(Z);if($==="any")return null;if($===Q)return null;if($==="number"&&Q==="number")return null;if($==="integer"&&Q==="number"&&Number.isInteger(Z))return null;if($==="non-negative-integer"&&Q==="number"&&Number.isInteger(Z)&&Z>=0)return null;if($==="object"&&Q==="object")return null;return j1(`Expected ${$} but got ${Q}`,{path:X,expected:$,actual:Q})}function o4(Z,$,X){for(let[Q,H]of Object.entries($.params)){let K=Z[Q];if(P1(K))return K;if(H.required&&K===void 0){let z=typeof H.type==="string"?H.type:H.type.description;return j1(`Missing required parameter '${Q}'`,{path:X?`${X}.${Q}`:Q,expected:z,actual:"undefined",loc:H.loc})}if(K===void 0)continue;let Y=x1(K,H.type,X?`${X}.${Q}`:Q);if(Y){if(H.loc)Y.loc=H.loc;return Y}}return null}function s4(Z,$){if(Z.__tjs=$,!(!$.polymorphic&&($.safe||$.safeReturn||Q1.safety!=="none"&&!$.unsafe||$.returns&&Q1.safety==="all"&&!$.unsafeReturn)))return Z;let Q=!!$.returns,H=!!$.unsafe,K=!!$.safe,Y=!!$.unsafeReturn,z=!!$.safeReturn,G=$.returns?.defaults,J=Object.entries($.params),W=J.length,U=Z.name||$.name||"anonymous",_=function(...L){if(a1>0)return Z.apply(this,L);let q=K||!H&&Q1.safety!=="none",A=Q&&(z||!Y&&Q1.safety==="all");if(!q&&!A)return Z.apply(this,L);if(L.length>0&&P1(L[0]))return L[0];if(q){let B=L.length===1&&typeof L[0]==="object"&&L[0]!==null&&!Array.isArray(L[0]),M=[];if(!B)for(let F=0;F<W;F++){let[R,w]=J[F],C=L[F];if(P1(C)){M.push(C);continue}if(w.required&&C===void 0){M.push(j1(`Missing required parameter '${R}'`,{path:`${U}.${R}`,expected:typeof w.type==="string"?w.type:w.type?.description||"value",actual:"undefined",loc:w.loc}));continue}if(C!==void 0){let P=x1(C,w.type,`${U}.${R}`);if(P){if(w.loc)P.loc=w.loc;M.push(P)}}}else{let F=L[0];for(let R=0;R<W;R++){let[w,C]=J[R],P=F[w];if(P1(P)){M.push(P);continue}if(C.required&&P===void 0){M.push(j1(`Missing required parameter '${w}'`,{path:`${U}.${w}`,expected:typeof C.type==="string"?C.type:C.type?.description||"value",actual:"undefined",loc:C.loc}));continue}if(P!==void 0){let O=x1(P,C.type,`${U}.${w}`);if(O){if(C.loc)O.loc=C.loc;M.push(O)}}}}if(M.length>0)return c4(M,U)}D7(U);try{let B=Z.apply(this,L);if(A&&$.returns&&!P1(B)){let M=G&&typeof B==="object"&&B!==null?Object.assign({},G,B):B,F=x1(M,$.returns.type,`${U}()`);if(F)return Q4(),F}return Q4(),B}catch(B){return Q4(),j1(B.message||String(B),{path:U,cause:B})}};return Object.defineProperty(_,"name",{value:Z.name}),_.__tjs=$,_}function M7(Z){let $=new Proxy(Z,{construct(X,Q,H){return Reflect.construct(X,Q,H)},apply(X,Q,H){return Reflect.construct(X,H)}});Object.defineProperty($,"name",{value:Z.name});for(let X of Object.getOwnPropertyNames(Z))if(X!=="length"&&X!=="name"&&X!=="prototype")Object.defineProperty($,X,Object.getOwnPropertyDescriptor(Z,X));return $}function xZ(){let Z={...Q1},$=[],X=0;function Q(M){Z={...Z,...M}}function H(){return{...Z}}function K(M){if(Z.debug&&M){$.push(M);let F=Z.maxStackSize??100;while($.length>F)$.shift()}}function Y(){if(Z.debug)$.pop()}function z(){return[...$]}function G(){Z={...p4},$.length=0,X=0}function J(){X++}function W(){if(X>0)X--}function U(){return X>0}let _=new Map;function L(M,F,R){if(!_.has(M))_.set(M,new Map);_.get(M).set(F,R)}function q(M,F){let R=typeof M,w;if(M===null||M===void 0)return;if(R==="string")w="String";else if(R==="number")w="Number";else if(R==="boolean")w="Boolean";else if(Array.isArray(M))w="Array";else if(R==="object")w=M.constructor?.name||"Object";else return;let C=w;while(C){let O=_.get(C);if(O?.has(F))return O.get(F);if(R==="object"&&!Array.isArray(M)){if(C=Object.getPrototypeOf(C===w?M:Object.getPrototypeOf(M))?.constructor?.name,C==="Object"||C===w)break}else break}let P=_.get("Object");if(P?.has(F))return P.get(F);return}function A(M,F,R){let w=R===null?"null":typeof R,C=Z.debug?z():void 0,P=new s1(`Expected ${F} for '${M}', got ${w}`,M,F,w,C);if(Z.logTypeErrors)console.error(`[TJS TypeError] ${P.message}`);if(Z.throwTypeErrors)throw P;return P}function B(M,F){let R={$error:!0,message:M,...F};if(Z.debug&&$.length>0){let w=F?.path?[...$,F.path]:[...$];R.stack=w}return R}return{version:K1,MonadicError:s1,typeError:A,isMonadicError:q7,isError:P1,error:B,composeErrors:c4,typeOf:o1,isNativeType:j7,checkType:x1,validateArgs:o4,wrap:s4,wrapClass:M7,compareVersions:m4,versionsCompatible:i4,configure:Q,getConfig:H,pushStack:K,popStack:Y,getStack:z,resetRuntime:G,enterUnsafe:J,exitUnsafe:W,isUnsafeMode:U,validate:U7,infer:H4.infer.bind(H4),Type:t,isRuntimeType:N1,Union:t0,Generic:n1,Enum:X4,FunctionPredicate:q0,Nullable:a0,Optional:r0,TArray:e0,TString:d0,TNumber:l0,TBoolean:m0,TInteger:i0,TPositiveInt:p0,TNonEmptyString:n0,TEmail:c0,TUrl:o0,TUuid:s0,TPair:Z4,TRecord:$4,Is:c1,IsNot:I7,Eq:n4,NotEq:w7,TypeOf:R7,IsBounded:B7,tjsEquals:D0,registerExtension:L,resolveExtension:q}}var h1={version:K1,MonadicError:s1,typeError:kZ,isMonadicError:q7,isError:P1,error:j1,composeErrors:c4,typeOf:o1,isNativeType:j7,checkType:x1,validateArgs:o4,wrap:s4,wrapClass:M7,compareVersions:m4,versionsCompatible:i4,configure:fZ,getConfig:yZ,pushStack:D7,popStack:Q4,getStack:A7,resetRuntime:hZ,enterUnsafe:gZ,exitUnsafe:bZ,isUnsafeMode:vZ,createRuntime:xZ,validate:U7,infer:H4.infer.bind(H4),Type:t,isRuntimeType:N1,Union:t0,Generic:n1,Enum:X4,FunctionPredicate:q0,Nullable:a0,Optional:r0,TArray:e0,TString:d0,TNumber:l0,TBoolean:m0,TInteger:i0,TPositiveInt:p0,TNonEmptyString:n0,TEmail:c0,TUrl:o0,TUuid:s0,Timestamp:d4,LegalDate:l4,TPair:Z4,TRecord:$4,Is:c1,IsNot:I7,Eq:n4,NotEq:w7,TypeOf:R7,IsBounded:B7};function a4(){let Z=globalThis;if(Z.__tjs){let $=Z.__tjs.version;if(typeof $!=="string")return Z.__tjs=h1,h1;let X=m4(K1,$);if(X===0)return Z.__tjs;if(i4(K1,$))if(X>0)console.info(`TJS runtime: upgrading ${$} → ${K1}`),Z.__tjs=h1;else console.info(`TJS runtime: keeping ${$} (newer than ${K1})`);else if(console.warn(`TJS runtime version conflict: ${$} vs ${K1} (major version mismatch)`),X>0)console.warn(`Upgrading to ${K1} - check for breaking changes`),Z.__tjs=h1;return Z.__tjs}return Z.__tjs=h1,h1}function uZ(Z){return`
170
170
  // TJS runtime wrapper (skips unsafe functions)
171
171
  if (typeof ${Z}.__tjs === 'object' && !${Z}.__tjs.unsafe && typeof globalThis.__tjs?.wrap === 'function') {
172
172
  ${Z} = globalThis.__tjs.wrap(${Z}, ${Z}.__tjs)
173
173
  }
174
- `.trim()}function j7(Z){return`
174
+ `.trim()}function F7(Z){return`
175
175
  // TJS: callable without new
176
176
  ${Z} = new Proxy(${Z}, { apply(t, _, a) { return Reflect.construct(t, a) } });
177
- `.trim()}function xZ(Z,$,X=0.000000001){if(Z===$)return!0;if(typeof Z==="number"&&typeof $==="number"){if(!Number.isInteger(Z)||!Number.isInteger($)){let Q=Math.abs(Z-$),H=Math.max(Math.abs(Z),Math.abs($),1);return Q/H<X}}return!1}function a4(Z,$){if(Z===$)return!0;if(typeof Z==="number"&&typeof $==="number"&&Number.isNaN(Z)&&Number.isNaN($))return!0;if(xZ(Z,$))return!0;if(Z===null||$===null)return Z===$;if(Z===void 0||$===void 0)return Z===$;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((H,K)=>a4(H,$[K]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),Q=Object.keys($);if(X.length!==Q.length)return!1;return X.every((H)=>a4(Z[H],$[H]))}function r4(Z,$,X=""){if($===null){if(Z===null)return{matches:!0};return{matches:!1,error:`Expected null at '${X}', got ${u1(Z)}`}}if($===void 0){if(Z===void 0)return{matches:!0};return{matches:!1,error:`Expected undefined at '${X}', got ${u1(Z)}`}}if(typeof $==="number"){if(typeof Z==="number")return{matches:!0};return{matches:!1,error:`Expected number at '${X}', got ${u1(Z)}`}}if(typeof $==="string"){if(typeof Z==="string")return{matches:!0};return{matches:!1,error:`Expected string at '${X}', got ${u1(Z)}`}}if(typeof $==="boolean"){if(typeof Z==="boolean")return{matches:!0};return{matches:!1,error:`Expected boolean at '${X}', got ${u1(Z)}`}}if(Array.isArray($)){if(!Array.isArray(Z))return{matches:!1,error:`Expected array at '${X}', got ${u1(Z)}`};if($.length===0)return{matches:!0};let Q=$[0];for(let H=0;H<Z.length;H++){let K=r4(Z[H],Q,`${X}[${H}]`);if(!K.matches)return K}return{matches:!0}}if(typeof $==="object"&&$!==null){if(typeof Z!=="object"||Z===null||Array.isArray(Z))return{matches:!1,error:`Expected object at '${X}', got ${u1(Z)}`};for(let Q of Object.keys($)){let H=X?`${X}.${Q}`:Q;if(!(Q in Z))return{matches:!1,error:`Missing property '${H}'`};let K=r4(Z[Q],$[Q],H);if(!K.matches)return K}return{matches:!0}}if(Z===$)return{matches:!0};return{matches:!1,error:`Type mismatch at '${X}'`}}function u1(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}function A0(Z,$=0){if(Z===null)return"null";if(Z===void 0)return"undefined";if(typeof Z==="string")return JSON.stringify(Z);if(typeof Z==="number")return String(Z);if(typeof Z==="boolean")return String(Z);if(Array.isArray(Z)){if(Z.length===0)return"[]";if(Z.length<=3)return`[${Z.map((X)=>A0(X,$)).join(", ")}]`;return`[${Z.slice(0,3).map((X)=>A0(X,$)).join(", ")}, ...]`}if(typeof Z==="object"){let X=Object.entries(Z);if(X.length===0)return"{}";let Q=(G)=>/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(G)?G:JSON.stringify(G);if(X.length<=2)return`{${X.map(([J,W])=>`${Q(J)}: ${A0(W,$)}`).join(", ")}}`;let H=" ".repeat($+1),K=" ".repeat($),Y=X.slice(0,8).map(([G,J])=>`${H}${Q(G)}: ${A0(J,$+1)}`).join(`,
177
+ `.trim()}function dZ(Z,$,X=0.000000001){if(Z===$)return!0;if(typeof Z==="number"&&typeof $==="number"){if(!Number.isInteger(Z)||!Number.isInteger($)){let Q=Math.abs(Z-$),H=Math.max(Math.abs(Z),Math.abs($),1);return Q/H<X}}return!1}function r4(Z,$){if(Z===$)return!0;if(typeof Z==="number"&&typeof $==="number"&&Number.isNaN(Z)&&Number.isNaN($))return!0;if(dZ(Z,$))return!0;if(Z===null||$===null)return Z===$;if(Z===void 0||$===void 0)return Z===$;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((H,K)=>r4(H,$[K]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),Q=Object.keys($);if(X.length!==Q.length)return!1;return X.every((H)=>r4(Z[H],$[H]))}function t4(Z,$,X=""){if($===null){if(Z===null)return{matches:!0};return{matches:!1,error:`Expected null at '${X}', got ${u1(Z)}`}}if($===void 0){if(Z===void 0)return{matches:!0};return{matches:!1,error:`Expected undefined at '${X}', got ${u1(Z)}`}}if(typeof $==="number"){if(typeof Z==="number")return{matches:!0};return{matches:!1,error:`Expected number at '${X}', got ${u1(Z)}`}}if(typeof $==="string"){if(typeof Z==="string")return{matches:!0};return{matches:!1,error:`Expected string at '${X}', got ${u1(Z)}`}}if(typeof $==="boolean"){if(typeof Z==="boolean")return{matches:!0};return{matches:!1,error:`Expected boolean at '${X}', got ${u1(Z)}`}}if(Array.isArray($)){if(!Array.isArray(Z))return{matches:!1,error:`Expected array at '${X}', got ${u1(Z)}`};if($.length===0)return{matches:!0};let Q=$[0];for(let H=0;H<Z.length;H++){let K=t4(Z[H],Q,`${X}[${H}]`);if(!K.matches)return K}return{matches:!0}}if(typeof $==="object"&&$!==null){if(typeof Z!=="object"||Z===null||Array.isArray(Z))return{matches:!1,error:`Expected object at '${X}', got ${u1(Z)}`};for(let Q of Object.keys($)){let H=X?`${X}.${Q}`:Q;if(!(Q in Z))return{matches:!1,error:`Missing property '${H}'`};let K=t4(Z[Q],$[Q],H);if(!K.matches)return K}return{matches:!0}}if(Z===$)return{matches:!0};return{matches:!1,error:`Type mismatch at '${X}'`}}function u1(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}function A0(Z,$=0){if(Z===null)return"null";if(Z===void 0)return"undefined";if(typeof Z==="string")return JSON.stringify(Z);if(typeof Z==="number")return String(Z);if(typeof Z==="boolean")return String(Z);if(Array.isArray(Z)){if(Z.length===0)return"[]";if(Z.length<=3)return`[${Z.map((X)=>A0(X,$)).join(", ")}]`;return`[${Z.slice(0,3).map((X)=>A0(X,$)).join(", ")}, ...]`}if(typeof Z==="object"){let X=Object.entries(Z);if(X.length===0)return"{}";let Q=(G)=>/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(G)?G:JSON.stringify(G);if(X.length<=2)return`{${X.map(([J,W])=>`${Q(J)}: ${A0(W,$)}`).join(", ")}}`;let H=" ".repeat($+1),K=" ".repeat($),Y=X.slice(0,8).map(([G,J])=>`${H}${Q(G)}: ${A0(J,$+1)}`).join(`,
178
178
  `),z=X.length>8?`,
179
179
  ${H}...`:"";return`{
180
180
  ${Y}${z}
181
- ${K}}`}return String(Z)}function uZ(Z){let $=Z.replace(/\/\*[\s\S]*?\*\//g,(X)=>{let Q=X.split(`
181
+ ${K}}`}return String(Z)}function lZ(Z){let $=Z.replace(/\/\*[\s\S]*?\*\//g,(X)=>{let Q=X.split(`
182
182
  `).length-1;return`
183
- `.repeat(Q)});return $=$.replace(/\/\/[^\n]*/g,""),$}function Y4(Z){let $=Z.replace(/^import\s+.*?from\s+['"][^'"]+['"];?\s*$/gm,"");return $=$.replace(/^import\s+['"][^'"]+['"];?\s*$/gm,""),$=$.replace(/^export\s+default\s+/gm,""),$=$.replace(/^export\s+/gm,""),$=$.replace(/^(\s*)((?:const|let|var)\s+\w+\s*=\s*)?await\s+.+$/gm,"$1/* top-level await removed for test execution */"),$}function M7(Z){let $=Z.replace(/^const __tjs = globalThis\.__tjs\?\.createRuntime\?\.\(\) \?\? globalThis\.__tjs;\n?/m,"");return $=$.replace(/^const \{ [\w, ]+ \} = __tjs \?\? \{\};\n?/m,""),$}function dZ(Z){if(Object.keys(Z).length===0)return"";let $=[];for(let[X,Q]of Object.entries(Z)){let H=Y4(Q);$.push(`// Resolved import: ${X}`),$.push(H)}return $.join(`
184
- `)}function lZ(Z){let $={},X=Z.trim();if(!X.startsWith("{")||!X.includes("="))try{return{pattern:Function(`return ${Z}`)(),defaults:$}}catch{return null}let Q="",H=0,K=0;while(K<X.length){let Y=X[K];if(Y==="{"||Y==="["||Y==="(")H++,Q+=Y,K++;else if(Y==="}"||Y==="]"||Y===")")H--,Q+=Y,K++;else if(Y==="'"||Y==='"'||Y==="`"){let z=Y;Q+=Y,K++;while(K<X.length&&X[K]!==z){if(X[K]==="\\")Q+=X[K++];Q+=X[K++]}if(K<X.length)Q+=X[K++]}else if(H===1&&Y==="="){let J=(Q.slice(Q.lastIndexOf("{")+1).split(",").pop()||"").match(/\s*(\w+)\s*$/);if(J){let W=K+1;while(W<X.length&&/\s/.test(X[W]))W++;let L="",_=0;while(W<X.length){let U=X[W];if(U==="{"||U==="["||U==="(")_++;else if(U==="}"||U==="]"||U===")"){if(_===0)break;_--}else if(U===","&&_===0)break;L+=U,W++}try{$[J[1]]=Function(`return ${L.trim()}`)()}catch{}Q+=":",K++;continue}Q+=Y,K++}else Q+=Y,K++}try{return{pattern:Function(`return ${Q}`)(),defaults:$}}catch{return null}}function F7(Z){let $=[],X=uZ(Z),Q=/(async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*(-[>?])\s*/g,H;while((H=Q.exec(X))!==null){let K=!!H[1],Y=H[2],z=H[3],G=H[4],J=X.slice(0,H.index).split(`
185
- `).length;if(G==="-!")continue;let W=X.slice(H.index+H[0].length),L=t4(W);if(!L)continue;let _=mZ(z);if(z.trim()&&_.length===0)continue;try{let U=lZ(L);if(!U)continue;let q=_.map((A)=>Function(`return ${A}`)());$.push({funcName:Y,args:q,expected:U.pattern,defaults:Object.keys(U.defaults).length>0?U.defaults:void 0,line:J,isAsync:K})}catch{}}return $}function P7(Z,$,X,Q,H={},K=new Map){let Y=[];if(Z.length===0&&X.length===0)return Y;let z=Q.match(/^import\s+.*?from\s+['"]([^'"]+)['"];?\s*$/gm)||[],G=z.length>0&&z.some((R)=>{let w=R.match(/from\s+['"]([^'"]+)['"]/);return w&&!(w[1]in H)}),J=Y4(Q),W=dZ(H),L=$.map((R)=>R.body).join(`
183
+ `.repeat(Q)});return $=$.replace(/\/\/[^\n]*/g,""),$}function Y4(Z){let $=Z.replace(/^import\s+.*?from\s+['"][^'"]+['"];?\s*$/gm,"");return $=$.replace(/^import\s+['"][^'"]+['"];?\s*$/gm,""),$=$.replace(/^export\s+default\s+/gm,""),$=$.replace(/^export\s+/gm,""),$=$.replace(/^(\s*)((?:const|let|var)\s+\w+\s*=\s*)?await\s+.+$/gm,"$1/* top-level await removed for test execution */"),$}function P7(Z){let $=Z.replace(/^const __tjs = globalThis\.__tjs\?\.createRuntime\?\.\(\) \?\? globalThis\.__tjs;\n?/m,"");return $=$.replace(/^const \{ [\w, ]+ \} = __tjs \?\? \{\};\n?/m,""),$}function mZ(Z){if(Object.keys(Z).length===0)return"";let $=[];for(let[X,Q]of Object.entries(Z)){let H=Y4(Q);$.push(`// Resolved import: ${X}`),$.push(H)}return $.join(`
184
+ `)}function iZ(Z){let $={},X=Z.trim();if(!X.startsWith("{")||!X.includes("="))try{return{pattern:Function(`return ${Z}`)(),defaults:$}}catch{return null}let Q="",H=0,K=0;while(K<X.length){let Y=X[K];if(Y==="{"||Y==="["||Y==="(")H++,Q+=Y,K++;else if(Y==="}"||Y==="]"||Y===")")H--,Q+=Y,K++;else if(Y==="'"||Y==='"'||Y==="`"){let z=Y;Q+=Y,K++;while(K<X.length&&X[K]!==z){if(X[K]==="\\")Q+=X[K++];Q+=X[K++]}if(K<X.length)Q+=X[K++]}else if(H===1&&Y==="="){let J=(Q.slice(Q.lastIndexOf("{")+1).split(",").pop()||"").match(/\s*(\w+)\s*$/);if(J){let W=K+1;while(W<X.length&&/\s/.test(X[W]))W++;let U="",_=0;while(W<X.length){let L=X[W];if(L==="{"||L==="["||L==="(")_++;else if(L==="}"||L==="]"||L===")"){if(_===0)break;_--}else if(L===","&&_===0)break;U+=L,W++}try{$[J[1]]=Function(`return ${U.trim()}`)()}catch{}Q+=":",K++;continue}Q+=Y,K++}else Q+=Y,K++}try{return{pattern:Function(`return ${Q}`)(),defaults:$}}catch{return null}}function V7(Z){let $=[],X=lZ(Z),Q=/(async\s+)?function\s+(\w+)\s*\(([^)]*)\)\s*(-[>?])\s*/g,H;while((H=Q.exec(X))!==null){let K=!!H[1],Y=H[2],z=H[3],G=H[4],J=X.slice(0,H.index).split(`
185
+ `).length;if(G==="-!")continue;let W=X.slice(H.index+H[0].length),U=e4(W);if(!U)continue;let _=pZ(z);if(z.trim()&&_.length===0)continue;try{let L=iZ(U);if(!L)continue;let q=_.map((A)=>Function(`return ${A}`)());$.push({funcName:Y,args:q,expected:L.pattern,defaults:Object.keys(L.defaults).length>0?L.defaults:void 0,line:J,isAsync:K})}catch{}}return $}function C7(Z,$,X,Q,H={},K=new Map){let Y=[];if(Z.length===0&&X.length===0)return Y;let z=Q.match(/^import\s+.*?from\s+['"]([^'"]+)['"];?\s*$/gm)||[],G=z.length>0&&z.some((R)=>{let w=R.match(/from\s+['"]([^'"]+)['"]/);return w&&!(w[1]in H)}),J=Y4(Q),W=mZ(H),U=$.map((R)=>R.body).join(`
186
186
  `),_=Z.map((R,w)=>{let C=K.size>0?J0(R.body,K):R.body;return`
187
187
  // Test ${w}: ${R.description}
188
188
  try {
@@ -192,7 +192,7 @@ ${K}}`}return String(Z)}function uZ(Z){let $=Z.replace(/\/\*[\s\S]*?\*\//g,(X)=>
192
192
  __testResults.push({ idx: ${w}, passed: false, error: e.message || String(e) });
193
193
  }
194
194
  `}).join(`
195
- `),U=X.filter((R)=>!R.isAsync),q=X.filter((R)=>R.isAsync),A=U.map((R,w)=>`
195
+ `),L=X.filter((R)=>!R.isAsync),q=X.filter((R)=>R.isAsync),A=L.map((R,w)=>`
196
196
  // Signature test ${w}: ${R.funcName}
197
197
  try {
198
198
  let __actual = ${R.funcName}(${R.args.map((C)=>JSON.stringify(C)).join(", ")});
@@ -208,7 +208,7 @@ ${K}}`}return String(Z)}function uZ(Z){let $=Z.replace(/\/\*[\s\S]*?\*\//g,(X)=>
208
208
  __sigTestResults.push({ idx: ${w}, passed: false, error: e.message || String(e) });
209
209
  }
210
210
  `).join(`
211
- `);s4();let F=`
211
+ `);a4();let F=`
212
212
  ${`
213
213
  const __saved_tjs = globalThis.__tjs;
214
214
  `}
@@ -280,7 +280,7 @@ ${K}}`}return String(Z)}function uZ(Z){let $=Z.replace(/\/\*[\s\S]*?\*\//g,(X)=>
280
280
 
281
281
  // Execute the module code ONCE
282
282
  ${J}
283
- ${L}
283
+ ${U}
284
284
 
285
285
  // Run explicit test blocks
286
286
  ${_}
@@ -292,8 +292,8 @@ ${K}}`}return String(Z)}function uZ(Z){let $=Z.replace(/\/\*[\s\S]*?\*\//g,(X)=>
292
292
  ${"globalThis.__tjs = __saved_tjs;"}
293
293
  }
294
294
  return { testResults: __testResults, sigTestResults: __sigTestResults };
295
- `;try{let R=Function("__deepEqual","__format","__typeMatches",F),{testResults:w,sigTestResults:C}=R(a4,A0,r4);for(let P of w){let O=Z[P.idx],k=G&&!P.passed&&P.error&&/is not defined$/.test(P.error);Y.push({description:O.description,passed:k?!0:P.passed,error:k?void 0:P.error,line:O.line})}for(let P of C){let O=U[P.idx],k=G&&!P.passed&&P.error&&/is not defined$/.test(P.error);Y.push({description:`${O.funcName} signature example`,passed:k?!0:P.passed,error:k?void 0:P.error,isSignatureTest:!0,line:O.line})}}catch(R){let w=G&&R instanceof ReferenceError;for(let C of Z)Y.push({description:C.description,passed:w,error:w?void 0:`Module execution failed: ${R.message}`,line:C.line});for(let C of U)Y.push({description:`${C.funcName} signature example`,passed:w,error:w?void 0:`Module execution failed: ${R.message}`,isSignatureTest:!0,line:C.line})}for(let R of q)Y.push({description:`${R.funcName} signature example`,passed:!0,isSignatureTest:!0,line:R.line});return Y}function t4(Z){let $="",X=0,Q=!1;for(let K=0;K<Z.length;K++){let Y=Z[K];if(Y==="{"||Y==="["||Y==="("){if(Y==="{"&&X===0&&Q)break;X++,$+=Y,Q=!0}else if(Y==="}"||Y==="]"||Y===")")X--,$+=Y;else if(!/\s/.test(Y))$+=Y,Q=!0;else $+=Y}return $.trim()||null}function mZ(Z){if(!Z.trim())return[];let $=[],X=iZ(Z);for(let Q of X){let H=Q.trim(),K=H.match(/^\.\.\.(\w+)\s*[:=]\s*(\[.+\])$/);if(K){try{let z=Function(`return ${K[2]}`)();if(Array.isArray(z))for(let G of z)$.push(JSON.stringify(G))}catch{}continue}if(H.startsWith("..."))continue;let Y=H.match(/(?:\(\s*[?!]\s*)?(\w+)\s*[:=]\s*(.+?)(?:\))?$/);if(Y)$.push(Y[2].trim());else return[]}return $}function iZ(Z){let $=[],X="",Q=0;for(let H of Z){if(H==="("||H==="["||H==="{")Q++;else if(H===")"||H==="]"||H==="}")Q--;else if(H===","&&Q===0){$.push(X.trim()),X="";continue}X+=H}if(X.trim())$.push(X.trim());return $}import*as C7 from"acorn";var R1={i32:127,i64:126,f32:125,f64:124,v128:123,funcref:112,externref:111,void:64},I0={custom:0,type:1,import:2,function:3,table:4,memory:5,global:6,export:7,start:8,element:9,code:10,data:11},D={unreachable:0,nop:1,block:2,loop:3,if:4,else:5,end:11,br:12,br_if:13,br_table:14,return:15,call:16,call_indirect:17,drop:26,select:27,local_get:32,local_set:33,local_tee:34,global_get:35,global_set:36,i32_load:40,i64_load:41,f32_load:42,f64_load:43,i32_load8_s:44,i32_load8_u:45,i32_load16_s:46,i32_load16_u:47,i32_store:54,i64_store:55,f32_store:56,f64_store:57,i32_store8:58,i32_store16:59,memory_size:63,memory_grow:64,i32_const:65,i64_const:66,f32_const:67,f64_const:68,i32_eqz:69,i32_eq:70,i32_ne:71,i32_lt_s:72,i32_lt_u:73,i32_gt_s:74,i32_gt_u:75,i32_le_s:76,i32_le_u:77,i32_ge_s:78,i32_ge_u:79,i64_eqz:80,i64_eq:81,i64_ne:82,i64_lt_s:83,i64_lt_u:84,i64_gt_s:85,i64_gt_u:86,i64_le_s:87,i64_le_u:88,i64_ge_s:89,i64_ge_u:90,f32_eq:91,f32_ne:92,f32_lt:93,f32_gt:94,f32_le:95,f32_ge:96,f64_eq:97,f64_ne:98,f64_lt:99,f64_gt:100,f64_le:101,f64_ge:102,i32_clz:103,i32_ctz:104,i32_popcnt:105,i32_add:106,i32_sub:107,i32_mul:108,i32_div_s:109,i32_div_u:110,i32_rem_s:111,i32_rem_u:112,i32_and:113,i32_or:114,i32_xor:115,i32_shl:116,i32_shr_s:117,i32_shr_u:118,i32_rotl:119,i32_rotr:120,i64_add:124,i64_sub:125,i64_mul:126,i64_div_s:127,f32_abs:139,f32_neg:140,f32_ceil:141,f32_floor:142,f32_trunc:143,f32_nearest:144,f32_sqrt:145,f32_add:146,f32_sub:147,f32_mul:148,f32_div:149,f32_min:150,f32_max:151,f32_copysign:152,f64_abs:153,f64_neg:154,f64_ceil:155,f64_floor:156,f64_trunc:157,f64_nearest:158,f64_sqrt:159,f64_add:160,f64_sub:161,f64_mul:162,f64_div:163,f64_min:164,f64_max:165,f64_copysign:166,i32_wrap_i64:167,i32_trunc_f32_s:168,i32_trunc_f32_u:169,i32_trunc_f64_s:170,i32_trunc_f64_u:171,i64_extend_i32_s:172,i64_extend_i32_u:173,f32_convert_i32_s:178,f32_convert_i32_u:179,f32_convert_i64_s:180,f32_demote_f64:182,f64_convert_i32_s:183,f64_convert_i32_u:184,f64_convert_i64_s:185,f64_promote_f32:187,i32_reinterpret_f32:188,f32_reinterpret_i32:190,f64_reinterpret_i64:191,i32_extend8_s:192,i32_extend16_s:193},pZ=Object.fromEntries(Object.entries(D).map(([Z,$])=>[$,Z.replace(/_/g,".")])),B0=253,$1={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},nZ=Object.fromEntries(Object.entries($1).map(([Z,$])=>[$,Z.replace(/_/g,".")]));function e4(Z){return[B0,...u(Z)]}function V7(Z,$,X){return[B0,...u(Z),...u($),...u(X)]}function u(Z){let $=[];do{let X=Z&127;if(Z>>>=7,Z!==0)X|=128;$.push(X)}while(Z!==0);return $}function w0(Z){let $=[],X=!0;while(X){let Q=Z&127;if(Z>>=7,Z===0&&(Q&64)===0||Z===-1&&(Q&64)!==0)X=!1;else Q|=128;$.push(Q)}return $}function $6(Z){let $=new ArrayBuffer(4);return new Float32Array($)[0]=Z,[...new Uint8Array($)]}function L1(Z){let $=new ArrayBuffer(8);return new Float64Array($)[0]=Z,[...new Uint8Array($)]}function Z6(Z){let $=new TextEncoder().encode(Z);return[...u($.length),...$]}function R0(Z,$){return[Z,...u($.length),...$]}function E1(Z,$){let X=0,Q=0,H=$;while(H<Z.length){let K=Z[H];if(X|=(K&127)<<Q,H++,(K&128)===0)break;Q+=7}return[X,H-$]}function cZ(Z,$){let X=new ArrayBuffer(8),Q=new Uint8Array(X);for(let H=0;H<8;H++)Q[H]=Z[$+H];return new Float64Array(X)[0]}function oZ(Z,$,X){let Q=[],H=1,K=()=>" ".repeat(H),Y=$.map((J,W)=>`(param $${J.name} ${J.type})`).join(" "),z=X.map((J,W)=>`(local $L${$.length+W} ${J})`).join(" ");if(Q.push(`(func (export "compute") ${Y} (result f64)`),z)Q.push(` ${z}`);let G=0;while(G<Z.length){let J=Z[G],W=pZ[J]||`unknown(0x${J.toString(16)})`;if(G++,J===D.local_get||J===D.local_set||J===D.local_tee){let[L,_]=E1(Z,G);G+=_;let U=L<$.length?`$${$[L].name}`:`$L${L}`;Q.push(`${K()}${W} ${U}`)}else if(J===D.br||J===D.br_if){let[L,_]=E1(Z,G);G+=_,Q.push(`${K()}${W} ${L}`)}else if(J===D.i32_const){let[L,_]=E1(Z,G);G+=_,Q.push(`${K()}i32.const ${L}`)}else if(J===D.f32_const){let L=new ArrayBuffer(4),_=new Uint8Array(L);for(let q=0;q<4;q++)_[q]=Z[G+q];let U=new Float32Array(L)[0];G+=4,Q.push(`${K()}f32.const ${U}`)}else if(J===D.f64_const){let L=cZ(Z,G);G+=8,Q.push(`${K()}f64.const ${L}`)}else if(J===D.block||J===D.loop){let L=Z[G];G++,Q.push(`${K()}${W}${L===R1.void?"":` (result ${L===R1.f64?"f64":"i32"})`}`),H++}else if(J===D.if){let L=Z[G];G++,Q.push(`${K()}if${L===R1.void?"":` (result ${L===R1.f64?"f64":"i32"})`}`),H++}else if(J===D.else)H--,Q.push(`${K()}else`),H++;else if(J===D.end)H=Math.max(1,H-1),Q.push(`${K()}end`);else if(J===D.f64_load||J===D.f64_store||J===D.f32_load||J===D.f32_store||J===D.i32_load||J===D.i32_store){let[L,_]=E1(Z,G);G+=_;let[U,q]=E1(Z,G);G+=q,Q.push(`${K()}${W}${U?` offset=${U}`:""}`)}else if(J===B0){let[L,_]=E1(Z,G);G+=_;let U=nZ[L]||`simd.unknown(0x${L.toString(16)})`;if(L===$1.v128_load||L===$1.v128_store){let[q,A]=E1(Z,G);G+=A;let[B,M]=E1(Z,G);G+=M,Q.push(`${K()}${U}${B?` offset=${B}`:""}`)}else if(L===$1.v128_const){let q=Z.slice(G,G+16);G+=16,Q.push(`${K()}v128.const ${q.map((A)=>"0x"+A.toString(16).padStart(2,"0")).join(" ")}`)}else if(L===$1.f32x4_extract_lane||L===$1.f32x4_replace_lane){let q=Z[G];G++,Q.push(`${K()}${U} ${q}`)}else Q.push(`${K()}${U}`)}else Q.push(`${K()}${W}`)}return Q.push(")"),Q.join(`
296
- `)}var G4={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:D.i32_load8_s,storeOp:D.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:D.i32_load8_u,storeOp:D.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:D.i32_load8_u,storeOp:D.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:D.i32_load16_s,storeOp:D.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:D.i32_load16_u,storeOp:D.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:D.i32_load,storeOp:D.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:D.i32_load,storeOp:D.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:D.f32_load,storeOp:D.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:D.f64_load,storeOp:D.f64_store}};function sZ(Z){let $={params:Z,locals:new Map,nextLocalIndex:Z.length,localTypes:[],warnings:[],errors:[],loopDepth:0,needsMathImports:new Set,needsMemory:!1,hasReturn:!1,wat:[],watIndent:1};return Z.forEach((X,Q)=>{$.locals.set(X.name,{index:Q,type:X.type})}),$}function z4(Z,$,X){if(Z.locals.has($))return Z.errors.push(`Duplicate local declaration: ${$}`),Z.locals.get($).index;let Q=Z.nextLocalIndex++;return Z.locals.set($,{index:Q,type:X}),Z.localTypes.push(X),Q}function d1(Z,$){return Z.locals.get($)}function r1(Z,$){switch(Z.type){case"ExpressionStatement":{let X=Z.expression;return[...d(X,$),D.drop]}case"ReturnStatement":{let X=Z;if($.hasReturn=!0,!X.argument)return[D.return];let Q=d(X.argument,$),H=s(X.argument,$);if(H==="i32")Q.push(D.f64_convert_i32_s);else if(H==="f32")Q.push(D.f64_promote_f32);return Q.push(D.return),Q}case"VariableDeclaration":{let X=Z,Q=[];for(let H of X.declarations){if(H.id.type!=="Identifier"){$.errors.push("Destructuring not supported in WASM blocks");continue}let K=H.id.name,Y="f64";if(H.init)Y=s(H.init,$);let z=z4($,K,Y);if(H.init)Q.push(...d(H.init,$)),Q.push(D.local_set,...u(z))}return Q}case"ForStatement":return aZ(Z,$);case"IfStatement":return rZ(Z,$);case"BlockStatement":{let X=Z,Q=[];for(let H of X.body)Q.push(...r1(H,$));return Q}default:return $.errors.push(`Unsupported statement type: ${Z.type}`),[]}}function aZ(Z,$){let X=[];if(Z.init)if(Z.init.type==="VariableDeclaration")X.push(...r1(Z.init,$));else X.push(...d(Z.init,$));if(X.push(D.block,R1.void),X.push(D.loop,R1.void),Z.test)X.push(...d(Z.test,$)),X.push(D.i32_eqz),X.push(D.br_if,1);if($.loopDepth++,Z.body)X.push(...r1(Z.body,$));if($.loopDepth--,Z.update)X.push(...d(Z.update,$)),X.push(D.drop);return X.push(D.br,0),X.push(D.end),X.push(D.end),X}function rZ(Z,$){let X=[];if(X.push(...d(Z.test,$)),X.push(D.if,R1.void),X.push(...r1(Z.consequent,$)),Z.alternate)X.push(D.else),X.push(...r1(Z.alternate,$));return X.push(D.end),X}function s(Z,$){switch(Z.type){case"Literal":{let X=Z;if(typeof X.value==="number"){if(X.raw&&(X.raw.includes(".")||X.raw.includes("e")))return"f64";if(Number.isInteger(X.value)&&X.value>=-2147483648&&X.value<=2147483647)return"i32";return"f64"}return"f64"}case"Identifier":return d1($,Z.name)?.type??"f64";case"BinaryExpression":case"AssignmentExpression":{let X=Z;if(["<",">","<=",">=","==","!=","===","!=="].includes(X.operator))return"i32";if(["|","&","^","<<",">>",">>>"].includes(X.operator))return"i32";let Q=s(X.left,$),H=s(X.right,$);if(Q==="v128"||H==="v128")return"v128";if(Q==="f64"||H==="f64")return"f64";if(Q==="f32"||H==="f32")return"f32";return"i32"}case"UnaryExpression":{let X=Z;if(X.operator==="!")return"i32";return s(X.argument,$)}case"MemberExpression":{let X=Z;if(X.object.type==="Identifier"){if(d1($,X.object.name)){let H=$.params.find((K)=>K.name===X.object.name);if(H?.arrayType){let K=G4[H.arrayType];if(K)return K.elementType}}}return"f64"}case"CallExpression":{let X=Z;if(X.callee.type==="MemberExpression"){let Q=X.callee;if(Q.object.type==="Identifier"&&Q.object.name==="Math")return"f64"}if(X.callee.type==="Identifier"){let Q=X.callee.name;if(Q==="f32x4_extract_lane")return"f32";if(Q.startsWith("f32x4_")||Q==="v128_load")return"v128"}return"f64"}default:return"f64"}}function d(Z,$){switch(Z.type){case"Literal":{let X=Z;if(typeof X.value==="number"){let Q=s(Z,$);if(Q==="i32")return[D.i32_const,...w0(X.value|0)];else if(Q==="f32")return[D.f32_const,...$6(X.value)];else return[D.f64_const,...L1(X.value)]}return $.errors.push(`Unsupported literal type: ${typeof X.value}`),[D.f64_const,...L1(0)]}case"Identifier":{let X=Z.name,Q=d1($,X);if(Q)return[D.local_get,...u(Q.index)];return $.errors.push(`Unknown identifier: ${X}`),[D.f64_const,...L1(0)]}case"BinaryExpression":return tZ(Z,$);case"UnaryExpression":return eZ(Z,$);case"AssignmentExpression":return Z5(Z,$);case"UpdateExpression":return $5(Z,$);case"MemberExpression":return X5(Z,$);case"CallExpression":return H5(Z,$);case"SequenceExpression":{let X=Z,Q=[];for(let H=0;H<X.expressions.length;H++)if(Q.push(...d(X.expressions[H],$)),H<X.expressions.length-1)Q.push(D.drop);return Q}default:return $.errors.push(`Unsupported expression type: ${Z.type}`),[D.f64_const,...L1(0)]}}function tZ(Z,$){let X=d(Z.left,$),Q=d(Z.right,$),H=s(Z,$),K=s(Z.left,$),Y=s(Z.right,$),z=["<",">","<=",">=","==","===","!=","!=="].includes(Z.operator),G;if(K==="f64"||Y==="f64")G="f64";else if(K==="f32"||Y==="f32")G="f32";else G="i32";if(!z&&H==="f64")G="f64";let J=X,W=Q;if(G==="f64"){if(K==="i32")J=[...X,D.f64_convert_i32_s];else if(K==="f32")J=[...X,D.f64_promote_f32];if(Y==="i32")W=[...Q,D.f64_convert_i32_s];else if(Y==="f32")W=[...Q,D.f64_promote_f32]}else if(G==="f32"){if(K==="i32")J=[...X,D.f32_convert_i32_s];if(Y==="i32")W=[...Q,D.f32_convert_i32_s]}let _={"+":{i32:D.i32_add,f32:D.f32_add,f64:D.f64_add},"-":{i32:D.i32_sub,f32:D.f32_sub,f64:D.f64_sub},"*":{i32:D.i32_mul,f32:D.f32_mul,f64:D.f64_mul},"/":{i32:D.i32_div_s,f32:D.f32_div,f64:D.f64_div},"%":{i32:D.i32_rem_s},"<":{i32:D.i32_lt_s,f32:D.f32_lt,f64:D.f64_lt},">":{i32:D.i32_gt_s,f32:D.f32_gt,f64:D.f64_gt},"<=":{i32:D.i32_le_s,f32:D.f32_le,f64:D.f64_le},">=":{i32:D.i32_ge_s,f32:D.f32_ge,f64:D.f64_ge},"==":{i32:D.i32_eq,f32:D.f32_eq,f64:D.f64_eq},"===":{i32:D.i32_eq,f32:D.f32_eq,f64:D.f64_eq},"!=":{i32:D.i32_ne,f32:D.f32_ne,f64:D.f64_ne},"!==":{i32:D.i32_ne,f32:D.f32_ne,f64:D.f64_ne},"|":{i32:D.i32_or},"&":{i32:D.i32_and},"^":{i32:D.i32_xor},"<<":{i32:D.i32_shl},">>":{i32:D.i32_shr_s},">>>":{i32:D.i32_shr_u}}[Z.operator];if(!_)return $.errors.push(`Unsupported operator: ${Z.operator}`),[D.f64_const,...L1(0)];let U=_[G]??_.f64??_.i32;if(U===void 0)return $.errors.push(`Operator ${Z.operator} not supported for type ${G}`),[D.f64_const,...L1(0)];return[...J,...W,U]}function eZ(Z,$){let X=d(Z.argument,$),Q=s(Z.argument,$);switch(Z.operator){case"-":if(Q==="i32")return[D.i32_const,0,...X,D.i32_sub];else if(Q==="f32")return[...X,D.f32_neg];else return[...X,D.f64_neg];case"!":return[...X,D.i32_eqz];case"~":return[...X,D.i32_const,...w0(-1),D.i32_xor];default:return $.errors.push(`Unsupported unary operator: ${Z.operator}`),X}}function Z5(Z,$){if(Z.left.type==="MemberExpression")return Q5(Z.left,Z.right,Z.operator,$);if(Z.left.type!=="Identifier")return $.errors.push("Assignment target must be identifier or array element"),[];let X=Z.left.name,Q=d1($,X);if(!Q)return $.errors.push(`Unknown variable: ${X}`),[];let H=[];if(Z.operator==="="){H.push(...d(Z.right,$));let K=s(Z.right,$);if(Q.type==="f64"&&K==="i32")H.push(D.f64_convert_i32_s);else if(Q.type==="f64"&&K==="f32")H.push(D.f64_promote_f32);else if(Q.type==="i32"&&K==="f64")H.push(D.i32_trunc_f64_s);else if(Q.type==="i32"&&K==="f32")H.push(D.i32_trunc_f32_s);else if(Q.type==="f32"&&K==="i32")H.push(D.f32_convert_i32_s);else if(Q.type==="f32"&&K==="f64")H.push(D.f32_demote_f64)}else{let K=s(Z.right,$),Y=Q.type;if(K==="f64"||Q.type==="f64")Y="f64";else if(K==="f32"||Q.type==="f32")Y="f32";if(H.push(D.local_get,...u(Q.index)),Y==="f64"&&Q.type==="i32")H.push(D.f64_convert_i32_s);else if(Y==="f64"&&Q.type==="f32")H.push(D.f64_promote_f32);else if(Y==="f32"&&Q.type==="i32")H.push(D.f32_convert_i32_s);if(H.push(...d(Z.right,$)),Y==="f64"&&K==="i32")H.push(D.f64_convert_i32_s);else if(Y==="f64"&&K==="f32")H.push(D.f64_promote_f32);else if(Y==="f32"&&K==="i32")H.push(D.f32_convert_i32_s);let z=Z.operator.slice(0,-1),J={"+":{i32:D.i32_add,f32:D.f32_add,f64:D.f64_add},"-":{i32:D.i32_sub,f32:D.f32_sub,f64:D.f64_sub},"*":{i32:D.i32_mul,f32:D.f32_mul,f64:D.f64_mul},"/":{i32:D.i32_div_s,f32:D.f32_div,f64:D.f64_div}}[z]?.[Y];if(!J)return $.errors.push(`Unsupported compound assignment: ${Z.operator}`),[];if(H.push(J),Q.type==="i32"&&Y==="f64")H.push(D.i32_trunc_f64_s);else if(Q.type==="i32"&&Y==="f32")H.push(D.i32_trunc_f32_s);else if(Q.type==="f32"&&Y==="f64")H.push(D.f32_demote_f64)}return H.push(D.local_tee,...u(Q.index)),H}function $5(Z,$){if(Z.argument.type!=="Identifier")return $.errors.push("Update expression argument must be identifier"),[];let X=Z.argument.name,Q=d1($,X);if(!Q)return $.errors.push(`Unknown variable: ${X}`),[];let H=[],K=Q.type==="i32";if(Z.prefix){if(H.push(D.local_get,...u(Q.index)),K)H.push(D.i32_const,1),H.push(Z.operator==="++"?D.i32_add:D.i32_sub);else H.push(D.f64_const,...L1(1)),H.push(Z.operator==="++"?D.f64_add:D.f64_sub);H.push(D.local_tee,...u(Q.index))}else{if(H.push(D.local_get,...u(Q.index)),H.push(D.local_get,...u(Q.index)),K)H.push(D.i32_const,1),H.push(Z.operator==="++"?D.i32_add:D.i32_sub);else H.push(D.f64_const,...L1(1)),H.push(Z.operator==="++"?D.f64_add:D.f64_sub);H.push(D.local_set,...u(Q.index))}return H}function X5(Z,$){if(Z.object.type!=="Identifier")return $.errors.push("Array access requires identifier"),[];let X=Z.object.name,Q=$.params.find((J)=>J.name===X);if(!Q?.isArray||!Q.arrayType)return $.errors.push(`${X} is not a typed array parameter`),[];let H=G4[Q.arrayType];if(!H)return $.errors.push(`Unknown array type: ${Q.arrayType}`),[];$.needsMemory=!0;let K=[],Y=d1($,X);if(!Y)return $.errors.push(`Unknown array: ${X}`),[];if(K.push(D.local_get,...u(Y.index)),!Z.computed||!Z.property)return $.errors.push("Array access requires computed index"),[];let z=d(Z.property,$),G=s(Z.property,$);if(K.push(...z),G==="f64")K.push(D.i32_trunc_f64_s);if(H.bytesPerElement>1)K.push(D.i32_const,...w0(H.bytesPerElement)),K.push(D.i32_mul);return K.push(D.i32_add),K.push(H.loadOp,0,0),K}function Q5(Z,$,X,Q){if(Z.object.type!=="Identifier")return Q.errors.push("Array store requires identifier"),[];let H=Z.object.name,K=Q.params.find((q)=>q.name===H);if(!K?.isArray||!K.arrayType)return Q.errors.push(`${H} is not a typed array parameter`),[];let Y=G4[K.arrayType];if(!Y)return Q.errors.push(`Unknown array type: ${K.arrayType}`),[];Q.needsMemory=!0;let z=[],G=d1(Q,H);if(!G)return[];if(!Z.computed||!Z.property)return Q.errors.push("Array store requires computed index"),[];let J=d(Z.property,Q),W=s(Z.property,Q),L=()=>{let q=[];if(q.push(D.local_get,...u(G.index)),q.push(...J),W==="f64")q.push(D.i32_trunc_f64_s);if(Y.bytesPerElement>1)q.push(D.i32_const,...w0(Y.bytesPerElement)),q.push(D.i32_mul);return q.push(D.i32_add),q};if(X==="=")z.push(...d($,Q));else{let q=z4(Q,`__addr_${Q.nextLocalIndex}`,"i32");z.push(...L()),z.push(D.local_tee,...u(q)),z.push(Y.loadOp,0,0),z.push(...d($,Q));let A=s($,Q);if(Y.elementType==="f32"&&A==="f64")z.push(D.f32_demote_f64);else if(Y.elementType==="f64"&&A==="f32")z.push(D.f64_promote_f32);else if(Y.elementType==="f32"&&A==="i32")z.push(D.f32_convert_i32_s);else if(Y.elementType==="f64"&&A==="i32")z.push(D.f64_convert_i32_s);else if(Y.elementType==="i32"&&A==="f64")z.push(D.i32_trunc_f64_s);else if(Y.elementType==="i32"&&A==="f32")z.push(D.i32_trunc_f32_s);let B=X.slice(0,-1),M={"+":Y.elementType==="i32"?D.i32_add:Y.elementType==="f32"?D.f32_add:D.f64_add,"-":Y.elementType==="i32"?D.i32_sub:Y.elementType==="f32"?D.f32_sub:D.f64_sub,"*":Y.elementType==="i32"?D.i32_mul:Y.elementType==="f32"?D.f32_mul:D.f64_mul};z.push(M[B]??D.f64_add);let F=z4(Q,`__val_${Q.nextLocalIndex}`,Y.elementType);return z.push(D.local_set,...u(F)),z.push(D.local_get,...u(q)),z.push(D.local_get,...u(F)),z.push(Y.storeOp,0,0),z.push(D.local_get,...u(F)),z}let _=s($,Q);if(Y.elementType==="f32"&&_==="f64")z.push(D.f32_demote_f64);else if(Y.elementType==="f64"&&_==="f32")z.push(D.f64_promote_f32);else if(Y.elementType==="i32"&&_==="f64")z.push(D.i32_trunc_f64_s);let U=z4(Q,`__tmp_${Q.nextLocalIndex}`,Y.elementType);if(z.push(D.local_set,...u(U)),z.push(D.local_get,...u(G.index)),z.push(...J),W==="f64")z.push(D.i32_trunc_f64_s);if(Y.bytesPerElement>1)z.push(D.i32_const,...w0(Y.bytesPerElement)),z.push(D.i32_mul);return z.push(D.i32_add),z.push(D.local_get,...u(U)),z.push(Y.storeOp,0,0),z.push(D.local_get,...u(U)),z}function H5(Z,$){if(Z.callee.type==="MemberExpression"){let X=Z.callee;if(X.object.type==="Identifier"&&X.object.name==="Math"&&X.property.type==="Identifier"){let Q=X.property.name;return Y5(Q,Z.arguments,$)}}if(Z.callee.type==="Identifier"){let X=Z.callee.name;if(X.startsWith("f32x4_")||X.startsWith("v128_"))return K5(X,Z.arguments,$)}return $.errors.push(`Unsupported function call: ${Z.callee.type}`),[D.f64_const,...L1(0)]}function K5(Z,$,X){X.needsMemory=!0;let Q=[];switch(Z){case"v128_load":case"f32x4_load":{if(Q.push(...d($[0],X)),s($[0],X)==="f64")Q.push(D.i32_trunc_f64_s);Q.push(...d($[1],X));let K=s($[1],X);if(K==="f64")Q.push(D.i32_trunc_f64_s);else if(K==="f32")Q.push(D.i32_trunc_f32_s);return Q.push(D.i32_add),Q.push(...V7($1.v128_load,2,0)),Q}case"v128_store":case"f32x4_store":{if(Q.push(...d($[0],X)),s($[0],X)==="f64")Q.push(D.i32_trunc_f64_s);Q.push(...d($[1],X));let K=s($[1],X);if(K==="f64")Q.push(D.i32_trunc_f64_s);else if(K==="f32")Q.push(D.i32_trunc_f32_s);return Q.push(D.i32_add),Q.push(...d($[2],X)),Q.push(...V7($1.v128_store,2,0)),Q.push(D.i32_const,0),Q}case"f32x4_splat":{Q.push(...d($[0],X));let H=s($[0],X);if(H==="i32")Q.push(D.f32_convert_i32_s);else if(H==="f64")Q.push(D.f32_demote_f64);return Q.push(...e4($1.f32x4_splat)),Q}case"f32x4_extract_lane":{Q.push(...d($[0],X));let H=$[1].value;if(!Number.isInteger(H)||H<0||H>3)return X.errors.push(`f32x4_extract_lane: lane must be 0-3, got ${H}`),[D.f32_const,...$6(0)];return Q.push(B0,...u($1.f32x4_extract_lane),H),Q}case"f32x4_replace_lane":{Q.push(...d($[0],X));let H=$[1].value;if(!Number.isInteger(H)||H<0||H>3)return X.errors.push(`f32x4_replace_lane: lane must be 0-3, got ${H}`),[D.f32_const,...$6(0)];Q.push(...d($[2],X));let K=s($[2],X);if(K==="i32")Q.push(D.f32_convert_i32_s);else if(K==="f64")Q.push(D.f32_demote_f64);return Q.push(B0,...u($1.f32x4_replace_lane),H),Q}case"f32x4_add":case"f32x4_sub":case"f32x4_mul":case"f32x4_div":{Q.push(...d($[0],X)),Q.push(...d($[1],X));let H={f32x4_add:$1.f32x4_add,f32x4_sub:$1.f32x4_sub,f32x4_mul:$1.f32x4_mul,f32x4_div:$1.f32x4_div};return Q.push(...e4(H[Z])),Q}case"f32x4_neg":case"f32x4_sqrt":{Q.push(...d($[0],X));let H={f32x4_neg:$1.f32x4_neg,f32x4_sqrt:$1.f32x4_sqrt};return Q.push(...e4(H[Z])),Q}default:return X.errors.push(`Unknown SIMD intrinsic: ${Z}`),[D.f64_const,...L1(0)]}}function Y5(Z,$,X){let Q=[];for(let z of $){Q.push(...d(z,X));let G=s(z,X);if(G==="i32")Q.push(D.f64_convert_i32_s);else if(G==="f32")Q.push(D.f64_promote_f32)}let K={abs:D.f64_abs,ceil:D.f64_ceil,floor:D.f64_floor,trunc:D.f64_trunc,sqrt:D.f64_sqrt,min:D.f64_min,max:D.f64_max}[Z];if(K!==void 0)return Q.push(K),Q;if(["sin","cos","tan","asin","acos","atan","atan2","exp","log","pow"].includes(Z))return X.needsMathImports.add(Z),X.errors.push(`Math.${Z} requires JS import (not yet implemented)`),[D.f64_const,...L1(0)];return X.errors.push(`Unknown Math method: ${Z}`),[D.f64_const,...L1(0)]}function O7(Z){let $=Z.split(":").map((K)=>K.trim()),X=$[0];if($.length===1)return{name:X,type:"f64"};let Q=$[1];if(G4[Q])return{name:X,type:"i32",isArray:!0,arrayType:Q};return{name:X,type:{i32:"i32",i64:"i64",f32:"f32",f64:"f64",number:"f64",int:"i32"}[Q]??"f64"}}function z5(Z,$,X,Q,H){let K=[0,97,115,109,1,0,0,0],Y=Z.map((F)=>R1[F.type]),z=H?[1,R1.f64]:[0],G=R0(I0.type,[1,96,...u(Z.length),...Y,...z]),J=[],W=[];if(Q)W=R0(I0.import,[1,...Z6("env"),...Z6("memory"),2,0,1]);let L=R0(I0.function,[1,0]),_=R0(I0.export,[1,...Z6("compute"),0,0]),U=[];if(X.length>0){let F=X[0],R=1;for(let w=1;w<X.length;w++)if(X[w]===F)R++;else U.push([...u(R),R1[F]]),F=X[w],R=1;U.push([...u(R),R1[F]])}let A=[...[...u(U.length),...U.flat()],...$,D.end],B=R0(I0.code,[1,...u(A.length),...A]),M=[...K,...G];if(W.length>0)M.push(...W);return M.push(...L,..._,...B),M}function J4(Z){try{let $=Z.captures.map(O7),X;try{let J=`function __wasm__(${$.map((W)=>W.name).join(", ")}) { ${Z.body} }`;X=C7.parse(J,{ecmaVersion:2022})}catch(J){return{bytes:new Uint8Array,warnings:[],success:!1,error:`Parse error: ${J.message}`}}let H=X.body[0].body.body,K=sZ($),Y=[];for(let J of H)Y.push(...r1(J,K));if(K.errors.length>0)return{bytes:new Uint8Array,warnings:K.warnings,success:!1,error:K.errors.join("; ")};let z=z5($,Y,K.localTypes,K.needsMemory,K.hasReturn),G=oZ(Y,$,K.localTypes);return{bytes:new Uint8Array(z),warnings:K.warnings,success:!0,needsMemory:K.needsMemory,wat:G}}catch($){return{bytes:new Uint8Array,warnings:[],success:!1,error:$.message}}}async function N7(Z,$){let X={};if($)X.env={memory:$};let Q=await WebAssembly.compile(Z);return WebAssembly.instantiate(Q,X)}async function G5(Z){let $=J4(Z);if(!$.success)return{fn:()=>0,success:!1,error:$.error};try{let X;if($.needsMemory)X=new WebAssembly.Memory({initial:256});let H=(await N7($.bytes,X)).exports.compute,K=Z.captures.map(O7);if(!K.some((G)=>G.isArray))return{fn:H,memory:X,success:!0};return{fn:(...G)=>{if(!X)throw Error("Memory not initialized");let J=new Uint8Array(X.buffer),W=0,L=[];for(let U=0;U<K.length;U++){let q=K[U],A=G[U];if(q.isArray&&A instanceof Object&&"buffer"in A){let B=A,M=new Uint8Array(B.buffer,B.byteOffset,B.byteLength);J.set(M,W),L.push(W),W+=M.length,W=W+15&-16}else L.push(A)}let _=H(...L);W=0;for(let U=0;U<K.length;U++){let q=K[U],A=G[U];if(q.isArray&&A instanceof Object&&"buffer"in A){let B=A,M=new Uint8Array(B.buffer,B.byteOffset,B.byteLength);M.set(J.slice(W,W+M.length)),W+=M.length,W=W+15&-16}}return _},memory:X,success:!0}}catch(X){return{fn:()=>0,success:!1,error:X.message}}}async function E7(Z){let $=await G5(Z);if(!$.success)return console.warn(`WASM compilation failed for ${Z.id}:`,$.error),!1;return globalThis[Z.id]=$.fn,!0}async function J5(Z){let $=0,X=0,Q=[];for(let H of Z)if(await E7(H))$++;else X++,Q.push(`Failed to compile ${H.id}`);return{compiled:$,failed:X,errors:Q}}function S7(Z){let $=[],X=[];for(let z of Z){let G=J4(z);if(G.success){let J=btoa(String.fromCharCode(...G.bytes));X.push({id:z.id,base64:J,captures:z.captures,needsMemory:G.needsMemory??!1,wat:G.wat??""}),$.push({id:z.id,success:!0,byteLength:G.bytes.length})}else $.push({id:z.id,success:!1,error:G.error})}if(X.length===0)return{code:"",results:$};let Q=X.map((z)=>{let G=z.wat.split(`
295
+ `;try{let R=Function("__deepEqual","__format","__typeMatches",F),{testResults:w,sigTestResults:C}=R(r4,A0,t4);for(let P of w){let O=Z[P.idx],k=G&&!P.passed&&P.error&&/is not defined$/.test(P.error);Y.push({description:O.description,passed:k?!0:P.passed,error:k?void 0:P.error,line:O.line})}for(let P of C){let O=L[P.idx],k=G&&!P.passed&&P.error&&/is not defined$/.test(P.error);Y.push({description:`${O.funcName} signature example`,passed:k?!0:P.passed,error:k?void 0:P.error,isSignatureTest:!0,line:O.line})}}catch(R){let w=G&&R instanceof ReferenceError;for(let C of Z)Y.push({description:C.description,passed:w,error:w?void 0:`Module execution failed: ${R.message}`,line:C.line});for(let C of L)Y.push({description:`${C.funcName} signature example`,passed:w,error:w?void 0:`Module execution failed: ${R.message}`,isSignatureTest:!0,line:C.line})}for(let R of q)Y.push({description:`${R.funcName} signature example`,passed:!0,isSignatureTest:!0,line:R.line});return Y}function e4(Z){let $="",X=0,Q=!1;for(let K=0;K<Z.length;K++){let Y=Z[K];if(Y==="{"||Y==="["||Y==="("){if(Y==="{"&&X===0&&Q)break;X++,$+=Y,Q=!0}else if(Y==="}"||Y==="]"||Y===")")X--,$+=Y;else if(!/\s/.test(Y))$+=Y,Q=!0;else $+=Y}return $.trim()||null}function pZ(Z){if(!Z.trim())return[];let $=[],X=nZ(Z);for(let Q of X){let H=Q.trim(),K=H.match(/^\.\.\.(\w+)\s*[:=]\s*(\[.+\])$/);if(K){try{let z=Function(`return ${K[2]}`)();if(Array.isArray(z))for(let G of z)$.push(JSON.stringify(G))}catch{}continue}if(H.startsWith("..."))continue;let Y=H.match(/(?:\(\s*[?!]\s*)?(\w+)\s*[:=]\s*(.+?)(?:\))?$/);if(Y)$.push(Y[2].trim());else return[]}return $}function nZ(Z){let $=[],X="",Q=0;for(let H of Z){if(H==="("||H==="["||H==="{")Q++;else if(H===")"||H==="]"||H==="}")Q--;else if(H===","&&Q===0){$.push(X.trim()),X="";continue}X+=H}if(X.trim())$.push(X.trim());return $}import*as N7 from"acorn";var R1={i32:127,i64:126,f32:125,f64:124,v128:123,funcref:112,externref:111,void:64},I0={custom:0,type:1,import:2,function:3,table:4,memory:5,global:6,export:7,start:8,element:9,code:10,data:11},D={unreachable:0,nop:1,block:2,loop:3,if:4,else:5,end:11,br:12,br_if:13,br_table:14,return:15,call:16,call_indirect:17,drop:26,select:27,local_get:32,local_set:33,local_tee:34,global_get:35,global_set:36,i32_load:40,i64_load:41,f32_load:42,f64_load:43,i32_load8_s:44,i32_load8_u:45,i32_load16_s:46,i32_load16_u:47,i32_store:54,i64_store:55,f32_store:56,f64_store:57,i32_store8:58,i32_store16:59,memory_size:63,memory_grow:64,i32_const:65,i64_const:66,f32_const:67,f64_const:68,i32_eqz:69,i32_eq:70,i32_ne:71,i32_lt_s:72,i32_lt_u:73,i32_gt_s:74,i32_gt_u:75,i32_le_s:76,i32_le_u:77,i32_ge_s:78,i32_ge_u:79,i64_eqz:80,i64_eq:81,i64_ne:82,i64_lt_s:83,i64_lt_u:84,i64_gt_s:85,i64_gt_u:86,i64_le_s:87,i64_le_u:88,i64_ge_s:89,i64_ge_u:90,f32_eq:91,f32_ne:92,f32_lt:93,f32_gt:94,f32_le:95,f32_ge:96,f64_eq:97,f64_ne:98,f64_lt:99,f64_gt:100,f64_le:101,f64_ge:102,i32_clz:103,i32_ctz:104,i32_popcnt:105,i32_add:106,i32_sub:107,i32_mul:108,i32_div_s:109,i32_div_u:110,i32_rem_s:111,i32_rem_u:112,i32_and:113,i32_or:114,i32_xor:115,i32_shl:116,i32_shr_s:117,i32_shr_u:118,i32_rotl:119,i32_rotr:120,i64_add:124,i64_sub:125,i64_mul:126,i64_div_s:127,f32_abs:139,f32_neg:140,f32_ceil:141,f32_floor:142,f32_trunc:143,f32_nearest:144,f32_sqrt:145,f32_add:146,f32_sub:147,f32_mul:148,f32_div:149,f32_min:150,f32_max:151,f32_copysign:152,f64_abs:153,f64_neg:154,f64_ceil:155,f64_floor:156,f64_trunc:157,f64_nearest:158,f64_sqrt:159,f64_add:160,f64_sub:161,f64_mul:162,f64_div:163,f64_min:164,f64_max:165,f64_copysign:166,i32_wrap_i64:167,i32_trunc_f32_s:168,i32_trunc_f32_u:169,i32_trunc_f64_s:170,i32_trunc_f64_u:171,i64_extend_i32_s:172,i64_extend_i32_u:173,f32_convert_i32_s:178,f32_convert_i32_u:179,f32_convert_i64_s:180,f32_demote_f64:182,f64_convert_i32_s:183,f64_convert_i32_u:184,f64_convert_i64_s:185,f64_promote_f32:187,i32_reinterpret_f32:188,f32_reinterpret_i32:190,f64_reinterpret_i64:191,i32_extend8_s:192,i32_extend16_s:193},cZ=Object.fromEntries(Object.entries(D).map(([Z,$])=>[$,Z.replace(/_/g,".")])),B0=253,$1={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},oZ=Object.fromEntries(Object.entries($1).map(([Z,$])=>[$,Z.replace(/_/g,".")]));function Z6(Z){return[B0,...u(Z)]}function O7(Z,$,X){return[B0,...u(Z),...u($),...u(X)]}function u(Z){let $=[];do{let X=Z&127;if(Z>>>=7,Z!==0)X|=128;$.push(X)}while(Z!==0);return $}function w0(Z){let $=[],X=!0;while(X){let Q=Z&127;if(Z>>=7,Z===0&&(Q&64)===0||Z===-1&&(Q&64)!==0)X=!1;else Q|=128;$.push(Q)}return $}function X6(Z){let $=new ArrayBuffer(4);return new Float32Array($)[0]=Z,[...new Uint8Array($)]}function L1(Z){let $=new ArrayBuffer(8);return new Float64Array($)[0]=Z,[...new Uint8Array($)]}function $6(Z){let $=new TextEncoder().encode(Z);return[...u($.length),...$]}function R0(Z,$){return[Z,...u($.length),...$]}function E1(Z,$){let X=0,Q=0,H=$;while(H<Z.length){let K=Z[H];if(X|=(K&127)<<Q,H++,(K&128)===0)break;Q+=7}return[X,H-$]}function sZ(Z,$){let X=new ArrayBuffer(8),Q=new Uint8Array(X);for(let H=0;H<8;H++)Q[H]=Z[$+H];return new Float64Array(X)[0]}function aZ(Z,$,X){let Q=[],H=1,K=()=>" ".repeat(H),Y=$.map((J,W)=>`(param $${J.name} ${J.type})`).join(" "),z=X.map((J,W)=>`(local $L${$.length+W} ${J})`).join(" ");if(Q.push(`(func (export "compute") ${Y} (result f64)`),z)Q.push(` ${z}`);let G=0;while(G<Z.length){let J=Z[G],W=cZ[J]||`unknown(0x${J.toString(16)})`;if(G++,J===D.local_get||J===D.local_set||J===D.local_tee){let[U,_]=E1(Z,G);G+=_;let L=U<$.length?`$${$[U].name}`:`$L${U}`;Q.push(`${K()}${W} ${L}`)}else if(J===D.br||J===D.br_if){let[U,_]=E1(Z,G);G+=_,Q.push(`${K()}${W} ${U}`)}else if(J===D.i32_const){let[U,_]=E1(Z,G);G+=_,Q.push(`${K()}i32.const ${U}`)}else if(J===D.f32_const){let U=new ArrayBuffer(4),_=new Uint8Array(U);for(let q=0;q<4;q++)_[q]=Z[G+q];let L=new Float32Array(U)[0];G+=4,Q.push(`${K()}f32.const ${L}`)}else if(J===D.f64_const){let U=sZ(Z,G);G+=8,Q.push(`${K()}f64.const ${U}`)}else if(J===D.block||J===D.loop){let U=Z[G];G++,Q.push(`${K()}${W}${U===R1.void?"":` (result ${U===R1.f64?"f64":"i32"})`}`),H++}else if(J===D.if){let U=Z[G];G++,Q.push(`${K()}if${U===R1.void?"":` (result ${U===R1.f64?"f64":"i32"})`}`),H++}else if(J===D.else)H--,Q.push(`${K()}else`),H++;else if(J===D.end)H=Math.max(1,H-1),Q.push(`${K()}end`);else if(J===D.f64_load||J===D.f64_store||J===D.f32_load||J===D.f32_store||J===D.i32_load||J===D.i32_store){let[U,_]=E1(Z,G);G+=_;let[L,q]=E1(Z,G);G+=q,Q.push(`${K()}${W}${L?` offset=${L}`:""}`)}else if(J===B0){let[U,_]=E1(Z,G);G+=_;let L=oZ[U]||`simd.unknown(0x${U.toString(16)})`;if(U===$1.v128_load||U===$1.v128_store){let[q,A]=E1(Z,G);G+=A;let[B,M]=E1(Z,G);G+=M,Q.push(`${K()}${L}${B?` offset=${B}`:""}`)}else if(U===$1.v128_const){let q=Z.slice(G,G+16);G+=16,Q.push(`${K()}v128.const ${q.map((A)=>"0x"+A.toString(16).padStart(2,"0")).join(" ")}`)}else if(U===$1.f32x4_extract_lane||U===$1.f32x4_replace_lane){let q=Z[G];G++,Q.push(`${K()}${L} ${q}`)}else Q.push(`${K()}${L}`)}else Q.push(`${K()}${W}`)}return Q.push(")"),Q.join(`
296
+ `)}var G4={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:D.i32_load8_s,storeOp:D.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:D.i32_load8_u,storeOp:D.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:D.i32_load8_u,storeOp:D.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:D.i32_load16_s,storeOp:D.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:D.i32_load16_u,storeOp:D.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:D.i32_load,storeOp:D.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:D.i32_load,storeOp:D.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:D.f32_load,storeOp:D.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:D.f64_load,storeOp:D.f64_store}};function rZ(Z){let $={params:Z,locals:new Map,nextLocalIndex:Z.length,localTypes:[],warnings:[],errors:[],loopDepth:0,needsMathImports:new Set,needsMemory:!1,hasReturn:!1,wat:[],watIndent:1};return Z.forEach((X,Q)=>{$.locals.set(X.name,{index:Q,type:X.type})}),$}function z4(Z,$,X){if(Z.locals.has($))return Z.errors.push(`Duplicate local declaration: ${$}`),Z.locals.get($).index;let Q=Z.nextLocalIndex++;return Z.locals.set($,{index:Q,type:X}),Z.localTypes.push(X),Q}function d1(Z,$){return Z.locals.get($)}function r1(Z,$){switch(Z.type){case"ExpressionStatement":{let X=Z.expression;return[...d(X,$),D.drop]}case"ReturnStatement":{let X=Z;if($.hasReturn=!0,!X.argument)return[D.return];let Q=d(X.argument,$),H=s(X.argument,$);if(H==="i32")Q.push(D.f64_convert_i32_s);else if(H==="f32")Q.push(D.f64_promote_f32);return Q.push(D.return),Q}case"VariableDeclaration":{let X=Z,Q=[];for(let H of X.declarations){if(H.id.type!=="Identifier"){$.errors.push("Destructuring not supported in WASM blocks");continue}let K=H.id.name,Y="f64";if(H.init)Y=s(H.init,$);let z=z4($,K,Y);if(H.init)Q.push(...d(H.init,$)),Q.push(D.local_set,...u(z))}return Q}case"ForStatement":return tZ(Z,$);case"IfStatement":return eZ(Z,$);case"BlockStatement":{let X=Z,Q=[];for(let H of X.body)Q.push(...r1(H,$));return Q}default:return $.errors.push(`Unsupported statement type: ${Z.type}`),[]}}function tZ(Z,$){let X=[];if(Z.init)if(Z.init.type==="VariableDeclaration")X.push(...r1(Z.init,$));else X.push(...d(Z.init,$));if(X.push(D.block,R1.void),X.push(D.loop,R1.void),Z.test)X.push(...d(Z.test,$)),X.push(D.i32_eqz),X.push(D.br_if,1);if($.loopDepth++,Z.body)X.push(...r1(Z.body,$));if($.loopDepth--,Z.update)X.push(...d(Z.update,$)),X.push(D.drop);return X.push(D.br,0),X.push(D.end),X.push(D.end),X}function eZ(Z,$){let X=[];if(X.push(...d(Z.test,$)),X.push(D.if,R1.void),X.push(...r1(Z.consequent,$)),Z.alternate)X.push(D.else),X.push(...r1(Z.alternate,$));return X.push(D.end),X}function s(Z,$){switch(Z.type){case"Literal":{let X=Z;if(typeof X.value==="number"){if(X.raw&&(X.raw.includes(".")||X.raw.includes("e")))return"f64";if(Number.isInteger(X.value)&&X.value>=-2147483648&&X.value<=2147483647)return"i32";return"f64"}return"f64"}case"Identifier":return d1($,Z.name)?.type??"f64";case"BinaryExpression":case"AssignmentExpression":{let X=Z;if(["<",">","<=",">=","==","!=","===","!=="].includes(X.operator))return"i32";if(["|","&","^","<<",">>",">>>"].includes(X.operator))return"i32";let Q=s(X.left,$),H=s(X.right,$);if(Q==="v128"||H==="v128")return"v128";if(Q==="f64"||H==="f64")return"f64";if(Q==="f32"||H==="f32")return"f32";return"i32"}case"UnaryExpression":{let X=Z;if(X.operator==="!")return"i32";return s(X.argument,$)}case"MemberExpression":{let X=Z;if(X.object.type==="Identifier"){if(d1($,X.object.name)){let H=$.params.find((K)=>K.name===X.object.name);if(H?.arrayType){let K=G4[H.arrayType];if(K)return K.elementType}}}return"f64"}case"CallExpression":{let X=Z;if(X.callee.type==="MemberExpression"){let Q=X.callee;if(Q.object.type==="Identifier"&&Q.object.name==="Math")return"f64"}if(X.callee.type==="Identifier"){let Q=X.callee.name;if(Q==="f32x4_extract_lane")return"f32";if(Q.startsWith("f32x4_")||Q==="v128_load")return"v128"}return"f64"}default:return"f64"}}function d(Z,$){switch(Z.type){case"Literal":{let X=Z;if(typeof X.value==="number"){let Q=s(Z,$);if(Q==="i32")return[D.i32_const,...w0(X.value|0)];else if(Q==="f32")return[D.f32_const,...X6(X.value)];else return[D.f64_const,...L1(X.value)]}return $.errors.push(`Unsupported literal type: ${typeof X.value}`),[D.f64_const,...L1(0)]}case"Identifier":{let X=Z.name,Q=d1($,X);if(Q)return[D.local_get,...u(Q.index)];return $.errors.push(`Unknown identifier: ${X}`),[D.f64_const,...L1(0)]}case"BinaryExpression":return Z5(Z,$);case"UnaryExpression":return $5(Z,$);case"AssignmentExpression":return X5(Z,$);case"UpdateExpression":return Q5(Z,$);case"MemberExpression":return H5(Z,$);case"CallExpression":return Y5(Z,$);case"SequenceExpression":{let X=Z,Q=[];for(let H=0;H<X.expressions.length;H++)if(Q.push(...d(X.expressions[H],$)),H<X.expressions.length-1)Q.push(D.drop);return Q}default:return $.errors.push(`Unsupported expression type: ${Z.type}`),[D.f64_const,...L1(0)]}}function Z5(Z,$){let X=d(Z.left,$),Q=d(Z.right,$),H=s(Z,$),K=s(Z.left,$),Y=s(Z.right,$),z=["<",">","<=",">=","==","===","!=","!=="].includes(Z.operator),G;if(K==="f64"||Y==="f64")G="f64";else if(K==="f32"||Y==="f32")G="f32";else G="i32";if(!z&&H==="f64")G="f64";let J=X,W=Q;if(G==="f64"){if(K==="i32")J=[...X,D.f64_convert_i32_s];else if(K==="f32")J=[...X,D.f64_promote_f32];if(Y==="i32")W=[...Q,D.f64_convert_i32_s];else if(Y==="f32")W=[...Q,D.f64_promote_f32]}else if(G==="f32"){if(K==="i32")J=[...X,D.f32_convert_i32_s];if(Y==="i32")W=[...Q,D.f32_convert_i32_s]}let _={"+":{i32:D.i32_add,f32:D.f32_add,f64:D.f64_add},"-":{i32:D.i32_sub,f32:D.f32_sub,f64:D.f64_sub},"*":{i32:D.i32_mul,f32:D.f32_mul,f64:D.f64_mul},"/":{i32:D.i32_div_s,f32:D.f32_div,f64:D.f64_div},"%":{i32:D.i32_rem_s},"<":{i32:D.i32_lt_s,f32:D.f32_lt,f64:D.f64_lt},">":{i32:D.i32_gt_s,f32:D.f32_gt,f64:D.f64_gt},"<=":{i32:D.i32_le_s,f32:D.f32_le,f64:D.f64_le},">=":{i32:D.i32_ge_s,f32:D.f32_ge,f64:D.f64_ge},"==":{i32:D.i32_eq,f32:D.f32_eq,f64:D.f64_eq},"===":{i32:D.i32_eq,f32:D.f32_eq,f64:D.f64_eq},"!=":{i32:D.i32_ne,f32:D.f32_ne,f64:D.f64_ne},"!==":{i32:D.i32_ne,f32:D.f32_ne,f64:D.f64_ne},"|":{i32:D.i32_or},"&":{i32:D.i32_and},"^":{i32:D.i32_xor},"<<":{i32:D.i32_shl},">>":{i32:D.i32_shr_s},">>>":{i32:D.i32_shr_u}}[Z.operator];if(!_)return $.errors.push(`Unsupported operator: ${Z.operator}`),[D.f64_const,...L1(0)];let L=_[G]??_.f64??_.i32;if(L===void 0)return $.errors.push(`Operator ${Z.operator} not supported for type ${G}`),[D.f64_const,...L1(0)];return[...J,...W,L]}function $5(Z,$){let X=d(Z.argument,$),Q=s(Z.argument,$);switch(Z.operator){case"-":if(Q==="i32")return[D.i32_const,0,...X,D.i32_sub];else if(Q==="f32")return[...X,D.f32_neg];else return[...X,D.f64_neg];case"!":return[...X,D.i32_eqz];case"~":return[...X,D.i32_const,...w0(-1),D.i32_xor];default:return $.errors.push(`Unsupported unary operator: ${Z.operator}`),X}}function X5(Z,$){if(Z.left.type==="MemberExpression")return K5(Z.left,Z.right,Z.operator,$);if(Z.left.type!=="Identifier")return $.errors.push("Assignment target must be identifier or array element"),[];let X=Z.left.name,Q=d1($,X);if(!Q)return $.errors.push(`Unknown variable: ${X}`),[];let H=[];if(Z.operator==="="){H.push(...d(Z.right,$));let K=s(Z.right,$);if(Q.type==="f64"&&K==="i32")H.push(D.f64_convert_i32_s);else if(Q.type==="f64"&&K==="f32")H.push(D.f64_promote_f32);else if(Q.type==="i32"&&K==="f64")H.push(D.i32_trunc_f64_s);else if(Q.type==="i32"&&K==="f32")H.push(D.i32_trunc_f32_s);else if(Q.type==="f32"&&K==="i32")H.push(D.f32_convert_i32_s);else if(Q.type==="f32"&&K==="f64")H.push(D.f32_demote_f64)}else{let K=s(Z.right,$),Y=Q.type;if(K==="f64"||Q.type==="f64")Y="f64";else if(K==="f32"||Q.type==="f32")Y="f32";if(H.push(D.local_get,...u(Q.index)),Y==="f64"&&Q.type==="i32")H.push(D.f64_convert_i32_s);else if(Y==="f64"&&Q.type==="f32")H.push(D.f64_promote_f32);else if(Y==="f32"&&Q.type==="i32")H.push(D.f32_convert_i32_s);if(H.push(...d(Z.right,$)),Y==="f64"&&K==="i32")H.push(D.f64_convert_i32_s);else if(Y==="f64"&&K==="f32")H.push(D.f64_promote_f32);else if(Y==="f32"&&K==="i32")H.push(D.f32_convert_i32_s);let z=Z.operator.slice(0,-1),J={"+":{i32:D.i32_add,f32:D.f32_add,f64:D.f64_add},"-":{i32:D.i32_sub,f32:D.f32_sub,f64:D.f64_sub},"*":{i32:D.i32_mul,f32:D.f32_mul,f64:D.f64_mul},"/":{i32:D.i32_div_s,f32:D.f32_div,f64:D.f64_div}}[z]?.[Y];if(!J)return $.errors.push(`Unsupported compound assignment: ${Z.operator}`),[];if(H.push(J),Q.type==="i32"&&Y==="f64")H.push(D.i32_trunc_f64_s);else if(Q.type==="i32"&&Y==="f32")H.push(D.i32_trunc_f32_s);else if(Q.type==="f32"&&Y==="f64")H.push(D.f32_demote_f64)}return H.push(D.local_tee,...u(Q.index)),H}function Q5(Z,$){if(Z.argument.type!=="Identifier")return $.errors.push("Update expression argument must be identifier"),[];let X=Z.argument.name,Q=d1($,X);if(!Q)return $.errors.push(`Unknown variable: ${X}`),[];let H=[],K=Q.type==="i32";if(Z.prefix){if(H.push(D.local_get,...u(Q.index)),K)H.push(D.i32_const,1),H.push(Z.operator==="++"?D.i32_add:D.i32_sub);else H.push(D.f64_const,...L1(1)),H.push(Z.operator==="++"?D.f64_add:D.f64_sub);H.push(D.local_tee,...u(Q.index))}else{if(H.push(D.local_get,...u(Q.index)),H.push(D.local_get,...u(Q.index)),K)H.push(D.i32_const,1),H.push(Z.operator==="++"?D.i32_add:D.i32_sub);else H.push(D.f64_const,...L1(1)),H.push(Z.operator==="++"?D.f64_add:D.f64_sub);H.push(D.local_set,...u(Q.index))}return H}function H5(Z,$){if(Z.object.type!=="Identifier")return $.errors.push("Array access requires identifier"),[];let X=Z.object.name,Q=$.params.find((J)=>J.name===X);if(!Q?.isArray||!Q.arrayType)return $.errors.push(`${X} is not a typed array parameter`),[];let H=G4[Q.arrayType];if(!H)return $.errors.push(`Unknown array type: ${Q.arrayType}`),[];$.needsMemory=!0;let K=[],Y=d1($,X);if(!Y)return $.errors.push(`Unknown array: ${X}`),[];if(K.push(D.local_get,...u(Y.index)),!Z.computed||!Z.property)return $.errors.push("Array access requires computed index"),[];let z=d(Z.property,$),G=s(Z.property,$);if(K.push(...z),G==="f64")K.push(D.i32_trunc_f64_s);if(H.bytesPerElement>1)K.push(D.i32_const,...w0(H.bytesPerElement)),K.push(D.i32_mul);return K.push(D.i32_add),K.push(H.loadOp,0,0),K}function K5(Z,$,X,Q){if(Z.object.type!=="Identifier")return Q.errors.push("Array store requires identifier"),[];let H=Z.object.name,K=Q.params.find((q)=>q.name===H);if(!K?.isArray||!K.arrayType)return Q.errors.push(`${H} is not a typed array parameter`),[];let Y=G4[K.arrayType];if(!Y)return Q.errors.push(`Unknown array type: ${K.arrayType}`),[];Q.needsMemory=!0;let z=[],G=d1(Q,H);if(!G)return[];if(!Z.computed||!Z.property)return Q.errors.push("Array store requires computed index"),[];let J=d(Z.property,Q),W=s(Z.property,Q),U=()=>{let q=[];if(q.push(D.local_get,...u(G.index)),q.push(...J),W==="f64")q.push(D.i32_trunc_f64_s);if(Y.bytesPerElement>1)q.push(D.i32_const,...w0(Y.bytesPerElement)),q.push(D.i32_mul);return q.push(D.i32_add),q};if(X==="=")z.push(...d($,Q));else{let q=z4(Q,`__addr_${Q.nextLocalIndex}`,"i32");z.push(...U()),z.push(D.local_tee,...u(q)),z.push(Y.loadOp,0,0),z.push(...d($,Q));let A=s($,Q);if(Y.elementType==="f32"&&A==="f64")z.push(D.f32_demote_f64);else if(Y.elementType==="f64"&&A==="f32")z.push(D.f64_promote_f32);else if(Y.elementType==="f32"&&A==="i32")z.push(D.f32_convert_i32_s);else if(Y.elementType==="f64"&&A==="i32")z.push(D.f64_convert_i32_s);else if(Y.elementType==="i32"&&A==="f64")z.push(D.i32_trunc_f64_s);else if(Y.elementType==="i32"&&A==="f32")z.push(D.i32_trunc_f32_s);let B=X.slice(0,-1),M={"+":Y.elementType==="i32"?D.i32_add:Y.elementType==="f32"?D.f32_add:D.f64_add,"-":Y.elementType==="i32"?D.i32_sub:Y.elementType==="f32"?D.f32_sub:D.f64_sub,"*":Y.elementType==="i32"?D.i32_mul:Y.elementType==="f32"?D.f32_mul:D.f64_mul};z.push(M[B]??D.f64_add);let F=z4(Q,`__val_${Q.nextLocalIndex}`,Y.elementType);return z.push(D.local_set,...u(F)),z.push(D.local_get,...u(q)),z.push(D.local_get,...u(F)),z.push(Y.storeOp,0,0),z.push(D.local_get,...u(F)),z}let _=s($,Q);if(Y.elementType==="f32"&&_==="f64")z.push(D.f32_demote_f64);else if(Y.elementType==="f64"&&_==="f32")z.push(D.f64_promote_f32);else if(Y.elementType==="i32"&&_==="f64")z.push(D.i32_trunc_f64_s);let L=z4(Q,`__tmp_${Q.nextLocalIndex}`,Y.elementType);if(z.push(D.local_set,...u(L)),z.push(D.local_get,...u(G.index)),z.push(...J),W==="f64")z.push(D.i32_trunc_f64_s);if(Y.bytesPerElement>1)z.push(D.i32_const,...w0(Y.bytesPerElement)),z.push(D.i32_mul);return z.push(D.i32_add),z.push(D.local_get,...u(L)),z.push(Y.storeOp,0,0),z.push(D.local_get,...u(L)),z}function Y5(Z,$){if(Z.callee.type==="MemberExpression"){let X=Z.callee;if(X.object.type==="Identifier"&&X.object.name==="Math"&&X.property.type==="Identifier"){let Q=X.property.name;return G5(Q,Z.arguments,$)}}if(Z.callee.type==="Identifier"){let X=Z.callee.name;if(X.startsWith("f32x4_")||X.startsWith("v128_"))return z5(X,Z.arguments,$)}return $.errors.push(`Unsupported function call: ${Z.callee.type}`),[D.f64_const,...L1(0)]}function z5(Z,$,X){X.needsMemory=!0;let Q=[];switch(Z){case"v128_load":case"f32x4_load":{if(Q.push(...d($[0],X)),s($[0],X)==="f64")Q.push(D.i32_trunc_f64_s);Q.push(...d($[1],X));let K=s($[1],X);if(K==="f64")Q.push(D.i32_trunc_f64_s);else if(K==="f32")Q.push(D.i32_trunc_f32_s);return Q.push(D.i32_add),Q.push(...O7($1.v128_load,2,0)),Q}case"v128_store":case"f32x4_store":{if(Q.push(...d($[0],X)),s($[0],X)==="f64")Q.push(D.i32_trunc_f64_s);Q.push(...d($[1],X));let K=s($[1],X);if(K==="f64")Q.push(D.i32_trunc_f64_s);else if(K==="f32")Q.push(D.i32_trunc_f32_s);return Q.push(D.i32_add),Q.push(...d($[2],X)),Q.push(...O7($1.v128_store,2,0)),Q.push(D.i32_const,0),Q}case"f32x4_splat":{Q.push(...d($[0],X));let H=s($[0],X);if(H==="i32")Q.push(D.f32_convert_i32_s);else if(H==="f64")Q.push(D.f32_demote_f64);return Q.push(...Z6($1.f32x4_splat)),Q}case"f32x4_extract_lane":{Q.push(...d($[0],X));let H=$[1].value;if(!Number.isInteger(H)||H<0||H>3)return X.errors.push(`f32x4_extract_lane: lane must be 0-3, got ${H}`),[D.f32_const,...X6(0)];return Q.push(B0,...u($1.f32x4_extract_lane),H),Q}case"f32x4_replace_lane":{Q.push(...d($[0],X));let H=$[1].value;if(!Number.isInteger(H)||H<0||H>3)return X.errors.push(`f32x4_replace_lane: lane must be 0-3, got ${H}`),[D.f32_const,...X6(0)];Q.push(...d($[2],X));let K=s($[2],X);if(K==="i32")Q.push(D.f32_convert_i32_s);else if(K==="f64")Q.push(D.f32_demote_f64);return Q.push(B0,...u($1.f32x4_replace_lane),H),Q}case"f32x4_add":case"f32x4_sub":case"f32x4_mul":case"f32x4_div":{Q.push(...d($[0],X)),Q.push(...d($[1],X));let H={f32x4_add:$1.f32x4_add,f32x4_sub:$1.f32x4_sub,f32x4_mul:$1.f32x4_mul,f32x4_div:$1.f32x4_div};return Q.push(...Z6(H[Z])),Q}case"f32x4_neg":case"f32x4_sqrt":{Q.push(...d($[0],X));let H={f32x4_neg:$1.f32x4_neg,f32x4_sqrt:$1.f32x4_sqrt};return Q.push(...Z6(H[Z])),Q}default:return X.errors.push(`Unknown SIMD intrinsic: ${Z}`),[D.f64_const,...L1(0)]}}function G5(Z,$,X){let Q=[];for(let z of $){Q.push(...d(z,X));let G=s(z,X);if(G==="i32")Q.push(D.f64_convert_i32_s);else if(G==="f32")Q.push(D.f64_promote_f32)}let K={abs:D.f64_abs,ceil:D.f64_ceil,floor:D.f64_floor,trunc:D.f64_trunc,sqrt:D.f64_sqrt,min:D.f64_min,max:D.f64_max}[Z];if(K!==void 0)return Q.push(K),Q;if(["sin","cos","tan","asin","acos","atan","atan2","exp","log","pow"].includes(Z))return X.needsMathImports.add(Z),X.errors.push(`Math.${Z} requires JS import (not yet implemented)`),[D.f64_const,...L1(0)];return X.errors.push(`Unknown Math method: ${Z}`),[D.f64_const,...L1(0)]}function E7(Z){let $=Z.split(":").map((K)=>K.trim()),X=$[0];if($.length===1)return{name:X,type:"f64"};let Q=$[1];if(G4[Q])return{name:X,type:"i32",isArray:!0,arrayType:Q};return{name:X,type:{i32:"i32",i64:"i64",f32:"f32",f64:"f64",number:"f64",int:"i32"}[Q]??"f64"}}function J5(Z,$,X,Q,H){let K=[0,97,115,109,1,0,0,0],Y=Z.map((F)=>R1[F.type]),z=H?[1,R1.f64]:[0],G=R0(I0.type,[1,96,...u(Z.length),...Y,...z]),J=[],W=[];if(Q)W=R0(I0.import,[1,...$6("env"),...$6("memory"),2,0,1]);let U=R0(I0.function,[1,0]),_=R0(I0.export,[1,...$6("compute"),0,0]),L=[];if(X.length>0){let F=X[0],R=1;for(let w=1;w<X.length;w++)if(X[w]===F)R++;else L.push([...u(R),R1[F]]),F=X[w],R=1;L.push([...u(R),R1[F]])}let A=[...[...u(L.length),...L.flat()],...$,D.end],B=R0(I0.code,[1,...u(A.length),...A]),M=[...K,...G];if(W.length>0)M.push(...W);return M.push(...U,..._,...B),M}function J4(Z){try{let $=Z.captures.map(E7),X;try{let J=`function __wasm__(${$.map((W)=>W.name).join(", ")}) { ${Z.body} }`;X=N7.parse(J,{ecmaVersion:2022})}catch(J){return{bytes:new Uint8Array,warnings:[],success:!1,error:`Parse error: ${J.message}`}}let H=X.body[0].body.body,K=rZ($),Y=[];for(let J of H)Y.push(...r1(J,K));if(K.errors.length>0)return{bytes:new Uint8Array,warnings:K.warnings,success:!1,error:K.errors.join("; ")};let z=J5($,Y,K.localTypes,K.needsMemory,K.hasReturn),G=aZ(Y,$,K.localTypes);return{bytes:new Uint8Array(z),warnings:K.warnings,success:!0,needsMemory:K.needsMemory,wat:G}}catch($){return{bytes:new Uint8Array,warnings:[],success:!1,error:$.message}}}async function S7(Z,$){let X={};if($)X.env={memory:$};let Q=await WebAssembly.compile(Z);return WebAssembly.instantiate(Q,X)}async function W5(Z){let $=J4(Z);if(!$.success)return{fn:()=>0,success:!1,error:$.error};try{let X;if($.needsMemory)X=new WebAssembly.Memory({initial:256});let H=(await S7($.bytes,X)).exports.compute,K=Z.captures.map(E7);if(!K.some((G)=>G.isArray))return{fn:H,memory:X,success:!0};return{fn:(...G)=>{if(!X)throw Error("Memory not initialized");let J=new Uint8Array(X.buffer),W=0,U=[];for(let L=0;L<K.length;L++){let q=K[L],A=G[L];if(q.isArray&&A instanceof Object&&"buffer"in A){let B=A,M=new Uint8Array(B.buffer,B.byteOffset,B.byteLength);J.set(M,W),U.push(W),W+=M.length,W=W+15&-16}else U.push(A)}let _=H(...U);W=0;for(let L=0;L<K.length;L++){let q=K[L],A=G[L];if(q.isArray&&A instanceof Object&&"buffer"in A){let B=A,M=new Uint8Array(B.buffer,B.byteOffset,B.byteLength);M.set(J.slice(W,W+M.length)),W+=M.length,W=W+15&-16}}return _},memory:X,success:!0}}catch(X){return{fn:()=>0,success:!1,error:X.message}}}async function T7(Z){let $=await W5(Z);if(!$.success)return console.warn(`WASM compilation failed for ${Z.id}:`,$.error),!1;return globalThis[Z.id]=$.fn,!0}async function _5(Z){let $=0,X=0,Q=[];for(let H of Z)if(await T7(H))$++;else X++,Q.push(`Failed to compile ${H.id}`);return{compiled:$,failed:X,errors:Q}}function k7(Z){let $=[],X=[];for(let z of Z){let G=J4(z);if(G.success){let J=btoa(String.fromCharCode(...G.bytes));X.push({id:z.id,base64:J,captures:z.captures,needsMemory:G.needsMemory??!1,wat:G.wat??""}),$.push({id:z.id,success:!0,byteLength:G.bytes.length})}else $.push({id:z.id,success:!1,error:G.error})}if(X.length===0)return{code:"",results:$};let Q=X.map((z)=>{let G=z.wat.split(`
297
297
  `).map((J)=>` * ${J}`);return`/**
298
298
  * WASM: ${z.id}
299
299
  ${G.join(`
@@ -330,67 +330,69 @@ for(const{id,b64,c,m}of __wasmBlocks){
330
330
  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}}
331
331
  return r};
332
332
  }})();
333
- `.trim(),results:$}}function W5(Z,$,X){if(!Z||!$)return!1;let Q=new RegExp(`function\\s+${$}\\s*\\([^)]*?\\b${X}\\s*([=:])`,"s"),H=Z.match(Q);if(!H)return!1;return H[1]===":"}function _5(Z,$,X,Q,H){let K=[],Y=W0($,Z),z={},G=!1,J,W;if(Z.params.length===1&&(Z.params[0].type==="ObjectPattern"||Z.params[0].type==="AssignmentPattern"&&Z.params[0].left.type==="ObjectPattern")){G=!0;let U=Z.params[0],q=U.type==="ObjectPattern"?U:U.left,A=O1(q,X);if(A.type.kind==="object"&&A.type.destructuredParams){J={},W=new Set;for(let[B,M]of Object.entries(A.type.destructuredParams))if(z[B]={...M,description:Y.params[B]},J[B]=M.type,M.required)W.add(B)}}else for(let U of Z.params)if(U.type==="Identifier"){let q=O1(U,X);z[U.name]={...q,required:X.has(U.name),description:Y.params[U.name]}}else if(U.type==="AssignmentPattern"&&U.left.type==="Identifier"){let q=O1(U,X),A=W5(H||"",Z.id?.name||"",U.left.name);z[U.left.name]={...q,required:A,default:A?null:q.example??q.default,description:Y.params[U.left.name]}}else if(U.type==="ObjectPattern"){let q=O1(U,X);if(q.type.kind==="object"&&q.type.destructuredParams)for(let[A,B]of Object.entries(q.type.destructuredParams))z[A]={...B,description:Y.params[A]}}else if(U.type==="RestElement"&&U.argument?.type==="Identifier"){let q=U.argument.name,A=$.match(new RegExp(`\\.\\.\\.${q}\\s*:\\s*([^)]+?)\\s*\\)`));if(A)try{let B=T7(A[1].trim(),0,{ecmaVersion:2022}),M=G1(B);z[q]={name:q,type:M,required:!1,description:Y.params[q]}}catch{z[q]={name:q,type:{kind:"array"},required:!1,description:Y.params[q]}}else z[q]={name:q,type:{kind:"array"},required:!1,description:Y.params[q]}}let L;if(Q)try{let U=Q.includes("=")?k7(Q):Q,q=T7(U,0,{ecmaVersion:2022});L=G1(q)}catch{L={kind:"any"},K.push(`Could not parse return type: ${Q}`)}return{types:{name:Z.id?.name||"anonymous",params:z,returns:L,description:Y.description,isDestructuredParam:G,destructuredShape:J,destructuredRequired:W},warnings:K}}function L5(Z,$,X){let Q=[],H=X?`${X}:`:"",K=X?`${X}:${Z}`:Z;if($.isDestructuredParam&&$.destructuredShape){let z=$.destructuredShape,G=$.destructuredRequired||new Set,J=Object.keys(z);if(J.length===0)return null;for(let W of J)Q.push(`if (${W} instanceof Error) return ${W};`);for(let[W,L]of Object.entries(z)){let _=G.has(W),U=`${H}${Z}.${W}`,q=X6(W,L);if(q){let A=L.kind;if(_)Q.push(`if (${q}) return __tjs.typeError('${U}', '${A}', ${W});`);else Q.push(`if (${W} !== undefined && ${q}) return __tjs.typeError('${U}', '${A}', ${W});`)}}if(Q.length===0)return null;return Q.unshift(`__tjs.pushStack('${K}');`),Q.unshift("try {"),{preamble:Q.join(`
334
- `),suffix:"} finally { __tjs.popStack(); }"}}let Y=Object.entries($.params);if(Y.length===0)return null;for(let[z]of Y)Q.push(`if (${z} instanceof Error) return ${z};`);for(let[z,G]of Y){let J=`${H}${Z}.${z}`,W=X6(z,G.type);if(W){let L=G.type.kind==="union"?G.type.members.map((_)=>_.kind).join(" | "):G.type.kind;if(G.required)Q.push(`if (${W}) return __tjs.typeError('${J}', '${L}', ${z});`);else Q.push(`if (${z} !== undefined && ${W}) return __tjs.typeError('${J}', '${L}', ${z});`)}}if(Q.length===0)return null;return Q.unshift(`__tjs.pushStack('${K}');`),Q.unshift("try {"),{preamble:Q.join(`
335
- `),suffix:"} finally { __tjs.popStack(); }"}}function k7(Z){let $="",X=0;for(let Q=0;Q<Z.length;Q++){let H=Z[Q];if(H==="{"||H==="["||H==="(")X++,$+=H;else if(H==="}"||H==="]"||H===")")X--,$+=H;else if(H==="'"||H==='"'||H==="`"){$+=H,Q++;while(Q<Z.length&&Z[Q]!==H){if(Z[Q]==="\\")$+=Z[Q++];$+=Z[Q++]}if(Q<Z.length)$+=Z[Q]}else if(X===1&&H==="="&&Z[Q-1]!=="!"&&Z[Q+1]!=="=")$+=":";else $+=H}return $}function U5(Z,$){let Q=new RegExp(`function\\s+${$}\\s*\\([^)]*\\)\\s*(-[>?!])\\s*`,"g").exec(Z);if(!Q)return null;let H=Z.slice(Q.index+Q[0].length);return t4(H)}function q5(Z,$){let Q=new RegExp(`function\\s+${$}\\s*\\([^)]*\\)\\s*-([>?!])`,"g").exec(Z);if(!Q)return;let H=Q[1];if(H==="?")return"safe";if(H==="!")return"unsafe";return}function D5(Z){let $=Z.match(/^\/\*\s*tjs\s*<-\s*([^*]+?)\s*\*\//);return $?$[1].trim():void 0}function A5(Z,$){let X=new RegExp(`\\/\\*\\s*line\\s+(\\d+)\\s*\\*\\/\\s*(?:async\\s+)?function\\s+${$}\\s*\\(`,"m"),Q=Z.match(X);return Q?parseInt(Q[1],10):void 0}function M0(Z,$={}){let{filename:X="<source>",runTests:Q=!0,debug:H=!1,resolvedImports:K={}}=$,Y=[],G=D5(Z)||X,{code:J,tests:W,mocks:L,testRunner:_}=v4(Z),{ast:U,originalSource:q,requiredParams:A,unsafeFunctions:B}=F1(J,{filename:X,colonShorthand:!0}),M=I5(U),F=y0(J),R={},w=[],C=[];for(let y of M){let i=y.id?.name||"anonymous",l=U5(J,i),D1;if(l&&l.includes("="))try{let W1=l.matchAll(/(\w+)\s*=\s*/g),A1=k7(l),f1=Function(`return ${A1}`)(),I1={};for(let y8 of W1){let E4=y8[1];if(E4 in f1)I1[E4]=f1[E4]}if(Object.keys(I1).length>0)D1=I1}catch{}let{types:v1,warnings:k8}=_5(y,q,A,l,J);Y.push(...k8),R[i]=v1;for(let W1 of y.params)if(W1.type==="AssignmentPattern"){let A1=W1.left?.name||W1.left?.value,f1=A1?v1.params[A1]:null;if(f1?.required&&f1.default===null)C.push({start:W1.left.end,end:W1.right.end});else{let I1=W1.right;if(I1.type==="BinaryExpression"&&I1.operator==="|")C.push({start:I1.left.end,end:I1.end})}}let O6=F.moduleSafety==="none"||B.has(i),g8=F.safeFunctions.has(i),b8=q5(J,i),v8=A5(Z,i),p1={file:G,line:v8??y.loc?.start.line??0,column:y.loc?.start.column??0},f8={unsafe:O6,safe:g8,returnSafety:b8},N6=F.polymorphicNames.has(i),N4;if(N6){let W1=[];for(let f1 of M){let I1=f1.id?.name||"";if(I1.startsWith(i+"$"))W1.push(I1)}let A1={polymorphic:!0,variants:W1};if(p1)A1.source=`${p1.file}:${p1.line}`;N4=`${i}.__tjs = ${JSON.stringify(A1,null,2)}`}else N4=R5(i,v1,f8,{debug:H,source:p1,returnDefaults:D1});if(w.push({position:y.end,text:`
336
- ${N4}`}),!O6&&!N6){let W1=`${p1.file}:${p1.line}`,A1=L5(i,v1,W1);if(A1&&y.body&&y.body.start!==void 0)w.push({position:y.body.start+1,text:`
333
+ `.trim(),results:$}}function L5(Z,$,X){if(!Z||!$)return!1;let Q=new RegExp(`function\\s+${$}\\s*\\([^)]*?\\b${X}\\s*([=:])`,"s"),H=Z.match(Q);if(!H)return!1;return H[1]===":"}function U5(Z,$,X,Q,H){let K=[],Y=W0($,Z),z={},G=!1,J,W;if(Z.params.length===1&&(Z.params[0].type==="ObjectPattern"||Z.params[0].type==="AssignmentPattern"&&Z.params[0].left.type==="ObjectPattern")){G=!0;let L=Z.params[0],q=L.type==="ObjectPattern"?L:L.left,A=O1(q,X);if(A.type.kind==="object"&&A.type.destructuredParams){J={},W=new Set;for(let[B,M]of Object.entries(A.type.destructuredParams))if(z[B]={...M,description:Y.params[B]},J[B]=M.type,M.required)W.add(B)}}else for(let L of Z.params)if(L.type==="Identifier"){let q=O1(L,X);z[L.name]={...q,required:X.has(L.name),description:Y.params[L.name]}}else if(L.type==="AssignmentPattern"&&L.left.type==="Identifier"){let q=O1(L,X),A=L5(H||"",Z.id?.name||"",L.left.name);z[L.left.name]={...q,required:A,default:A?null:q.example??q.default,description:Y.params[L.left.name]}}else if(L.type==="ObjectPattern"){let q=O1(L,X);if(q.type.kind==="object"&&q.type.destructuredParams)for(let[A,B]of Object.entries(q.type.destructuredParams))z[A]={...B,description:Y.params[A]}}else if(L.type==="RestElement"&&L.argument?.type==="Identifier"){let q=L.argument.name,A=$.match(new RegExp(`\\.\\.\\.${q}\\s*:\\s*([^)]+?)\\s*\\)`));if(A)try{let B=g7(A[1].trim(),0,{ecmaVersion:2022}),M=G1(B);z[q]={name:q,type:M,required:!1,description:Y.params[q]}}catch{z[q]={name:q,type:{kind:"array"},required:!1,description:Y.params[q]}}else z[q]={name:q,type:{kind:"array"},required:!1,description:Y.params[q]}}let U;if(Q)try{let L=Q.includes("=")?b7(Q):Q,q=g7(L,0,{ecmaVersion:2022});U=G1(q)}catch{U={kind:"any"},K.push(`Could not parse return type: ${Q}`)}return{types:{name:Z.id?.name||"anonymous",params:z,returns:U,description:Y.description,isDestructuredParam:G,destructuredShape:J,destructuredRequired:W},warnings:K}}function q5(Z,$,X){let Q=[],H=X?`${X}:`:"",K=X?`${X}:${Z}`:Z;if($.isDestructuredParam&&$.destructuredShape){let z=$.destructuredShape,G=$.destructuredRequired||new Set,J=Object.keys(z);if(J.length===0)return null;for(let W of J)Q.push(`if (${W} instanceof Error) return ${W};`);for(let[W,U]of Object.entries(z)){let _=G.has(W),L=`${H}${Z}.${W}`,q=Q6(W,U);if(q){let A=U.kind;if(_)Q.push(`if (${q}) return __tjs.typeError('${L}', '${A}', ${W});`);else Q.push(`if (${W} !== undefined && ${q}) return __tjs.typeError('${L}', '${A}', ${W});`)}}if(Q.length===0)return null;return Q.unshift(`__tjs.pushStack('${K}');`),Q.unshift("try {"),{preamble:Q.join(`
334
+ `),suffix:"} finally { __tjs.popStack(); }"}}let Y=Object.entries($.params);if(Y.length===0)return null;for(let[z]of Y)Q.push(`if (${z} instanceof Error) return ${z};`);for(let[z,G]of Y){let J=`${H}${Z}.${z}`,W=Q6(z,G.type);if(W){let U=G.type.kind==="union"?G.type.members.map((_)=>_.kind).join(" | "):G.type.kind;if(G.required)Q.push(`if (${W}) return __tjs.typeError('${J}', '${U}', ${z});`);else Q.push(`if (${z} !== undefined && ${W}) return __tjs.typeError('${J}', '${U}', ${z});`)}}if(Q.length===0)return null;return Q.unshift(`__tjs.pushStack('${K}');`),Q.unshift("try {"),{preamble:Q.join(`
335
+ `),suffix:"} finally { __tjs.popStack(); }"}}function b7(Z){let $="",X=0;for(let Q=0;Q<Z.length;Q++){let H=Z[Q];if(H==="{"||H==="["||H==="(")X++,$+=H;else if(H==="}"||H==="]"||H===")")X--,$+=H;else if(H==="'"||H==='"'||H==="`"){$+=H,Q++;while(Q<Z.length&&Z[Q]!==H){if(Z[Q]==="\\")$+=Z[Q++];$+=Z[Q++]}if(Q<Z.length)$+=Z[Q]}else if(X===1&&H==="="&&Z[Q-1]!=="!"&&Z[Q+1]!=="=")$+=":";else $+=H}return $}function D5(Z,$){let Q=new RegExp(`function\\s+${$}\\s*\\([^)]*\\)\\s*(-[>?!])\\s*`,"g").exec(Z);if(!Q)return null;let H=Z.slice(Q.index+Q[0].length);return e4(H)}function A5(Z,$){let Q=new RegExp(`function\\s+${$}\\s*\\([^)]*\\)\\s*-([>?!])`,"g").exec(Z);if(!Q)return;let H=Q[1];if(H==="?")return"safe";if(H==="!")return"unsafe";return}function I5(Z){let $=Z.match(/^\/\*\s*tjs\s*<-\s*([^*]+?)\s*\*\//);return $?$[1].trim():void 0}function R5(Z,$){let X=new RegExp(`\\/\\*\\s*line\\s+(\\d+)\\s*\\*\\/\\s*(?:async\\s+)?function\\s+${$}\\s*\\(`,"m"),Q=Z.match(X);return Q?parseInt(Q[1],10):void 0}function M0(Z,$={}){let{filename:X="<source>",runTests:Q=!0,debug:H=!1,resolvedImports:K={}}=$,Y=[],G=I5(Z)||X,{code:J,tests:W,mocks:U,testRunner:_}=f4(Z),{ast:L,originalSource:q,requiredParams:A,unsafeFunctions:B}=F1(J,{filename:X,colonShorthand:!0}),M=B5(L),F=y0(J),R={},w=[],C=[];for(let f of M){let i=f.id?.name||"anonymous",l=D5(J,i),D1;if(l&&l.includes("="))try{let W1=l.matchAll(/(\w+)\s*=\s*/g),A1=b7(l),f1=Function(`return ${A1}`)(),I1={};for(let x8 of W1){let S4=x8[1];if(S4 in f1)I1[S4]=f1[S4]}if(Object.keys(I1).length>0)D1=I1}catch{}let{types:v1,warnings:b8}=U5(f,q,A,l,J);Y.push(...b8),R[i]=v1;for(let W1 of f.params)if(W1.type==="AssignmentPattern"){let A1=W1.left?.name||W1.left?.value,f1=A1?v1.params[A1]:null;if(f1?.required&&f1.default===null)C.push({start:W1.left.end,end:W1.right.end});else{let I1=W1.right;if(I1.type==="BinaryExpression"&&I1.operator==="|")C.push({start:I1.left.end,end:I1.end})}}let N6=F.moduleSafety==="none"||B.has(i),v8=F.safeFunctions.has(i),f8=A5(J,i),y8=R5(Z,i),p1={file:G,line:y8??f.loc?.start.line??0,column:f.loc?.start.column??0},h8={unsafe:N6,safe:v8,returnSafety:f8},E6=F.polymorphicNames.has(i),E4;if(E6){let W1=[];for(let f1 of M){let I1=f1.id?.name||"";if(I1.startsWith(i+"$"))W1.push(I1)}let A1={polymorphic:!0,variants:W1};if(p1)A1.source=`${p1.file}:${p1.line}`;E4=`${i}.__tjs = ${JSON.stringify(A1,null,2)}`}else E4=w5(i,v1,h8,{debug:H,source:p1,returnDefaults:D1});if(w.push({position:f.end,text:`
336
+ ${E4}`}),!N6&&!E6){let W1=`${p1.file}:${p1.line}`,A1=q5(i,v1,W1);if(A1&&f.body&&f.body.start!==void 0)w.push({position:f.body.start+1,text:`
337
337
  ${A1.preamble}
338
- `}),w.push({position:y.body.end-1,text:`
338
+ `}),w.push({position:f.body.end-1,text:`
339
339
  ${A1.suffix}
340
- `})}}C.sort((y,i)=>i.start-y.start);let P=F.source;for(let{start:y,end:i}of C)P=P.slice(0,y)+P.slice(i);for(let y of w){let i=0;for(let l of C)if(l.start<y.position)i+=l.end-l.start;y.position-=i}w.sort((y,i)=>i.position-y.position);for(let{position:y,text:i}of w)P=P.slice(0,y)+i+P.slice(y);let O=P.includes("__tjs.typeError("),k=P.includes("__tjs.pushStack("),V=P.includes("Is("),T=P.includes("IsNot("),N=P.includes("Eq("),g=P.includes("NotEq("),b=P.includes("TypeOf("),f=/\bType\(/.test(P),n=/\bGeneric\(/.test(P),m=/\bFunctionPredicate\(/.test(P),X1=/\bEnum\(/.test(P),b1=/\bUnion\(/.test(P),C6=F.tjsModes.tjsSafeEval;if(O||k||V||T||N||g||b||f||n||m||X1||b1||C6){let y=[];if(O)y.push("class MonadicError extends Error{constructor(m,p,e,a,c){super(m);this.name='MonadicError';this.path=p;this.expected=e;this.actual=a;this.callStack=c}}",`function typeError(p,e,v){const a=v===null?'null':typeof v;const err=new MonadicError('Expected '+e+" for '"+p+"', got "+a,p,e,a);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}");if(k)y.push("const __stack=[];function pushStack(n){__stack.push(n)}function popStack(){__stack.pop()}function getStack(){return[...__stack]}");if(N)y.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((a===null||a===undefined)&&(b===null||b===undefined))return true;return false}");if(g)y.push("function NotEq(a,b){return!Eq(a,b)}");if(b)y.push("function TypeOf(v){return v===null?'null':typeof v}");if(V)y.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((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]))}");if(T)y.push("function IsNot(a,b){return!Is(a,b)}");if(f)y.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}");if(n)y.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}");if(m)y.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}}");if(X1)y.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}}");if(b1)y.push("function Union(d,...v){const vals=v.flat();return{description:d,check:x=>vals.includes(x),values:vals,__runtimeType:true}}");let i=y.length>0?y.join(`;
340
+ `})}}C.sort((f,i)=>i.start-f.start);let P=F.source;for(let{start:f,end:i}of C)P=P.slice(0,f)+P.slice(i);for(let f of w){let i=0;for(let l of C)if(l.start<f.position)i+=l.end-l.start;f.position-=i}w.sort((f,i)=>i.position-f.position);for(let{position:f,text:i}of w)P=P.slice(0,f)+i+P.slice(f);let O=P.includes("__tjs.typeError("),k=P.includes("__tjs.pushStack("),V=P.includes("Is("),T=P.includes("IsNot("),N=P.includes("Eq("),g=P.includes("NotEq("),b=P.includes("TypeOf("),y=/\bType\(/.test(P),n=/\bGeneric\(/.test(P),m=/\bFunctionPredicate\(/.test(P),X1=/\bEnum\(/.test(P),b1=/\bUnion\(/.test(P),O4=P.includes("IsBounded("),O6=F.tjsModes.tjsSafeEval;if(O||k||V||T||N||g||b||y||n||m||X1||b1||O4||O6){let f=[];if(O)f.push("class MonadicError extends Error{constructor(m,p,e,a,c){super(m);this.name='MonadicError';this.path=p;this.expected=e;this.actual=a;this.callStack=c}}",`function typeError(p,e,v){const a=v===null?'null':typeof v;const err=new MonadicError('Expected '+e+" for '"+p+"', got "+a,p,e,a);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}");if(k)f.push("const __stack=[];function pushStack(n){__stack.push(n)}function popStack(){__stack.pop()}function getStack(){return[...__stack]}");if(N)f.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}");if(g)f.push("function NotEq(a,b){return!Eq(a,b)}");if(b)f.push("function TypeOf(v){return v===null?'null':typeof v}");if(V)f.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]))}");if(T)f.push("function IsNot(a,b){return!Is(a,b)}");if(y)f.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}");if(n)f.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}");if(m)f.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}}");if(X1)f.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}}");if(b1)f.push("function Union(d,...v){const vals=v.flat();return{description:d,check:x=>vals.includes(x),values:vals,__runtimeType:true}}");if(O4)f.push("function IsBounded(v){return typeof v==='number'&&isFinite(v)&&!isNaN(v)}");let i=f.length>0?f.join(`;
341
341
  `)+`;
342
- `:"",l=[];if(O)l.push("typeError","isMonadicError");if(k)l.push("pushStack","popStack","getStack");if(N)l.push("Eq");if(g)l.push("NotEq");if(b)l.push("TypeOf");if(V)l.push("Is","tjsEquals");if(T)l.push("IsNot");if(f)l.push("Type");if(n)l.push("Generic");if(m)l.push("FunctionPredicate");if(X1)l.push("Enum");if(b1)l.push("Union");let D1=l.length>0?`{${l.join(",")}}`:"undefined";P=i+`const __tjs = globalThis.__tjs?.createRuntime?.() ?? ${D1};
343
- `+P}if(C6)P=`import { Eval, SafeFunction } from 'tjs-lang';
344
- `+P;let K0;if(Q){let y=F7(Z);K0=P7(W,L,y,P,K,F.extensions);let i=K0.filter((l)=>!l.passed);if(i.length>0&&Q===!0){let l=i.map((D1)=>{if(D1.isSignatureTest)return` Function signature example is inconsistent:
342
+ `:"",l=[];if(O)l.push("typeError","isMonadicError");if(k)l.push("pushStack","popStack","getStack");if(N)l.push("Eq");if(g)l.push("NotEq");if(b)l.push("TypeOf");if(V)l.push("Is","tjsEquals");if(T)l.push("IsNot");if(y)l.push("Type");if(n)l.push("Generic");if(m)l.push("FunctionPredicate");if(X1)l.push("Enum");if(b1)l.push("Union");if(O4)l.push("IsBounded");let D1=l.length>0?`{${l.join(",")}}`:"undefined";P=i+`const __tjs = globalThis.__tjs?.createRuntime?.() ?? ${D1};
343
+ `+P}if(O6)P=`import { Eval, SafeFunction } from 'tjs-lang';
344
+ `+P;let K0;if(Q){let f=V7(Z);K0=C7(W,U,f,P,K,F.extensions);let i=K0.filter((l)=>!l.passed);if(i.length>0&&Q===!0){let l=i.map((D1)=>{if(D1.isSignatureTest)return` Function signature example is inconsistent:
345
345
  ${D1.error}`;let v1=D1.line?` (line ${D1.line})`:"";return` Test '${D1.description}'${v1} failed:
346
346
  ${D1.error}`});throw Error(`Transpile-time test failures:
347
347
  ${l.join(`
348
- `)}`)}}if(Q==="only")return{code:"",types:R,metadata:R,testResults:K0,testCount:K0?.length};let O4;if(F.wasmBlocks.length>0){O4=[];let y=S7(F.wasmBlocks);if(y.code)P=y.code+`
349
- `+P;O4=y.results}return{code:P,types:R,metadata:R,warnings:Y.length>0?Y:void 0,testRunner:W.length>0?_:void 0,testCount:W.length>0?W.length:void 0,testResults:K0,wasmCompiled:O4}}function I5(Z){let $=[];for(let X of Z.body)if(X.type==="FunctionDeclaration")$.push(X);else if(X.type==="ExportNamedDeclaration"&&X.declaration?.type==="FunctionDeclaration")$.push(X.declaration);else if(X.type==="ExportDefaultDeclaration"&&X.declaration?.type==="FunctionDeclaration")$.push(X.declaration);return $}function j0(Z){let $={kind:Z.kind};if(Z.nullable)$.nullable=!0;if(Z.items)$.items=j0(Z.items);if(Z.shape)$.shape=Object.fromEntries(Object.entries(Z.shape).map(([X,Q])=>[X,j0(Q)]));if(Z.members)$.members=Z.members.map(j0);return $}function R5(Z,$,X={},Q={}){let H={};for(let[Y,z]of Object.entries($.params)){if(H[Y]={type:j0(z.type),required:z.required},z.default!==void 0)H[Y].default=z.default;if(z.description)H[Y].description=z.description}let K={params:H};if($.returns){if(K.returns={type:j0($.returns)},Q.returnDefaults)K.returns.defaults=Q.returnDefaults;if(X.returnSafety==="safe")K.safeReturn=!0;else if(X.returnSafety==="unsafe")K.unsafeReturn=!0}if($.description)K.description=$.description;if(X.unsafe)K.unsafe=!0;if(X.safe)K.safe=!0;if(Q.source){let{file:Y,line:z}=Q.source;K.source=`${Y}:${z}`}return`${Z}.__tjs = ${JSON.stringify(K,null,2)}`}function X6(Z,$){let X;switch($.kind){case"string":X=`typeof ${Z} !== 'string'`;break;case"number":X=`typeof ${Z} !== 'number'`;break;case"integer":X=`(typeof ${Z} !== 'number' || !Number.isInteger(${Z}))`;break;case"non-negative-integer":X=`(typeof ${Z} !== 'number' || !Number.isInteger(${Z}) || ${Z} < 0)`;break;case"boolean":X=`typeof ${Z} !== 'boolean'`;break;case"null":return`${Z} !== null`;case"undefined":return`${Z} !== undefined`;case"array":X=`!Array.isArray(${Z})`;break;case"object":X=`(typeof ${Z} !== 'object' || ${Z} === null || Array.isArray(${Z}))`;break;case"union":{let Q=$.members.map((H)=>X6(Z,H)).filter((H)=>H!==null);if(Q.length===0)return null;X=`(${Q.join(" && ")})`;break}case"any":return null;default:return null}if(X&&$.nullable)X=`(${Z} !== null && ${X})`;return X}function t1(Z){let $;switch(Z.kind){case"string":$="string";break;case"number":case"integer":case"non-negative-integer":$="number";break;case"boolean":$="boolean";break;case"null":return"null";case"undefined":return"undefined";case"any":$="any";break;case"array":if(Z.items){let X=t1(Z.items);$=X.includes("|")?`(${X})[]`:`${X}[]`}else $="any[]";break;case"object":if(Z.shape&&Object.keys(Z.shape).length>0)$=`{ ${Object.entries(Z.shape).map(([Q,H])=>`${Q}: ${t1(H)}`).join("; ")} }`;else $="Record<string, any>";break;case"union":if(Z.members&&Z.members.length>0)return Z.members.map(t1).join(" | ");$="any";break;default:$="any"}if(Z.nullable)return`${$} | null`;return $}function B5(Z,$,X,Q){let H=Object.entries($.params).map(([z,G])=>{let J=!G.required,W=t1(G.type);return J?`${z}?: ${W}`:`${z}: ${W}`}).join(", "),K=$.returns?t1($.returns):"any";return`${X?Q?"export default function":"export declare function":"declare function"} ${Z}(${H}): ${K};`}function w5(Z){let $=new Map,X,Q=/^[ \t]*export\s+(default\s+)?function\s+(\w+)/gm;while((X=Q.exec(Z))!==null)$.set(X[2],{exported:!0,isDefault:!!X[1]});let H=/^[ \t]*export\s+(default\s+)?class\s+(\w+)/gm;while((X=H.exec(Z))!==null)$.set(X[2],{exported:!0,isDefault:!!X[1]});let K=/^[ \t]*export\s+(default\s+)?(?:const|let|var)\s+(\w+)/gm;while((X=K.exec(Z))!==null)$.set(X[2],{exported:!0,isDefault:!!X[1]});let Y=/^[ \t]*export\s+Type\s+(\w+)/gm;while((X=Y.exec(Z))!==null)$.set(X[1],{exported:!0,isDefault:!1});let z=/^[ \t]*export\s+Generic\s+(\w+)/gm;while((X=z.exec(Z))!==null)$.set(X[1],{exported:!0,isDefault:!1});let G=/^[ \t]*export\s+FunctionPredicate\s+(\w+)/gm;while((X=G.exec(Z))!==null)$.set(X[1],{exported:!0,isDefault:!1});let J=/^[ \t]*export\s*\{([^}]+)\}/gm;while((X=J.exec(Z))!==null){let W=X[1].split(",").map((L)=>L.trim().split(/\s+as\s+/));for(let L of W){let _=L.length>1?L[1]:L[0];if(_&&/^\w+$/.test(_))$.set(_,{exported:!0,isDefault:!1})}}return $}function j5(Z){let $=new Map,X=/^[ \t]*(?:export\s+)?FunctionPredicate\s+(\w+)\s*(?:<([^>]+)>)?\s*\{/gm,Q;while((Q=X.exec(Z))!==null){let H=Q[1],K=Q[2],Y=Q.index+Q[0].length-1,z=1,G=Y+1;while(G<Z.length&&z>0){if(Z[G]==="{")z++;else if(Z[G]==="}")z--;G++}let J=Z.slice(Y+1,G-1),W;if(K)W=K.split(",").map((A)=>A.trim());let L=[],_=J.match(/params\s*:\s*\{([^}]*)\}/);if(_){let A=_[1],B=b7(A);for(let M of B){let F=M.match(/^(\w+)\s*:\s*(.+)$/);if(F)L.push({name:F[1],example:F[2].trim()})}}let U,q=J.match(/returns\s*:\s*(.+?)(?:\n|$)/);if(q)U=q[1].trim();$.set(H,{params:L,returns:U,typeParams:W})}return $}function M5(Z){let $=new Map,X=/^[ \t]*(?:export\s+(?:default\s+)?)?class\s+(\w+)(?:\s+extends\s+\w+)?\s*\{/gm,Q;while((Q=X.exec(Z))!==null){let H=Q[1],K=Q.index+Q[0].length-1,Y=1,z=K+1;while(z<Z.length&&Y>0){if(Z[z]==="{")Y++;else if(Z[z]==="}")Y--;z++}let G=Z.slice(K+1,z-1),J=G.indexOf("constructor"),W="";if(J!==-1){let _=G.indexOf("(",J);if(_!==-1){let U=1,q=_+1;while(q<G.length&&U>0){if(G[q]==="(")U++;else if(G[q]===")")U--;q++}W=G.slice(_+1,q-1).trim()}}let L=[];{let _=0,U=0;while(_<G.length){let q=G[_];if(q==="{"){U++,_++;continue}if(q==="}"){U--,_++;continue}if(U===0){let A=G.slice(_).match(/^(\w+)\s*\(/);if(A){let B=A[1];if(B==="constructor"||B==="get"||B==="set"){_+=B.length;continue}else{let M=_+A[0].length-1,F=1,R=M+1;while(R<G.length&&F>0){if(G[R]==="(")F++;else if(G[R]===")")F--;R++}let w=G.slice(M+1,R-1).trim(),C=G.slice(R).match(/^\s*->\s*(.+?)\s*\{/),P=C?C[1].trim():null;L.push({name:B,params:w,returnType:P}),_=R;continue}}}_++}}$.set(H,{name:H,constructorParams:W,methods:L})}return $}function b7(Z){let $=[],X=0,Q="";for(let H of Z){if(H==="{"||H==="["||H==="(")X++;else if(H==="}"||H==="]"||H===")")X--;if(H===","&&X===0)$.push(Q.trim()),Q="";else Q+=H}if(Q.trim())$.push(Q.trim());return $}function g7(Z){if(!Z.trim())return"";return b7(Z).map(($)=>{let X=$.match(/^(\w+)\s*:\s*(.+)$/);if(X){let H=X[1],K=S1(X[2].trim());return`${H}: ${K}`}let Q=$.match(/^(\w+)\s*=\s*(.+)$/);if(Q){let H=Q[1],K=S1(Q[2].trim());return`${H}?: ${K}`}if($.startsWith("{"))return"options: any";return`${$}: any`}).join(", ")}function F5(Z){let $=new Map,X,Q=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s*=\s*(.+)$/gm;while((X=Q.exec(Z))!==null)$.set(X[1],X[2].trim());let H=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s+([^{=].*)$/gm;while((X=H.exec(Z))!==null)if(!$.has(X[1]))$.set(X[1],X[2].trim());let K=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s*\{[^}]*example\s*:\s*(.+?)(?:\n|\s*[,}])/gm;while((X=K.exec(Z))!==null)$.set(X[1],X[2].trim());let Y=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s*\{\s*\}/gm;while((X=Y.exec(Z))!==null)if(!$.has(X[1]))$.set(X[1],"");return $}function P5(Z){let $=new Map,X=/^[ \t]*(?:export\s+)?Generic\s+(\w+)\s*<([^>]+)>\s*\{/gm,Q;while((Q=X.exec(Z))!==null){let H=Q[1],K=Q[2].split(",").map((_)=>{return _.trim().split(/\s*=/)[0].trim()}),Y=Q.index+Q[0].length-1,z=1,G=Y+1;while(G<Z.length&&z>0){if(Z[G]==="{")z++;else if(Z[G]==="}")z--;G++}let J=Z.slice(Y+1,G-1),W,L=J.match(/\bdeclaration\s*\{/);if(L&&L.index!==void 0){let _=L.index+L[0].length-1,U=1,q=_+1;while(q<J.length&&U>0){if(J[q]==="{")U++;else if(J[q]==="}")U--;q++}W=J.slice(_+1,q-1).trim()}$.set(H,{typeParams:K,declaration:W})}return $}function V5(Z){let $=[],X=/^[ \t]*export\s+(?:default\s+)?(const|let|var)\s+(\w+)\s*(?::\s*\w+\s*)?=\s*(.+)/gm,Q;while((Q=X.exec(Z))!==null){let H=Q[3].trim();if(H.endsWith(";"))H=H.slice(0,-1).trim();$.push({name:Q[2],value:H,kind:Q[1]})}return $}function C5(Z){if(/^['"]/.test(Z))return"string";if(Z.startsWith("`"))return"string";if(Z==="true"||Z==="false")return"boolean";if(/^[+-]?\d+(\.\d+)?$/.test(Z))return"number";if(Z.startsWith("Symbol(")||Z.startsWith("Symbol."))return"symbol";if(Z.startsWith("["))return"any[]";if(Z.startsWith("new WeakMap"))return"WeakMap<any, any>";if(Z.startsWith("new Map"))return"Map<any, any>";if(Z.startsWith("new Set"))return"Set<any>";if(Z.startsWith("new "))return"any";if(Z.startsWith("{"))return"Record<string, any>";if(Z==="null")return"null";if(Z==="undefined")return"undefined";return"any"}function O5(Z,$,X={}){let Q=[],H=w5($),K=F5($),Y=M5($),z=P5($),G=H.size>0,J=new Set;for(let[_,U]of Object.entries(Z.types)){if(_.includes("$"))continue;let q=H.get(_),A=G?!!q?.exported:!0,B=q?.isDefault??!1;if(!A)continue;if(U.description)Q.push(`/** ${U.description} */`);Q.push(B5(_,U,!0,B)),J.add(_)}for(let[_,U]of Y){if(J.has(_))continue;let q=H.get(_);if(!(G?!!q?.exported:!0))continue;let B=U.constructorParams?g7(U.constructorParams):"";if(Q.push(`export declare function ${_}(${B}): any;`),B||U.methods.length>0){if(Q.push(`export declare class ${_} {`),U.constructorParams)Q.push(` constructor(${B});`);for(let M of U.methods){let F=M.params?g7(M.params):"";Q.push(` ${M.name}(${F}): any;`)}Q.push("}")}J.add(_)}for(let[_,U]of K){if(J.has(_))continue;let q=H.get(_);if(!(G?!!q?.exported:!0))continue;if(U==="")Q.push(`export type ${_} = any;`);else{let B=S1(U);Q.push(`export declare const ${_}: { check(value: any): boolean; default: ${B}; (value: any): boolean; };`)}J.add(_)}for(let[_,U]of z){if(J.has(_))continue;let q=H.get(_);if(!(G?!!q?.exported:!0))continue;let B=U.typeParams.length>0?`<${U.typeParams.join(", ")}>`:"";if(U.declaration){let M=U.declaration.trim(),F=M.match(/^\/\/\s*TS:\s*(.+)$/s);if(F)Q.push(`export type ${_}${B} = ${F[1].trim()};`);else{let R=M.split(`
348
+ `)}`)}}if(Q==="only")return{code:"",types:R,metadata:R,testResults:K0,testCount:K0?.length};let N4;if(F.wasmBlocks.length>0){N4=[];let f=k7(F.wasmBlocks);if(f.code)P=f.code+`
349
+ `+P;N4=f.results}return{code:P,types:R,metadata:R,warnings:Y.length>0?Y:void 0,testRunner:W.length>0?_:void 0,testCount:W.length>0?W.length:void 0,testResults:K0,wasmCompiled:N4}}function B5(Z){let $=[];for(let X of Z.body)if(X.type==="FunctionDeclaration")$.push(X);else if(X.type==="ExportNamedDeclaration"&&X.declaration?.type==="FunctionDeclaration")$.push(X.declaration);else if(X.type==="ExportDefaultDeclaration"&&X.declaration?.type==="FunctionDeclaration")$.push(X.declaration);return $}function j0(Z){let $={kind:Z.kind};if(Z.nullable)$.nullable=!0;if(Z.items)$.items=j0(Z.items);if(Z.shape)$.shape=Object.fromEntries(Object.entries(Z.shape).map(([X,Q])=>[X,j0(Q)]));if(Z.members)$.members=Z.members.map(j0);return $}function w5(Z,$,X={},Q={}){let H={};for(let[Y,z]of Object.entries($.params)){if(H[Y]={type:j0(z.type),required:z.required},z.default!==void 0)H[Y].default=z.default;if(z.description)H[Y].description=z.description}let K={params:H};if($.returns){if(K.returns={type:j0($.returns)},Q.returnDefaults)K.returns.defaults=Q.returnDefaults;if(X.returnSafety==="safe")K.safeReturn=!0;else if(X.returnSafety==="unsafe")K.unsafeReturn=!0}if($.description)K.description=$.description;if(X.unsafe)K.unsafe=!0;if(X.safe)K.safe=!0;if(Q.source){let{file:Y,line:z}=Q.source;K.source=`${Y}:${z}`}return`${Z}.__tjs = ${JSON.stringify(K,null,2)}`}function Q6(Z,$){let X;switch($.kind){case"string":X=`typeof ${Z} !== 'string'`;break;case"number":X=`typeof ${Z} !== 'number'`;break;case"integer":X=`(typeof ${Z} !== 'number' || !Number.isInteger(${Z}))`;break;case"non-negative-integer":X=`(typeof ${Z} !== 'number' || !Number.isInteger(${Z}) || ${Z} < 0)`;break;case"boolean":X=`typeof ${Z} !== 'boolean'`;break;case"null":return`${Z} !== null`;case"undefined":return`${Z} !== undefined`;case"array":X=`!Array.isArray(${Z})`;break;case"object":X=`(typeof ${Z} !== 'object' || ${Z} === null || Array.isArray(${Z}))`;break;case"union":{let Q=$.members.map((H)=>Q6(Z,H)).filter((H)=>H!==null);if(Q.length===0)return null;X=`(${Q.join(" && ")})`;break}case"any":return null;default:return null}if(X&&$.nullable)X=`(${Z} !== null && ${X})`;return X}function t1(Z){let $;switch(Z.kind){case"string":$="string";break;case"number":case"integer":case"non-negative-integer":$="number";break;case"boolean":$="boolean";break;case"null":return"null";case"undefined":return"undefined";case"any":$="any";break;case"array":if(Z.items){let X=t1(Z.items);$=X.includes("|")?`(${X})[]`:`${X}[]`}else $="any[]";break;case"object":if(Z.shape&&Object.keys(Z.shape).length>0)$=`{ ${Object.entries(Z.shape).map(([Q,H])=>`${Q}: ${t1(H)}`).join("; ")} }`;else $="Record<string, any>";break;case"union":if(Z.members&&Z.members.length>0)return Z.members.map(t1).join(" | ");$="any";break;default:$="any"}if(Z.nullable)return`${$} | null`;return $}function j5(Z,$,X,Q){let H=Object.entries($.params).map(([z,G])=>{let J=!G.required,W=t1(G.type);return J?`${z}?: ${W}`:`${z}: ${W}`}).join(", "),K=$.returns?t1($.returns):"any";return`${X?Q?"export default function":"export declare function":"declare function"} ${Z}(${H}): ${K};`}function M5(Z){let $=new Map,X,Q=/^[ \t]*export\s+(default\s+)?function\s+(\w+)/gm;while((X=Q.exec(Z))!==null)$.set(X[2],{exported:!0,isDefault:!!X[1]});let H=/^[ \t]*export\s+(default\s+)?class\s+(\w+)/gm;while((X=H.exec(Z))!==null)$.set(X[2],{exported:!0,isDefault:!!X[1]});let K=/^[ \t]*export\s+(default\s+)?(?:const|let|var)\s+(\w+)/gm;while((X=K.exec(Z))!==null)$.set(X[2],{exported:!0,isDefault:!!X[1]});let Y=/^[ \t]*export\s+Type\s+(\w+)/gm;while((X=Y.exec(Z))!==null)$.set(X[1],{exported:!0,isDefault:!1});let z=/^[ \t]*export\s+Generic\s+(\w+)/gm;while((X=z.exec(Z))!==null)$.set(X[1],{exported:!0,isDefault:!1});let G=/^[ \t]*export\s+FunctionPredicate\s+(\w+)/gm;while((X=G.exec(Z))!==null)$.set(X[1],{exported:!0,isDefault:!1});let J=/^[ \t]*export\s*\{([^}]+)\}/gm;while((X=J.exec(Z))!==null){let W=X[1].split(",").map((U)=>U.trim().split(/\s+as\s+/));for(let U of W){let _=U.length>1?U[1]:U[0];if(_&&/^\w+$/.test(_))$.set(_,{exported:!0,isDefault:!1})}}return $}function F5(Z){let $=new Map,X=/^[ \t]*(?:export\s+)?FunctionPredicate\s+(\w+)\s*(?:<([^>]+)>)?\s*\{/gm,Q;while((Q=X.exec(Z))!==null){let H=Q[1],K=Q[2],Y=Q.index+Q[0].length-1,z=1,G=Y+1;while(G<Z.length&&z>0){if(Z[G]==="{")z++;else if(Z[G]==="}")z--;G++}let J=Z.slice(Y+1,G-1),W;if(K)W=K.split(",").map((A)=>A.trim());let U=[],_=J.match(/params\s*:\s*\{([^}]*)\}/);if(_){let A=_[1],B=f7(A);for(let M of B){let F=M.match(/^(\w+)\s*:\s*(.+)$/);if(F)U.push({name:F[1],example:F[2].trim()})}}let L,q=J.match(/returns\s*:\s*(.+?)(?:\n|$)/);if(q)L=q[1].trim();$.set(H,{params:U,returns:L,typeParams:W})}return $}function P5(Z){let $=new Map,X=/^[ \t]*(?:export\s+(?:default\s+)?)?class\s+(\w+)(?:\s+extends\s+\w+)?\s*\{/gm,Q;while((Q=X.exec(Z))!==null){let H=Q[1],K=Q.index+Q[0].length-1,Y=1,z=K+1;while(z<Z.length&&Y>0){if(Z[z]==="{")Y++;else if(Z[z]==="}")Y--;z++}let G=Z.slice(K+1,z-1),J=G.indexOf("constructor"),W="";if(J!==-1){let _=G.indexOf("(",J);if(_!==-1){let L=1,q=_+1;while(q<G.length&&L>0){if(G[q]==="(")L++;else if(G[q]===")")L--;q++}W=G.slice(_+1,q-1).trim()}}let U=[];{let _=0,L=0;while(_<G.length){let q=G[_];if(q==="{"){L++,_++;continue}if(q==="}"){L--,_++;continue}if(L===0){let A=G.slice(_).match(/^(\w+)\s*\(/);if(A){let B=A[1];if(B==="constructor"||B==="get"||B==="set"){_+=B.length;continue}else{let M=_+A[0].length-1,F=1,R=M+1;while(R<G.length&&F>0){if(G[R]==="(")F++;else if(G[R]===")")F--;R++}let w=G.slice(M+1,R-1).trim(),C=G.slice(R).match(/^\s*->\s*(.+?)\s*\{/),P=C?C[1].trim():null;U.push({name:B,params:w,returnType:P}),_=R;continue}}}_++}}$.set(H,{name:H,constructorParams:W,methods:U})}return $}function f7(Z){let $=[],X=0,Q="";for(let H of Z){if(H==="{"||H==="["||H==="(")X++;else if(H==="}"||H==="]"||H===")")X--;if(H===","&&X===0)$.push(Q.trim()),Q="";else Q+=H}if(Q.trim())$.push(Q.trim());return $}function v7(Z){if(!Z.trim())return"";return f7(Z).map(($)=>{let X=$.match(/^(\w+)\s*:\s*(.+)$/);if(X){let H=X[1],K=S1(X[2].trim());return`${H}: ${K}`}let Q=$.match(/^(\w+)\s*=\s*(.+)$/);if(Q){let H=Q[1],K=S1(Q[2].trim());return`${H}?: ${K}`}if($.startsWith("{"))return"options: any";return`${$}: any`}).join(", ")}function V5(Z){let $=new Map,X,Q=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s*=\s*(.+)$/gm;while((X=Q.exec(Z))!==null)$.set(X[1],X[2].trim());let H=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s+([^{=].*)$/gm;while((X=H.exec(Z))!==null)if(!$.has(X[1]))$.set(X[1],X[2].trim());let K=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s*\{[^}]*example\s*:\s*(.+?)(?:\n|\s*[,}])/gm;while((X=K.exec(Z))!==null)$.set(X[1],X[2].trim());let Y=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s*\{[^}]*\/\/\s*TS:\s*(.+?)(?:\n|\s*\})/gm;while((X=Y.exec(Z))!==null)if(!$.has(X[1]))$.set(X[1],`__ts__:${X[2].trim()}`);let z=/^[ \t]*(?:export\s+)?Type\s+(\w+)\s*\{\s*\}/gm;while((X=z.exec(Z))!==null)if(!$.has(X[1]))$.set(X[1],"");return $}function C5(Z){let $=new Map,X=/^[ \t]*(?:export\s+)?Generic\s+(\w+)\s*<([^>]+)>\s*\{/gm,Q;while((Q=X.exec(Z))!==null){let H=Q[1],K=Q[2].split(",").map((_)=>{return _.trim().split(/\s*=/)[0].trim()}),Y=Q.index+Q[0].length-1,z=1,G=Y+1;while(G<Z.length&&z>0){if(Z[G]==="{")z++;else if(Z[G]==="}")z--;G++}let J=Z.slice(Y+1,G-1),W,U=J.match(/\bdeclaration\s*\{/);if(U&&U.index!==void 0){let _=U.index+U[0].length-1,L=1,q=_+1;while(q<J.length&&L>0){if(J[q]==="{")L++;else if(J[q]==="}")L--;q++}W=J.slice(_+1,q-1).trim()}$.set(H,{typeParams:K,declaration:W})}return $}function O5(Z){let $=[],X=/^[ \t]*export\s+(?:default\s+)?(const|let|var)\s+(\w+)\s*(?::\s*\w+\s*)?=\s*(.+)/gm,Q;while((Q=X.exec(Z))!==null){let H=Q[3].trim();if(H.endsWith(";"))H=H.slice(0,-1).trim();$.push({name:Q[2],value:H,kind:Q[1]})}return $}function N5(Z){if(/^['"]/.test(Z))return"string";if(Z.startsWith("`"))return"string";if(Z==="true"||Z==="false")return"boolean";if(/^[+-]?\d+(\.\d+)?$/.test(Z))return"number";if(Z.startsWith("Symbol(")||Z.startsWith("Symbol."))return"symbol";if(Z.startsWith("["))return"any[]";if(Z.startsWith("new WeakMap"))return"WeakMap<any, any>";if(Z.startsWith("new Map"))return"Map<any, any>";if(Z.startsWith("new Set"))return"Set<any>";if(Z.startsWith("new "))return"any";if(Z.startsWith("{"))return"Record<string, any>";if(Z==="null")return"null";if(Z==="undefined")return"undefined";return"any"}function E5(Z,$,X={}){let Q=[],H=M5($),K=V5($),Y=P5($),z=C5($),G=H.size>0,J=new Set;for(let[_,L]of Object.entries(Z.types)){if(_.includes("$"))continue;let q=H.get(_),A=G?!!q?.exported:!0,B=q?.isDefault??!1;if(!A)continue;if(L.description)Q.push(`/** ${L.description} */`);Q.push(j5(_,L,!0,B)),J.add(_)}for(let[_,L]of Y){if(J.has(_))continue;let q=H.get(_);if(!(G?!!q?.exported:!0))continue;let B=L.constructorParams?v7(L.constructorParams):"";if(Q.push(`export declare function ${_}(${B}): any;`),B||L.methods.length>0){if(Q.push(`export declare class ${_} {`),L.constructorParams)Q.push(` constructor(${B});`);for(let M of L.methods){let F=M.params?v7(M.params):"";Q.push(` ${M.name}(${F}): any;`)}Q.push("}")}J.add(_)}for(let[_,L]of K){if(J.has(_))continue;let q=H.get(_);if(!(G?!!q?.exported:!0))continue;if(L.startsWith("__ts__:")){let B=L.slice(7);Q.push(`export type ${_} = ${B};`)}else if(L==="")Q.push(`export type ${_} = any;`);else{let B=S1(L);Q.push(`export declare const ${_}: { check(value: any): boolean; default: ${B}; (value: any): boolean; };`)}J.add(_)}for(let[_,L]of z){if(J.has(_))continue;let q=H.get(_);if(!(G?!!q?.exported:!0))continue;let B=L.typeParams.length>0?`<${L.typeParams.join(", ")}>`:"";if(L.declaration){let M=L.declaration.trim(),F=M.match(/^\/\/\s*TS:\s*(.+)$/s);if(F)Q.push(`export type ${_}${B} = ${F[1].trim()};`);else{let R=M.split(`
350
350
  `).map((w)=>w.trim()).filter((w)=>w.length>0).map((w)=>` ${w}`).join(`
351
351
  `);Q.push(`export interface ${_}${B} {
352
352
  ${R}
353
- }`)}}else Q.push(`export declare function ${_}(...args: any[]): { check(value: any): boolean; (value: any): boolean; };`);J.add(_)}let W=j5($);for(let[_,U]of W){if(J.has(_))continue;let q=H.get(_);if(!(G?!!q?.exported:!0))continue;let B=new Set(U.typeParams?.map((w)=>w.split("=")[0].trim())??[]),M=U.typeParams?`<${U.typeParams.join(", ")}>`:"",F=U.params.map((w,C)=>{let P=C===U.params.length-1;if(w.example.startsWith("[")&&w.example.endsWith("]")&&P){let k=w.example.slice(1,-1).trim(),V=!k||k==="null"?"any":B.has(k)?k:S1(k);return`...${w.name}: ${V}[]`}if(w.example.startsWith("[")&&w.example.endsWith("]")){let k=w.example.slice(1,-1).trim(),V=!k||k==="null"?"any":B.has(k)?k:S1(k);return`${w.name}: ${V}[]`}let O=w.example==="null"?"any":B.has(w.example)?w.example:S1(w.example);return`${w.name}: ${O}`}).join(", "),R=U.returns!==void 0?U.returns==="null"?"any":B.has(U.returns)?U.returns:S1(U.returns):"void";Q.push(`export type ${_}${M} = (${F}) => ${R};`),J.add(_)}let L=V5($);for(let _ of L){if(J.has(_.name))continue;let U=H.get(_.name);if(!(G?!!U?.exported:!0))continue;let A=C5(_.value);Q.push(`export declare const ${_.name}: ${A};`),J.add(_.name)}if(X.moduleName){let _=Q.map((U)=>` ${U}`).join(`
353
+ }`)}}else Q.push(`export declare function ${_}(...args: any[]): { check(value: any): boolean; (value: any): boolean; };`);J.add(_)}let W=F5($);for(let[_,L]of W){if(J.has(_))continue;let q=H.get(_);if(!(G?!!q?.exported:!0))continue;let B=new Set(L.typeParams?.map((w)=>w.split("=")[0].trim())??[]),M=L.typeParams?`<${L.typeParams.join(", ")}>`:"",F=L.params.map((w,C)=>{let P=C===L.params.length-1;if(w.example.startsWith("[")&&w.example.endsWith("]")&&P){let k=w.example.slice(1,-1).trim(),V=!k||k==="null"?"any":B.has(k)?k:S1(k);return`...${w.name}: ${V}[]`}if(w.example.startsWith("[")&&w.example.endsWith("]")){let k=w.example.slice(1,-1).trim(),V=!k||k==="null"?"any":B.has(k)?k:S1(k);return`${w.name}: ${V}[]`}let O=w.example==="null"?"any":B.has(w.example)?w.example:S1(w.example);return`${w.name}: ${O}`}).join(", "),R=L.returns!==void 0?L.returns==="null"?"any":B.has(L.returns)?L.returns:S1(L.returns):"void";Q.push(`export type ${_}${M} = (${F}) => ${R};`),J.add(_)}let U=O5($);for(let _ of U){if(J.has(_.name))continue;let L=H.get(_.name);if(!(G?!!L?.exported:!0))continue;let A=N5(_.value);Q.push(`export declare const ${_.name}: ${A};`),J.add(_.name)}if(X.moduleName){let _=Q.map((L)=>` ${L}`).join(`
354
354
  `);return`declare module '${X.moduleName}' {
355
355
  ${_}
356
356
  }
357
357
  `}return Q.join(`
358
358
  `)+`
359
- `}function S1(Z){let $=Z.trim();if(N5($)){let X=E5($).map((Q)=>S1(Q.trim()));return[...new Set(X)].join(" | ")}if(/^['"]/.test($))return"string";if($==="true"||$==="false")return"boolean";if($==="null")return"null";if($==="undefined")return"undefined";if(/^[+-]?\d+\.\d+$/.test($))return"number";if(/^[+-]?\d+$/.test($))return"number";if($.startsWith("["))return"any[]";if($.startsWith("{"))return"Record<string, any>";return"any"}function N5(Z){let $=0,X=null;for(let Q of Z){if(X){if(Q===X)X=null;continue}if(Q==="'"||Q==='"'||Q==="`"){X=Q;continue}if(Q==="{"||Q==="["||Q==="(")$++;else if(Q==="}"||Q==="]"||Q===")")$--;else if(Q==="|"&&$===0)return!0}return!1}function E5(Z){let $=[],X=0,Q=null,H="";for(let K of Z){if(Q){if(H+=K,K===Q)Q=null;continue}if(K==="'"||K==='"'||K==="`"){Q=K,H+=K;continue}if(K==="{"||K==="["||K==="(")X++;else if(K==="}"||K==="]"||K===")")X--;if(K==="|"&&X===0)$.push(H),H="";else H+=K}if(H)$.push(H);return $}import j from"typescript";var f7=new Set(["Event","CustomEvent","MouseEvent","KeyboardEvent","PointerEvent","TouchEvent","FocusEvent","InputEvent","CompositionEvent","WheelEvent","DragEvent","AnimationEvent","TransitionEvent","ClipboardEvent","UIEvent","ProgressEvent","ErrorEvent","MessageEvent","PopStateEvent","HashChangeEvent","PageTransitionEvent","StorageEvent","BeforeUnloadEvent","SubmitEvent","EventTarget","EventListener","Node","Element","HTMLElement","SVGElement","Document","DocumentFragment","ShadowRoot","Text","Comment","Attr","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","HTMLButtonElement","HTMLFormElement","HTMLAnchorElement","HTMLImageElement","HTMLVideoElement","HTMLAudioElement","HTMLCanvasElement","HTMLDivElement","HTMLSpanElement","HTMLParagraphElement","HTMLTableElement","HTMLTemplateElement","HTMLSlotElement","HTMLDialogElement","HTMLDetailsElement","HTMLLabelElement","HTMLOptionElement","HTMLIFrameElement","HTMLScriptElement","HTMLStyleElement","HTMLLinkElement","HTMLMetaElement","HTMLHeadElement","HTMLBodyElement","HTMLMediaElement","SVGSVGElement","SVGPathElement","SVGGElement","SVGCircleElement","SVGRectElement","SVGTextElement","SVGLineElement","SVGPolygonElement","NodeList","HTMLCollection","NamedNodeMap","DOMTokenList","DOMStringMap","CSSStyleDeclaration","DOMRect","DOMRectReadOnly","DOMPoint","DOMMatrix","Range","Selection","StaticRange","MutationObserver","MutationRecord","IntersectionObserver","IntersectionObserverEntry","ResizeObserver","ResizeObserverEntry","PerformanceObserver","PerformanceEntry","Window","Location","History","Navigator","Screen","Storage","CanvasRenderingContext2D","WebGLRenderingContext","WebGL2RenderingContext","OffscreenCanvas","ImageData","ImageBitmap","MediaStream","MediaRecorder","AudioContext","AudioNode","AudioBuffer","Worker","SharedWorker","ServiceWorker","ServiceWorkerRegistration","BroadcastChannel","MessageChannel","MessagePort","WebSocket","XMLHttpRequest","FileReader","FileList","DataTransfer","Crypto","SubtleCrypto","CryptoKey","Geolocation","Notification","PermissionStatus","MediaQueryList","TreeWalker","NodeIterator","ClipboardItem"]);function x(Z,$,X,Q){if(!Z)return"undefined";switch(Z.kind){case j.SyntaxKind.StringKeyword:return"''";case j.SyntaxKind.NumberKeyword:return"0.0";case j.SyntaxKind.BooleanKeyword:return"false";case j.SyntaxKind.NullKeyword:return"null";case j.SyntaxKind.UndefinedKeyword:return"undefined";case j.SyntaxKind.VoidKeyword:return"undefined";case j.SyntaxKind.AnyKeyword:return"any";case j.SyntaxKind.UnknownKeyword:return"any";case j.SyntaxKind.NeverKeyword:return"null";case j.SyntaxKind.SymbolKeyword:return"Symbol('example')";case j.SyntaxKind.BigIntKeyword:return"0n";case j.SyntaxKind.ObjectKeyword:return"{}";case j.SyntaxKind.ArrayType:{let K=x(Z.elementType,$);if(K==="any")K="null";return`[${K}]`}case j.SyntaxKind.TypeReference:{let H=Z,K=H.typeName.getText();if(K==="Array"&&H.typeArguments?.length)return`[${x(H.typeArguments[0],$,X,Q)}]`;if(K==="Promise"){if(H.typeArguments?.length)return x(H.typeArguments[0],$,X,Q);return"undefined"}if(K==="Generator"||K==="AsyncGenerator"||K==="IterableIterator"||K==="AsyncIterableIterator"){if(H.typeArguments?.length)return x(H.typeArguments[0],$,X,Q);return"undefined"}if(K==="Record")return"{}";let Y={Map:"new Map()",Set:"new Set()",WeakMap:"new WeakMap()",WeakSet:"new WeakSet()",WeakRef:"new WeakRef({})",Error:"new Error('example')",TypeError:"new TypeError('example')",RangeError:"new RangeError('example')",SyntaxError:"new SyntaxError('example')",ReferenceError:"new ReferenceError('example')",URIError:"new URIError('example')",EvalError:"new EvalError('example')",Date:"new Date()",RegExp:"/example/",ArrayBuffer:"new ArrayBuffer(0)",SharedArrayBuffer:"new SharedArrayBuffer(0)",DataView:"new DataView(new ArrayBuffer(0))",Float32Array:"new Float32Array(0)",Float64Array:"new Float64Array(0)",Int8Array:"new Int8Array(0)",Int16Array:"new Int16Array(0)",Int32Array:"new Int32Array(0)",Uint8Array:"new Uint8Array(0)",Uint16Array:"new Uint16Array(0)",Uint32Array:"new Uint32Array(0)",Uint8ClampedArray:"new Uint8ClampedArray(0)",BigInt64Array:"new BigInt64Array(0)",BigUint64Array:"new BigUint64Array(0)",URL:"new URL('https://example.com')",URLSearchParams:"new URLSearchParams()",Headers:"new Headers()",FormData:"new FormData()",Blob:"new Blob()",File:"new File([], 'example')",Response:"new Response()",Request:"new Request('https://example.com')",AbortController:"new AbortController()",AbortSignal:"AbortSignal.abort()",ReadableStream:"new ReadableStream()",WritableStream:"new WritableStream()",TransformStream:"new TransformStream()",TextEncoder:"new TextEncoder()",TextDecoder:"new TextDecoder()",Promise:"Promise.resolve(null)"};if(K in Y)return Y[K];if(Q?.typeAliases?.has(K)){let z=Q.visited??new Set;if(z.has(K))return X?.push(`Circular type reference '${K}' - using 'any'`),"any";z.add(K);let G=Q.typeAliases.get(K);return x(G,$,X,{...Q,visited:z})}if(Q?.interfaces?.has(K)){let z=Q.visited??new Set;if(z.has(K))return X?.push(`Circular type reference '${K}' - using 'any'`),"any";z.add(K);let G=Q.interfaces.get(K),J=[];for(let W of G.members)if(j.isPropertySignature(W)&&W.name){let L=W.name.getText(Q.sourceFile),_=x(W.type,$,X,{...Q,visited:z});J.push(`${L}: ${_}`)}return`{ ${J.join(", ")} }`}if(Q?.typeParams?.has(K)){let z=Q.typeParams.get(K);if(z.constraint)return x(z.constraint,$,X,Q);if(z.default)return x(z.default,$,X,Q)}if(f7.has(K))return"{}";if(/^[A-Z]$/.test(K)||["T","K","V","U","TKey","TValue","TItem","TResult"].includes(K))return X?.push(`Generic type parameter '${K}' converted to 'any' - consider specializing`),"any";return X?.push(`Unknown type '${K}' converted to 'any' - may need manual review`),"any"}case j.SyntaxKind.TypeLiteral:{let H=Z,K=[];for(let Y of H.members)if(j.isPropertySignature(Y)&&Y.name){let z=Y.name.getText(),G=x(Y.type,$);if(G==="any")G="null";K.push(`${z}: ${G}`)}return`{ ${K.join(", ")} }`}case j.SyntaxKind.UnionType:{let H=Z,K=(L)=>L.kind===j.SyntaxKind.NullKeyword||j.isLiteralTypeNode(L)&&L.literal.kind===j.SyntaxKind.NullKeyword,Y=(L)=>L.kind===j.SyntaxKind.UndefinedKeyword||j.isLiteralTypeNode(L)&&L.literal.kind===j.SyntaxKind.UndefinedKeyword,z=H.types.filter((L)=>!K(L)&&!Y(L)),G=H.types.some(K),J=H.types.some(Y);if(z.length===0){if(G)return"null";return"undefined"}if(z.length===1&&(G||J)){let L=x(z[0],$,X,Q);if(L==="any")return"any";if(G)return`${L} | null`;if(J)return`${L} | undefined`}let W=H.types.map((L)=>x(L,$,X,Q)).filter((L,_,U)=>U.indexOf(L)===_);if(W.some((L)=>L==="any"))return"any";if(W.length===1)return W[0];if(W.length>0){if(W.some((_)=>/[()]/.test(_)||_.startsWith("new ")))return"any";return W.join(" | ")}return"undefined"}case j.SyntaxKind.LiteralType:{let H=Z;if(j.isStringLiteral(H.literal))return`'${H.literal.text}'`;if(j.isNumericLiteral(H.literal))return H.literal.text;if(H.literal.kind===j.SyntaxKind.TrueKeyword)return"true";if(H.literal.kind===j.SyntaxKind.FalseKeyword)return"false";if(H.literal.kind===j.SyntaxKind.NullKeyword)return"null";return"undefined"}case j.SyntaxKind.ParenthesizedType:return x(Z.type,$);case j.SyntaxKind.FunctionType:{let H=Z,K=[];for(let G of H.parameters){let J=G.name?.getText()||"_";if(J==="this")continue;let W=x(G.type,$,X,Q);if(W==="any")W="null";K.push(`${J}: ${W}`)}let Y=x(H.type,$,X,Q);if(Y==="any")Y="null";let z=[];if(K.length>0)z.push(`params: { ${K.join(", ")} }`);if(Y!=="undefined")z.push(`returns: ${Y}`);return`FunctionPredicate('function', { ${z.join(", ")} })`}case j.SyntaxKind.TupleType:return`[${Z.elements.map((Y)=>{let z=j.isNamedTupleMember(Y)?x(Y.type,$):x(Y,$);return z==="any"?"null":z}).join(", ")}]`;default:return"undefined"}}function a(Z,$){if(!Z)return{kind:"any"};switch(Z.kind){case j.SyntaxKind.StringKeyword:return{kind:"string"};case j.SyntaxKind.NumberKeyword:return{kind:"number"};case j.SyntaxKind.BooleanKeyword:return{kind:"boolean"};case j.SyntaxKind.NullKeyword:return{kind:"null"};case j.SyntaxKind.UndefinedKeyword:case j.SyntaxKind.VoidKeyword:return{kind:"undefined"};case j.SyntaxKind.ArrayType:return{kind:"array",items:a(Z.elementType,$)};case j.SyntaxKind.TypeLiteral:{let X=Z,Q={};for(let H of X.members)if(j.isPropertySignature(H)&&H.name){let K=H.name.getText();Q[K]=a(H.type,$)}return{kind:"object",shape:Q}}case j.SyntaxKind.UnionType:{let X=Z,Q=X.types.filter((K)=>K.kind!==j.SyntaxKind.NullKeyword&&K.kind!==j.SyntaxKind.UndefinedKeyword),H=X.types.some((K)=>K.kind===j.SyntaxKind.NullKeyword);if(Q.length===1&&H)return{...a(Q[0],$),nullable:!0};return{kind:"union",members:X.types.map((K)=>a(K,$))}}case j.SyntaxKind.IntersectionType:{let X=Z,Q={};for(let H of X.types){let K=a(H,$);if(K.kind==="object"&&K.shape)Object.assign(Q,K.shape)}if(Object.keys(Q).length>0)return{kind:"object",shape:Q};return{kind:"any"}}case j.SyntaxKind.TupleType:{let X=Z,Q=[];for(let H of X.elements)if(j.isNamedTupleMember(H))Q.push(a(H.type,$));else Q.push(a(H,$));return{kind:"tuple",elements:Q}}case j.SyntaxKind.TypeReference:{let X=Z,Q=X.typeName.getText();if(Q==="Array"&&X.typeArguments?.length)return{kind:"array",items:a(X.typeArguments[0],$)};if(Q==="Promise"&&X.typeArguments?.length)return a(X.typeArguments[0],$);if((Q==="Generator"||Q==="AsyncGenerator"||Q==="IterableIterator"||Q==="AsyncIterableIterator")&&X.typeArguments?.length)return a(X.typeArguments[0],$);if(X.typeArguments?.length){let H=a(X.typeArguments[0],$);if(Q==="Partial")return H;if(Q==="Required")return H;if(Q==="Readonly")return H;if(Q==="Record"&&X.typeArguments.length>=2)return{kind:"object",shape:{"[key]":a(X.typeArguments[1],$)}};if(Q==="Pick"||Q==="Omit")return H;if(Q==="NonNullable"){if(H.nullable)return{...H,nullable:!1};return H}if(["ReturnType","Parameters","ConstructorParameters"].includes(Q))return{kind:"any"}}if($?.typeAliases?.has(Q)){let H=$.visited??new Set;if(H.has(Q))return{kind:"any"};H.add(Q);let K=$.typeAliases.get(Q);return a(K,{...$,visited:H})}if($?.interfaces?.has(Q)){let H=$.visited??new Set;if(H.has(Q))return{kind:"any"};H.add(Q);let K=$.interfaces.get(Q),Y={};if(K.heritageClauses){for(let z of K.heritageClauses)if(z.token===j.SyntaxKind.ExtendsKeyword)for(let G of z.types){let J=G.expression.getText($.sourceFile);if($.interfaces?.has(J)&&!H.has(J)){let W={kind:j.SyntaxKind.TypeReference,typeName:{getText:()=>J}},L=a(W,{...$,visited:H});if(L.kind==="object"&&L.shape)Object.assign(Y,L.shape)}}}for(let z of K.members)if(j.isPropertySignature(z)&&z.name){let G=z.name.getText($.sourceFile);Y[G]=a(z.type,{...$,visited:H})}return{kind:"object",shape:Y}}if($?.typeParams?.has(Q)){let H=$.typeParams.get(Q);if(H.constraint)return a(H.constraint,$);if(H.default)return a(H.default,$)}if(f7.has(Q))return{kind:"object"};return{kind:"any"}}default:return{kind:"any"}}}function S5(Z,$){if(!Z.typeParameters||Z.typeParameters.length===0)return;let X={};for(let Q of Z.typeParameters){let H=Q.name.getText(),K={};if(Q.constraint){let Y=x(Q.constraint,void 0,$);if(Y.startsWith("{"))try{K.constraint=Y}catch{K.constraint=Y}else K.constraint=Y}if(Q.default){let Y=x(Q.default,void 0,$);K.default=Y}X[H]=K}return Object.keys(X).length>0?X:void 0}function T5(Z,$,X,Q){let H=Z.name.getText($);if(Z.typeParameters&&Z.typeParameters.length>0)return k5(Z,$,X,Q);let K=Q?.find((J)=>J.kind==="example"),Y=Q?.find((J)=>J.kind==="predicate"),z;if(K?.text)z=K.text;else{let J=[];for(let W of Z.members)if(j.isPropertySignature(W)&&W.name){let L=W.name.getText($),_=x(W.type,void 0,X);if(_==="any")_="null";J.push(`${L}: ${_}`)}if(J.length===0&&!Y)return`Type ${H} {}`;z=J.length>0?`{ ${J.join(", ")} }`:"{}"}let G=[`example: ${z}`];if(Y?.text)G.push(Y.text);return`Type ${H} {
359
+ `}function S1(Z){let $=Z.trim();if(S5($)){let X=T5($).map((Q)=>S1(Q.trim()));return[...new Set(X)].join(" | ")}if(/^['"]/.test($))return"string";if($==="true"||$==="false")return"boolean";if($==="null")return"null";if($==="undefined")return"undefined";if(/^[+-]?\d+\.\d+$/.test($))return"number";if(/^[+-]?\d+$/.test($))return"number";if($.startsWith("["))return"any[]";if($.startsWith("{"))return"Record<string, any>";return"any"}function S5(Z){let $=0,X=null;for(let Q of Z){if(X){if(Q===X)X=null;continue}if(Q==="'"||Q==='"'||Q==="`"){X=Q;continue}if(Q==="{"||Q==="["||Q==="(")$++;else if(Q==="}"||Q==="]"||Q===")")$--;else if(Q==="|"&&$===0)return!0}return!1}function T5(Z){let $=[],X=0,Q=null,H="";for(let K of Z){if(Q){if(H+=K,K===Q)Q=null;continue}if(K==="'"||K==='"'||K==="`"){Q=K,H+=K;continue}if(K==="{"||K==="["||K==="(")X++;else if(K==="}"||K==="]"||K===")")X--;if(K==="|"&&X===0)$.push(H),H="";else H+=K}if(H)$.push(H);return $}import j from"typescript";var h7=new Set(["Event","CustomEvent","MouseEvent","KeyboardEvent","PointerEvent","TouchEvent","FocusEvent","InputEvent","CompositionEvent","WheelEvent","DragEvent","AnimationEvent","TransitionEvent","ClipboardEvent","UIEvent","ProgressEvent","ErrorEvent","MessageEvent","PopStateEvent","HashChangeEvent","PageTransitionEvent","StorageEvent","BeforeUnloadEvent","SubmitEvent","EventTarget","EventListener","Node","Element","HTMLElement","SVGElement","Document","DocumentFragment","ShadowRoot","Text","Comment","Attr","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","HTMLButtonElement","HTMLFormElement","HTMLAnchorElement","HTMLImageElement","HTMLVideoElement","HTMLAudioElement","HTMLCanvasElement","HTMLDivElement","HTMLSpanElement","HTMLParagraphElement","HTMLTableElement","HTMLTemplateElement","HTMLSlotElement","HTMLDialogElement","HTMLDetailsElement","HTMLLabelElement","HTMLOptionElement","HTMLIFrameElement","HTMLScriptElement","HTMLStyleElement","HTMLLinkElement","HTMLMetaElement","HTMLHeadElement","HTMLBodyElement","HTMLMediaElement","SVGSVGElement","SVGPathElement","SVGGElement","SVGCircleElement","SVGRectElement","SVGTextElement","SVGLineElement","SVGPolygonElement","NodeList","HTMLCollection","NamedNodeMap","DOMTokenList","DOMStringMap","CSSStyleDeclaration","DOMRect","DOMRectReadOnly","DOMPoint","DOMMatrix","Range","Selection","StaticRange","MutationObserver","MutationRecord","IntersectionObserver","IntersectionObserverEntry","ResizeObserver","ResizeObserverEntry","PerformanceObserver","PerformanceEntry","Window","Location","History","Navigator","Screen","Storage","CanvasRenderingContext2D","WebGLRenderingContext","WebGL2RenderingContext","OffscreenCanvas","ImageData","ImageBitmap","MediaStream","MediaRecorder","AudioContext","AudioNode","AudioBuffer","Worker","SharedWorker","ServiceWorker","ServiceWorkerRegistration","BroadcastChannel","MessageChannel","MessagePort","WebSocket","XMLHttpRequest","FileReader","FileList","DataTransfer","Crypto","SubtleCrypto","CryptoKey","Geolocation","Notification","PermissionStatus","MediaQueryList","TreeWalker","NodeIterator","ClipboardItem"]);function x(Z,$,X,Q){if(!Z)return"undefined";switch(Z.kind){case j.SyntaxKind.StringKeyword:return"''";case j.SyntaxKind.NumberKeyword:return"0.0";case j.SyntaxKind.BooleanKeyword:return"false";case j.SyntaxKind.NullKeyword:return"null";case j.SyntaxKind.UndefinedKeyword:return"undefined";case j.SyntaxKind.VoidKeyword:return"undefined";case j.SyntaxKind.AnyKeyword:return"any";case j.SyntaxKind.UnknownKeyword:return"any";case j.SyntaxKind.NeverKeyword:return"null";case j.SyntaxKind.SymbolKeyword:return"Symbol('example')";case j.SyntaxKind.BigIntKeyword:return"0n";case j.SyntaxKind.ObjectKeyword:return"{}";case j.SyntaxKind.ArrayType:{let K=x(Z.elementType,$);if(K==="any")K="null";return`[${K}]`}case j.SyntaxKind.TypeReference:{let H=Z,K=H.typeName.getText();if(K==="Array"&&H.typeArguments?.length)return`[${x(H.typeArguments[0],$,X,Q)}]`;if(K==="Promise"){if(H.typeArguments?.length)return x(H.typeArguments[0],$,X,Q);return"undefined"}if(K==="Generator"||K==="AsyncGenerator"||K==="IterableIterator"||K==="AsyncIterableIterator"){if(H.typeArguments?.length)return x(H.typeArguments[0],$,X,Q);return"undefined"}if(K==="Record")return"{}";let Y={Map:"new Map()",Set:"new Set()",WeakMap:"new WeakMap()",WeakSet:"new WeakSet()",WeakRef:"new WeakRef({})",Error:"new Error('example')",TypeError:"new TypeError('example')",RangeError:"new RangeError('example')",SyntaxError:"new SyntaxError('example')",ReferenceError:"new ReferenceError('example')",URIError:"new URIError('example')",EvalError:"new EvalError('example')",Date:"new Date()",RegExp:"/example/",ArrayBuffer:"new ArrayBuffer(0)",SharedArrayBuffer:"new SharedArrayBuffer(0)",DataView:"new DataView(new ArrayBuffer(0))",Float32Array:"new Float32Array(0)",Float64Array:"new Float64Array(0)",Int8Array:"new Int8Array(0)",Int16Array:"new Int16Array(0)",Int32Array:"new Int32Array(0)",Uint8Array:"new Uint8Array(0)",Uint16Array:"new Uint16Array(0)",Uint32Array:"new Uint32Array(0)",Uint8ClampedArray:"new Uint8ClampedArray(0)",BigInt64Array:"new BigInt64Array(0)",BigUint64Array:"new BigUint64Array(0)",URL:"new URL('https://example.com')",URLSearchParams:"new URLSearchParams()",Headers:"new Headers()",FormData:"new FormData()",Blob:"new Blob()",File:"new File([], 'example')",Response:"new Response()",Request:"new Request('https://example.com')",AbortController:"new AbortController()",AbortSignal:"AbortSignal.abort()",ReadableStream:"new ReadableStream()",WritableStream:"new WritableStream()",TransformStream:"new TransformStream()",TextEncoder:"new TextEncoder()",TextDecoder:"new TextDecoder()",Promise:"Promise.resolve(null)"};if(K in Y)return Y[K];if(Q?.typeAliases?.has(K)){let z=Q.visited??new Set;if(z.has(K))return X?.push(`Circular type reference '${K}' - using 'any'`),"any";z.add(K);let G=Q.typeAliases.get(K);return x(G,$,X,{...Q,visited:z})}if(Q?.interfaces?.has(K)){let z=Q.visited??new Set;if(z.has(K))return X?.push(`Circular type reference '${K}' - using 'any'`),"any";z.add(K);let G=Q.interfaces.get(K),J=[];for(let W of G.members)if(j.isPropertySignature(W)&&W.name){let U=W.name.getText(Q.sourceFile),_=x(W.type,$,X,{...Q,visited:z});J.push(`${U}: ${_}`)}return`{ ${J.join(", ")} }`}if(Q?.typeParams?.has(K)){let z=Q.typeParams.get(K);if(z.constraint)return x(z.constraint,$,X,Q);if(z.default)return x(z.default,$,X,Q)}if(h7.has(K))return"{}";if(/^[A-Z]$/.test(K)||["T","K","V","U","TKey","TValue","TItem","TResult"].includes(K))return X?.push(`Generic type parameter '${K}' converted to 'any' - consider specializing`),"any";return X?.push(`Unknown type '${K}' converted to 'any' - may need manual review`),"any"}case j.SyntaxKind.TypeLiteral:{let H=Z,K=[];for(let Y of H.members)if(j.isPropertySignature(Y)&&Y.name){let z=Y.name.getText(),G=x(Y.type,$);if(G==="any")G="null";K.push(`${z}: ${G}`)}return`{ ${K.join(", ")} }`}case j.SyntaxKind.UnionType:{let H=Z,K=(U)=>U.kind===j.SyntaxKind.NullKeyword||j.isLiteralTypeNode(U)&&U.literal.kind===j.SyntaxKind.NullKeyword,Y=(U)=>U.kind===j.SyntaxKind.UndefinedKeyword||j.isLiteralTypeNode(U)&&U.literal.kind===j.SyntaxKind.UndefinedKeyword,z=H.types.filter((U)=>!K(U)&&!Y(U)),G=H.types.some(K),J=H.types.some(Y);if(z.length===0){if(G)return"null";return"undefined"}if(z.length===1&&(G||J)){let U=x(z[0],$,X,Q);if(U==="any")return"any";if(G)return`${U} | null`;if(J)return`${U} | undefined`}let W=H.types.map((U)=>x(U,$,X,Q)).filter((U,_,L)=>L.indexOf(U)===_);if(W.some((U)=>U==="any"))return"any";if(W.length===1)return W[0];if(W.length>0){if(W.some((_)=>/[()]/.test(_)||_.startsWith("new ")))return"any";return W.join(" | ")}return"undefined"}case j.SyntaxKind.LiteralType:{let H=Z;if(j.isStringLiteral(H.literal))return`'${H.literal.text}'`;if(j.isNumericLiteral(H.literal))return H.literal.text;if(H.literal.kind===j.SyntaxKind.TrueKeyword)return"true";if(H.literal.kind===j.SyntaxKind.FalseKeyword)return"false";if(H.literal.kind===j.SyntaxKind.NullKeyword)return"null";return"undefined"}case j.SyntaxKind.ParenthesizedType:return x(Z.type,$);case j.SyntaxKind.FunctionType:{let H=Z,K=[];for(let G of H.parameters){let J=G.name?.getText()||"_";if(J==="this")continue;let W=x(G.type,$,X,Q);if(W==="any")W="null";K.push(`${J}: ${W}`)}let Y=x(H.type,$,X,Q);if(Y==="any")Y="null";let z=[];if(K.length>0)z.push(`params: { ${K.join(", ")} }`);if(Y!=="undefined")z.push(`returns: ${Y}`);return`FunctionPredicate('function', { ${z.join(", ")} })`}case j.SyntaxKind.TupleType:return`[${Z.elements.map((Y)=>{let z=j.isNamedTupleMember(Y)?x(Y.type,$):x(Y,$);return z==="any"?"null":z}).join(", ")}]`;default:return"undefined"}}function a(Z,$){if(!Z)return{kind:"any"};switch(Z.kind){case j.SyntaxKind.StringKeyword:return{kind:"string"};case j.SyntaxKind.NumberKeyword:return{kind:"number"};case j.SyntaxKind.BooleanKeyword:return{kind:"boolean"};case j.SyntaxKind.NullKeyword:return{kind:"null"};case j.SyntaxKind.UndefinedKeyword:case j.SyntaxKind.VoidKeyword:return{kind:"undefined"};case j.SyntaxKind.ArrayType:return{kind:"array",items:a(Z.elementType,$)};case j.SyntaxKind.TypeLiteral:{let X=Z,Q={};for(let H of X.members)if(j.isPropertySignature(H)&&H.name){let K=H.name.getText();Q[K]=a(H.type,$)}return{kind:"object",shape:Q}}case j.SyntaxKind.UnionType:{let X=Z,Q=X.types.filter((K)=>K.kind!==j.SyntaxKind.NullKeyword&&K.kind!==j.SyntaxKind.UndefinedKeyword),H=X.types.some((K)=>K.kind===j.SyntaxKind.NullKeyword);if(Q.length===1&&H)return{...a(Q[0],$),nullable:!0};return{kind:"union",members:X.types.map((K)=>a(K,$))}}case j.SyntaxKind.IntersectionType:{let X=Z,Q={};for(let H of X.types){let K=a(H,$);if(K.kind==="object"&&K.shape)Object.assign(Q,K.shape)}if(Object.keys(Q).length>0)return{kind:"object",shape:Q};return{kind:"any"}}case j.SyntaxKind.TupleType:{let X=Z,Q=[];for(let H of X.elements)if(j.isNamedTupleMember(H))Q.push(a(H.type,$));else Q.push(a(H,$));return{kind:"tuple",elements:Q}}case j.SyntaxKind.TypeReference:{let X=Z,Q=X.typeName.getText();if(Q==="Array"&&X.typeArguments?.length)return{kind:"array",items:a(X.typeArguments[0],$)};if(Q==="Promise"&&X.typeArguments?.length)return a(X.typeArguments[0],$);if((Q==="Generator"||Q==="AsyncGenerator"||Q==="IterableIterator"||Q==="AsyncIterableIterator")&&X.typeArguments?.length)return a(X.typeArguments[0],$);if(X.typeArguments?.length){let H=a(X.typeArguments[0],$);if(Q==="Partial")return H;if(Q==="Required")return H;if(Q==="Readonly")return H;if(Q==="Record"&&X.typeArguments.length>=2)return{kind:"object",shape:{"[key]":a(X.typeArguments[1],$)}};if(Q==="Pick"||Q==="Omit")return H;if(Q==="NonNullable"){if(H.nullable)return{...H,nullable:!1};return H}if(["ReturnType","Parameters","ConstructorParameters"].includes(Q))return{kind:"any"}}if($?.typeAliases?.has(Q)){let H=$.visited??new Set;if(H.has(Q))return{kind:"any"};H.add(Q);let K=$.typeAliases.get(Q);return a(K,{...$,visited:H})}if($?.interfaces?.has(Q)){let H=$.visited??new Set;if(H.has(Q))return{kind:"any"};H.add(Q);let K=$.interfaces.get(Q),Y={};if(K.heritageClauses){for(let z of K.heritageClauses)if(z.token===j.SyntaxKind.ExtendsKeyword)for(let G of z.types){let J=G.expression.getText($.sourceFile);if($.interfaces?.has(J)&&!H.has(J)){let W={kind:j.SyntaxKind.TypeReference,typeName:{getText:()=>J}},U=a(W,{...$,visited:H});if(U.kind==="object"&&U.shape)Object.assign(Y,U.shape)}}}for(let z of K.members)if(j.isPropertySignature(z)&&z.name){let G=z.name.getText($.sourceFile);Y[G]=a(z.type,{...$,visited:H})}return{kind:"object",shape:Y}}if($?.typeParams?.has(Q)){let H=$.typeParams.get(Q);if(H.constraint)return a(H.constraint,$);if(H.default)return a(H.default,$)}if(h7.has(Q))return{kind:"object"};return{kind:"any"}}default:return{kind:"any"}}}function k5(Z,$){if(!Z.typeParameters||Z.typeParameters.length===0)return;let X={};for(let Q of Z.typeParameters){let H=Q.name.getText(),K={};if(Q.constraint){let Y=x(Q.constraint,void 0,$);if(Y.startsWith("{"))try{K.constraint=Y}catch{K.constraint=Y}else K.constraint=Y}if(Q.default){let Y=x(Q.default,void 0,$);K.default=Y}X[H]=K}return Object.keys(X).length>0?X:void 0}function g5(Z,$,X,Q){let H=Z.name.getText($);if(Z.typeParameters&&Z.typeParameters.length>0)return b5(Z,$,X,Q);let K=Q?.find((J)=>J.kind==="example"),Y=Q?.find((J)=>J.kind==="predicate"),z;if(K?.text)z=K.text;else{let J=[];for(let W of Z.members)if(j.isPropertySignature(W)&&W.name){let U=W.name.getText($),_=x(W.type,void 0,X);if(_==="any")_="null";J.push(`${U}: ${_}`)}if(J.length===0&&!Y)return`Type ${H} {}`;z=J.length>0?`{ ${J.join(", ")} }`:"{}"}let G=[`example: ${z}`];if(Y?.text)G.push(Y.text);return`Type ${H} {
360
360
  ${G.join(`
361
361
  `)}
362
- }`}function k5(Z,$,X,Q){let H=Z.name.getText($),K=[];for(let W of Z.typeParameters||[]){let L=W.name.getText($);if(W.default){let _=x(W.default,void 0,X);K.push(`${L} = ${_}`)}else K.push(L)}let Y=Q?.find((W)=>W.kind==="predicate"),z=Q?.find((W)=>W.kind==="declaration"),G;if(Y?.text)G=Y.text;else{let W=(Z.typeParameters||[]).map((U)=>U.name.getText($)),L=["typeof x === 'object'","x !== null"];for(let U of Z.members)if(j.isPropertySignature(U)&&U.name){let q=U.name.getText($),A=q.startsWith("[")&&q.endsWith("]"),B=A?q.slice(1,-1):null;if(A)L.push(`${B} in x`);else L.push(`'${q}' in x`);if(U.type&&j.isTypeReferenceNode(U.type)){let M=U.type.typeName.getText($);if(W.includes(M))if(A)L.push(`${M}(x[${B}])`);else L.push(`${M}(x.${q})`)}}G=`predicate(${["x",...W].join(", ")}) { return ${L.join(" && ")} }`}let J=[`description: '${H}'`,G];if(z?.text)J.push(`declaration ${z.text}`);else{let W=[];for(let L of Z.members)if(j.isPropertySignature(L)&&L.name){let _=L.name.getText($),U=L.questionToken?"?":"",q=L.type?L.type.getText($):"any";W.push(`${_}${U}: ${q}`)}else if(j.isMethodSignature(L)&&L.name){let _=L.getText($).trim();W.push(_.replace(/;$/,""))}if(W.length>0)J.push(`declaration {
362
+ }`}function b5(Z,$,X,Q){let H=Z.name.getText($),K=[];for(let W of Z.typeParameters||[]){let U=W.name.getText($);if(W.default){let _=x(W.default,void 0,X);K.push(`${U} = ${_}`)}else K.push(U)}let Y=Q?.find((W)=>W.kind==="predicate"),z=Q?.find((W)=>W.kind==="declaration"),G;if(Y?.text)G=Y.text;else{let W=(Z.typeParameters||[]).map((L)=>L.name.getText($)),U=["typeof x === 'object'","x !== null"];for(let L of Z.members)if(j.isPropertySignature(L)&&L.name){let q=L.name.getText($),A=q.startsWith("[")&&q.endsWith("]"),B=A?q.slice(1,-1):null;if(A)U.push(`${B} in x`);else U.push(`'${q}' in x`);if(L.type&&j.isTypeReferenceNode(L.type)){let M=L.type.typeName.getText($);if(W.includes(M))if(A)U.push(`${M}(x[${B}])`);else U.push(`${M}(x.${q})`)}}G=`predicate(${["x",...W].join(", ")}) { return ${U.join(" && ")} }`}let J=[`description: '${H}'`,G];if(z?.text)J.push(`declaration ${z.text}`);else{let W=[];for(let U of Z.members)if(j.isPropertySignature(U)&&U.name){let _=U.name.getText($),L=U.questionToken?"?":"",q=U.type?U.type.getText($):"any";W.push(`${_}${L}: ${q}`)}else if(j.isMethodSignature(U)&&U.name){let _=U.getText($).trim();W.push(_.replace(/;$/,""))}if(W.length>0)J.push(`declaration {
363
363
  ${W.join(`
364
364
  `)}
365
365
  }`)}return`Generic ${H}<${K.join(", ")}> {
366
366
  ${J.join(`
367
367
  `)}
368
- }`}function g5(Z,$){if(!j.isUnionTypeNode(Z))return null;let X=[];for(let Q of Z.types)if(j.isLiteralTypeNode(Q))if(j.isStringLiteral(Q.literal))X.push(`'${Q.literal.text}'`);else if(j.isNumericLiteral(Q.literal))X.push(Q.literal.text);else if(Q.literal.kind===j.SyntaxKind.TrueKeyword)X.push("true");else if(Q.literal.kind===j.SyntaxKind.FalseKeyword)X.push("false");else if(Q.literal.kind===j.SyntaxKind.NullKeyword)X.push("null");else return null;else if(Q.kind===j.SyntaxKind.NullKeyword)X.push("null");else if(Q.kind===j.SyntaxKind.UndefinedKeyword)X.push("undefined");else return null;return X.length>0?X:null}function b5(Z,$,X){let Q=Z.name.getText($),H=[],K=0;for(let Y of Z.members){let z=Y.name.getText($);if(Y.initializer)if(j.isStringLiteral(Y.initializer))H.push(` ${z} = '${Y.initializer.text}'`);else if(j.isNumericLiteral(Y.initializer)){let G=parseInt(Y.initializer.text,10);H.push(` ${z} = ${G}`),K=G+1}else if(j.isPrefixUnaryExpression(Y.initializer)&&Y.initializer.operator===j.SyntaxKind.MinusToken){let G=Y.initializer.operand;if(j.isNumericLiteral(G)){let J=-parseInt(G.text,10);H.push(` ${z} = ${J}`),K=J+1}}else H.push(` ${z} = ${Y.initializer.getText($)}`);else H.push(` ${z} = ${K}`),K++}return`Enum ${Q} '${Q}' {
368
+ }`}function v5(Z,$){if(!j.isUnionTypeNode(Z))return null;let X=[];for(let Q of Z.types)if(j.isLiteralTypeNode(Q))if(j.isStringLiteral(Q.literal))X.push(`'${Q.literal.text}'`);else if(j.isNumericLiteral(Q.literal))X.push(Q.literal.text);else if(Q.literal.kind===j.SyntaxKind.TrueKeyword)X.push("true");else if(Q.literal.kind===j.SyntaxKind.FalseKeyword)X.push("false");else if(Q.literal.kind===j.SyntaxKind.NullKeyword)X.push("null");else return null;else if(Q.kind===j.SyntaxKind.NullKeyword)X.push("null");else if(Q.kind===j.SyntaxKind.UndefinedKeyword)X.push("undefined");else return null;return X.length>0?X:null}function f5(Z,$,X){let Q=Z.name.getText($),H=[],K=0;for(let Y of Z.members){let z=Y.name.getText($);if(Y.initializer)if(j.isStringLiteral(Y.initializer))H.push(` ${z} = '${Y.initializer.text}'`);else if(j.isNumericLiteral(Y.initializer)){let G=parseInt(Y.initializer.text,10);H.push(` ${z} = ${G}`),K=G+1}else if(j.isPrefixUnaryExpression(Y.initializer)&&Y.initializer.operator===j.SyntaxKind.MinusToken){let G=Y.initializer.operand;if(j.isNumericLiteral(G)){let J=-parseInt(G.text,10);H.push(` ${z} = ${J}`),K=J+1}}else H.push(` ${z} = ${Y.initializer.getText($)}`);else H.push(` ${z} = ${K}`),K++}return`Enum ${Q} '${Q}' {
369
369
  ${H.join(`
370
370
  `)}
371
- }`}function v5(Z,$,X,Q){let H=Z.name.getText($);if(Z.typeParameters&&Z.typeParameters.length>0){if(Z.type.kind===j.SyntaxKind.FunctionType)return f5(Z,$,X);return y5(Z,$,X,Q)}let K=g5(Z.type,$);if(K)return`Union ${H} '${H}' ${K.join(" | ")}`;if(Z.type.kind===j.SyntaxKind.FunctionType){let z=Z.type,G=[];for(let L of z.parameters){let _=L.name?.getText($)||"_";if(_==="this")continue;let U=x(L.type,void 0,X);if(U==="any")U="null";G.push(`${_}: ${U}`)}let J=x(z.type,void 0,X);if(J==="any")J="null";let W=[];if(G.length>0)W.push(`params: { ${G.join(", ")} }`);if(J!=="undefined")W.push(`returns: ${J}`);return`FunctionPredicate ${H} {
371
+ }`}function y5(Z,$,X,Q){let H=Z.name.getText($);if(Z.typeParameters&&Z.typeParameters.length>0){if(Z.type.kind===j.SyntaxKind.FunctionType)return h5(Z,$,X);return x5(Z,$,X,Q)}let K=v5(Z.type,$);if(K)return`Union ${H} '${H}' ${K.join(" | ")}`;if(Z.type.kind===j.SyntaxKind.FunctionType){let z=Z.type,G=[];for(let U of z.parameters){let _=U.name?.getText($)||"_";if(_==="this")continue;let L=x(U.type,void 0,X);if(L==="any")L="null";G.push(`${_}: ${L}`)}let J=x(z.type,void 0,X);if(J==="any")J="null";let W=[];if(G.length>0)W.push(`params: { ${G.join(", ")} }`);if(J!=="undefined")W.push(`returns: ${J}`);return`FunctionPredicate ${H} {
372
372
  ${W.join(`
373
373
  `)}
374
- }`}let Y=x(Z.type,void 0,X);if(Y==="any"||Y==="undefined")return`Type ${H} {}`;if(Y==="''"||Y==="0"||Y==="true"||Y==="null")return`Type ${H} ${Y}`;return`Type ${H} {
374
+ }`}let Y=x(Z.type,void 0,X);if(Y==="any"||Y==="undefined"){let z=Z.type.getText($).trim();return`Type ${H} {
375
+ // TS: ${z}
376
+ }`}if(Y==="''"||Y==="0"||Y==="true"||Y==="null")return`Type ${H} ${Y}`;return`Type ${H} {
375
377
  example: ${Y}
376
- }`}function f5(Z,$,X){let Q=Z.name.getText($),H=Z.type,K=new Set,Y=[];for(let L of Z.typeParameters){let _=L.name.getText($);if(K.add(_),L.default){let U=x(L.default,void 0,X);Y.push(`${_} = ${U}`)}else Y.push(_)}let z=[];for(let L of H.parameters){let _=L.name?.getText($)||"_";if(_==="this")continue;let U=L.type?.getText($)||"any";if(K.has(U))z.push(`${_}: ${U}`);else{let q=x(L.type,void 0,X);if(q==="any")q="null";z.push(`${_}: ${q}`)}}let G=H.type?.getText($)||"void",J;if(G!=="void")if(K.has(G))J=G;else{if(J=x(H.type,void 0,X),J==="any")J="null";if(J==="undefined")J=void 0}let W=[];if(z.length>0)W.push(`params: { ${z.join(", ")} }`);if(J!==void 0)W.push(`returns: ${J}`);return`FunctionPredicate ${Q}<${Y.join(", ")}> {
378
+ }`}function h5(Z,$,X){let Q=Z.name.getText($),H=Z.type,K=new Set,Y=[];for(let U of Z.typeParameters){let _=U.name.getText($);if(K.add(_),U.default){let L=x(U.default,void 0,X);Y.push(`${_} = ${L}`)}else Y.push(_)}let z=[];for(let U of H.parameters){let _=U.name?.getText($)||"_";if(_==="this")continue;let L=U.type?.getText($)||"any";if(K.has(L))z.push(`${_}: ${L}`);else{let q=x(U.type,void 0,X);if(q==="any")q="null";z.push(`${_}: ${q}`)}}let G=H.type?.getText($)||"void",J;if(G!=="void")if(K.has(G))J=G;else{if(J=x(H.type,void 0,X),J==="any")J="null";if(J==="undefined")J=void 0}let W=[];if(z.length>0)W.push(`params: { ${z.join(", ")} }`);if(J!==void 0)W.push(`returns: ${J}`);return`FunctionPredicate ${Q}<${Y.join(", ")}> {
377
379
  ${W.join(`
378
380
  `)}
379
- }`}function y5(Z,$,X,Q){let H=Z.name.getText($),K=[];for(let L of Z.typeParameters||[]){let _=L.name.getText($);if(L.default){let U=x(L.default,void 0,X);K.push(`${_} = ${U}`)}else K.push(_)}let Y=(Z.typeParameters||[]).map((L)=>L.name.getText($)),z=Q?.find((L)=>L.kind==="predicate"),G=Q?.find((L)=>L.kind==="declaration"),J;if(z?.text)J=z.text;else J=`predicate(${["x",...Y].join(", ")}) { return true }`;let W=[`description: '${H}'`,J];if(G?.text)W.push(`declaration ${G.text}`);else{let L=Z.type;if(L&&j.isTypeLiteralNode(L)){let _=[];for(let U of L.members)if(j.isPropertySignature(U)&&U.name){let q=U.name.getText($),A=U.questionToken?"?":"",B=U.type?U.type.getText($):"any";_.push(`${q}${A}: ${B}`)}else if(j.isMethodSignature(U)&&U.name)_.push(U.getText($).trim().replace(/;$/,""));if(_.length>0)W.push(`declaration {
381
+ }`}function x5(Z,$,X,Q){let H=Z.name.getText($),K=[];for(let U of Z.typeParameters||[]){let _=U.name.getText($);if(U.default){let L=x(U.default,void 0,X);K.push(`${_} = ${L}`)}else K.push(_)}let Y=(Z.typeParameters||[]).map((U)=>U.name.getText($)),z=Q?.find((U)=>U.kind==="predicate"),G=Q?.find((U)=>U.kind==="declaration"),J;if(z?.text)J=z.text;else J=`predicate(${["x",...Y].join(", ")}) { return true }`;let W=[`description: '${H}'`,J];if(G?.text)W.push(`declaration ${G.text}`);else{let U=Z.type;if(U&&j.isTypeLiteralNode(U)){let _=[];for(let L of U.members)if(j.isPropertySignature(L)&&L.name){let q=L.name.getText($),A=L.questionToken?"?":"",B=L.type?L.type.getText($):"any";_.push(`${q}${A}: ${B}`)}else if(j.isMethodSignature(L)&&L.name)_.push(L.getText($).trim().replace(/;$/,""));if(_.length>0)W.push(`declaration {
380
382
  ${_.join(`
381
383
  `)}
382
- }`)}else if(L){let _=L.getText($).trim();W.push(`declaration {
384
+ }`)}else if(U){let _=U.getText($).trim();W.push(`declaration {
383
385
  // TS: ${_}
384
386
  }`)}}return`Generic ${H}<${K.join(", ")}> {
385
387
  ${W.join(`
386
388
  `)}
387
- }`}function v7(Z,$,X,Q,H,K){let Y;if(Z.typeParameters&&Z.typeParameters.length>0){Y=new Map;for(let O of Z.typeParameters)Y.set(O.name.getText($),{constraint:O.constraint,default:O.default})}let z=Y||K?{...K,typeParams:Y??K?.typeParams}:K,G=[],J=e1(Z.parameters,$,Q,G,z),{line:W}=$.getLineAndCharacterOfPosition(Z.getStart($)),L=H?`/* line ${W+1} */
388
- `:"",_=X||(j.isFunctionDeclaration(Z)&&Z.name?Z.name.getText($):""),U=Z.type?x(Z.type,void 0,Q,z):"",q=U&&U!=="undefined"&&U!=="any"&&!U.startsWith("new ")?` -! ${U}`:"";if(Z.type&&(U==="any"||U==="undefined")){let O=Z.type.getText($);if(O!=="any"&&O!=="unknown"&&O!=="void")G.push(`return: ${O}`)}let A="";if(Z.body){let O=j.isBlock(Z.body)?Z.body.getText($):`{ return ${Z.body.getText($)} }`;A=j.transpileModule(O,{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}else A="{ }";let B=Z.modifiers?.some((O)=>O.kind===j.SyntaxKind.ExportKeyword),M=Z.modifiers?.some((O)=>O.kind===j.SyntaxKind.AsyncKeyword),F=!!Z.asteriskToken,R=B?"export ":"",w=M?"async ":"",C=F?"function* ":"function ",P=G.length>0?`/* TODO: TS types degraded — ${G.join(", ")} */
389
- `:"";return`${L}${P}${R}${w}${C}${_}(${J.join(", ")})${q} ${A}`}function h5(Z,$,X,Q){let H=$.name?.getText(X)||"",K=`_${H}_impl`,Y=[],z=e1($.parameters,X,Q),G="{ }";if($.body){let U=$.body.getText(X);G=j.transpileModule(U,{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}let J=$.modifiers?.some((U)=>U.kind===j.SyntaxKind.AsyncKeyword),W=!!$.asteriskToken,L=J?"async ":"",_=W?"function* ":"function ";Y.push(`${L}${_}${K}(${z.join(", ")}) ${G}`);for(let U of Z){let q=e1(U.parameters,X,Q),A=U.parameters.map((C)=>C.name.getText(X)),B=U.type?x(U.type,void 0,Q):"",M=B&&B!=="undefined"&&B!=="any"?` -! ${B}`:"",{line:F}=X.getLineAndCharacterOfPosition(U.getStart(X)),R=`/* line ${F+1} */
390
- `,w=W?"yield* ":"return ";Y.push(`${R}${L}${_}${H}(${q.join(", ")})${M} { ${w}${K}(${A.join(", ")}) }`)}return Y}function x5(Z,$,X,Q,H=!1){let K=Q;if(Z.typeParameters&&Z.typeParameters.length>0){let A=new Map;for(let B of Z.typeParameters)A.set(B.name.getText($),{constraint:B.constraint,default:B.default});K={...Q,typeParams:A}}let Y=Z.name?.getText($)||"Anonymous",G=Z.heritageClauses?.find((A)=>A.token===j.SyntaxKind.ExtendsKeyword)?.types[0]?.expression?.getText($),J=new Map;if(H){for(let A of Z.members)if(j.isPropertyDeclaration(A)&&A.name){let B=A.name.getText($);if(A.modifiers?.some((F)=>F.kind===j.SyntaxKind.PrivateKeyword)&&!B.startsWith("#"))J.set(B,`#${B}`)}}let W=(A)=>{let B=A;for(let[M,F]of J)B=B.replace(new RegExp(`(\\b\\w+)\\.${M}\\b`,"g"),`$1.${F}`);return B},L=[];for(let A of Z.members){if(j.isConstructorDeclaration(A)){let B=e1(A.parameters,$,X),M="{ }";if(A.body){let F=j.transpileModule(A.body.getText($),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});M=W(F.outputText.trim())}L.push(` constructor(${B.join(", ")}) ${M}`)}if(j.isMethodDeclaration(A)&&A.name){let B=A.name.getText($),M=A.modifiers?.some((N)=>N.kind===j.SyntaxKind.StaticKeyword),F=A.modifiers?.some((N)=>N.kind===j.SyntaxKind.AsyncKeyword),R=e1(A.parameters,$,X,void 0,K),w=A.type?x(A.type,void 0,X,K):"",C=w&&w!=="undefined"&&w!=="any"?` -! ${w}`:"",P="{ }";if(A.body){let N=j.transpileModule(A.body.getText($),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});P=W(N.outputText.trim())}let O=!!A.asteriskToken,k=M?"static ":"",V=F?"async ":"",T=O?"*":"";L.push(` ${k}${V}${T}${B}(${R.join(", ")})${C} ${P}`)}if(j.isGetAccessorDeclaration(A)&&A.name){let B=A.name.getText($),F=A.modifiers?.some((P)=>P.kind===j.SyntaxKind.StaticKeyword)?"static ":"",R=A.type?x(A.type,void 0,X,K):"",w=R&&R!=="undefined"&&R!=="any"&&!R.startsWith("new ")?` -> ${R}`:"",C="{ }";if(A.body){let P=j.transpileModule(A.body.getText($),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});C=W(P.outputText.trim())}L.push(` ${F}get ${B}()${w} ${C}`)}if(j.isSetAccessorDeclaration(A)&&A.name){let B=A.name.getText($),F=A.modifiers?.some((C)=>C.kind===j.SyntaxKind.StaticKeyword)?"static ":"",R=e1(A.parameters,$,X),w="{ }";if(A.body){let C=j.transpileModule(A.body.getText($),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});w=W(C.outputText.trim())}L.push(` ${F}set ${B}(${R.join(", ")}) ${w}`)}if(j.isPropertyDeclaration(A)&&A.name){let B=A.name.getText($),F=A.modifiers?.some((w)=>w.kind===j.SyntaxKind.StaticKeyword)?"static ":"",R=J.get(B)||B;if(A.initializer){let w=A.initializer.getText($),C=w.trimStart().startsWith("{")?`(${w})`:w,O=j.transpileModule(C,{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();if(C!==w)O=O.replace(/^\(/,"").replace(/\);?\s*$/,"");L.push(` ${F}${R} = ${O}`)}else L.push(` ${F}${R}`)}}let U=Z.modifiers?.some((A)=>A.kind===j.SyntaxKind.ExportKeyword)?"export ":"",q=G?` extends ${G}`:"";return`${U}class ${Y}${q} {
391
- ${L.join(`
389
+ }`}function y7(Z,$,X,Q,H,K){let Y;if(Z.typeParameters&&Z.typeParameters.length>0){Y=new Map;for(let O of Z.typeParameters)Y.set(O.name.getText($),{constraint:O.constraint,default:O.default})}let z=Y||K?{...K,typeParams:Y??K?.typeParams}:K,G=[],J=e1(Z.parameters,$,Q,G,z),{line:W}=$.getLineAndCharacterOfPosition(Z.getStart($)),U=H?`/* line ${W+1} */
390
+ `:"",_=X||(j.isFunctionDeclaration(Z)&&Z.name?Z.name.getText($):""),L=Z.type?x(Z.type,void 0,Q,z):"",q=L&&L!=="undefined"&&L!=="any"&&!L.startsWith("new ")?` -! ${L}`:"";if(Z.type&&(L==="any"||L==="undefined")){let O=Z.type.getText($);if(O!=="any"&&O!=="unknown"&&O!=="void")G.push(`return: ${O}`)}let A="";if(Z.body){let O=j.isBlock(Z.body)?Z.body.getText($):`{ return ${Z.body.getText($)} }`;A=j.transpileModule(O,{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}else A="{ }";let B=Z.modifiers?.some((O)=>O.kind===j.SyntaxKind.ExportKeyword),M=Z.modifiers?.some((O)=>O.kind===j.SyntaxKind.AsyncKeyword),F=!!Z.asteriskToken,R=B?"export ":"",w=M?"async ":"",C=F?"function* ":"function ",P=G.length>0?`/* TODO: TS types degraded — ${G.join(", ")} */
391
+ `:"";return`${U}${P}${R}${w}${C}${_}(${J.join(", ")})${q} ${A}`}function u5(Z,$,X,Q){let H=$.name?.getText(X)||"",K=`_${H}_impl`,Y=[],z=e1($.parameters,X,Q),G="{ }";if($.body){let L=$.body.getText(X);G=j.transpileModule(L,{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}let J=$.modifiers?.some((L)=>L.kind===j.SyntaxKind.AsyncKeyword),W=!!$.asteriskToken,U=J?"async ":"",_=W?"function* ":"function ";Y.push(`${U}${_}${K}(${z.join(", ")}) ${G}`);for(let L of Z){let q=e1(L.parameters,X,Q),A=L.parameters.map((C)=>C.name.getText(X)),B=L.type?x(L.type,void 0,Q):"",M=B&&B!=="undefined"&&B!=="any"?` -! ${B}`:"",{line:F}=X.getLineAndCharacterOfPosition(L.getStart(X)),R=`/* line ${F+1} */
392
+ `,w=W?"yield* ":"return ";Y.push(`${R}${U}${_}${H}(${q.join(", ")})${M} { ${w}${K}(${A.join(", ")}) }`)}return Y}function d5(Z,$,X,Q,H=!1){let K=Q;if(Z.typeParameters&&Z.typeParameters.length>0){let A=new Map;for(let B of Z.typeParameters)A.set(B.name.getText($),{constraint:B.constraint,default:B.default});K={...Q,typeParams:A}}let Y=Z.name?.getText($)||"Anonymous",G=Z.heritageClauses?.find((A)=>A.token===j.SyntaxKind.ExtendsKeyword)?.types[0]?.expression?.getText($),J=new Map;if(H){for(let A of Z.members)if(j.isPropertyDeclaration(A)&&A.name){let B=A.name.getText($);if(A.modifiers?.some((F)=>F.kind===j.SyntaxKind.PrivateKeyword)&&!B.startsWith("#"))J.set(B,`#${B}`)}}let W=(A)=>{let B=A;for(let[M,F]of J)B=B.replace(new RegExp(`(\\b\\w+)\\.${M}\\b`,"g"),`$1.${F}`);return B},U=[];for(let A of Z.members){if(j.isConstructorDeclaration(A)){let B=e1(A.parameters,$,X),M="{ }";if(A.body){let F=j.transpileModule(A.body.getText($),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});M=W(F.outputText.trim())}U.push(` constructor(${B.join(", ")}) ${M}`)}if(j.isMethodDeclaration(A)&&A.name){let B=A.name.getText($),M=A.modifiers?.some((N)=>N.kind===j.SyntaxKind.StaticKeyword),F=A.modifiers?.some((N)=>N.kind===j.SyntaxKind.AsyncKeyword),R=e1(A.parameters,$,X,void 0,K),w=A.type?x(A.type,void 0,X,K):"",C=w&&w!=="undefined"&&w!=="any"?` -! ${w}`:"",P="{ }";if(A.body){let N=j.transpileModule(A.body.getText($),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});P=W(N.outputText.trim())}let O=!!A.asteriskToken,k=M?"static ":"",V=F?"async ":"",T=O?"*":"";U.push(` ${k}${V}${T}${B}(${R.join(", ")})${C} ${P}`)}if(j.isGetAccessorDeclaration(A)&&A.name){let B=A.name.getText($),F=A.modifiers?.some((P)=>P.kind===j.SyntaxKind.StaticKeyword)?"static ":"",R=A.type?x(A.type,void 0,X,K):"",w=R&&R!=="undefined"&&R!=="any"&&!R.startsWith("new ")?` -> ${R}`:"",C="{ }";if(A.body){let P=j.transpileModule(A.body.getText($),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});C=W(P.outputText.trim())}U.push(` ${F}get ${B}()${w} ${C}`)}if(j.isSetAccessorDeclaration(A)&&A.name){let B=A.name.getText($),F=A.modifiers?.some((C)=>C.kind===j.SyntaxKind.StaticKeyword)?"static ":"",R=e1(A.parameters,$,X),w="{ }";if(A.body){let C=j.transpileModule(A.body.getText($),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});w=W(C.outputText.trim())}U.push(` ${F}set ${B}(${R.join(", ")}) ${w}`)}if(j.isPropertyDeclaration(A)&&A.name){let B=A.name.getText($),F=A.modifiers?.some((w)=>w.kind===j.SyntaxKind.StaticKeyword)?"static ":"",R=J.get(B)||B;if(A.initializer){let w=A.initializer.getText($),C=w.trimStart().startsWith("{")?`(${w})`:w,O=j.transpileModule(C,{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();if(C!==w)O=O.replace(/^\(/,"").replace(/\);?\s*$/,"");U.push(` ${F}${R} = ${O}`)}else U.push(` ${F}${R}`)}}let L=Z.modifiers?.some((A)=>A.kind===j.SyntaxKind.ExportKeyword)?"export ":"",q=G?` extends ${G}`:"";return`${L}class ${Y}${q} {
393
+ ${U.join(`
392
394
  `)}
393
- }`}function e1(Z,$,X,Q,H){let K=[];for(let Y of Z){let z=Y.name.getText($);if(z==="this")continue;let G=!!Y.dotDotDotToken,J=!!Y.questionToken||!!Y.initializer,W=x(Y.type,void 0,X,H);if(G)if(W==="any"||W==="undefined")K.push(`...${z}: [null]`);else K.push(`...${z}: ${W}`);else if(Y.initializer){let L=Y.initializer.getText($);K.push(`${z} = ${L}`)}else if(W==="any"||W==="undefined"){if(K.push(z),Q&&Y.type){let L=Y.type.getText($);if(L!=="any"&&L!=="unknown")Q.push(`${z}: ${L}`)}}else if(J)K.push(`${z}: ${W} | undefined`);else K.push(`${z}: ${W}`)}return K}function W4(Z,$,X,Q){let H=Q;if(Z.typeParameters&&Z.typeParameters.length>0){let J=new Map;for(let W of Z.typeParameters)J.set(W.name.getText($),{constraint:W.constraint,default:W.default});H={...Q,typeParams:J}}let K=j.isFunctionDeclaration(Z)&&Z.name?Z.name.getText($):"anonymous",Y={};for(let J of Z.parameters){let W=J.name.getText($),L=!!J.questionToken||!!J.initializer,_=void 0;if(J.initializer){let U=J.initializer.getText($);try{_=JSON.parse(U)}catch{_=U}}Y[W]={type:a(J.type,H),required:!L,default:_}}let z={name:K,params:Y,returns:Z.type?a(Z.type,H):void 0},G=S5(Z,X);if(G)z.typeParams=G;return z}function u5(Z,$,X,Q){let H=Q;if(Z.typeParameters&&Z.typeParameters.length>0){let W=new Map;for(let L of Z.typeParameters)W.set(L.name.getText($),{constraint:L.constraint,default:L.default});H={...Q,typeParams:W}}let K=Z.name?.getText($)||"anonymous",Y={},z={},G;for(let W of Z.members){if(j.isConstructorDeclaration(W)){let L={};for(let _ of W.parameters){let U=_.name.getText($),q=!!_.questionToken||!!_.initializer,A=void 0;if(_.initializer){let B=_.initializer.getText($);try{A=JSON.parse(B)}catch{A=B}}L[U]={type:a(_.type,H),required:!q,default:A}}G={params:L}}if(j.isMethodDeclaration(W)&&W.name){let L=W.name.getText($),_=W.modifiers?.some((A)=>A.kind===j.SyntaxKind.StaticKeyword),U={};for(let A of W.parameters){let B=A.name.getText($),M=!!A.questionToken||!!A.initializer,F=void 0;if(A.initializer){let R=A.initializer.getText($);try{F=JSON.parse(R)}catch{F=R}}U[B]={type:a(A.type,H),required:!M,default:F}}let q={name:L,params:U,returns:W.type?a(W.type,H):void 0};if(_)z[L]=q;else Y[L]=q}}let J={name:K,methods:Y,staticMethods:z,constructor:G};if(Z.typeParameters&&Z.typeParameters.length>0){let W={};for(let L of Z.typeParameters){let _=L.name.getText($),U={};if(L.constraint)U.constraint=x(L.constraint,void 0,X,Q);if(L.default)U.default=x(L.default,void 0,X,Q);W[_]=U}J.typeParams=W}return J}var d5=new Set(["TjsStrict","TjsEquals","TjsClass","TjsDate","TjsNoeval","TjsNoVar","TjsStandard","TjsSafeEval"]);function l5(Z){let $=[],X=/\/\*\s*@tjs\s+((?:Tjs\w+\s*)+)\*\//g,Q;while((Q=X.exec(Z))!==null){let H=Q[1].trim().split(/\s+/);for(let K of H)if(d5.has(K)&&!$.includes(K))$.push(K)}return $}function m5(Z){let $=[],X=/\/\*\s*@tjs-skip\s*\*\//g,Q;while((Q=X.exec(Z))!==null)$.push({index:Q.index,kind:"skip"});let H=/\/\*\s*@tjs\s+predicate(\([^)]*\)\s*\{[\s\S]*?\})\s*\*\//g;while((Q=H.exec(Z))!==null)$.push({index:Q.index,kind:"predicate",text:`predicate${Q[1].trim()}`});let K=/\/\*\s*@tjs\s+example:\s*([\s\S]*?)\s*\*\//g;while((Q=K.exec(Z))!==null)$.push({index:Q.index,kind:"example",text:Q[1].trim()});let Y=/\/\*\s*@tjs\s+declaration\s*(\{[\s\S]*?\})\s*\*\//g;while((Q=Y.exec(Z))!==null)$.push({index:Q.index,kind:"declaration",text:Q[1].trim()});return $.sort((z,G)=>z.index-G.index)}function i5(Z,$){let X=new Map;if(Z.length===0)return X;let Q=$.statements;for(let H=0;H<Q.length;H++){let K=Q[H],Y;if(j.isInterfaceDeclaration(K))Y=K.name.getText($);else if(j.isTypeAliasDeclaration(K))Y=K.name.getText($);else if(j.isEnumDeclaration(K))Y=K.name.getText($);if(!Y)continue;let z=K.getStart($),G=H>0?Q[H-1].getEnd():0,J=Z.filter((W)=>W.index>=G&&W.index<z);if(J.length>0)X.set(Y,J)}return X}function p5(Z){let $=[],X=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{[\s\S]*?\}\s*\*\/|\/\*test\s*\{[\s\S]*?\}\s*\*\//g,Q;while((Q=X.exec(Z))!==null)$.push(Q[0]);return $}function n5(Z){let $=[],X=/\/\*#[\s\S]*?\*\//g,Q=0,H=null,K=[];for(let z=0;z<Z.length;z++){let G=Z[z],J=z>0?Z[z-1]:"";if(!H&&(G==='"'||G==="'"||G==="`"))H=G;else if(H&&G===H&&J!=="\\")H=null;if(!H){if(G==="{")Q++;if(G==="}")Q--}K[z]=Q}let Y;while((Y=X.exec(Z))!==null)if(K[Y.index]===0)$.push({content:Y[0],index:Y.index});return $}function c5(Z,$={}){let{emitTJS:X=!1,filename:Q="input.ts"}=$,H=[],K=p5(Z),Y=X?n5(Z):[],z=X?m5(Z):[],G=l5(Z),J=G.includes("TjsClass")||G.includes("TjsStrict"),W=j.createSourceFile(Q,Z,j.ScriptTarget.Latest,!0),L=X?i5(z,W):new Map,_=[],U=new Set,q={},A={},B=new Set,M=(V)=>{for(let T=0;T<Y.length;T++){let N=Y[T];if(!B.has(T)&&N.index<V)_.push(N.content),B.add(T)}},F=new Map,R=new Map;function w(V){if(j.isTypeAliasDeclaration(V))F.set(V.name.getText(W),V.type);if(j.isInterfaceDeclaration(V)){let T=V.name.getText(W),N=R.get(T);if(N){let g=j.factory.updateInterfaceDeclaration(N,N.modifiers,N.name,N.typeParameters,N.heritageClauses,[...N.members,...V.members]);R.set(T,g)}else R.set(T,V)}j.forEachChild(V,w)}w(W);let C={typeAliases:F,interfaces:R,sourceFile:W,warnings:H},P=new Map;for(let V of W.statements)if(j.isFunctionDeclaration(V)&&V.name){let T=V.name.getText(W);if(!P.has(T))P.set(T,{signatures:[],implementation:null});let N=P.get(T);if(V.body)N.implementation=V;else N.signatures.push(V)}for(let[V,T]of P)if(T.signatures.length===0||!T.implementation)P.delete(V);for(let V of W.statements){let T=!1;if(X)M(V.getStart(W));if(j.isFunctionDeclaration(V)&&V.name){let N=V.name.getText(W);T=!0;let g=P.get(N);if(g)if(!V.body);else if(X)_.push(...h5(g.signatures,V,W,H));else{let b=[];for(let n of g.signatures)b.push(W4(n,W,H,C));let f=W4(V,W,H,C);f.overloads=b,q[N]=f}else if(X)_.push(v7(V,W,void 0,H,!0,C));else q[N]=W4(V,W,H,C)}if(j.isVariableStatement(V)){let N=!1,g=V.modifiers?.some((b)=>b.kind===j.SyntaxKind.ExportKeyword);for(let b of V.declarationList.declarations)if(j.isIdentifier(b.name)&&b.initializer&&(j.isArrowFunction(b.initializer)||j.isFunctionExpression(b.initializer))){N=!0;let f=b.name.getText(W),n=b.initializer;if(X){let m=v7(n,W,f,H,!0,C);if(g&&!m.includes("export ")){let X1=m.search(/^(async\s+)?function[\s*]/m);if(X1>0)m=m.slice(0,X1)+"export "+m.slice(X1);else m="export "+m}_.push(m)}else{let m=W4(n,W,H,C);m.name=f,q[f]=m}}if(!N&&X){let b=j.transpileModule(V.getText(W),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});_.push(b.outputText.trim())}T=!0}if(j.isInterfaceDeclaration(V)){if(T=!0,X){let N=V.name.getText(W),g=L.get(N);if(!U.has(N))if(U.add(N),g?.some((b)=>b.kind==="skip"));else{let b=R.get(N)||V,f=T5(b,W,H,g);if(f){let n=V.modifiers?.some((m)=>m.kind===j.SyntaxKind.ExportKeyword);_.push(n?f.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):f)}}}}if(j.isTypeAliasDeclaration(V)){if(T=!0,X){let N=V.name.getText(W),g=L.get(N);if(!U.has(N))if(U.add(N),g?.some((b)=>b.kind==="skip"));else{let b=v5(V,W,H,g);if(b){let f=V.modifiers?.some((n)=>n.kind===j.SyntaxKind.ExportKeyword);_.push(f?b.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):b)}}}}if(j.isEnumDeclaration(V)){if(T=!0,X){let N=V.name.getText(W),g=L.get(N);if(!U.has(N))if(U.add(N),g?.some((b)=>b.kind==="skip"));else{let b=b5(V,W,H);if(b)_.push(b)}}}if(j.isClassDeclaration(V)&&V.name){let N=V.name.getText(W);if(T=!0,X){let g=x5(V,W,H,void 0,J);_.push(g)}else A[N]=u5(V,W,H,C)}if(j.isImportDeclaration(V)){if(T=!0,X){if(!(V.importClause?.isTypeOnly||V.importClause?.namedBindings&&j.isNamedImports(V.importClause.namedBindings)&&V.importClause.namedBindings.elements.every((g)=>g.isTypeOnly)))if(V.importClause?.namedBindings&&j.isNamedImports(V.importClause.namedBindings)){let g=V.importClause.namedBindings.elements.filter((b)=>!b.isTypeOnly).map((b)=>{let f=b.name.getText(W),n=b.propertyName?.getText(W);return n?`${n} as ${f}`:f});if(g.length>0){let b=V.moduleSpecifier.text;_.push(`import { ${g.join(", ")} } from '${b}'`)}}else{let b=V.getText(W).replace(/\btype\s+/g,"").replace(/\s*:\s*\w+/g,"");_.push(b)}}}if(j.isExportDeclaration(V)||j.isExportAssignment(V)){if(T=!0,X){let g=j.transpileModule(V.getText(W),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();if(g)_.push(g)}}if(!T&&X){let g=j.transpileModule(V.getText(W),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();if(g)_.push(g)}}if(X){M(1/0);let V=Q||"unknown",N=`${G.length>0?G.join(`
395
+ }`}function e1(Z,$,X,Q,H){let K=[];for(let Y of Z){let z=Y.name.getText($);if(z==="this")continue;let G=!!Y.dotDotDotToken,J=!!Y.questionToken||!!Y.initializer,W=x(Y.type,void 0,X,H);if(G)if(W==="any"||W==="undefined")K.push(`...${z}: [null]`);else K.push(`...${z}: ${W}`);else if(Y.initializer){let U=Y.initializer.getText($);K.push(`${z} = ${U}`)}else if(W==="any"||W==="undefined"){if(K.push(z),Q&&Y.type){let U=Y.type.getText($);if(U!=="any"&&U!=="unknown")Q.push(`${z}: ${U}`)}}else if(J)K.push(`${z}: ${W} | undefined`);else K.push(`${z}: ${W}`)}return K}function W4(Z,$,X,Q){let H=Q;if(Z.typeParameters&&Z.typeParameters.length>0){let J=new Map;for(let W of Z.typeParameters)J.set(W.name.getText($),{constraint:W.constraint,default:W.default});H={...Q,typeParams:J}}let K=j.isFunctionDeclaration(Z)&&Z.name?Z.name.getText($):"anonymous",Y={};for(let J of Z.parameters){let W=J.name.getText($),U=!!J.questionToken||!!J.initializer,_=void 0;if(J.initializer){let L=J.initializer.getText($);try{_=JSON.parse(L)}catch{_=L}}Y[W]={type:a(J.type,H),required:!U,default:_}}let z={name:K,params:Y,returns:Z.type?a(Z.type,H):void 0},G=k5(Z,X);if(G)z.typeParams=G;return z}function l5(Z,$,X,Q){let H=Q;if(Z.typeParameters&&Z.typeParameters.length>0){let W=new Map;for(let U of Z.typeParameters)W.set(U.name.getText($),{constraint:U.constraint,default:U.default});H={...Q,typeParams:W}}let K=Z.name?.getText($)||"anonymous",Y={},z={},G;for(let W of Z.members){if(j.isConstructorDeclaration(W)){let U={};for(let _ of W.parameters){let L=_.name.getText($),q=!!_.questionToken||!!_.initializer,A=void 0;if(_.initializer){let B=_.initializer.getText($);try{A=JSON.parse(B)}catch{A=B}}U[L]={type:a(_.type,H),required:!q,default:A}}G={params:U}}if(j.isMethodDeclaration(W)&&W.name){let U=W.name.getText($),_=W.modifiers?.some((A)=>A.kind===j.SyntaxKind.StaticKeyword),L={};for(let A of W.parameters){let B=A.name.getText($),M=!!A.questionToken||!!A.initializer,F=void 0;if(A.initializer){let R=A.initializer.getText($);try{F=JSON.parse(R)}catch{F=R}}L[B]={type:a(A.type,H),required:!M,default:F}}let q={name:U,params:L,returns:W.type?a(W.type,H):void 0};if(_)z[U]=q;else Y[U]=q}}let J={name:K,methods:Y,staticMethods:z,constructor:G};if(Z.typeParameters&&Z.typeParameters.length>0){let W={};for(let U of Z.typeParameters){let _=U.name.getText($),L={};if(U.constraint)L.constraint=x(U.constraint,void 0,X,Q);if(U.default)L.default=x(U.default,void 0,X,Q);W[_]=L}J.typeParams=W}return J}var m5=new Set(["TjsStrict","TjsEquals","TjsClass","TjsDate","TjsNoeval","TjsNoVar","TjsStandard","TjsSafeEval"]);function i5(Z){let $=[],X=/\/\*\s*@tjs\s+((?:Tjs\w+\s*)+)\*\//g,Q;while((Q=X.exec(Z))!==null){let H=Q[1].trim().split(/\s+/);for(let K of H)if(m5.has(K)&&!$.includes(K))$.push(K)}return $}function p5(Z){let $=[],X=/\/\*\s*@tjs-skip\s*\*\//g,Q;while((Q=X.exec(Z))!==null)$.push({index:Q.index,kind:"skip"});let H=/\/\*\s*@tjs\s+predicate(\([^)]*\)\s*\{[\s\S]*?\})\s*\*\//g;while((Q=H.exec(Z))!==null)$.push({index:Q.index,kind:"predicate",text:`predicate${Q[1].trim()}`});let K=/\/\*\s*@tjs\s+example:\s*([\s\S]*?)\s*\*\//g;while((Q=K.exec(Z))!==null)$.push({index:Q.index,kind:"example",text:Q[1].trim()});let Y=/\/\*\s*@tjs\s+declaration\s*(\{[\s\S]*?\})\s*\*\//g;while((Q=Y.exec(Z))!==null)$.push({index:Q.index,kind:"declaration",text:Q[1].trim()});return $.sort((z,G)=>z.index-G.index)}function n5(Z,$){let X=new Map;if(Z.length===0)return X;let Q=$.statements;for(let H=0;H<Q.length;H++){let K=Q[H],Y;if(j.isInterfaceDeclaration(K))Y=K.name.getText($);else if(j.isTypeAliasDeclaration(K))Y=K.name.getText($);else if(j.isEnumDeclaration(K))Y=K.name.getText($);if(!Y)continue;let z=K.getStart($),G=H>0?Q[H-1].getEnd():0,J=Z.filter((W)=>W.index>=G&&W.index<z);if(J.length>0)X.set(Y,J)}return X}function c5(Z){let $=[],X=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{[\s\S]*?\}\s*\*\/|\/\*test\s*\{[\s\S]*?\}\s*\*\//g,Q;while((Q=X.exec(Z))!==null)$.push(Q[0]);return $}function o5(Z){let $=[],X=/\/\*#[\s\S]*?\*\//g,Q=0,H=null,K=[];for(let z=0;z<Z.length;z++){let G=Z[z],J=z>0?Z[z-1]:"";if(!H&&(G==='"'||G==="'"||G==="`"))H=G;else if(H&&G===H&&J!=="\\")H=null;if(!H){if(G==="{")Q++;if(G==="}")Q--}K[z]=Q}let Y;while((Y=X.exec(Z))!==null)if(K[Y.index]===0)$.push({content:Y[0],index:Y.index});return $}function s5(Z,$={}){let{emitTJS:X=!1,filename:Q="input.ts"}=$,H=[],K=c5(Z),Y=X?o5(Z):[],z=X?p5(Z):[],G=i5(Z),J=G.includes("TjsClass")||G.includes("TjsStrict"),W=j.createSourceFile(Q,Z,j.ScriptTarget.Latest,!0),U=X?n5(z,W):new Map,_=[],L=new Set,q={},A={},B=new Set,M=(V)=>{for(let T=0;T<Y.length;T++){let N=Y[T];if(!B.has(T)&&N.index<V)_.push(N.content),B.add(T)}},F=new Map,R=new Map;function w(V){if(j.isTypeAliasDeclaration(V))F.set(V.name.getText(W),V.type);if(j.isInterfaceDeclaration(V)){let T=V.name.getText(W),N=R.get(T);if(N){let g=j.factory.updateInterfaceDeclaration(N,N.modifiers,N.name,N.typeParameters,N.heritageClauses,[...N.members,...V.members]);R.set(T,g)}else R.set(T,V)}j.forEachChild(V,w)}w(W);let C={typeAliases:F,interfaces:R,sourceFile:W,warnings:H},P=new Map;for(let V of W.statements)if(j.isFunctionDeclaration(V)&&V.name){let T=V.name.getText(W);if(!P.has(T))P.set(T,{signatures:[],implementation:null});let N=P.get(T);if(V.body)N.implementation=V;else N.signatures.push(V)}for(let[V,T]of P)if(T.signatures.length===0||!T.implementation)P.delete(V);for(let V of W.statements){let T=!1;if(X)M(V.getStart(W));if(j.isFunctionDeclaration(V)&&V.name){let N=V.name.getText(W);T=!0;let g=P.get(N);if(g)if(!V.body);else if(X)_.push(...u5(g.signatures,V,W,H));else{let b=[];for(let n of g.signatures)b.push(W4(n,W,H,C));let y=W4(V,W,H,C);y.overloads=b,q[N]=y}else if(X)_.push(y7(V,W,void 0,H,!0,C));else q[N]=W4(V,W,H,C)}if(j.isVariableStatement(V)){let N=!1,g=V.modifiers?.some((b)=>b.kind===j.SyntaxKind.ExportKeyword);for(let b of V.declarationList.declarations)if(j.isIdentifier(b.name)&&b.initializer&&(j.isArrowFunction(b.initializer)||j.isFunctionExpression(b.initializer))){N=!0;let y=b.name.getText(W),n=b.initializer;if(X){let m=y7(n,W,y,H,!0,C);if(g&&!m.includes("export ")){let X1=m.search(/^(async\s+)?function[\s*]/m);if(X1>0)m=m.slice(0,X1)+"export "+m.slice(X1);else m="export "+m}_.push(m)}else{let m=W4(n,W,H,C);m.name=y,q[y]=m}}if(!N&&X){let b=j.transpileModule(V.getText(W),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}});_.push(b.outputText.trim())}T=!0}if(j.isInterfaceDeclaration(V)){if(T=!0,X){let N=V.name.getText(W),g=U.get(N);if(!L.has(N))if(L.add(N),g?.some((b)=>b.kind==="skip"));else{let b=R.get(N)||V,y=g5(b,W,H,g);if(y){let n=V.modifiers?.some((m)=>m.kind===j.SyntaxKind.ExportKeyword);_.push(n?y.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):y)}}}}if(j.isTypeAliasDeclaration(V)){if(T=!0,X){let N=V.name.getText(W),g=U.get(N);if(!L.has(N))if(L.add(N),g?.some((b)=>b.kind==="skip"));else{let b=y5(V,W,H,g);if(b){let y=V.modifiers?.some((n)=>n.kind===j.SyntaxKind.ExportKeyword);_.push(y?b.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):b)}}}}if(j.isEnumDeclaration(V)){if(T=!0,X){let N=V.name.getText(W),g=U.get(N);if(!L.has(N))if(L.add(N),g?.some((b)=>b.kind==="skip"));else{let b=f5(V,W,H);if(b)_.push(b)}}}if(j.isClassDeclaration(V)&&V.name){let N=V.name.getText(W);if(T=!0,X){let g=d5(V,W,H,void 0,J);_.push(g)}else A[N]=l5(V,W,H,C)}if(j.isImportDeclaration(V)){if(T=!0,X){if(!(V.importClause?.isTypeOnly||V.importClause?.namedBindings&&j.isNamedImports(V.importClause.namedBindings)&&V.importClause.namedBindings.elements.every((g)=>g.isTypeOnly)))if(V.importClause?.namedBindings&&j.isNamedImports(V.importClause.namedBindings)){let g=V.importClause.namedBindings.elements.filter((b)=>!b.isTypeOnly).map((b)=>{let y=b.name.getText(W),n=b.propertyName?.getText(W);return n?`${n} as ${y}`:y});if(g.length>0){let b=V.moduleSpecifier.text;_.push(`import { ${g.join(", ")} } from '${b}'`)}}else{let b=V.getText(W).replace(/\btype\s+/g,"").replace(/\s*:\s*\w+/g,"");_.push(b)}}}if(j.isExportDeclaration(V)||j.isExportAssignment(V)){if(T=!0,X){let g=j.transpileModule(V.getText(W),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();if(g)_.push(g)}}if(!T&&X){let g=j.transpileModule(V.getText(W),{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();if(g)_.push(g)}}if(X){M(1/0);let V=Q||"unknown",N=`${G.length>0?G.join(`
394
396
  `)+`
395
397
 
396
398
  `:""}/* tjs <- ${V} */
@@ -401,19 +403,19 @@ ${L.join(`
401
403
 
402
404
  `):"";return{code:N+_.join(`
403
405
 
404
- `)+g,warnings:H.length>0?H:void 0}}let k=j.transpileModule(Z,{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText;for(let[V,T]of Object.entries(q)){let N={params:Object.fromEntries(Object.entries(T.params).map(([b,f])=>[b,{type:f.type.kind,required:f.required,default:f.default}])),returns:T.returns?{type:T.returns.kind}:void 0};if(T.typeParams)N.typeParams=T.typeParams;let g=JSON.stringify(N,null,2);k+=`
406
+ `)+g,warnings:H.length>0?H:void 0}}let k=j.transpileModule(Z,{compilerOptions:{target:j.ScriptTarget.ESNext,module:j.ModuleKind.ESNext,removeComments:!1}}).outputText;for(let[V,T]of Object.entries(q)){let N={params:Object.fromEntries(Object.entries(T.params).map(([b,y])=>[b,{type:y.type.kind,required:y.required,default:y.default}])),returns:T.returns?{type:T.returns.kind}:void 0};if(T.typeParams)N.typeParams=T.typeParams;let g=JSON.stringify(N,null,2);k+=`
405
407
  ${V}.__tjs = ${g};
406
- `}for(let[V,T]of Object.entries(A)){let N={constructor:T.constructor?{params:Object.fromEntries(Object.entries(T.constructor.params??{}).map(([b,f])=>[b,{type:f.type.kind,required:f.required,default:f.default}]))}:void 0,methods:Object.fromEntries(Object.entries(T.methods??{}).map(([b,f])=>[b,{params:Object.fromEntries(Object.entries(f.params??{}).map(([n,m])=>[n,{type:m.type.kind,required:m.required}])),returns:f.returns?{type:f.returns.kind}:void 0}])),staticMethods:Object.fromEntries(Object.entries(T.staticMethods??{}).map(([b,f])=>[b,{params:Object.fromEntries(Object.entries(f.params??{}).map(([n,m])=>[n,{type:m.type.kind,required:m.required}])),returns:f.returns?{type:f.returns.kind}:void 0}]))};if(T.typeParams)N.typeParams=T.typeParams;let g=JSON.stringify(N,null,2);k+=`
408
+ `}for(let[V,T]of Object.entries(A)){let N={constructor:T.constructor?{params:Object.fromEntries(Object.entries(T.constructor.params??{}).map(([b,y])=>[b,{type:y.type.kind,required:y.required,default:y.default}]))}:void 0,methods:Object.fromEntries(Object.entries(T.methods??{}).map(([b,y])=>[b,{params:Object.fromEntries(Object.entries(y.params??{}).map(([n,m])=>[n,{type:m.type.kind,required:m.required}])),returns:y.returns?{type:y.returns.kind}:void 0}])),staticMethods:Object.fromEntries(Object.entries(T.staticMethods??{}).map(([b,y])=>[b,{params:Object.fromEntries(Object.entries(y.params??{}).map(([n,m])=>[n,{type:m.type.kind,required:m.required}])),returns:y.returns?{type:y.returns.kind}:void 0}]))};if(T.typeParams)N.typeParams=T.typeParams;let g=JSON.stringify(N,null,2);k+=`
407
409
  ${V}.__tjs = ${g};
408
410
  `,k+=`
409
- ${j7(V)}
410
- `}return{code:k,types:q,classes:Object.keys(A).length>0?A:void 0,warnings:H.length>0?H:void 0}}import{s as y7}from"tosijs-schema";function h7(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}function _4(Z){return y7.infer(Z)}function Q6(Z){return _4(Z)}Q6.type=h7;Q6.infer=_4;var o5=new Proxy(Q6,{get(Z,$){if($==="type")return h7;if($==="infer")return _4;return y7[$]},apply(Z,$,X){return _4(X[0])}});async function L4(Z){let $=`${K1}:${Z}`;if(typeof crypto<"u"&&crypto.subtle){let H=new TextEncoder().encode($),K=await crypto.subtle.digest("SHA-256",H);return Array.from(new Uint8Array(K)).map((z)=>z.toString(16).padStart(2,"0")).join("")}let X=5381;for(let Q=0;Q<$.length;Q++)X=(X<<5)+X+$.charCodeAt(Q)>>>0;return X.toString(16)}function s5(Z){let $=`${K1}:${Z}`,X=5381;for(let Q=0;Q<$.length;Q++)X=(X<<5)+X+$.charCodeAt(Q)>>>0;return X.toString(16)}var a5="tjs-metadata-cache",r5=1,e="modules";class H6{db=null;stats={hits:0,misses:0};pendingOpen=null;async open(){if(this.db)return;if(this.pendingOpen)return this.pendingOpen;this.pendingOpen=this._open(),await this.pendingOpen,this.pendingOpen=null}async _open(){return new Promise((Z,$)=>{if(typeof indexedDB>"u"){Z();return}let X=indexedDB.open(a5,r5);X.onerror=()=>{console.warn("MetadataCache: Failed to open IndexedDB",X.error),Z()},X.onsuccess=()=>{this.db=X.result,Z()},X.onupgradeneeded=(Q)=>{let H=Q.target.result;if(!H.objectStoreNames.contains(e)){let K=H.createObjectStore(e,{keyPath:"hash"});K.createIndex("timestamp","timestamp"),K.createIndex("version","version")}}})}async get(Z){if(!this.db){this.stats.misses++;return}let $=await L4(Z);return new Promise((X)=>{let K=this.db.transaction(e,"readonly").objectStore(e).get($);K.onerror=()=>{this.stats.misses++,X(void 0)},K.onsuccess=()=>{let Y=K.result;if(Y&&Y.version!==K1){this.stats.misses++,X(void 0);return}if(Y)this.stats.hits++;else this.stats.misses++;X(Y)}})}async getTranspile(Z){return(await this.get(Z))?.transpile}async getTJS(Z){return(await this.get(Z))?.tjs}async setTranspile(Z,$){await this._set(Z,{transpile:$})}async setTJS(Z,$){await this._set(Z,{tjs:$})}async _set(Z,$){if(!this.db)return;let X=await L4(Z);return new Promise((Q,H)=>{let Y=this.db.transaction(e,"readwrite").objectStore(e),z=Y.get(X);z.onsuccess=()=>{let G=z.result,J={hash:X,version:K1,timestamp:Date.now(),transpile:$.transpile??G?.transpile,tjs:$.tjs??G?.tjs},W=Y.put(J);W.onerror=()=>H(W.error),W.onsuccess=()=>Q()},z.onerror=()=>H(z.error)})}async delete(Z){if(!this.db)return;let $=await L4(Z);return new Promise((X,Q)=>{let Y=this.db.transaction(e,"readwrite").objectStore(e).delete($);Y.onerror=()=>Q(Y.error),Y.onsuccess=()=>X()})}async clear(){if(!this.db)return;return new Promise((Z,$)=>{let H=this.db.transaction(e,"readwrite").objectStore(e).clear();H.onerror=()=>$(H.error),H.onsuccess=()=>{this.stats={hits:0,misses:0},Z()}})}async prune(Z){if(!this.db)return 0;let $=Date.now()-Z;return new Promise((X,Q)=>{let Y=this.db.transaction(e,"readwrite").objectStore(e).index("timestamp"),z=IDBKeyRange.upperBound($),G=0,J=Y.openCursor(z);J.onsuccess=(W)=>{let L=W.target.result;if(L)L.delete(),G++,L.continue();else X(G)},J.onerror=()=>Q(J.error)})}async pruneOldVersions(){if(!this.db)return 0;return new Promise((Z,$)=>{let Q=this.db.transaction(e,"readwrite").objectStore(e),H=0,K=Q.openCursor();K.onsuccess=(Y)=>{let z=Y.target.result;if(z){if(z.value.version!==K1)z.delete(),H++;z.continue()}else Z(H)},K.onerror=()=>$(K.error)})}async getStats(){let Z=await this.count(),$=await this.estimateSize(),X=this.stats.hits+this.stats.misses,Q=X>0?this.stats.hits/X:0;return{entries:Z,bytes:$,hits:this.stats.hits,misses:this.stats.misses,hitRate:Q}}async count(){if(!this.db)return 0;return new Promise((Z,$)=>{let H=this.db.transaction(e,"readonly").objectStore(e).count();H.onerror=()=>$(H.error),H.onsuccess=()=>Z(H.result)})}async estimateSize(){if(!this.db)return 0;if(typeof navigator<"u"&&navigator.storage?.estimate)try{return(await navigator.storage.estimate()).usage??0}catch{}return new Promise((Z,$)=>{let Q=this.db.transaction(e,"readonly").objectStore(e),H=0,K=Q.openCursor();K.onsuccess=(Y)=>{let z=Y.target.result;if(z)H+=JSON.stringify(z.value).length*2,z.continue();else Z(H)},K.onerror=()=>$(K.error)})}close(){if(this.db)this.db.close(),this.db=null}isAvailable(){return this.db!==null}resetStats(){this.stats={hits:0,misses:0}}}var F0=null;async function U4(){if(!F0)F0=new H6,await F0.open();return F0}function t5(Z){F0=Z}function q4(Z,$,X,Q,H){if(!X)X=S;(function K(Y,z,G){var J=G||Y.type;if(X[J](Y,z,K),$[J])$[J](Y,z)})(Z,Q,H)}function x7(Z,$,X,Q,H){var K=[];if(!X)X=S;(function Y(z,G,J){var W=J||z.type,L=z!==K[K.length-1];if(L)K.push(z);if(X[W](z,G,Y),$[W])$[W](z,G||K,K);if(L)K.pop()})(Z,Q,H)}function K6(Z,$,X){X(Z,$)}function l1(Z,$,X){}var S={};S.Program=S.BlockStatement=S.StaticBlock=function(Z,$,X){for(var Q=0,H=Z.body;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Statement")}};S.Statement=K6;S.EmptyStatement=l1;S.ExpressionStatement=S.ParenthesizedExpression=S.ChainExpression=function(Z,$,X){return X(Z.expression,$,"Expression")};S.IfStatement=function(Z,$,X){if(X(Z.test,$,"Expression"),X(Z.consequent,$,"Statement"),Z.alternate)X(Z.alternate,$,"Statement")};S.LabeledStatement=function(Z,$,X){return X(Z.body,$,"Statement")};S.BreakStatement=S.ContinueStatement=l1;S.WithStatement=function(Z,$,X){X(Z.object,$,"Expression"),X(Z.body,$,"Statement")};S.SwitchStatement=function(Z,$,X){X(Z.discriminant,$,"Expression");for(var Q=0,H=Z.cases;Q<H.length;Q+=1){var K=H[Q];X(K,$)}};S.SwitchCase=function(Z,$,X){if(Z.test)X(Z.test,$,"Expression");for(var Q=0,H=Z.consequent;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Statement")}};S.ReturnStatement=S.YieldExpression=S.AwaitExpression=function(Z,$,X){if(Z.argument)X(Z.argument,$,"Expression")};S.ThrowStatement=S.SpreadElement=function(Z,$,X){return X(Z.argument,$,"Expression")};S.TryStatement=function(Z,$,X){if(X(Z.block,$,"Statement"),Z.handler)X(Z.handler,$);if(Z.finalizer)X(Z.finalizer,$,"Statement")};S.CatchClause=function(Z,$,X){if(Z.param)X(Z.param,$,"Pattern");X(Z.body,$,"Statement")};S.WhileStatement=S.DoWhileStatement=function(Z,$,X){X(Z.test,$,"Expression"),X(Z.body,$,"Statement")};S.ForStatement=function(Z,$,X){if(Z.init)X(Z.init,$,"ForInit");if(Z.test)X(Z.test,$,"Expression");if(Z.update)X(Z.update,$,"Expression");X(Z.body,$,"Statement")};S.ForInStatement=S.ForOfStatement=function(Z,$,X){X(Z.left,$,"ForInit"),X(Z.right,$,"Expression"),X(Z.body,$,"Statement")};S.ForInit=function(Z,$,X){if(Z.type==="VariableDeclaration")X(Z,$);else X(Z,$,"Expression")};S.DebuggerStatement=l1;S.FunctionDeclaration=function(Z,$,X){return X(Z,$,"Function")};S.VariableDeclaration=function(Z,$,X){for(var Q=0,H=Z.declarations;Q<H.length;Q+=1){var K=H[Q];X(K,$)}};S.VariableDeclarator=function(Z,$,X){if(X(Z.id,$,"Pattern"),Z.init)X(Z.init,$,"Expression")};S.Function=function(Z,$,X){if(Z.id)X(Z.id,$,"Pattern");for(var Q=0,H=Z.params;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Pattern")}X(Z.body,$,Z.expression?"Expression":"Statement")};S.Pattern=function(Z,$,X){if(Z.type==="Identifier")X(Z,$,"VariablePattern");else if(Z.type==="MemberExpression")X(Z,$,"MemberPattern");else X(Z,$)};S.VariablePattern=l1;S.MemberPattern=K6;S.RestElement=function(Z,$,X){return X(Z.argument,$,"Pattern")};S.ArrayPattern=function(Z,$,X){for(var Q=0,H=Z.elements;Q<H.length;Q+=1){var K=H[Q];if(K)X(K,$,"Pattern")}};S.ObjectPattern=function(Z,$,X){for(var Q=0,H=Z.properties;Q<H.length;Q+=1){var K=H[Q];if(K.type==="Property"){if(K.computed)X(K.key,$,"Expression");X(K.value,$,"Pattern")}else if(K.type==="RestElement")X(K.argument,$,"Pattern")}};S.Expression=K6;S.ThisExpression=S.Super=S.MetaProperty=l1;S.ArrayExpression=function(Z,$,X){for(var Q=0,H=Z.elements;Q<H.length;Q+=1){var K=H[Q];if(K)X(K,$,"Expression")}};S.ObjectExpression=function(Z,$,X){for(var Q=0,H=Z.properties;Q<H.length;Q+=1){var K=H[Q];X(K,$)}};S.FunctionExpression=S.ArrowFunctionExpression=S.FunctionDeclaration;S.SequenceExpression=function(Z,$,X){for(var Q=0,H=Z.expressions;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Expression")}};S.TemplateLiteral=function(Z,$,X){for(var Q=0,H=Z.quasis;Q<H.length;Q+=1){var K=H[Q];X(K,$)}for(var Y=0,z=Z.expressions;Y<z.length;Y+=1){var G=z[Y];X(G,$,"Expression")}};S.TemplateElement=l1;S.UnaryExpression=S.UpdateExpression=function(Z,$,X){X(Z.argument,$,"Expression")};S.BinaryExpression=S.LogicalExpression=function(Z,$,X){X(Z.left,$,"Expression"),X(Z.right,$,"Expression")};S.AssignmentExpression=S.AssignmentPattern=function(Z,$,X){X(Z.left,$,"Pattern"),X(Z.right,$,"Expression")};S.ConditionalExpression=function(Z,$,X){X(Z.test,$,"Expression"),X(Z.consequent,$,"Expression"),X(Z.alternate,$,"Expression")};S.NewExpression=S.CallExpression=function(Z,$,X){if(X(Z.callee,$,"Expression"),Z.arguments)for(var Q=0,H=Z.arguments;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Expression")}};S.MemberExpression=function(Z,$,X){if(X(Z.object,$,"Expression"),Z.computed)X(Z.property,$,"Expression")};S.ExportNamedDeclaration=S.ExportDefaultDeclaration=function(Z,$,X){if(Z.declaration)X(Z.declaration,$,Z.type==="ExportNamedDeclaration"||Z.declaration.id?"Statement":"Expression");if(Z.source)X(Z.source,$,"Expression")};S.ExportAllDeclaration=function(Z,$,X){if(Z.exported)X(Z.exported,$);X(Z.source,$,"Expression")};S.ImportDeclaration=function(Z,$,X){for(var Q=0,H=Z.specifiers;Q<H.length;Q+=1){var K=H[Q];X(K,$)}X(Z.source,$,"Expression")};S.ImportExpression=function(Z,$,X){X(Z.source,$,"Expression")};S.ImportSpecifier=S.ImportDefaultSpecifier=S.ImportNamespaceSpecifier=S.Identifier=S.PrivateIdentifier=S.Literal=l1;S.TaggedTemplateExpression=function(Z,$,X){X(Z.tag,$,"Expression"),X(Z.quasi,$,"Expression")};S.ClassDeclaration=S.ClassExpression=function(Z,$,X){return X(Z,$,"Class")};S.Class=function(Z,$,X){if(Z.id)X(Z.id,$,"Pattern");if(Z.superClass)X(Z.superClass,$,"Expression");X(Z.body,$)};S.ClassBody=function(Z,$,X){for(var Q=0,H=Z.body;Q<H.length;Q+=1){var K=H[Q];X(K,$)}};S.MethodDefinition=S.PropertyDefinition=S.Property=function(Z,$,X){if(Z.computed)X(Z.key,$,"Expression");if(Z.value)X(Z.value,$,"Expression")};var Z$={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function $$(Z,$={}){let X={...Z$,...$},Q=[],H;try{H=F1(Z,{filename:X.filename,colonShorthand:!0}).ast}catch(Y){return{diagnostics:[{severity:"error",message:Y.message,line:Y.loc?.line,column:Y.loc?.column,rule:"parse-error"}],valid:!1}}let K=[u7()];if(x7(H,{FunctionDeclaration(Y,z,G){let J=u7();K.push(J);for(let W of Y.params)X$(J,W,"parameter");if(Y.id)(K[K.length-2]||K[0]).declarations.set(Y.id.name,{node:Y.id,kind:"function",used:!1})},VariableDeclaration(Y){let z=K[K.length-1];for(let G of Y.declarations)if(G.id.type==="Identifier")z.declarations.set(G.id.name,{node:G.id,kind:Y.kind,used:!1})}}),q4(H,{Identifier(Y){for(let z=K.length-1;z>=0;z--){let G=K[z].declarations.get(Y.name);if(G){G.used=!0;break}}}}),X.unusedVariables)for(let Y of K)for(let[z,G]of Y.declarations){if(z.startsWith("_"))continue;if(!G.used&&G.kind!=="function")Q.push({severity:"warning",message:`'${z}' is declared but never used`,line:G.node.loc?.start?.line,column:G.node.loc?.start?.column,rule:"no-unused-vars"})}if(X.unreachableCode)q4(H,{BlockStatement(Y){let z=!1;for(let G of Y.body){if(z){Q.push({severity:"warning",message:"Unreachable code after return statement",line:G.loc?.start?.line,column:G.loc?.start?.column,rule:"no-unreachable"});break}if(G.type==="ReturnStatement")z=!0}}});if(X.noExplicitNew)q4(H,{NewExpression(Y){let z="class";if(Y.callee.type==="Identifier")z=Y.callee.name;else if(Y.callee.type==="MemberExpression"){if(Y.callee.property.type==="Identifier")z=Y.callee.property.name}Q.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${z}(...) instead of new ${z}(...)`,line:Y.loc?.start?.line,column:Y.loc?.start?.column,rule:"no-explicit-new"})}});return{diagnostics:Q,valid:Q.filter((Y)=>Y.severity==="error").length===0}}function u7(){return{declarations:new Map}}function X$(Z,$,X){if($.type==="Identifier")Z.declarations.set($.name,{node:$,kind:X,used:!1});else if($.type==="AssignmentPattern"&&$.left.type==="Identifier")Z.declarations.set($.left.name,{node:$.left,kind:X,used:!1})}function Q$(Z){let $=[],X=0,Q=null;for(let H=0;H<Z.length;H++){let K=Z[H],Y=H>0?Z[H-1]:"";if(!Q&&(K==='"'||K==="'"||K==="`"))Q=K;else if(Q&&K===Q&&Y!=="\\")Q=null;if(!Q){if(K==="{")X++;if(K==="}")X--}$[H]=X}return $}function d7(Z){let $=[],X=Q$(Z),Q=/\/\*#([\s\S]*?)\*\//g,H=/function\s+(\w+)\s*\(([^)]*)\)\s*(?:(-[>?!])\s*('[^']*'|"[^"]*"|[^\s{]+)|:\s*(\w+))?\s*\{/g,K=[],Y;while((Y=Q.exec(Z))!==null){if(X[Y.index]!==0)continue;let G=Y[1],J=G.split(`
411
- `),W=J.filter((L)=>L.trim().length>0).reduce((L,_)=>{let U=_.match(/^(\s*)/)?.[1].length||0;return Math.min(L,U)},1/0);if(W>0&&W<1/0)G=J.map((L)=>L.slice(W)).join(`
412
- `);K.push({type:"doc",index:Y.index,data:G.trim()})}while((Y=H.exec(Z))!==null){let G=Y[1],J=Y[2],W=Y[3]||"",L=Y[4]||"",_=Y[5]||"",U=`function ${G}(${J})`;if(W)U+=` ${W} ${L}`;else if(_)U+=`: ${_}`;K.push({type:"function",index:Y.index,data:{name:G,signature:U}})}K.sort((G,J)=>G.index-J.index);for(let G of K)if(G.type==="doc")$.push({type:"doc",content:G.data});else $.push({type:"function",name:G.data.name,signature:G.data.signature});let z=$.map((G)=>{if(G.type==="doc")return G.content;else return`\`\`\`tjs
411
+ ${F7(V)}
412
+ `}return{code:k,types:q,classes:Object.keys(A).length>0?A:void 0,warnings:H.length>0?H:void 0}}import{s as x7}from"tosijs-schema";function u7(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}function _4(Z){return x7.infer(Z)}function H6(Z){return _4(Z)}H6.type=u7;H6.infer=_4;var a5=new Proxy(H6,{get(Z,$){if($==="type")return u7;if($==="infer")return _4;return x7[$]},apply(Z,$,X){return _4(X[0])}});async function L4(Z){let $=`${K1}:${Z}`;if(typeof crypto<"u"&&crypto.subtle){let H=new TextEncoder().encode($),K=await crypto.subtle.digest("SHA-256",H);return Array.from(new Uint8Array(K)).map((z)=>z.toString(16).padStart(2,"0")).join("")}let X=5381;for(let Q=0;Q<$.length;Q++)X=(X<<5)+X+$.charCodeAt(Q)>>>0;return X.toString(16)}function r5(Z){let $=`${K1}:${Z}`,X=5381;for(let Q=0;Q<$.length;Q++)X=(X<<5)+X+$.charCodeAt(Q)>>>0;return X.toString(16)}var t5="tjs-metadata-cache",e5=1,e="modules";class K6{db=null;stats={hits:0,misses:0};pendingOpen=null;async open(){if(this.db)return;if(this.pendingOpen)return this.pendingOpen;this.pendingOpen=this._open(),await this.pendingOpen,this.pendingOpen=null}async _open(){return new Promise((Z,$)=>{if(typeof indexedDB>"u"){Z();return}let X=indexedDB.open(t5,e5);X.onerror=()=>{console.warn("MetadataCache: Failed to open IndexedDB",X.error),Z()},X.onsuccess=()=>{this.db=X.result,Z()},X.onupgradeneeded=(Q)=>{let H=Q.target.result;if(!H.objectStoreNames.contains(e)){let K=H.createObjectStore(e,{keyPath:"hash"});K.createIndex("timestamp","timestamp"),K.createIndex("version","version")}}})}async get(Z){if(!this.db){this.stats.misses++;return}let $=await L4(Z);return new Promise((X)=>{let K=this.db.transaction(e,"readonly").objectStore(e).get($);K.onerror=()=>{this.stats.misses++,X(void 0)},K.onsuccess=()=>{let Y=K.result;if(Y&&Y.version!==K1){this.stats.misses++,X(void 0);return}if(Y)this.stats.hits++;else this.stats.misses++;X(Y)}})}async getTranspile(Z){return(await this.get(Z))?.transpile}async getTJS(Z){return(await this.get(Z))?.tjs}async setTranspile(Z,$){await this._set(Z,{transpile:$})}async setTJS(Z,$){await this._set(Z,{tjs:$})}async _set(Z,$){if(!this.db)return;let X=await L4(Z);return new Promise((Q,H)=>{let Y=this.db.transaction(e,"readwrite").objectStore(e),z=Y.get(X);z.onsuccess=()=>{let G=z.result,J={hash:X,version:K1,timestamp:Date.now(),transpile:$.transpile??G?.transpile,tjs:$.tjs??G?.tjs},W=Y.put(J);W.onerror=()=>H(W.error),W.onsuccess=()=>Q()},z.onerror=()=>H(z.error)})}async delete(Z){if(!this.db)return;let $=await L4(Z);return new Promise((X,Q)=>{let Y=this.db.transaction(e,"readwrite").objectStore(e).delete($);Y.onerror=()=>Q(Y.error),Y.onsuccess=()=>X()})}async clear(){if(!this.db)return;return new Promise((Z,$)=>{let H=this.db.transaction(e,"readwrite").objectStore(e).clear();H.onerror=()=>$(H.error),H.onsuccess=()=>{this.stats={hits:0,misses:0},Z()}})}async prune(Z){if(!this.db)return 0;let $=Date.now()-Z;return new Promise((X,Q)=>{let Y=this.db.transaction(e,"readwrite").objectStore(e).index("timestamp"),z=IDBKeyRange.upperBound($),G=0,J=Y.openCursor(z);J.onsuccess=(W)=>{let U=W.target.result;if(U)U.delete(),G++,U.continue();else X(G)},J.onerror=()=>Q(J.error)})}async pruneOldVersions(){if(!this.db)return 0;return new Promise((Z,$)=>{let Q=this.db.transaction(e,"readwrite").objectStore(e),H=0,K=Q.openCursor();K.onsuccess=(Y)=>{let z=Y.target.result;if(z){if(z.value.version!==K1)z.delete(),H++;z.continue()}else Z(H)},K.onerror=()=>$(K.error)})}async getStats(){let Z=await this.count(),$=await this.estimateSize(),X=this.stats.hits+this.stats.misses,Q=X>0?this.stats.hits/X:0;return{entries:Z,bytes:$,hits:this.stats.hits,misses:this.stats.misses,hitRate:Q}}async count(){if(!this.db)return 0;return new Promise((Z,$)=>{let H=this.db.transaction(e,"readonly").objectStore(e).count();H.onerror=()=>$(H.error),H.onsuccess=()=>Z(H.result)})}async estimateSize(){if(!this.db)return 0;if(typeof navigator<"u"&&navigator.storage?.estimate)try{return(await navigator.storage.estimate()).usage??0}catch{}return new Promise((Z,$)=>{let Q=this.db.transaction(e,"readonly").objectStore(e),H=0,K=Q.openCursor();K.onsuccess=(Y)=>{let z=Y.target.result;if(z)H+=JSON.stringify(z.value).length*2,z.continue();else Z(H)},K.onerror=()=>$(K.error)})}close(){if(this.db)this.db.close(),this.db=null}isAvailable(){return this.db!==null}resetStats(){this.stats={hits:0,misses:0}}}var F0=null;async function U4(){if(!F0)F0=new K6,await F0.open();return F0}function Z$(Z){F0=Z}function q4(Z,$,X,Q,H){if(!X)X=S;(function K(Y,z,G){var J=G||Y.type;if(X[J](Y,z,K),$[J])$[J](Y,z)})(Z,Q,H)}function d7(Z,$,X,Q,H){var K=[];if(!X)X=S;(function Y(z,G,J){var W=J||z.type,U=z!==K[K.length-1];if(U)K.push(z);if(X[W](z,G,Y),$[W])$[W](z,G||K,K);if(U)K.pop()})(Z,Q,H)}function Y6(Z,$,X){X(Z,$)}function l1(Z,$,X){}var S={};S.Program=S.BlockStatement=S.StaticBlock=function(Z,$,X){for(var Q=0,H=Z.body;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Statement")}};S.Statement=Y6;S.EmptyStatement=l1;S.ExpressionStatement=S.ParenthesizedExpression=S.ChainExpression=function(Z,$,X){return X(Z.expression,$,"Expression")};S.IfStatement=function(Z,$,X){if(X(Z.test,$,"Expression"),X(Z.consequent,$,"Statement"),Z.alternate)X(Z.alternate,$,"Statement")};S.LabeledStatement=function(Z,$,X){return X(Z.body,$,"Statement")};S.BreakStatement=S.ContinueStatement=l1;S.WithStatement=function(Z,$,X){X(Z.object,$,"Expression"),X(Z.body,$,"Statement")};S.SwitchStatement=function(Z,$,X){X(Z.discriminant,$,"Expression");for(var Q=0,H=Z.cases;Q<H.length;Q+=1){var K=H[Q];X(K,$)}};S.SwitchCase=function(Z,$,X){if(Z.test)X(Z.test,$,"Expression");for(var Q=0,H=Z.consequent;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Statement")}};S.ReturnStatement=S.YieldExpression=S.AwaitExpression=function(Z,$,X){if(Z.argument)X(Z.argument,$,"Expression")};S.ThrowStatement=S.SpreadElement=function(Z,$,X){return X(Z.argument,$,"Expression")};S.TryStatement=function(Z,$,X){if(X(Z.block,$,"Statement"),Z.handler)X(Z.handler,$);if(Z.finalizer)X(Z.finalizer,$,"Statement")};S.CatchClause=function(Z,$,X){if(Z.param)X(Z.param,$,"Pattern");X(Z.body,$,"Statement")};S.WhileStatement=S.DoWhileStatement=function(Z,$,X){X(Z.test,$,"Expression"),X(Z.body,$,"Statement")};S.ForStatement=function(Z,$,X){if(Z.init)X(Z.init,$,"ForInit");if(Z.test)X(Z.test,$,"Expression");if(Z.update)X(Z.update,$,"Expression");X(Z.body,$,"Statement")};S.ForInStatement=S.ForOfStatement=function(Z,$,X){X(Z.left,$,"ForInit"),X(Z.right,$,"Expression"),X(Z.body,$,"Statement")};S.ForInit=function(Z,$,X){if(Z.type==="VariableDeclaration")X(Z,$);else X(Z,$,"Expression")};S.DebuggerStatement=l1;S.FunctionDeclaration=function(Z,$,X){return X(Z,$,"Function")};S.VariableDeclaration=function(Z,$,X){for(var Q=0,H=Z.declarations;Q<H.length;Q+=1){var K=H[Q];X(K,$)}};S.VariableDeclarator=function(Z,$,X){if(X(Z.id,$,"Pattern"),Z.init)X(Z.init,$,"Expression")};S.Function=function(Z,$,X){if(Z.id)X(Z.id,$,"Pattern");for(var Q=0,H=Z.params;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Pattern")}X(Z.body,$,Z.expression?"Expression":"Statement")};S.Pattern=function(Z,$,X){if(Z.type==="Identifier")X(Z,$,"VariablePattern");else if(Z.type==="MemberExpression")X(Z,$,"MemberPattern");else X(Z,$)};S.VariablePattern=l1;S.MemberPattern=Y6;S.RestElement=function(Z,$,X){return X(Z.argument,$,"Pattern")};S.ArrayPattern=function(Z,$,X){for(var Q=0,H=Z.elements;Q<H.length;Q+=1){var K=H[Q];if(K)X(K,$,"Pattern")}};S.ObjectPattern=function(Z,$,X){for(var Q=0,H=Z.properties;Q<H.length;Q+=1){var K=H[Q];if(K.type==="Property"){if(K.computed)X(K.key,$,"Expression");X(K.value,$,"Pattern")}else if(K.type==="RestElement")X(K.argument,$,"Pattern")}};S.Expression=Y6;S.ThisExpression=S.Super=S.MetaProperty=l1;S.ArrayExpression=function(Z,$,X){for(var Q=0,H=Z.elements;Q<H.length;Q+=1){var K=H[Q];if(K)X(K,$,"Expression")}};S.ObjectExpression=function(Z,$,X){for(var Q=0,H=Z.properties;Q<H.length;Q+=1){var K=H[Q];X(K,$)}};S.FunctionExpression=S.ArrowFunctionExpression=S.FunctionDeclaration;S.SequenceExpression=function(Z,$,X){for(var Q=0,H=Z.expressions;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Expression")}};S.TemplateLiteral=function(Z,$,X){for(var Q=0,H=Z.quasis;Q<H.length;Q+=1){var K=H[Q];X(K,$)}for(var Y=0,z=Z.expressions;Y<z.length;Y+=1){var G=z[Y];X(G,$,"Expression")}};S.TemplateElement=l1;S.UnaryExpression=S.UpdateExpression=function(Z,$,X){X(Z.argument,$,"Expression")};S.BinaryExpression=S.LogicalExpression=function(Z,$,X){X(Z.left,$,"Expression"),X(Z.right,$,"Expression")};S.AssignmentExpression=S.AssignmentPattern=function(Z,$,X){X(Z.left,$,"Pattern"),X(Z.right,$,"Expression")};S.ConditionalExpression=function(Z,$,X){X(Z.test,$,"Expression"),X(Z.consequent,$,"Expression"),X(Z.alternate,$,"Expression")};S.NewExpression=S.CallExpression=function(Z,$,X){if(X(Z.callee,$,"Expression"),Z.arguments)for(var Q=0,H=Z.arguments;Q<H.length;Q+=1){var K=H[Q];X(K,$,"Expression")}};S.MemberExpression=function(Z,$,X){if(X(Z.object,$,"Expression"),Z.computed)X(Z.property,$,"Expression")};S.ExportNamedDeclaration=S.ExportDefaultDeclaration=function(Z,$,X){if(Z.declaration)X(Z.declaration,$,Z.type==="ExportNamedDeclaration"||Z.declaration.id?"Statement":"Expression");if(Z.source)X(Z.source,$,"Expression")};S.ExportAllDeclaration=function(Z,$,X){if(Z.exported)X(Z.exported,$);X(Z.source,$,"Expression")};S.ImportDeclaration=function(Z,$,X){for(var Q=0,H=Z.specifiers;Q<H.length;Q+=1){var K=H[Q];X(K,$)}X(Z.source,$,"Expression")};S.ImportExpression=function(Z,$,X){X(Z.source,$,"Expression")};S.ImportSpecifier=S.ImportDefaultSpecifier=S.ImportNamespaceSpecifier=S.Identifier=S.PrivateIdentifier=S.Literal=l1;S.TaggedTemplateExpression=function(Z,$,X){X(Z.tag,$,"Expression"),X(Z.quasi,$,"Expression")};S.ClassDeclaration=S.ClassExpression=function(Z,$,X){return X(Z,$,"Class")};S.Class=function(Z,$,X){if(Z.id)X(Z.id,$,"Pattern");if(Z.superClass)X(Z.superClass,$,"Expression");X(Z.body,$)};S.ClassBody=function(Z,$,X){for(var Q=0,H=Z.body;Q<H.length;Q+=1){var K=H[Q];X(K,$)}};S.MethodDefinition=S.PropertyDefinition=S.Property=function(Z,$,X){if(Z.computed)X(Z.key,$,"Expression");if(Z.value)X(Z.value,$,"Expression")};var X$={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function Q$(Z,$={}){let X={...X$,...$},Q=[],H;try{H=F1(Z,{filename:X.filename,colonShorthand:!0}).ast}catch(Y){return{diagnostics:[{severity:"error",message:Y.message,line:Y.loc?.line,column:Y.loc?.column,rule:"parse-error"}],valid:!1}}let K=[l7()];if(d7(H,{FunctionDeclaration(Y,z,G){let J=l7();K.push(J);for(let W of Y.params)H$(J,W,"parameter");if(Y.id)(K[K.length-2]||K[0]).declarations.set(Y.id.name,{node:Y.id,kind:"function",used:!1})},VariableDeclaration(Y){let z=K[K.length-1];for(let G of Y.declarations)if(G.id.type==="Identifier")z.declarations.set(G.id.name,{node:G.id,kind:Y.kind,used:!1})}}),q4(H,{Identifier(Y){for(let z=K.length-1;z>=0;z--){let G=K[z].declarations.get(Y.name);if(G){G.used=!0;break}}}}),X.unusedVariables)for(let Y of K)for(let[z,G]of Y.declarations){if(z.startsWith("_"))continue;if(!G.used&&G.kind!=="function")Q.push({severity:"warning",message:`'${z}' is declared but never used`,line:G.node.loc?.start?.line,column:G.node.loc?.start?.column,rule:"no-unused-vars"})}if(X.unreachableCode)q4(H,{BlockStatement(Y){let z=!1;for(let G of Y.body){if(z){Q.push({severity:"warning",message:"Unreachable code after return statement",line:G.loc?.start?.line,column:G.loc?.start?.column,rule:"no-unreachable"});break}if(G.type==="ReturnStatement")z=!0}}});if(X.noExplicitNew)q4(H,{NewExpression(Y){let z="class";if(Y.callee.type==="Identifier")z=Y.callee.name;else if(Y.callee.type==="MemberExpression"){if(Y.callee.property.type==="Identifier")z=Y.callee.property.name}Q.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${z}(...) instead of new ${z}(...)`,line:Y.loc?.start?.line,column:Y.loc?.start?.column,rule:"no-explicit-new"})}});return{diagnostics:Q,valid:Q.filter((Y)=>Y.severity==="error").length===0}}function l7(){return{declarations:new Map}}function H$(Z,$,X){if($.type==="Identifier")Z.declarations.set($.name,{node:$,kind:X,used:!1});else if($.type==="AssignmentPattern"&&$.left.type==="Identifier")Z.declarations.set($.left.name,{node:$.left,kind:X,used:!1})}function K$(Z){let $=[],X=0,Q=null;for(let H=0;H<Z.length;H++){let K=Z[H],Y=H>0?Z[H-1]:"";if(!Q&&(K==='"'||K==="'"||K==="`"))Q=K;else if(Q&&K===Q&&Y!=="\\")Q=null;if(!Q){if(K==="{")X++;if(K==="}")X--}$[H]=X}return $}function m7(Z){let $=[],X=K$(Z),Q=/\/\*#([\s\S]*?)\*\//g,H=/function\s+(\w+)\s*\(([^)]*)\)\s*(?:(-[>?!])\s*('[^']*'|"[^"]*"|[^\s{]+)|:\s*(\w+))?\s*\{/g,K=[],Y;while((Y=Q.exec(Z))!==null){if(X[Y.index]!==0)continue;let G=Y[1],J=G.split(`
413
+ `),W=J.filter((U)=>U.trim().length>0).reduce((U,_)=>{let L=_.match(/^(\s*)/)?.[1].length||0;return Math.min(U,L)},1/0);if(W>0&&W<1/0)G=J.map((U)=>U.slice(W)).join(`
414
+ `);K.push({type:"doc",index:Y.index,data:G.trim()})}while((Y=H.exec(Z))!==null){let G=Y[1],J=Y[2],W=Y[3]||"",U=Y[4]||"",_=Y[5]||"",L=`function ${G}(${J})`;if(W)L+=` ${W} ${U}`;else if(_)L+=`: ${_}`;K.push({type:"function",index:Y.index,data:{name:G,signature:L}})}K.sort((G,J)=>G.index-J.index);for(let G of K)if(G.type==="doc")$.push({type:"doc",content:G.data});else $.push({type:"function",name:G.data.name,signature:G.data.signature});let z=$.map((G)=>{if(G.type==="doc")return G.content;else return`\`\`\`tjs
413
415
  ${G.signature}
414
416
  \`\`\``}).join(`
415
417
 
416
- `);return{items:$,markdown:z}}function H$(Z,$){let X=d7(Z),Q="";for(let H of X.items)if(H.type==="doc")Q+=H.content+`
418
+ `);return{items:$,markdown:z}}function Y$(Z,$){let X=m7(Z),Q="";for(let H of X.items)if(H.type==="doc")Q+=H.content+`
417
419
 
418
420
  `;else if(H.type==="function"){let K=$?.[H.name];if(Q+=`## ${H.name}
419
421
 
@@ -426,8 +428,8 @@ ${H.signature}
426
428
  `}Q+=`
427
429
  `}if(K?.returns)Q+=`**Returns:** ${K.returns.kind||"void"}
428
430
 
429
- `}return Q.trim()||"*No documentation available*"}import{s as I,validate as Y6,filter as o7}from"tosijs-schema";var D4=Symbol.for("tjs.equals");function I4(Z,$){if(Z!==null&&typeof Z==="object"&&typeof Z[D4]==="function")return Z[D4]($);if($!==null&&typeof $==="object"&&typeof $[D4]==="function")return $[D4](Z);if(Z!==null&&typeof Z==="object"&&typeof Z.Equals==="function")return Z.Equals($);if($!==null&&typeof $==="object"&&typeof $.Equals==="function")return $.Equals(Z);if(Z===$)return!0;if((Z===null||Z===void 0)&&($===null||$===void 0))return!0;if(Z===null||Z===void 0||$===null||$===void 0)return!1;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((H,K)=>I4(H,$[K]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),Q=Object.keys($);if(X.length!==Q.length)return!1;return X.every((H)=>I4(Z[H],$[H]))}class J1{$error=!0;message;op;cause;constructor(Z,$,X){this.message=Z,this.op=$,this.cause=X}toString(){return`AgentError[${this.op}]: ${this.message}`}toJSON(){return{$error:!0,message:this.message,op:this.op}}}function K$(Z){return Z instanceof J1||Z&&Z.$error===!0}var $0=new Map,Y$=3600000,z$=102400,z6="proc_";function G6(Z){return typeof Z==="string"&&Z.startsWith(z6)}function J6(Z){let $=$0.get(Z);if(!$)throw Error(`Procedure not found: ${Z}`);if(Date.now()>$.expiresAt)throw $0.delete(Z),Error(`Procedure expired: ${Z}`);return $.ast}function G$(){if(typeof crypto<"u"&&crypto.randomUUID)return z6+crypto.randomUUID();return z6+Math.random().toString(36).slice(2)+Date.now().toString(36)}var s7=new Set(["__proto__","constructor","prototype"]);function l7(Z){if(s7.has(Z))throw Error(`Security Error: Access to '${Z}' is forbidden`)}var J$=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function W$(Z){try{let $=new URL(Z);if($.protocol!=="http:"&&$.protocol!=="https:")return!0;let X=$.hostname.toLowerCase();if(J$.has(X))return!0;if(X.endsWith(".internal")||X.endsWith(".local"))return!0;if(X==="169.254.169.254")return!0;if(/^10\./.test(X)||/^192\.168\./.test(X)||/^172\.(1[6-9]|2\d|3[01])\./.test(X))return!0;return!1}catch{return!0}}function _$(Z){if(/\([^)]*[+*][^)]*\)[+*]/.test(Z))return!0;if(/\(([^|)]+)\|\1\)[+*]/.test(Z))return!0;if(/\(\.\*\)\+/.test(Z))return!0;if(/\(\.\+\)\+/.test(Z))return!0;if(/\(\[.*\]\+\)\+/.test(Z))return!0;return!1}function T1(Z){return{...Z,state:Object.create(Z.state)}}function L$(Z,$){let X={},Q=new Set([...Object.keys(Z),...Object.keys($)]);for(let H of Q){let K=Z[H],Y=$[H];if(Y!==K)X[H]=Y}return X}function E(Z,$){if(Z&&typeof Z==="object"&&Z.$kind==="arg")return $.args[Z.path];if(Z&&typeof Z==="object"&&Z.$expr)return r(Z,$);if(typeof Z==="string"){if(Z.startsWith("args.")&&!("args"in $.state))return $.args[Z.replace("args.","")];if(Z.includes(".")){let X=Z.split(".");for(let H of X)if(s7.has(H))throw Error(`Security Error: Access to '${H}' is forbidden`);let Q=$.state[X[0]];if(Q!==void 0){for(let H=1;H<X.length;H++)Q=Q?.[X[H]];return Q}}if(Z in $.state)return $.state[Z];return Z}if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Z.constructor===Object){let X={};for(let Q of Object.keys(Z))X[Q]=E(Z[Q],$);return X}if(Array.isArray(Z))return Z.map((X)=>E(X,$));return Z}function m1(Z,$,X){return new Proxy($,{get(Q,H){if(H in Q)return Q[H];let K=X?.[H];if(K)throw Error(`${Z}.${H} is not available. ${K}`);throw Error(`${Z}.${H} is not supported in AsyncJS. Check docs for available ${Z} methods.`)}})}function Z0(Z){if(Z===null)return{type:"null"};if(Z===void 0)return{};if(typeof Z==="object"&&Z!==null&&"type"in Z&&typeof Z.type==="string")return Z;if(typeof Z==="object"&&Z!==null&&"schema"in Z&&typeof Z.schema==="object")return Z.schema;let $=typeof Z;if($==="string")return{type:"string"};if($==="number")return Number.isInteger(Z)?{type:"integer"}:{type:"number"};if($==="boolean")return{type:"boolean"};if(Array.isArray(Z)){if(Z.length===0)return{type:"array"};return{type:"array",items:Z0(Z[0])}}if($==="object"){let X={},Q=[];for(let[H,K]of Object.entries(Z))X[H]=Z0(K),Q.push(H);return{type:"object",properties:X,required:Q}}return{}}var C1={Math:m1("Math",{PI:Math.PI,E:Math.E,LN2:Math.LN2,LN10:Math.LN10,LOG2E:Math.LOG2E,LOG10E:Math.LOG10E,SQRT2:Math.SQRT2,SQRT1_2:Math.SQRT1_2,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc,sign:Math.sign,sqrt:Math.sqrt,cbrt:Math.cbrt,pow:Math.pow,exp:Math.exp,expm1:Math.expm1,log:Math.log,log2:Math.log2,log10:Math.log10,log1p:Math.log1p,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,hypot:Math.hypot,min:Math.min,max:Math.max,clz32:Math.clz32,imul:Math.imul,fround:Math.fround,random:()=>{if(typeof crypto<"u"&&crypto.getRandomValues){let Z=new Uint32Array(1);return crypto.getRandomValues(Z),Z[0]/4294967296}return Math.random()}}),JSON:m1("JSON",{parse:(Z)=>JSON.parse(Z),stringify:(Z,$,X)=>JSON.stringify(Z,$,X)}),console:m1("console",{log:(...Z)=>{return},warn:(...Z)=>{return},error:(...Z)=>{return},info:(...Z)=>{return}},{table:"Use console.log with JSON.stringify for structured data.",dir:"Use console.log instead.",trace:"Stack traces are not available in AsyncJS."}),Array:m1("Array",{isArray:(Z)=>Array.isArray(Z),from:(Z,$,X)=>Array.from(Z,$,X),of:(...Z)=>Array.of(...Z)},{prototype:"Prototype access is not allowed."}),Object:m1("Object",{keys:(Z)=>Object.keys(Z),values:(Z)=>Object.values(Z),entries:(Z)=>Object.entries(Z),fromEntries:(Z)=>Object.fromEntries(Z),assign:(Z,...$)=>Object.assign({},Z,...$),hasOwn:(Z,$)=>Object.hasOwn(Z,$)},{prototype:"Prototype access is not allowed.",create:"Use object literals instead.",defineProperty:"Property descriptors are not supported.",getPrototypeOf:"Prototype access is not allowed.",setPrototypeOf:"Prototype modification is not allowed."}),String:m1("String",{fromCharCode:(...Z)=>String.fromCharCode(...Z),fromCodePoint:(...Z)=>String.fromCodePoint(...Z)}),Number:m1("Number",{isNaN:Number.isNaN,isFinite:Number.isFinite,isInteger:Number.isInteger,isSafeInteger:Number.isSafeInteger,parseFloat,parseInt,MAX_VALUE:Number.MAX_VALUE,MIN_VALUE:Number.MIN_VALUE,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,POSITIVE_INFINITY:Number.POSITIVE_INFINITY,NEGATIVE_INFINITY:Number.NEGATIVE_INFINITY,NaN:Number.NaN,EPSILON:Number.EPSILON}),parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,undefined:void 0,null:null,NaN:NaN,Infinity:1/0,filter:(Z,$)=>{let X=Z0($),Q=o7(Z,X);if(Q instanceof Error)throw Q;return Q},Schema:{...I,response:(Z,$)=>{let X=$?.schema!=null?$.schema:Z0($);return{type:"json_schema",json_schema:{name:Z,strict:!0,schema:X}}},fromExample:(Z)=>Z0(Z),isValid:(Z,$)=>{if($?.schema!=null)return Y6(Z,$);return Y6(Z,Z0($))}},Set:(Z=[])=>{let $=[...new globalThis.Set(Z)];return{add(X){if(!$.includes(X))$.push(X);return this},remove(X){let Q=$.indexOf(X);if(Q!==-1)$.splice(Q,1);return this},clear(){return $.length=0,this},has(X){return $.includes(X)},get size(){return $.length},toArray(){return[...$]},union(X){let Q=X?.toArray?.()??X??[];return C1.Set([...$,...Q])},intersection(X){let Q=X?.toArray?.()??X??[];return C1.Set($.filter((H)=>Q.includes(H)))},diff(X){let Q=X?.toArray?.()??X??[];return C1.Set($.filter((H)=>!Q.includes(H)))},forEach(X){$.forEach(X)},map(X){return C1.Set($.map(X))},filter(X){return C1.Set($.filter(X))},toJSON(){return[...$]}}},Date:(()=>{let Z=(X)=>({get value(){return X.toISOString()},get timestamp(){return X.getTime()},get year(){return X.getFullYear()},get month(){return X.getMonth()+1},get day(){return X.getDate()},get hours(){return X.getHours()},get minutes(){return X.getMinutes()},get seconds(){return X.getSeconds()},get dayOfWeek(){return X.getDay()},add({years:Q=0,months:H=0,days:K=0,hours:Y=0,minutes:z=0,seconds:G=0,ms:J=0}={}){let W=new globalThis.Date(X.getTime());if(Q)W.setFullYear(W.getFullYear()+Q);if(H)W.setMonth(W.getMonth()+H);if(K)W.setDate(W.getDate()+K);if(Y)W.setHours(W.getHours()+Y);if(z)W.setMinutes(W.getMinutes()+z);if(G)W.setSeconds(W.getSeconds()+G);if(J)W.setMilliseconds(W.getMilliseconds()+J);return Z(W)},diff(Q,H="ms"){let K=typeof Q==="object"&&Q.timestamp?Q.timestamp:new globalThis.Date(Q).getTime(),Y=X.getTime()-K;switch(H){case"seconds":return Y/1000;case"minutes":return Y/60000;case"hours":return Y/3600000;case"days":return Y/86400000;default:return Y}},format(Q="ISO"){if(Q==="ISO")return X.toISOString();if(Q==="date")return X.toISOString().split("T")[0];if(Q==="time")return X.toISOString().split("T")[1].split(".")[0];return Q.replace("YYYY",String(X.getFullYear())).replace("MM",String(X.getMonth()+1).padStart(2,"0")).replace("DD",String(X.getDate()).padStart(2,"0")).replace("HH",String(X.getHours()).padStart(2,"0")).replace("mm",String(X.getMinutes()).padStart(2,"0")).replace("ss",String(X.getSeconds()).padStart(2,"0"))},isBefore(Q){let H=typeof Q==="object"&&Q.timestamp?Q.timestamp:new globalThis.Date(Q).getTime();return X.getTime()<H},isAfter(Q){let H=typeof Q==="object"&&Q.timestamp?Q.timestamp:new globalThis.Date(Q).getTime();return X.getTime()>H},toString(){return X.toISOString()},toJSON(){return X.toISOString()}}),$=(X)=>{let Q=X!==void 0?new globalThis.Date(X):new globalThis.Date;if(isNaN(Q.getTime()))throw Error(`Invalid date: ${X}`);return Z(Q)};return $.now=()=>globalThis.Date.now(),$.parse=(X)=>Z(new globalThis.Date(X)),$})()},A4={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."},U$=0.01,m7=0.0001,i7=0.001,q$=new Set(["concat","slice","map","filter","flatMap","flat","toReversed","toSorted","toSpliced","repeat","padStart","padEnd","split","join","replace","replaceAll","substring","substr","trim","trimStart","trimEnd","toLowerCase","toUpperCase","match","matchAll","parse","stringify"]);function r(Z,$){if(Z===null||Z===void 0)return Z;if(typeof Z!=="object"||!("$expr"in Z))return Z;if($.fuel){if($.fuel.current-=U$,$.fuel.current<=0)throw Error("Out of Fuel")}switch(Z.$expr){case"literal":return Z.value;case"ident":{if(Z.name in $.state)return $.state[Z.name];if(Z.name in $.args)return $.args[Z.name];if(Z.name in C1)return C1[Z.name];if(Z.name in A4)throw Error(A4[Z.name]);return}case"member":{let X=r(Z.object,$);if(Z.optional&&(X===null||X===void 0))return;let Q=Z.property;return l7(Q),X?.[Q]}case"binary":{let X=r(Z.left,$),Q=r(Z.right,$);switch(Z.op){case"+":{let H=X+Q;if(typeof H==="string"&&$.fuel){if($.fuel.current-=H.length*m7,$.fuel.current<=0){$.error=new J1("Out of Fuel","expr.concat");return}}return H}case"-":return X-Q;case"*":return X*Q;case"/":return X/Q;case"%":return X%Q;case"**":return X**Q;case">":return X>Q;case"<":return X<Q;case">=":return X>=Q;case"<=":return X<=Q;case"==":return I4(X,Q);case"!=":return!I4(X,Q);case"===":return X===Q;case"!==":return X!==Q;default:throw Error(`Unknown binary operator: ${Z.op}`)}}case"unary":{let X=r(Z.argument,$);switch(Z.op){case"!":return!X;case"-":return-X;case"+":return+X;case"typeof":return typeof X;default:throw Error(`Unknown unary operator: ${Z.op}`)}}case"logical":{let X=r(Z.left,$);if(Z.op==="&&")return X?r(Z.right,$):X;else if(Z.op==="??")return X??r(Z.right,$);else return X?X:r(Z.right,$)}case"conditional":return r(Z.test,$)?r(Z.consequent,$):r(Z.alternate,$);case"array":return Z.elements.map((X)=>r(X,$));case"object":{let X={};for(let Q of Z.properties)X[Q.key]=r(Q.value,$);return X}case"call":{if(Z.callee==="Error"){let Q=Z.arguments.map((K)=>r(K,$)),H=typeof Q[0]==="string"?Q[0]:"Error";$.error=new J1(H,"Error");return}if(Z.callee in C1){let Q=C1[Z.callee];if(typeof Q==="function"){let H=Z.arguments.map((K)=>r(K,$));return Q(...H)}}if(!$.resolver(Z.callee)){if(Z.callee in A4)throw Error(A4[Z.callee]);throw Error(`Unknown function: ${Z.callee}`)}throw Error(`Atom calls in expressions not yet supported: ${Z.callee}`)}case"methodCall":{let X=r(Z.object,$);if(Z.optional&&(X===null||X===void 0))return;let Q=Z.method;if(l7(Q),X===null||X===void 0)throw Error(`Cannot call method '${Q}' on ${X}`);let H=X[Q];if(typeof H!=="function")throw Error(`'${Q}' is not a function`);let K=Z.arguments.map((z)=>r(z,$)),Y=H.apply(X,K);if($.fuel&&q$.has(Q)){let z=0;if(typeof Y==="string")z=Y.length*m7;else if(Array.isArray(Y))z=Y.length*i7;else if(typeof Y==="object"&&Y!==null)z=Object.keys(Y).length*i7;if($.fuel.current-=z,$.fuel.current<=0){$.error=new J1("Out of Fuel",`expr.${Q}`);return}}return Y}default:throw Error(`Unknown expression type: ${Z.$expr}`)}}function v(Z,$,X,Q,H={}){let{docs:K="",timeoutMs:Y=1000,cost:z=1}=typeof H==="string"?{docs:H}:H;return{op:Z,inputSchema:$,outputSchema:X,exec:async(J,W)=>{let{op:L,result:_,...U}=J;if(W.error)return;let q=W.trace?{...W.state}:null,A=W.fuel.current,B,M;try{let F=W.costOverrides?.[Z],R=F!==void 0?F:z,w=typeof R==="function"?R(U,W):R;if((W.fuel.current-=w)<=0){W.error=new J1("Out of Fuel",Z);return}let C,P=async()=>Q(J,W);if(B=Y>0?await Promise.race([P(),new Promise((O,k)=>{C=setTimeout(()=>k(Error(`Atom '${Z}' timed out`)),Y)})]).finally(()=>clearTimeout(C)):await P(),J.result){if(W.consts.has(J.result))throw Error(`Cannot reassign const variable '${J.result}'`);if(B!==void 0&&X&&!Y6(B,X)){W.error=new J1(`Output validation failed for '${Z}'`,Z);return}if(W.state[J.result]=B,J.resultConst)W.consts.add(J.result)}}catch(F){M=F.message||String(F),W.error=new J1(M,Z,F)}finally{if(W.trace&&q){let F=L$(q,W.state);W.trace.push({op:Z,input:U,stateDiff:F,result:B,error:M,fuelBefore:A,fuelAfter:W.fuel.current,timestamp:new Date().toISOString()})}}},docs:K,timeoutMs:Y,cost:z,create:(J)=>({op:Z,...J})}}var U1=v("seq",I.object({steps:I.array(I.any)}),void 0,async({steps:Z},$)=>{for(let X of Z){if($.output!==void 0)return;if($.error)return;let Q=$.resolver(X.op);if(!Q)throw Error(`Unknown Atom: ${X.op}`);await Q.exec(X,$)}},{docs:"Sequence",timeoutMs:0,cost:0.1}),D$=v("if",I.object({condition:I.any,then:I.array(I.any),else:I.array(I.any).optional}),void 0,async(Z,$)=>{if(r(Z.condition,$))await U1.exec({op:"seq",steps:Z.then},$);else if(Z.else)await U1.exec({op:"seq",steps:Z.else},$)},{docs:"If/Else",timeoutMs:0,cost:0.1}),A$=v("while",I.object({condition:I.any,body:I.array(I.any)}),void 0,async(Z,$)=>{while(r(Z.condition,$)){if($.signal?.aborted)throw Error("Execution aborted");if(($.fuel.current-=0.1)<=0)throw Error("Out of Fuel");if(await U1.exec({op:"seq",steps:Z.body},$),$.output!==void 0)return}},{docs:"While Loop",timeoutMs:0,cost:0.1}),I$=v("return",void 0,I.any,async(Z,$)=>{if($.error)return $.output=$.error,$.error;if("value"in Z){let Q=E(Z.value,$);if(Q!==void 0&&Q!==null&&!K$(Q)&&(typeof Q!=="object"||Array.isArray(Q))){let H=new J1(`Agent must return an object, got ${Array.isArray(Q)?"array":typeof Q}`,"return");return $.error=H,$.output=H,H}return $.output=Q,Q}let X={};if(Z.schema?.properties){for(let Q of Object.keys(Z.schema.properties))X[Q]=$.state[Q];if(Z.filter!==!1){let Q=o7(X,Z.schema);if(!(Q instanceof Error))X=Q}}return $.output=X,X},{docs:"Return",cost:0.1}),R$=v("try",I.object({try:I.array(I.any),catch:I.array(I.any).optional,catchParam:I.string.optional}),void 0,async(Z,$)=>{if(await U1.exec({op:"seq",steps:Z.try},$),$.error&&Z.catch){let X=Z.catchParam||"error";$.state[X]=$.error.message,$.state.errorOp=$.error.op,$.error=void 0,await U1.exec({op:"seq",steps:Z.catch},$)}},{docs:"Try/Catch",timeoutMs:0,cost:0.1}),B$=v("Error",I.object({args:I.array(I.any).optional}),void 0,async(Z,$)=>{let X=Z.args?.[0]??"Error";$.error=new J1(String(X),"Error")},{docs:"Trigger error flow",cost:0.1}),w$=v("varSet",I.object({key:I.string,value:I.any}),void 0,async({key:Z,value:$},X)=>{if(X.consts.has(Z))throw Error(`Cannot reassign const variable '${Z}'`);X.state[Z]=E($,X)},{docs:"Set Variable",cost:0.1}),j$=v("constSet",I.object({key:I.string,value:I.any}),void 0,async({key:Z,value:$},X)=>{if(X.consts.has(Z))throw Error(`Cannot reassign const variable '${Z}'`);if(Z in X.state)throw Error(`Cannot redeclare variable '${Z}' as const`);X.state[Z]=E($,X),X.consts.add(Z)},{docs:"Set Const Variable (immutable)",cost:0.1}),M$=v("varGet",I.object({key:I.string}),I.any,async({key:Z},$)=>{return E(Z,$)},{docs:"Get Variable",cost:0.1}),F$=v("varsImport",I.object({keys:I.union([I.array(I.string),I.record(I.string)])}),void 0,async({keys:Z},$)=>{if(Array.isArray(Z))for(let X of Z)$.state[X]=E({$kind:"arg",path:X},$);else for(let[X,Q]of Object.entries(Z))$.state[X]=E({$kind:"arg",path:Q},$)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:0.2}),P$=v("varsLet",I.record(I.any),void 0,async(Z,$)=>{for(let X of Object.keys(Z)){if(X==="op"||X==="result")continue;$.state[X]=E(Z[X],$)}},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:0.1}),V$=v("varsExport",I.object({keys:I.union([I.array(I.string),I.record(I.string)])}),I.record(I.any),async({keys:Z},$)=>{let X={};if(Array.isArray(Z))for(let Q of Z)X[Q]=E(Q,$);else for(let[Q,H]of Object.entries(Z))X[Q]=E(H,$);return X},{docs:"Export variables from the current scope, with optional renaming.",cost:0.2}),C$=v("scope",I.object({steps:I.array(I.any)}),void 0,async({steps:Z},$)=>{let X=T1($);if(await U1.exec({op:"seq",steps:Z},X),X.output!==void 0)$.output=X.output},{docs:"Create new scope",timeoutMs:0,cost:0.1}),O$=v("map",I.object({items:I.array(I.any),as:I.string,steps:I.array(I.any)}),I.array(I.any),async({items:Z,as:$,steps:X},Q)=>{let H=[],K=E(Z,Q);if(!Array.isArray(K))throw Error("map: items is not an array");for(let Y of K){if(Q.signal?.aborted)throw Error("Execution aborted");let z=T1(Q);z.state[$]=Y,await U1.exec({op:"seq",steps:X},z),H.push(z.state.result??null)}return H},{docs:"Map Array",timeoutMs:0,cost:1}),N$=v("filter",I.object({items:I.array(I.any),as:I.string,condition:I.any}),I.array(I.any),async({items:Z,as:$,condition:X},Q)=>{let H=[],K=E(Z,Q);if(!Array.isArray(K))throw Error("filter: items is not an array");for(let Y of K){if(Q.signal?.aborted)throw Error("Execution aborted");let z=T1(Q);if(z.state[$]=Y,r(X,z))H.push(Y)}return H},{docs:"Filter Array",timeoutMs:0,cost:1}),E$=v("reduce",I.object({items:I.array(I.any),as:I.string,accumulator:I.string,initial:I.any,steps:I.array(I.any)}),I.any,async({items:Z,as:$,accumulator:X,initial:Q,steps:H},K)=>{let Y=E(Z,K),z=E(Q,K);if(!Array.isArray(Y))throw Error("reduce: items is not an array");let G=z;for(let J of Y){if(K.signal?.aborted)throw Error("Execution aborted");let W=T1(K);W.state[$]=J,W.state[X]=G,await U1.exec({op:"seq",steps:H},W),G=W.state.result??G}return G},{docs:"Reduce Array",timeoutMs:0,cost:1}),S$=v("find",I.object({items:I.array(I.any),as:I.string,condition:I.any}),I.any,async({items:Z,as:$,condition:X},Q)=>{let H=E(Z,Q);if(!Array.isArray(H))throw Error("find: items is not an array");for(let K of H){if(Q.signal?.aborted)throw Error("Execution aborted");let Y=T1(Q);if(Y.state[$]=K,r(X,Y))return K}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),T$=v("push",I.object({list:I.array(I.any),item:I.any}),I.array(I.any),async({list:Z,item:$},X)=>{let Q=E(Z,X),H=E($,X);if(Array.isArray(Q))Q.push(H);return Q},{docs:"Push to Array",cost:1}),k$=v("len",I.object({list:I.any}),I.number,async({list:Z},$)=>{let X=E(Z,$);return Array.isArray(X)||typeof X==="string"?X.length:0},{docs:"Length",cost:1}),g$=v("split",I.object({str:I.string,sep:I.string}),I.array(I.string),async({str:Z,sep:$},X)=>E(Z,X).split(E($,X)),{docs:"Split String",cost:1}),b$=v("join",I.object({list:I.array(I.string),sep:I.string}),I.string,async({list:Z,sep:$},X)=>E(Z,X).join(E($,X)),{docs:"Join String",cost:1}),v$=v("template",I.object({tmpl:I.string,vars:I.record(I.any)}),I.string,async({tmpl:Z,vars:$},X)=>{return E(Z,X).replace(/\{\{(\w+)\}\}/g,(H,K)=>String(E($[K],X)??""))},{docs:"String Template",cost:1}),f$=v("regexMatch",I.object({pattern:I.string,value:I.any}),I.boolean,async({pattern:Z,value:$},X)=>{if(_$(Z))throw Error(`Suspicious regex pattern rejected (potential ReDoS): ${Z}`);let Q=E($,X);return new RegExp(Z).test(Q)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),y$=v("pick",I.object({obj:I.record(I.any),keys:I.array(I.string)}),I.record(I.any),async({obj:Z,keys:$},X)=>{let Q=E(Z,X),H=E($,X),K={};if(Q&&Array.isArray(H))H.forEach((Y)=>K[Y]=Q[Y]);return K},{docs:"Pick Keys",cost:1}),h$=v("omit",I.object({obj:I.record(I.any),keys:I.array(I.string)}),I.record(I.any),async({obj:Z,keys:$},X)=>{let Q=E(Z,X),H=new Set(E($,X)),K={};if(Q)Object.keys(Q).forEach((Y)=>{if(!H.has(Y))K[Y]=Q[Y]});return K},{docs:"Omit Keys",cost:1}),x$=v("merge",I.object({a:I.record(I.any),b:I.record(I.any)}),I.record(I.any),async({a:Z,b:$},X)=>({...E(Z,X),...E($,X)}),{docs:"Merge Objects",cost:1}),u$=v("keys",I.object({obj:I.record(I.any)}),I.array(I.string),async({obj:Z},$)=>Object.keys(E(Z,$)??{}),{docs:"Object Keys",cost:1}),p7=10,n7="X-Agent-Depth";function d$(Z,$){try{let Q=new URL(Z).hostname.toLowerCase();for(let H of $){let K=H.toLowerCase();if(K.startsWith("*.")){let Y=K.slice(1);if(Q.endsWith(Y)||Q===K.slice(2))return!0}else if(Q===K)return!0}return!1}catch{return!1}}var l$=v("httpFetch",I.object({url:I.string,method:I.string.optional,headers:I.record(I.string).optional,body:I.any.optional,responseType:I.string.optional}),I.any,async(Z,$)=>{let X=E(Z.url,$),Q=E(Z.method,$),H=E(Z.headers,$)||{},K=E(Z.body,$),Y=E(Z.responseType,$),z=$.context?.requestDepth??0;if(z>=p7)throw Error(`Agent request depth exceeded (max ${p7}). This prevents recursive agent loops.`);if($.capabilities.fetch)return $.capabilities.fetch(X,{method:Q,headers:{...H,[n7]:String(z+1)},body:K,signal:$.signal,responseType:Y});let G=$.context?.allowedFetchDomains;if(G){if(!d$(X,G))throw Error(`Fetch blocked: domain not in allowlist. Allowed: ${G.join(", ")}`)}else{if(W$(X))throw Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let W=new URL(X).hostname.toLowerCase();if(W!=="localhost"&&W!=="127.0.0.1"&&W!=="[::1]")throw Error("Fetch blocked: no allowedFetchDomains configured. Set ctx.context.allowedFetchDomains or provide a custom fetch capability.")}catch(J){if(J.message.includes("allowedFetchDomains"))throw J;throw Error(`Invalid URL: ${X}`)}}if(typeof globalThis.fetch==="function"){let J=await globalThis.fetch(X,{method:Q,headers:{...H,[n7]:String(z+1)},body:K?JSON.stringify(K):void 0,signal:$.signal});if(Y==="dataUrl"){let L=await J.arrayBuffer(),_=new Uint8Array(L),U="";for(let B=0;B<_.length;B++)U+=String.fromCharCode(_[B]);let q=btoa(U);return`data:${J.headers.get("content-type")||"application/octet-stream"};base64,${q}`}let W=J.headers.get("content-type");if(Y==="json"||W&&W.includes("application/json"))return J.json();return J.text()}throw Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:30000,cost:5}),m$=v("storeGet",I.object({key:I.string}),I.any,async({key:Z},$)=>{let X=E(Z,$);return $.capabilities.store?.get(X)},{docs:"Store Get",cost:5}),i$=v("storeSet",I.object({key:I.string,value:I.any}),void 0,async({key:Z,value:$},X)=>{let Q=E(Z,X),H=E($,X);return X.capabilities.store?.set(Q,H)},{docs:"Store Set",cost:5}),p$=v("storeQuery",I.object({query:I.any}),I.array(I.any),async({query:Z},$)=>$.capabilities.store?.query?.(E(Z,$))??[],{docs:"Store Query",cost:5}),n$=v("storeVectorSearch",I.object({collection:I.string.optional,vector:I.array(I.number),k:I.number.optional}),I.array(I.any),async({collection:Z,vector:$,k:X},Q)=>Q.capabilities.store?.vectorSearch?.(E(Z,Q),E($,Q),E(X,Q))??[],{docs:"Vector Search",cost:(Z,$)=>5+(E(Z.k,$)??5)}),c$=v("llmPredict",I.object({prompt:I.string,options:I.any.optional}),I.string,async({prompt:Z,options:$},X)=>{if(!X.capabilities.llm?.predict)throw Error("Capability 'llm.predict' missing");return X.capabilities.llm.predict(E(Z,X),E($,X))},{docs:"LLM Predict",timeoutMs:120000,cost:100}),o$=v("agentRun",I.object({agentId:I.any,input:I.any}),I.any,async({agentId:Z,input:$},X)=>{let Q=E(Z,X),H=E($,X),K=H;if(H&&typeof H==="object"&&!Array.isArray(H)){K={};for(let z in H)K[z]=E(H[z],X)}if(G6(Q)){let z=J6(Q),G={...X,args:K,state:{},consts:new Set,output:void 0,error:void 0},J=X.resolver("seq");if(!J)throw Error("seq atom not found");if(await J.exec(z,G),G.error)throw Error(G.error.message||"Sub-agent failed");return G.output}if(Q&&typeof Q==="object"&&"op"in Q){let z={...X,args:K,state:{},consts:new Set,output:void 0,error:void 0},G=X.resolver("seq");if(!G)throw Error("seq atom not found");if(await G.exec(Q,z),z.error)throw Error(z.error.message||"Sub-agent failed");return z.output}if(!X.capabilities.agent?.run)throw Error("Capability 'agent.run' missing");let Y=await X.capabilities.agent.run(Q,K);if(Y&&typeof Y==="object"&&"fuelUsed"in Y&&typeof Y.fuelUsed==="number"){if(Y.error)throw Error(Y.error.message||"Sub-agent failed");return Y.result}return Y},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),s$=v("transpileCode",I.object({code:I.string}),I.any,async({code:Z},$)=>{if(!$.capabilities.code?.transpile)throw Error("Capability 'code.transpile' missing. Enable code transpilation by providing the code capability.");let X=E(Z,$);try{return $.capabilities.code.transpile(X)}catch(Q){throw Error(`Code transpilation failed: ${Q.message}`)}},{docs:"Transpile AsyncJS code to AST",cost:1}),c7=10,a$=v("runCode",I.object({code:I.string,args:I.record(I.any).optional}),I.any,async({code:Z,args:$},X)=>{let Q=X.runCodeDepth??0;if(Q>=c7)throw Error(`runCode recursion limit exceeded (max ${c7}). This prevents infinite loops from dynamically generated code calling runCode.`);if(!X.capabilities.code?.transpile)throw Error("Capability 'code.transpile' missing. Enable dynamic code execution by providing the code capability.");let H=E(Z,X),K=$?E($,X):{},Y;try{Y=X.capabilities.code.transpile(H)}catch(G){throw Error(`Code transpilation failed: ${G.message}`)}if(Y.op!=="seq")throw Error("Transpiled code must be a seq node");let z=T1(X);if(z.args=K,z.output=void 0,z.runCodeDepth=Q+1,await U1.exec(Y,z),z.error){X.error=z.error;return}return z.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),r$=v("jsonParse",I.object({str:I.string}),I.any,async({str:Z},$)=>JSON.parse(E(Z,$)),{docs:"Parse JSON",cost:1}),t$=v("jsonStringify",I.object({value:I.any}),I.string,async({value:Z},$)=>JSON.stringify(E(Z,$)),{docs:"Stringify JSON",cost:1}),e$=v("xmlParse",I.object({str:I.string}),I.any,async({str:Z},$)=>{if(!$.capabilities.xml?.parse)throw Error("Capability 'xml.parse' missing");return $.capabilities.xml.parse(E(Z,$))},{docs:"Parse XML",cost:1}),ZX=v("memoize",I.object({key:I.string.optional,steps:I.array(I.any)}),I.any,async({key:Z,steps:$},X)=>{if(!X.memo)X.memo=new Map;let Q=E(Z,X)??await W6.exec({value:$,algorithm:"SHA-256"},X);if(X.memo.has(Q))return X.memo.get(Q);let H=T1(X);await U1.exec({op:"seq",steps:$},H);let K=H.output??H.state.result;return X.memo.set(Q,K),K},{docs:"Memoize steps result in memory",cost:1}),$X=v("cache",I.object({key:I.string.optional,steps:I.array(I.any),ttlMs:I.number.optional}),I.any,async({key:Z,steps:$,ttlMs:X},Q)=>{if(!Q.capabilities.store)throw Error("Capability 'store' missing for caching");let K=`cache:${E(Z,Q)??await W6.exec({value:$,algorithm:"SHA-256"},Q)}`,Y=await Q.capabilities.store.get(K);if(Y)if(typeof Y==="object"&&Y._exp){if(Date.now()<Y._exp)return Y.val}else return Y;let z=T1(Q);await U1.exec({op:"seq",steps:$},z);let G=z.output??z.state.result,J=Date.now()+(X??86400000);if((Q.fuel.current-=5)<=0)throw Error("Out of Fuel");return await Q.capabilities.store.set(K,{val:G,_exp:J}),G},{docs:"Cache steps result in store with TTL",cost:5}),XX=v("random",I.object({min:I.number.optional,max:I.number.optional,format:I.string.optional,length:I.number.optional}),I.any,async({min:Z,max:$,format:X,length:Q},H)=>{let K=E(X,H)??"float",Y=E(Q,H)??10,z=E(Z,H)??0,G=E($,H)??1;if(K==="base36"){let U="";if(typeof crypto<"u"&&crypto.getRandomValues){let q=new Uint8Array(Y);crypto.getRandomValues(q);for(let A=0;A<Y;A++)U+="0123456789abcdefghijklmnopqrstuvwxyz"[q[A]%36]}else for(let q=0;q<Y;q++)U+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(Math.floor(Math.random()*36));return U}let J;if(typeof crypto<"u"&&crypto.getRandomValues){let _=new Uint32Array(1);crypto.getRandomValues(_),J=_[0]/4294967296}else J=Math.random();let W=G-z,L=J*W+z;if(K==="integer")return Math.floor(L);return L},{docs:"Generate Random",cost:1}),QX=v("uuid",void 0,I.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let Z=new Uint8Array(16);crypto.getRandomValues(Z),Z[6]=Z[6]&15|64,Z[8]=Z[8]&63|128;let $=Array.from(Z,(X)=>X.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(Z)=>{let $=Math.random()*16|0;return(Z==="x"?$:$&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),W6=v("hash",I.object({value:I.any,algorithm:I.string.optional}),I.string,async({value:Z,algorithm:$},X)=>{let Q=typeof Z==="string"?Z:JSON.stringify(E(Z,X)),H=E($,X)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let z=new TextEncoder().encode(Q),G=await crypto.subtle.digest(H,z);return Array.from(new Uint8Array(G)).map((W)=>W.toString(16).padStart(2,"0")).join("")}let K=0;for(let Y=0;Y<Q.length;Y++){let z=Q.charCodeAt(Y);K=(K<<5)-K+z,K|=0}return String(K)},{docs:"Hash a value",cost:1}),HX=v("consoleLog",I.object({message:I.any}),void 0,async({message:Z},$)=>{let X=E(Z,$);if($.trace)$.trace.push({op:"console.log",input:{message:X},stateDiff:{},result:X,fuelBefore:$.fuel.current,fuelAfter:$.fuel.current,timestamp:new Date().toISOString()})},{docs:"Log to trace",cost:0.1}),KX=v("consoleWarn",I.object({message:I.any}),void 0,async({message:Z},$)=>{let X=E(Z,$),Q=typeof X==="string"?X:JSON.stringify(X);if(!$.warnings)$.warnings=[];if($.warnings.push(Q),$.trace)$.trace.push({op:"console.warn",input:{message:X},stateDiff:{},result:X,fuelBefore:$.fuel.current,fuelAfter:$.fuel.current,timestamp:new Date().toISOString()})},{docs:"Add warning",cost:0.1}),YX=v("consoleError",I.object({message:I.any}),void 0,async({message:Z},$)=>{let X=E(Z,$),Q=typeof X==="string"?X:JSON.stringify(X);$.error=new J1(Q,"console.error")},{docs:"Emit error and stop",cost:0.1}),zX=v("storeProcedure",I.object({ast:I.any,ttl:I.number.optional,maxSize:I.number.optional}),I.string,async({ast:Z,ttl:$,maxSize:X},Q)=>{let H=E(Z,Q),K=$?E($,Q):Y$,Y=X?E(X,Q):z$;if(!H||typeof H!=="object"||!H.op)throw Error('Invalid AST: must be an object with an "op" property');let z=JSON.stringify(H);if(z.length>Y)throw Error(`AST too large: ${z.length} bytes exceeds limit of ${Y} bytes. Consider reducing AST size or using a shorter TTL.`);let G=G$(),J=Date.now();return $0.set(G,{ast:H,createdAt:J,expiresAt:J+K}),G},{docs:"Store an AST and return a token for later execution",cost:1}),GX=v("releaseProcedure",I.object({token:I.string}),I.boolean,async({token:Z},$)=>{let X=E(Z,$);return $0.delete(X)},{docs:"Release a stored procedure by token",cost:0.1}),JX=v("clearExpiredProcedures",void 0,I.number,async()=>{let Z=Date.now(),$=0;for(let[X,Q]of $0)if(Z>Q.expiresAt)$0.delete(X),$++;return $},{docs:"Clear all expired procedures and return count",cost:0.5}),R4={seq:U1,if:D$,while:A$,return:I$,try:R$,Error:B$,varSet:w$,constSet:j$,varGet:M$,varsImport:F$,varsLet:P$,varsExport:V$,scope:C$,map:O$,filter:N$,reduce:E$,find:S$,push:T$,len:k$,split:g$,join:b$,template:v$,regexMatch:f$,pick:y$,omit:h$,merge:x$,keys:u$,httpFetch:l$,storeGet:m$,storeSet:i$,storeQuery:p$,storeVectorSearch:n$,llmPredict:c$,agentRun:o$,transpileCode:s$,runCode:a$,jsonParse:r$,jsonStringify:t$,xmlParse:e$,memoize:ZX,cache:$X,random:XX,uuid:QX,hash:W6,consoleLog:HX,consoleWarn:KX,consoleError:YX,storeProcedure:zX,releaseProcedure:GX,clearExpiredProcedures:JX};var WX=new Set(["true","false","null","undefined","and","or","not"]);function _X(Z,$){let X=Z.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),Q=[],H=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,K;while((K=H.exec(X))!==null)Q.push(K[1]);let z=[...new Set(Q)].filter((G)=>!WX.has(G)&&!(G in $)&&!new RegExp(`\\b${G}\\s*\\(`).test(X));if(z.length>0)console.warn(`[Agent99 Builder] Condition "${Z}" references variables not in vars mapping: ${z.join(", ")}. Add them to vars or use AsyncJS syntax (ajs\`...\`) which handles this automatically.`)}function B4(Z,$){_X(Z,$);let X=LX(Z),Q=Z8(X,0,$);if(Q.pos<X.length){let H=X.slice(Q.pos).join(" ");throw Error(`Unsupported condition syntax near '${H}' in: ${Z}
430
- Supported: comparisons, &&, ||, !, arithmetic, member access (a.b), literals`)}return Q.node}function LX(Z){let $=[],X=0;while(X<Z.length){while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)break;if(Z[X]==='"'||Z[X]==="'"){let Q=Z[X++],H="";while(X<Z.length&&Z[X]!==Q)if(Z[X]==="\\"&&X+1<Z.length)X++,H+=Z[X++];else H+=Z[X++];X++,$.push(JSON.stringify(H));continue}if(Z.slice(X,X+2).match(/^(&&|\|\||==|!=|>=|<=)$/)){$.push(Z.slice(X,X+2)),X+=2;continue}if("+-*/%><!().?:[]".includes(Z[X])){$.push(Z[X]),X++;continue}if(/\d/.test(Z[X])){let Q="";while(X<Z.length&&/[\d.]/.test(Z[X]))Q+=Z[X++];$.push(Q);continue}if(/[a-zA-Z_]/.test(Z[X])){let Q="";while(X<Z.length&&/[a-zA-Z0-9_]/.test(Z[X]))Q+=Z[X++];$.push(Q);continue}X++}return $}function Z8(Z,$,X){return UX(Z,$,X)}function UX(Z,$,X){let{node:Q,pos:H}=a7(Z,$,X);while(Z[H]==="||"){H++;let{node:K,pos:Y}=a7(Z,H,X);Q={$expr:"logical",op:"||",left:Q,right:K},H=Y}return{node:Q,pos:H}}function a7(Z,$,X){let{node:Q,pos:H}=r7(Z,$,X);while(Z[H]==="&&"){H++;let{node:K,pos:Y}=r7(Z,H,X);Q={$expr:"logical",op:"&&",left:Q,right:K},H=Y}return{node:Q,pos:H}}function r7(Z,$,X){let{node:Q,pos:H}=t7(Z,$,X),K=["==","!=",">","<",">=","<="];while(K.includes(Z[H])){let Y=Z[H++],{node:z,pos:G}=t7(Z,H,X);Q={$expr:"binary",op:Y,left:Q,right:z},H=G}return{node:Q,pos:H}}function t7(Z,$,X){let{node:Q,pos:H}=e7(Z,$,X);while(Z[H]==="+"||Z[H]==="-"){let K=Z[H++],{node:Y,pos:z}=e7(Z,H,X);Q={$expr:"binary",op:K,left:Q,right:Y},H=z}return{node:Q,pos:H}}function e7(Z,$,X){let{node:Q,pos:H}=_6(Z,$,X);while(Z[H]==="*"||Z[H]==="/"||Z[H]==="%"){let K=Z[H++],{node:Y,pos:z}=_6(Z,H,X);Q={$expr:"binary",op:K,left:Q,right:Y},H=z}return{node:Q,pos:H}}function _6(Z,$,X){if(Z[$]==="!"||Z[$]==="-"){let Q=Z[$++],{node:H,pos:K}=_6(Z,$,X);return{node:{$expr:"unary",op:Q,argument:H},pos:K}}return qX(Z,$,X)}function qX(Z,$,X){let Q=Z[$];if(Q==="("){let{node:H,pos:K}=Z8(Z,$+1,X);return{node:H,pos:K+1}}if(Q&&Q.startsWith('"'))return{node:{$expr:"literal",value:JSON.parse(Q)},pos:$+1};if(Q&&/^\d/.test(Q))return{node:{$expr:"literal",value:parseFloat(Q)},pos:$+1};if(Q==="true")return{node:{$expr:"literal",value:!0},pos:$+1};if(Q==="false")return{node:{$expr:"literal",value:!1},pos:$+1};if(Q==="null")return{node:{$expr:"literal",value:null},pos:$+1};if(Q&&/^[a-zA-Z_]/.test(Q)){let H={$expr:"ident",name:Q},K=$+1;while(Z[K]==="."){K++;let Y=Z[K++];H={$expr:"member",object:H,property:Y}}return{node:H,pos:K}}return{node:{$expr:"literal",value:null},pos:$+1}}class H1{steps=[];atoms;proxy;constructor(Z){return this.atoms=Z,this.proxy=new Proxy(this,{get:($,X,Q)=>{if(X in $)return $[X];if(typeof X==="string"&&X in $.atoms)return(H)=>{let K=$.atoms[X];return $.add(K.create(H)),Q};return}}),this.proxy}add(Z){return this.steps.push(Z),this.proxy}as(Z){if(this.steps.length===0)throw Error("No step to capture");let $=this.steps[this.steps.length-1];return $.result=Z,this.proxy}step(Z){return this.add(Z)}return(Z){let $=this.atoms.return;if(!$)throw Error("Atom 'return' not found");let X=Z.schema??Z;return this.add($.create({schema:X}))}toJSON(){return{op:"seq",steps:[...this.steps]}}varsImport(Z){return this.add(this.atoms.varsImport.create({keys:Z}))}varsExport(Z){return this.add(this.atoms.varsExport.create({keys:Z}))}if(Z,$,X,Q){let H=new H1(this.atoms);X(H);let K;if(Q){let G=new H1(this.atoms);Q(G),K=G.steps}let Y=B4(Z,$),z=this.atoms.if;return this.add(z.create({condition:Y,then:H.steps,else:K}))}while(Z,$,X){let Q=new H1(this.atoms);X(Q);let H=B4(Z,$),K=this.atoms.while;return this.add(K.create({condition:H,body:Q.steps}))}scope(Z){let $=new H1(this.atoms);Z($);let X=this.atoms.scope;return this.add(X.create({steps:$.steps}))}map(Z,$,X){let Q=new H1(this.atoms);X(Q);let H=this.atoms.map;return this.add(H.create({items:Z,as:$,steps:Q.steps}))}filter(Z,$,X,Q={}){let H=B4(X,Q),K=this.atoms.filter;return this.add(K.create({items:Z,as:$,condition:H}))}find(Z,$,X,Q={}){let H=B4(X,Q),K=this.atoms.find;return this.add(K.create({items:Z,as:$,condition:H}))}reduce(Z,$,X,Q,H){let K=new H1(this.atoms);H(K);let Y=this.atoms.reduce;return this.add(Y.create({items:Z,as:$,accumulator:X,initial:Q,steps:K.steps}))}memoize(Z,$){let X=new H1(this.atoms);Z(X);let Q=this.atoms.memoize;return this.add(Q.create({key:$,steps:X.steps}))}cache(Z,$,X){let Q=new H1(this.atoms);Z(Q);let H=this.atoms.cache;return this.add(H.create({key:$,steps:Q.steps,ttlMs:X}))}try(Z){let $=new H1(this.atoms);Z.try($);let X;if(Z.catch){let H=new H1(this.atoms);Z.catch(H),X=H.steps}let Q=this.atoms.try;return this.add(Q.create({try:$.steps,catch:X}))}}var DX={take(Z){return new H1(R4)},custom(Z){return new H1(Z)},args(Z){return{$kind:"arg",path:Z}},val(Z){return Z}},cH=DX;import{validate as AX}from"tosijs-schema";function P0(Z,$={}){let{ast:X,returnType:Q,originalSource:H,requiredParams:K}=F1(Z,{filename:$.filename,colonShorthand:!0,vmTarget:!0}),Y=h0(X,$.filename),{ast:z,signature:G,warnings:J}=U0(Y,H,Q,$,K);return{ast:z,signature:G,warnings:J}}var IX=10;class L6{atoms;constructor(Z={}){this.atoms={...R4,...Z}}get builder(){return new H1(this.atoms)}get Agent(){return new H1(this.atoms)}get A99(){return this.Agent}resolve(Z){return this.atoms[Z]}getTools(Z="all"){let $=Object.values(this.atoms);if(Array.isArray(Z))$=$.filter((X)=>Z.includes(X.op));else if(Z==="flow"){let X=["seq","if","while","return","try","varSet","varGet","scope"];$=$.filter((Q)=>X.includes(Q.op))}return $.map((X)=>({type:"function",function:{name:X.op,description:X.docs,parameters:X.inputSchema?.schema??{}}}))}async run(Z,$={},X={}){let Q;if(typeof Z==="string")if(G6(Z))Q=J6(Z);else try{Q=P0(Z).ast}catch(U){throw Error(`AJS transpilation failed: ${U.message}`)}else Q=Z;let H=X.fuel??1000,K=X.timeoutMs??H*IX,Y=X.capabilities??{},z=[];if(!Y.store){let U=new Map,q=!1;Y.store={get:async(A)=>{if(!q)q=!0,z.push("Using default in-memory store (not suitable for production)");return U.get(A)},set:async(A,B)=>{if(!q)q=!0,z.push("Using default in-memory store (not suitable for production)");U.set(A,B)}}}let G=new AbortController,J=setTimeout(()=>G.abort(),K);if(X.signal)X.signal.addEventListener("abort",()=>G.abort());let W={fuel:{current:H},args:$,state:{},consts:new Set,capabilities:Y,resolver:(U)=>this.resolve(U),output:void 0,signal:G.signal,costOverrides:X.costOverrides,context:X.context,warnings:z};if(X.trace)W.trace=[];if(Q.op!=="seq")throw Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let L=Q.inputSchema;if(L&&!AX($,L)){let U=new J1("Input validation failed: args do not match expected schema","vm.run");return{result:U,error:U,fuelUsed:0,trace:W.trace,warnings:z.length>0?z:void 0}}try{await Promise.race([this.resolve("seq")?.exec(Q,W),new Promise((U,q)=>{if(G.signal.addEventListener("abort",()=>{q(Error(`Execution timeout after ${K}ms (fuel: ${H}). Consider increasing fuel or optimizing your agent.`))}),G.signal.aborted)q(Error(`Execution timeout after ${K}ms (fuel: ${H}). Consider increasing fuel or optimizing your agent.`))})])}catch(U){if(U.message?.includes("timeout")||U.message?.includes("aborted")||G.signal.aborted)W.error=new J1(`Execution timeout after ${K}ms (fuel: ${H}). Consider increasing fuel or optimizing your agent.`,"vm.run");else throw U}finally{clearTimeout(J)}if(W.error&&W.output===void 0)W.output=W.error;let _=[...z,...W.warnings??[]];return{result:W.output,error:W.error,fuelUsed:H-W.fuel.current,trace:W.trace,warnings:_.length>0?_:void 0}}}var RX=null,$8=()=>RX??=new L6;function i1(Z){if(!Z||typeof Z!=="object")return;if(Array.isArray(Z)){for(let $ of Z)i1($);return}if(Z.op==="return"&&"value"in Z)Z.value={__result:Z.value};if(Z.steps)i1(Z.steps);if(Z.then)i1(Z.then);if(Z.else)i1(Z.else);if(Z.body)i1(Z.body)}async function BX(Z){let{code:$,context:X={},fuel:Q=1000,timeoutMs:H,capabilities:K={}}=Z,Y=$8(),G=/\breturn\b/.test($)?`function __eval() { ${$} }`:`function __eval() { return (${$}) }`;try{let{ast:J}=P0(G);i1(J);let W=await Y.run(J,X,{fuel:Q,timeoutMs:H,capabilities:K}),L=W.result;return{result:L&&typeof L==="object"&&"__result"in L?L.__result:L,fuelUsed:W.fuelUsed,error:W.error?{message:W.error.message||String(W.error)}:void 0}}catch(J){return{result:void 0,fuelUsed:Q,error:{message:J.message||String(J)}}}}async function wX(Z){let{body:$,params:X=[],fuel:Q=1000,timeoutMs:H,capabilities:K={}}=Z,Y=$8(),G=`function __safeFn(${X.join(", ")}) { ${$} }`,{ast:J}=P0(G);return i1(J),async(...W)=>{let L={};for(let _=0;_<X.length;_++)L[X[_]]=W[_];try{let _=await Y.run(J,L,{fuel:Q,timeoutMs:H,capabilities:K}),U=_.result;return{result:U&&typeof U==="object"&&"__result"in U?U.__result:U,fuelUsed:_.fuelUsed,error:_.error?{message:_.error.message||String(_.error)}:void 0}}catch(_){return{result:void 0,fuelUsed:Q,error:{message:_.message||String(_)}}}}}function j4(Z,$={}){let{ast:X,returnType:Q,originalSource:H,requiredParams:K}=F1(Z,{filename:$.filename,colonShorthand:!0,vmTarget:!0}),Y=h0(X,$.filename),{ast:z,signature:G,warnings:J}=U0(Y,H,Q,$,K);return{ast:z,signature:G,warnings:J}}function _K(Z,...$){if(typeof Z==="string")return j4(Z).ast;let X=Z.reduce((Q,H,K)=>Q+H+($[K]!==void 0?String($[K]):""),"");return j4(X).ast}function UK(Z,$,...X){if(typeof Z==="string")return M0(Z,$);let Q=$!==void 0?[$,...X]:X,H=Z.reduce((K,Y,z)=>K+Y+(Q[z]!==void 0?String(Q[z]):""),"");return M0(H)}async function qK(Z,$={},X){let Q=X??await U4(),H=await Q.getTranspile(Z);if(H)return{ast:H.ast,signature:H.signature,warnings:H.warnings};let K=j4(Z,$);return Q.setTranspile(Z,{ast:K.ast,signature:K.signature,warnings:K.warnings}),K}async function DK(Z,$={},X){let Q=X??await U4(),H=await Q.getTJS(Z);if(H)return{code:H.code,types:H.types,metadata:H.types,testRunner:H.testRunner,testCount:H.testCount,warnings:H.warnings};let K=M0(Z,$);return Q.setTJS(Z,{code:K.code,types:K.types,testRunner:K.testRunner,testCount:K.testCount,warnings:K.warnings}),K}function AK(Z,$,X){let{ast:Q,signature:H}=j4(Z),K=async(Y)=>{return(await $.run(Q,Y,X)).result};return K.signature=H,K.ast=Q,K}function IK(Z){return Object.entries(Z).map(([$,X])=>{let Q=X.signature,H={},K=[];for(let[Y,z]of Object.entries(Q.parameters)){if(H[Y]=w4(z.type),z.description)H[Y].description=z.description;if(z.required)K.push(Y)}return{type:"function",function:{name:Q.name||$,description:Q.description,parameters:{type:"object",properties:H,required:K}}}})}function w4(Z){switch(Z.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:Z.items?w4(Z.items):{}};case"object":if(!Z.shape)return{type:"object"};return{type:"object",properties:Object.fromEntries(Object.entries(Z.shape).map(([$,X])=>[$,w4(X)]))};case"union":if(!Z.members)return{};return{anyOf:Z.members.map(w4)};case"any":default:return{}}}import{s as h}from"tosijs-schema";var X8=v("storeVectorize",h.object({text:h.string,model:h.string.optional}),h.array(h.number),async({text:Z},$)=>{let X=$.capabilities.vector;if(!X)throw Error("Capability 'vector' missing. Ensure vector battery is loaded.");let Q=E(Z,$);return X.embed(Q)},{docs:"Generate embeddings using vector battery",cost:20}),Q8=v("storeCreateCollection",h.object({collection:h.string,dimension:h.number.optional}),void 0,async({collection:Z,dimension:$},X)=>{let Q=X.capabilities.store;if(!Q?.createCollection)throw Error("Capability 'store' missing or does not support createCollection.");let H=E(Z,X),K=E($,X);return Q.createCollection(H,void 0,K)},{docs:"Create a vector store collection",cost:5}),H8=v("storeVectorAdd",h.object({collection:h.string,doc:h.any}),void 0,async({collection:Z,doc:$},X)=>{let Q=X.capabilities.store;if(!Q?.vectorAdd)throw Error("Capability 'store' missing or does not support vectorAdd.");let H=E(Z,X),K=E($,X);return Q.vectorAdd(H,K)},{docs:"Add a document to a vector store collection",cost:5}),K8=v("storeSearch",h.object({collection:h.string,queryVector:h.array(h.number),k:h.number.optional,filter:h.record(h.any).optional}),h.array(h.any),async({collection:Z,queryVector:$,k:X,filter:Q},H)=>{let K=H.capabilities.store;if(!K?.vectorSearch)throw Error("Capability 'store' missing or does not support vectorSearch.");let Y=E(Z,H),z=E($,H),G=E(X,H)??5,J=E(Q,H);return K.vectorSearch(Y,z,G,J)},{docs:"Search vector store",cost:(Z,$)=>5+(E(Z.k,$)??5)}),Y8=v("llmPredictBattery",h.object({system:h.string.optional,user:h.string,tools:h.array(h.any).optional,responseFormat:h.any.optional}),h.object({role:h.string.optional,content:h.string.optional,tool_calls:h.array(h.any).optional}),async({system:Z,user:$,tools:X,responseFormat:Q},H)=>{let K=H.capabilities.llmBattery;if(!K?.predict)throw Error("Capability 'llmBattery' missing or invalid.");let Y=E(Z,H)??"You are a helpful agent.",z=E($,H),G=E(X,H),J=E(Q,H);return K.predict(Y,z,G,J)},{docs:"Generate completion using LLM battery",cost:100}),z8=v("llmVision",h.object({system:h.string.optional,prompt:h.string,images:h.array(h.string),responseFormat:h.any.optional}),h.object({role:h.string.optional,content:h.string.optional,tool_calls:h.array(h.any).optional}),async({system:Z,prompt:$,images:X,responseFormat:Q},H)=>{let K=H.capabilities.llmBattery;if(!K?.predict)throw Error("Capability 'llmBattery' missing or invalid.");let Y=E(Z,H)??"You analyze images accurately and concisely.",z=E($,H),G=E(X,H)??[],J=E(Q,H);return K.predict(Y,{text:z,images:G},void 0,J)},{docs:"Analyze images using a vision model",timeoutMs:120000,cost:150});var xK={storeCreateCollection:Q8,storeSearch:K8,storeVectorAdd:H8,storeVectorize:X8,llmPredictBattery:Y8,llmVision:z8};var G8=new Map,M4=new Map;function jX(Z,$){if(Z.length!==$.length)throw Error("Vectors must have the same length for cosine similarity.");let X=0,Q=0,H=0;for(let K=0;K<Z.length;K++)X+=Z[K]*$[K],Q+=Z[K]*Z[K],H+=$[K]*$[K];if(Q=Math.sqrt(Q),H=Math.sqrt(H),Q===0||H===0)return 0;return X/(Q*H)}function U6(){return{async get(Z){return G8.get(Z)},async set(Z,$){G8.set(Z,$)},async createCollection(Z,$,X){if(M4.has(Z))console.warn(`Collection '${Z}' already exists. Overwriting.`);M4.set(Z,[])},async vectorAdd(Z,$){let X=M4.get(Z);if(!X)throw Error(`Collection '${Z}' not found. Create it first.`);if(!$.embedding||!Array.isArray($.embedding))throw Error("Document must have an 'embedding' property that is an array of numbers.");X.push($)},async vectorSearch(Z,$,X=5){let Q=M4.get(Z);if(!Q)throw Error(`Collection '${Z}' not found. Create it first.`);let H=Q.map((K)=>({doc:K,score:jX($,K.embedding)}));return H.sort((K,Y)=>Y.score-K.score),H.slice(0,X).map((K)=>K.doc)}}}function MX(Z){if(typeof Z==="string")return{role:"user",content:Z};let $=[{type:"text",text:Z.text}];for(let X of Z.images||[])$.push({type:"image_url",image_url:{url:X}});return{role:"user",content:$}}var FX="http://localhost:1234/v1";function J8(Z,$=FX){return{async predict(X,Q,H,K){try{let Y=K?Z.getStructuredLLM():Z.getLLM(),z=[{role:"system",content:X},MX(Q)],G=await fetch(`${$}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Y.id,messages:z,temperature:0.7,tools:H,response_format:K})});if(!G.ok)throw Error(`LLM Error: ${G.status} ${G.statusText}`);return(await G.json()).choices[0]?.message??{content:""}}catch(Y){if(Y.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw Y}},async embed(X){try{let Q=Z.getEmbedding(),H=await fetch(`${$}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Q.id,input:X})});if(!H.ok)throw Error(`Embedding Error: ${H.status}`);return(await H.json()).data[0]?.embedding??[]}catch(Q){if(Q.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw Q}}}}var V0=typeof window<"u"&&typeof window.localStorage<"u";async function CX(Z){try{if(V0){let $=window.localStorage.getItem(".models.cache.json");if(!$)return null;let X=JSON.parse($);if(X.baseUrl!==Z)return null;if(Date.now()-X.timestamp>86400000)return null;return X.models}else{let $=await import("node:fs/promises"),Q=(await Promise.resolve().then(() => (A6(),D6))).join(process.cwd(),".models.cache.json");try{let H=await $.readFile(Q,"utf-8"),K=JSON.parse(H);if(K.baseUrl!==Z)return null;if(Date.now()-K.timestamp>86400000)return null;return K.models}catch{return null}}}catch($){return console.warn("⚠️ Error reading model cache:",$),null}}async function OX(Z,$){let X={timestamp:Date.now(),baseUrl:Z,models:$};try{if(V0)window.localStorage.setItem(".models.cache.json",JSON.stringify(X));else{let Q=await import("node:fs/promises"),K=(await Promise.resolve().then(() => (A6(),D6))).join(process.cwd(),".models.cache.json");await Q.writeFile(K,JSON.stringify(X,null,2))}}catch(Q){console.error("❌ Error writing model cache:",Q)}}var C0=async(Z,$)=>{let X=new AbortController,Q=setTimeout(()=>X.abort(),60000);try{let H=await fetch(Z,{...$,signal:X.signal});return clearTimeout(Q),H}catch(H){throw clearTimeout(Q),H}};async function NX(Z,$){try{let X={type:"json_schema",json_schema:{name:"test",strict:!1,schema:{type:"object",properties:{status:{type:"string"}}}}},Q=await C0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"system",content:"You respond in JSON."},{role:"user",content:'Return JSON: {"status": "ok"}'}],response_format:X,max_tokens:20})});if(!Q.ok){if(Q.status===400)return EX(Z,$);return{ok:!1,msg:`HTTP ${Q.status}`}}let H=await Q.json();return JSON.parse(H.choices[0].message.content),{ok:!0,msg:"OK (Schema)"}}catch(X){return{ok:!1,msg:X.message||"Error"}}}async function EX(Z,$){try{if((await C0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:'JSON: {"a":1}'}],response_format:{type:"json_object"},max_tokens:10})})).ok)return{ok:!0,msg:"OK (Legacy Mode)"};return{ok:!1,msg:"Not Supported"}}catch{return{ok:!1,msg:"Legacy Fail"}}}async function SX(Z,$){try{return(await C0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:"hi"}],max_tokens:1})})).ok}catch{return!1}}async function TX(Z,$){try{let X=await C0(`${Z}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,input:"test"})});if(!X.ok)return null;return(await X.json()).data[0]?.embedding?.length??null}catch{return null}}var kX="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";async function gX(Z,$){try{return(await C0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:[{type:"text",text:"What color is this?"},{type:"image_url",image_url:{url:kX}}]}],max_tokens:10})})).ok}catch{return!1}}async function F8(Z){let $=await CX(Z),X=[];try{let Y=await fetch(`${Z}/models`);if(!Y.ok)throw Error("Could not connect");X=(await Y.json()).data.map((G)=>G.id).sort()}catch(Y){if($)return console.log("⚠️ LM Studio unavailable, using cached model audit."),$;return console.error("❌ Failed to connect to LM Studio."),[]}if($){let Y=$.map((z)=>z.id).sort();if(JSON.stringify(X)===JSON.stringify(Y))return console.log("✅ Using cached model audit."),$;console.log("\uD83D\uDD0D Model list changed. Re-running audit...")}console.log("\uD83D\uDD0D Scanning models (this may take a moment)...");let Q=[],H=X.map((Y)=>({id:Y})),K;if(!V0)K=await import("node:readline");for(let Y of H){if(!V0&&K)K.cursorTo(process.stdout,0),process.stdout.write(`\uD83D\uDC49 Testing: ${Y.id}...`),K.clearLine(process.stdout,1);let z="Unknown",G=!1,J=!1,W="",L=void 0,_=await SX(Z,Y.id),U=await TX(Z,Y.id);if(U)L=U;if(_){z="LLM";let q=await NX(Z,Y.id);if(G=q.ok,J=await gX(Z,Y.id),W=G?q.msg:`Fail: ${q.msg}`,J)W+=" +Vision"}else if(U)z="Embedding",W=`OK (Dim: ${U})`;else W="LLM Fail";Q.push({id:Y.id,type:z,structuredOutput:G,vision:J,dimension:L,status:W})}if(!V0&&K)K.cursorTo(process.stdout,0),K.clearLine(process.stdout,0);return console.log(`
431
- `),console.table(Q),await OX(Z,Q),console.log("\uD83D\uDCDD Audit results saved to cache."),Q}var bX="http://localhost:1234/v1";class I6{baseUrl;models=[];defaultLLM=null;defaultEmbedding=null;defaultStructuredLLM=null;constructor(Z=bX){this.baseUrl=Z}async audit(){this.models=await F8(this.baseUrl),this.selectDefaults()}selectDefaults(){if(this.defaultEmbedding=this.models.find((Z)=>Z.type==="Embedding")||null,this.defaultLLM=this.models.find((Z)=>Z.type==="LLM")||null,this.defaultStructuredLLM=this.models.find((Z)=>Z.type==="LLM"&&Z.structuredOutput)||null,!this.defaultEmbedding)console.warn("⚠️ No embedding model found.");if(!this.defaultLLM)console.warn("⚠️ No LLM found.");if(!this.defaultStructuredLLM)console.warn("⚠️ No LLM with structured output support found.")}getModels(){return this.models}_setDefaultModel(Z,$,X,Q){let H=this.models.find((K)=>K.id===Z&&X(K));if(!H)throw Error(`Model '${Z}' not found or is not ${Q}.`);this[$]=H}setDefaultLLM(Z){this._setDefaultModel(Z,"defaultLLM",($)=>$.type==="LLM","an LLM")}setDefaultEmbedding(Z){this._setDefaultModel(Z,"defaultEmbedding",($)=>$.dimension!==void 0,"an embedding model")}setDefaultStructuredLLM(Z){this._setDefaultModel(Z,"defaultStructuredLLM",($)=>$.type==="LLM"&&$.structuredOutput,"a structured-output LLM")}getLLM(){if(!this.defaultLLM)throw Error("No LLM available.");return this.defaultLLM}getEmbedding(){if(!this.defaultEmbedding)throw Error("No embedding model available.");return this.defaultEmbedding}getStructuredLLM(){if(!this.defaultStructuredLLM)throw Error("No structured-output LLM available.");return this.defaultStructuredLLM}}var vX=typeof window<"u",fX=vX&&window.location.protocol==="https:",O0=null,R6=null,P8=!1;async function yX(){if(P8)return{localModels:O0,llm:R6};if(P8=!0,fX)return console.log("\uD83D\uDCE1 HTTPS detected - local LLM endpoints disabled. Use HTTP for local LLM support."),{localModels:null,llm:null};try{O0=new I6,await O0.audit(),R6=J8(O0)}catch(Z){console.warn("⚠️ Could not connect to local LLM:",Z)}return{localModels:O0,llm:R6}}async function hX(){let{localModels:Z,llm:$}=await yX();return{vector:$?{embed:$.embed}:void 0,store:U6(),llmBattery:$,models:Z}}async function sK(){return hX()}var aK={store:U6(),llmBattery:null,vector:void 0,models:null};function xX(Z){if(typeof Z!=="string")return!1;let $=new Date(Z);return!isNaN($.getTime())&&Z.includes("T")}function uX(){return new Date().toISOString()}function X0(Z,$,X,Q=0,H=0,K=0,Y=0){return new Date(Date.UTC(Z,$-1,X,Q,H,K,Y)).toISOString()}function V8(Z){let $=new Date(Z);if(isNaN($.getTime()))throw Error(`Invalid date string: ${Z}`);return $.toISOString()}function dX(Z){try{return V8(Z)}catch{return null}}function N0(Z,$){let X=new Date(Z);return X.setTime(X.getTime()+$),X.toISOString()}function lX(Z,$){return N0(Z,$*1000)}function mX(Z,$){return N0(Z,$*60*1000)}function iX(Z,$){return N0(Z,$*60*60*1000)}function C8(Z,$){return N0(Z,$*24*60*60*1000)}function pX(Z,$){return C8(Z,$*7)}function nX(Z,$){let X=new Date(Z),Q=X.getUTCMonth()+$;if(X.setUTCMonth(Q),X.getUTCMonth()!==(Q%12+12)%12)X.setUTCDate(0);return X.toISOString()}function cX(Z,$){let X=new Date(Z),Q=X.getUTCDate();if(X.setUTCFullYear(X.getUTCFullYear()+$),X.getUTCDate()!==Q)X.setUTCDate(0);return X.toISOString()}function k1(Z,$){return new Date(Z).getTime()-new Date($).getTime()}function oX(Z,$){return Math.floor(k1(Z,$)/1000)}function sX(Z,$){return Math.floor(k1(Z,$)/60000)}function aX(Z,$){return Math.floor(k1(Z,$)/3600000)}function rX(Z,$){return Math.floor(k1(Z,$)/86400000)}function Q0(Z){return new Date(Z).getUTCFullYear()}function P4(Z){return new Date(Z).getUTCMonth()+1}function B6(Z){return new Date(Z).getUTCDate()}function tX(Z){return new Date(Z).getUTCHours()}function eX(Z){return new Date(Z).getUTCMinutes()}function ZQ(Z){return new Date(Z).getUTCSeconds()}function $Q(Z){return new Date(Z).getUTCMilliseconds()}function XQ(Z){let $=new Date(Z).getUTCDay();return $===0?7:$}function V4(Z,$,X){let Q=new Date(Z),H={timeZone:$,...X};return new Intl.DateTimeFormat(void 0,H).format(Q)}function QQ(Z,$){return V4(Z,$,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function HQ(Z,$){return V4(Z,$,{year:"numeric",month:"short",day:"numeric"})}function KQ(Z,$){return V4(Z,$,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function YQ(Z){return Z.slice(0,10)}function O8(Z,$){return k1(Z,$)<0}function N8(Z,$){return k1(Z,$)>0}function zQ(Z,$){return k1(Z,$)===0}function GQ(Z,$){return O8(Z,$)?Z:$}function JQ(Z,$){return N8(Z,$)?Z:$}function WQ(Z){return X0(Q0(Z),P4(Z),B6(Z))}function _Q(Z){return X0(Q0(Z),P4(Z),B6(Z),23,59,59,999)}function LQ(Z){return X0(Q0(Z),P4(Z),1)}function UQ(Z){let $=new Date(Z);return $.setUTCMonth($.getUTCMonth()+1,0),$.setUTCHours(23,59,59,999),$.toISOString()}function qQ(Z){return X0(Q0(Z),1,1)}function DQ(Z){return X0(Q0(Z),12,31,23,59,59,999)}var H0={isValid:xX,now:uX,from:X0,parse:V8,tryParse:dX,addMilliseconds:N0,addSeconds:lX,addMinutes:mX,addHours:iX,addDays:C8,addWeeks:pX,addMonths:nX,addYears:cX,diff:k1,diffSeconds:oX,diffMinutes:sX,diffHours:aX,diffDays:rX,year:Q0,month:P4,day:B6,hour:tX,minute:eX,second:ZQ,millisecond:$Q,dayOfWeek:XQ,toLocal:V4,format:QQ,formatDate:HQ,formatTime:KQ,toDate:YQ,isBefore:O8,isAfter:N8,isEqual:zQ,min:GQ,max:JQ,startOfDay:WQ,endOfDay:_Q,startOfMonth:LQ,endOfMonth:UQ,startOfYear:qQ,endOfYear:DQ};function w6(Z){if(typeof Z!=="string")return!1;if(!/^\d{4}-\d{2}-\d{2}$/.test(Z))return!1;let $=parseInt(Z.slice(0,4),10),X=parseInt(Z.slice(5,7),10),Q=parseInt(Z.slice(8,10),10);if(X<1||X>12)return!1;if(Q<1)return!1;let H=[31,28,31,30,31,30,31,31,30,31,30,31],K=X===2&&($%4===0&&$%100!==0||$%400===0)?29:H[X-1];return Q<=K}function AQ(){return H0.toDate(H0.now())}function IQ(Z){let $=new Date;return new Intl.DateTimeFormat("en-CA",{timeZone:Z,year:"numeric",month:"2-digit",day:"2-digit"}).format($)}function q1(Z,$,X){let Q=String(Z).padStart(4,"0"),H=String($).padStart(2,"0"),K=String(X).padStart(2,"0"),Y=`${Q}-${H}-${K}`;if(!w6(Y))throw Error(`Invalid date: ${Z}-${$}-${X}`);return Y}function E8(Z){if(/^\d{4}-\d{2}-\d{2}$/.test(Z)){if(!w6(Z))throw Error(`Invalid date: ${Z}`);return Z}let $=new Date(Z);if(isNaN($.getTime()))throw Error(`Invalid date string: ${Z}`);let X=$.getUTCFullYear(),Q=$.getUTCMonth()+1,H=$.getUTCDate();return q1(X,Q,H)}function RQ(Z){try{return E8(Z)}catch{return null}}function C4(Z,$){let X=T8(Z);return H0.toDate(H0.addDays(X,$))}function BQ(Z,$){return C4(Z,$*7)}function wQ(Z,$){let X=Y1(Z),Q=g1(Z),H=j6(Z),K=X*12+(Q-1)+$,Y=Math.floor(K/12),z=K%12+1,G=E0(Y,z),J=Math.min(H,G);return q1(Y,z,J)}function jQ(Z,$){let X=Y1(Z),Q=g1(Z),H=j6(Z),K=X+$,Y=E0(K,Q),z=Math.min(H,Y);return q1(K,Q,z)}function S8(Z,$){let Q=new Date(Z+"T00:00:00Z").getTime(),H=new Date($+"T00:00:00Z").getTime();return Math.round((Q-H)/86400000)}function MQ(Z,$){let X=Y1(Z),Q=g1(Z),H=Y1($),K=g1($);return(X-H)*12+(Q-K)}function FQ(Z,$){return Y1(Z)-Y1($)}function Y1(Z){return parseInt(Z.slice(0,4),10)}function g1(Z){return parseInt(Z.slice(5,7),10)}function j6(Z){return parseInt(Z.slice(8,10),10)}function M6(Z){let $=new Date(Z+"T00:00:00Z").getUTCDay();return $===0?7:$}function PQ(Z){let $=new Date(Z+"T00:00:00Z"),X=$.getUTCDay()||7;$.setUTCDate($.getUTCDate()+4-X);let Q=new Date(Date.UTC($.getUTCFullYear(),0,1));return Math.ceil((($.getTime()-Q.getTime())/86400000+1)/7)}function VQ(Z){let $=q1(Y1(Z),1,1);return S8(Z,$)+1}function F6(Z){return Math.ceil(g1(Z)/3)}function P6(Z){return Z%4===0&&Z%100!==0||Z%400===0}function E0(Z,$){let X=[31,28,31,30,31,30,31,31,30,31,30,31];if($===2&&P6(Z))return 29;return X[$-1]}function CQ(Z){return P6(Z)?366:365}function T8(Z){return Z+"T00:00:00.000Z"}function OQ(Z){return Math.floor(new Date(Z+"T00:00:00Z").getTime()/1000)}function NQ(Z){let $=new Date(Z*1000);return q1($.getUTCFullYear(),$.getUTCMonth()+1,$.getUTCDate())}function V6(Z,$){let X=new Date(Z+"T00:00:00Z"),Q={timeZone:"UTC",...$};return new Intl.DateTimeFormat(void 0,Q).format(X)}function EQ(Z){return V6(Z,{year:"numeric",month:"long",day:"numeric"})}function SQ(Z){return V6(Z,{year:"numeric",month:"short",day:"numeric"})}function TQ(Z,$){return Z<$}function kQ(Z,$){return Z>$}function gQ(Z,$){return Z===$}function bQ(Z,$){return Z<$?Z:$}function vQ(Z,$){return Z>$?Z:$}function fQ(Z,$,X){return Z>=$&&Z<=X}function yQ(Z){return q1(Y1(Z),g1(Z),1)}function hQ(Z){let $=Y1(Z),X=g1(Z);return q1($,X,E0($,X))}function xQ(Z){let X=(F6(Z)-1)*3+1;return q1(Y1(Z),X,1)}function uQ(Z){let X=F6(Z)*3;return q1(Y1(Z),X,E0(Y1(Z),X))}function dQ(Z){return q1(Y1(Z),1,1)}function lQ(Z){return q1(Y1(Z),12,31)}function mQ(Z){let $=M6(Z);return C4(Z,-($-1))}function iQ(Z){let $=M6(Z);return C4(Z,7-$)}var pQ={isValid:w6,today:AQ,todayIn:IQ,from:q1,parse:E8,tryParse:RQ,addDays:C4,addWeeks:BQ,addMonths:wQ,addYears:jQ,diff:S8,diffMonths:MQ,diffYears:FQ,year:Y1,month:g1,day:j6,dayOfWeek:M6,weekOfYear:PQ,dayOfYear:VQ,quarter:F6,isLeapYear:P6,daysInMonth:E0,daysInYear:CQ,toTimestamp:T8,toUnix:OQ,fromUnix:NQ,format:V6,formatLong:EQ,formatShort:SQ,isBefore:TQ,isAfter:kQ,isEqual:gQ,min:bQ,max:vQ,isBetween:fQ,startOfMonth:yQ,endOfMonth:hQ,startOfQuarter:xQ,endOfQuarter:uQ,startOfYear:dQ,endOfYear:lQ,startOfWeek:mQ,endOfWeek:iQ};export{e$ as xmlParse,o4 as wrap,A$ as whileLoop,n$ as vectorSearch,P$ as varsLet,F$ as varsImport,V$ as varsExport,w$ as varSet,M$ as varGet,c4 as validateArgs,QX as uuid,g4 as typeToString,o1 as typeOf,t1 as typeDescriptorToTS,R$ as tryCatch,qK as transpileWithCache,M0 as transpileToJS,s$ as transpileCode,j4 as transpile,U0 as transformFunction,DK as tjsWithCache,UK as tjs,MZ as testUtils,v$ as template,M7 as stripTjsPreamble,Y4 as stripModuleSyntax,i$ as storeSet,p$ as storeQuery,zX as storeProcedure,m$ as storeGet,g$ as split,t5 as setGlobalCache,U1 as seq,C$ as scope,h1 as runtime,a$ as runCode,I$ as ret,E as resolveValue,J6 as resolveProcedureToken,GX as releaseProcedure,E7 as registerWasmBlock,f$ as regexMatch,E$ as reduce,XX as random,T$ as push,$0 as procedureStore,y0 as preprocess,y$ as pick,Q7 as parseReturnType,O1 as parseParameter,F1 as parse,h$ as omit,x$ as merge,ZX as memoize,O$ as map,p8 as lookupVariable,c$ as llmPredict,$$ as lint,k$ as len,u$ as keys,t$ as jsonStringify,r$ as jsonParse,b$ as join,y4 as isValidUrl,h4 as isValidTimestamp,x4 as isValidLegalDate,N1 as isRuntimeType,G6 as isProcedureToken,P1 as isError,K$ as isAgentError,N7 as instantiateWasm,s4 as installRuntime,G1 as inferTypeFromValue,D$ as iff,s5 as hashSourceSync,L4 as hashSource,W6 as hash,IK as getToolDefinitions,U6 as getStoreCapabilityDefault,sK as getStandardCapabilities,o as getLocation,J8 as getLLMCapability,U4 as getGlobalCache,hX as getBatteries,H$ as generateDocsMarkdown,d7 as generateDocs,O5 as generateDTS,c5 as fromTS,S$ as find,N$ as filter,l$ as fetch,v4 as extractTests,W0 as extractTDoc,B1 as extractLiteralValue,J7 as expectFunction,r as evaluateExpr,B$ as errorAtom,j1 as error,hZ as emitRuntimeWrapper,v as defineAtom,T1 as createChildScope,_1 as createChildContext,AK as createAgent,R4 as coreAtoms,j$ as constSet,KX as consoleWarn,HX as consoleLog,YX as consoleError,J5 as compileWasmBlocks,J4 as compileToWasm,JX as clearExpiredProcedures,x1 as checkType,$X as cache,C1 as builtins,xK as batteryAtoms,aK as batteries,G7 as assertFunction,_K as ajs,o$ as agentRun,t0 as Union,H1 as TypedBuilder,i8 as TypeError,t as Type,c as TranspileError,u4 as TimestampType,H0 as Timestamp,s0 as TUuid,o0 as TUrl,d0 as TString,$4 as TRecord,p0 as TPositiveInt,Z4 as TPair,l0 as TNumber,n0 as TNonEmptyString,K1 as TJS_VERSION,i0 as TInteger,c0 as TEmail,m0 as TBoolean,e0 as TArray,z1 as SyntaxError,o5 as Schema,wX as SafeFunction,z6 as PROCEDURE_TOKEN_PREFIX,r0 as Optional,a0 as Nullable,H6 as MetadataCache,I6 as LocalModels,d4 as LegalDateType,pQ as LegalDate,n1 as Generic,q0 as FunctionPredicate,BX as Eval,X4 as Enum,Y$ as DEFAULT_PROCEDURE_TTL,z$ as DEFAULT_MAX_AST_SIZE,L6 as AgentVM,J1 as AgentError,DX as Agent,cH as A99};
431
+ `}return Q.trim()||"*No documentation available*"}import{s as I,validate as z6,filter as a7}from"tosijs-schema";var D4=Symbol.for("tjs.equals");function I4(Z,$){if(Z!==null&&typeof Z==="object"&&typeof Z[D4]==="function")return Z[D4]($);if($!==null&&typeof $==="object"&&typeof $[D4]==="function")return $[D4](Z);if(Z!==null&&typeof Z==="object"&&typeof Z.Equals==="function")return Z.Equals($);if($!==null&&typeof $==="object"&&typeof $.Equals==="function")return $.Equals(Z);if(Z===$)return!0;if((Z===null||Z===void 0)&&($===null||$===void 0))return!0;if(Z===null||Z===void 0||$===null||$===void 0)return!1;if(typeof Z!==typeof $)return!1;if(typeof Z!=="object")return!1;if(Array.isArray(Z)&&Array.isArray($)){if(Z.length!==$.length)return!1;return Z.every((H,K)=>I4(H,$[K]))}if(Array.isArray(Z)!==Array.isArray($))return!1;let X=Object.keys(Z),Q=Object.keys($);if(X.length!==Q.length)return!1;return X.every((H)=>I4(Z[H],$[H]))}class J1{$error=!0;message;op;cause;constructor(Z,$,X){this.message=Z,this.op=$,this.cause=X}toString(){return`AgentError[${this.op}]: ${this.message}`}toJSON(){return{$error:!0,message:this.message,op:this.op}}}function z$(Z){return Z instanceof J1||Z&&Z.$error===!0}var $0=new Map,G$=3600000,J$=102400,G6="proc_";function J6(Z){return typeof Z==="string"&&Z.startsWith(G6)}function W6(Z){let $=$0.get(Z);if(!$)throw Error(`Procedure not found: ${Z}`);if(Date.now()>$.expiresAt)throw $0.delete(Z),Error(`Procedure expired: ${Z}`);return $.ast}function W$(){if(typeof crypto<"u"&&crypto.randomUUID)return G6+crypto.randomUUID();return G6+Math.random().toString(36).slice(2)+Date.now().toString(36)}var r7=new Set(["__proto__","constructor","prototype"]);function i7(Z){if(r7.has(Z))throw Error(`Security Error: Access to '${Z}' is forbidden`)}var _$=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function L$(Z){try{let $=new URL(Z);if($.protocol!=="http:"&&$.protocol!=="https:")return!0;let X=$.hostname.toLowerCase();if(_$.has(X))return!0;if(X.endsWith(".internal")||X.endsWith(".local"))return!0;if(X==="169.254.169.254")return!0;if(/^10\./.test(X)||/^192\.168\./.test(X)||/^172\.(1[6-9]|2\d|3[01])\./.test(X))return!0;return!1}catch{return!0}}function U$(Z){if(/\([^)]*[+*][^)]*\)[+*]/.test(Z))return!0;if(/\(([^|)]+)\|\1\)[+*]/.test(Z))return!0;if(/\(\.\*\)\+/.test(Z))return!0;if(/\(\.\+\)\+/.test(Z))return!0;if(/\(\[.*\]\+\)\+/.test(Z))return!0;return!1}function T1(Z){return{...Z,state:Object.create(Z.state)}}function q$(Z,$){let X={},Q=new Set([...Object.keys(Z),...Object.keys($)]);for(let H of Q){let K=Z[H],Y=$[H];if(Y!==K)X[H]=Y}return X}function E(Z,$){if(Z&&typeof Z==="object"&&Z.$kind==="arg")return $.args[Z.path];if(Z&&typeof Z==="object"&&Z.$expr)return r(Z,$);if(typeof Z==="string"){if(Z.startsWith("args.")&&!("args"in $.state))return $.args[Z.replace("args.","")];if(Z.includes(".")){let X=Z.split(".");for(let H of X)if(r7.has(H))throw Error(`Security Error: Access to '${H}' is forbidden`);let Q=$.state[X[0]];if(Q!==void 0){for(let H=1;H<X.length;H++)Q=Q?.[X[H]];return Q}}if(Z in $.state)return $.state[Z];return Z}if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Z.constructor===Object){let X={};for(let Q of Object.keys(Z))X[Q]=E(Z[Q],$);return X}if(Array.isArray(Z))return Z.map((X)=>E(X,$));return Z}function m1(Z,$,X){return new Proxy($,{get(Q,H){if(H in Q)return Q[H];let K=X?.[H];if(K)throw Error(`${Z}.${H} is not available. ${K}`);throw Error(`${Z}.${H} is not supported in AsyncJS. Check docs for available ${Z} methods.`)}})}function Z0(Z){if(Z===null)return{type:"null"};if(Z===void 0)return{};if(typeof Z==="object"&&Z!==null&&"type"in Z&&typeof Z.type==="string")return Z;if(typeof Z==="object"&&Z!==null&&"schema"in Z&&typeof Z.schema==="object")return Z.schema;let $=typeof Z;if($==="string")return{type:"string"};if($==="number")return Number.isInteger(Z)?{type:"integer"}:{type:"number"};if($==="boolean")return{type:"boolean"};if(Array.isArray(Z)){if(Z.length===0)return{type:"array"};return{type:"array",items:Z0(Z[0])}}if($==="object"){let X={},Q=[];for(let[H,K]of Object.entries(Z))X[H]=Z0(K),Q.push(H);return{type:"object",properties:X,required:Q}}return{}}var C1={Math:m1("Math",{PI:Math.PI,E:Math.E,LN2:Math.LN2,LN10:Math.LN10,LOG2E:Math.LOG2E,LOG10E:Math.LOG10E,SQRT2:Math.SQRT2,SQRT1_2:Math.SQRT1_2,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc,sign:Math.sign,sqrt:Math.sqrt,cbrt:Math.cbrt,pow:Math.pow,exp:Math.exp,expm1:Math.expm1,log:Math.log,log2:Math.log2,log10:Math.log10,log1p:Math.log1p,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,hypot:Math.hypot,min:Math.min,max:Math.max,clz32:Math.clz32,imul:Math.imul,fround:Math.fround,random:()=>{if(typeof crypto<"u"&&crypto.getRandomValues){let Z=new Uint32Array(1);return crypto.getRandomValues(Z),Z[0]/4294967296}return Math.random()}}),JSON:m1("JSON",{parse:(Z)=>JSON.parse(Z),stringify:(Z,$,X)=>JSON.stringify(Z,$,X)}),console:m1("console",{log:(...Z)=>{return},warn:(...Z)=>{return},error:(...Z)=>{return},info:(...Z)=>{return}},{table:"Use console.log with JSON.stringify for structured data.",dir:"Use console.log instead.",trace:"Stack traces are not available in AsyncJS."}),Array:m1("Array",{isArray:(Z)=>Array.isArray(Z),from:(Z,$,X)=>Array.from(Z,$,X),of:(...Z)=>Array.of(...Z)},{prototype:"Prototype access is not allowed."}),Object:m1("Object",{keys:(Z)=>Object.keys(Z),values:(Z)=>Object.values(Z),entries:(Z)=>Object.entries(Z),fromEntries:(Z)=>Object.fromEntries(Z),assign:(Z,...$)=>Object.assign({},Z,...$),hasOwn:(Z,$)=>Object.hasOwn(Z,$)},{prototype:"Prototype access is not allowed.",create:"Use object literals instead.",defineProperty:"Property descriptors are not supported.",getPrototypeOf:"Prototype access is not allowed.",setPrototypeOf:"Prototype modification is not allowed."}),String:m1("String",{fromCharCode:(...Z)=>String.fromCharCode(...Z),fromCodePoint:(...Z)=>String.fromCodePoint(...Z)}),Number:m1("Number",{isNaN:Number.isNaN,isFinite:Number.isFinite,isInteger:Number.isInteger,isSafeInteger:Number.isSafeInteger,parseFloat,parseInt,MAX_VALUE:Number.MAX_VALUE,MIN_VALUE:Number.MIN_VALUE,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,POSITIVE_INFINITY:Number.POSITIVE_INFINITY,NEGATIVE_INFINITY:Number.NEGATIVE_INFINITY,NaN:Number.NaN,EPSILON:Number.EPSILON}),parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,undefined:void 0,null:null,NaN:NaN,Infinity:1/0,filter:(Z,$)=>{let X=Z0($),Q=a7(Z,X);if(Q instanceof Error)throw Q;return Q},Schema:{...I,response:(Z,$)=>{let X=$?.schema!=null?$.schema:Z0($);return{type:"json_schema",json_schema:{name:Z,strict:!0,schema:X}}},fromExample:(Z)=>Z0(Z),isValid:(Z,$)=>{if($?.schema!=null)return z6(Z,$);return z6(Z,Z0($))}},Set:(Z=[])=>{let $=[...new globalThis.Set(Z)];return{add(X){if(!$.includes(X))$.push(X);return this},remove(X){let Q=$.indexOf(X);if(Q!==-1)$.splice(Q,1);return this},clear(){return $.length=0,this},has(X){return $.includes(X)},get size(){return $.length},toArray(){return[...$]},union(X){let Q=X?.toArray?.()??X??[];return C1.Set([...$,...Q])},intersection(X){let Q=X?.toArray?.()??X??[];return C1.Set($.filter((H)=>Q.includes(H)))},diff(X){let Q=X?.toArray?.()??X??[];return C1.Set($.filter((H)=>!Q.includes(H)))},forEach(X){$.forEach(X)},map(X){return C1.Set($.map(X))},filter(X){return C1.Set($.filter(X))},toJSON(){return[...$]}}},Date:(()=>{let Z=(X)=>({get value(){return X.toISOString()},get timestamp(){return X.getTime()},get year(){return X.getFullYear()},get month(){return X.getMonth()+1},get day(){return X.getDate()},get hours(){return X.getHours()},get minutes(){return X.getMinutes()},get seconds(){return X.getSeconds()},get dayOfWeek(){return X.getDay()},add({years:Q=0,months:H=0,days:K=0,hours:Y=0,minutes:z=0,seconds:G=0,ms:J=0}={}){let W=new globalThis.Date(X.getTime());if(Q)W.setFullYear(W.getFullYear()+Q);if(H)W.setMonth(W.getMonth()+H);if(K)W.setDate(W.getDate()+K);if(Y)W.setHours(W.getHours()+Y);if(z)W.setMinutes(W.getMinutes()+z);if(G)W.setSeconds(W.getSeconds()+G);if(J)W.setMilliseconds(W.getMilliseconds()+J);return Z(W)},diff(Q,H="ms"){let K=typeof Q==="object"&&Q.timestamp?Q.timestamp:new globalThis.Date(Q).getTime(),Y=X.getTime()-K;switch(H){case"seconds":return Y/1000;case"minutes":return Y/60000;case"hours":return Y/3600000;case"days":return Y/86400000;default:return Y}},format(Q="ISO"){if(Q==="ISO")return X.toISOString();if(Q==="date")return X.toISOString().split("T")[0];if(Q==="time")return X.toISOString().split("T")[1].split(".")[0];return Q.replace("YYYY",String(X.getFullYear())).replace("MM",String(X.getMonth()+1).padStart(2,"0")).replace("DD",String(X.getDate()).padStart(2,"0")).replace("HH",String(X.getHours()).padStart(2,"0")).replace("mm",String(X.getMinutes()).padStart(2,"0")).replace("ss",String(X.getSeconds()).padStart(2,"0"))},isBefore(Q){let H=typeof Q==="object"&&Q.timestamp?Q.timestamp:new globalThis.Date(Q).getTime();return X.getTime()<H},isAfter(Q){let H=typeof Q==="object"&&Q.timestamp?Q.timestamp:new globalThis.Date(Q).getTime();return X.getTime()>H},toString(){return X.toISOString()},toJSON(){return X.toISOString()}}),$=(X)=>{let Q=X!==void 0?new globalThis.Date(X):new globalThis.Date;if(isNaN(Q.getTime()))throw Error(`Invalid date: ${X}`);return Z(Q)};return $.now=()=>globalThis.Date.now(),$.parse=(X)=>Z(new globalThis.Date(X)),$})()},A4={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."},D$=0.01,p7=0.0001,n7=0.001,A$=new Set(["concat","slice","map","filter","flatMap","flat","toReversed","toSorted","toSpliced","repeat","padStart","padEnd","split","join","replace","replaceAll","substring","substr","trim","trimStart","trimEnd","toLowerCase","toUpperCase","match","matchAll","parse","stringify"]);function r(Z,$){if(Z===null||Z===void 0)return Z;if(typeof Z!=="object"||!("$expr"in Z))return Z;if($.fuel){if($.fuel.current-=D$,$.fuel.current<=0)throw Error("Out of Fuel")}switch(Z.$expr){case"literal":return Z.value;case"ident":{if(Z.name in $.state)return $.state[Z.name];if(Z.name in $.args)return $.args[Z.name];if(Z.name in C1)return C1[Z.name];if(Z.name in A4)throw Error(A4[Z.name]);return}case"member":{let X=r(Z.object,$);if(Z.optional&&(X===null||X===void 0))return;let Q=Z.property;return i7(Q),X?.[Q]}case"binary":{let X=r(Z.left,$),Q=r(Z.right,$);switch(Z.op){case"+":{let H=X+Q;if(typeof H==="string"&&$.fuel){if($.fuel.current-=H.length*p7,$.fuel.current<=0){$.error=new J1("Out of Fuel","expr.concat");return}}return H}case"-":return X-Q;case"*":return X*Q;case"/":return X/Q;case"%":return X%Q;case"**":return X**Q;case">":return X>Q;case"<":return X<Q;case">=":return X>=Q;case"<=":return X<=Q;case"==":return I4(X,Q);case"!=":return!I4(X,Q);case"===":return X===Q;case"!==":return X!==Q;default:throw Error(`Unknown binary operator: ${Z.op}`)}}case"unary":{let X=r(Z.argument,$);switch(Z.op){case"!":return!X;case"-":return-X;case"+":return+X;case"typeof":return typeof X;default:throw Error(`Unknown unary operator: ${Z.op}`)}}case"logical":{let X=r(Z.left,$);if(Z.op==="&&")return X?r(Z.right,$):X;else if(Z.op==="??")return X??r(Z.right,$);else return X?X:r(Z.right,$)}case"conditional":return r(Z.test,$)?r(Z.consequent,$):r(Z.alternate,$);case"array":return Z.elements.map((X)=>r(X,$));case"object":{let X={};for(let Q of Z.properties)X[Q.key]=r(Q.value,$);return X}case"call":{if(Z.callee==="Error"){let Q=Z.arguments.map((K)=>r(K,$)),H=typeof Q[0]==="string"?Q[0]:"Error";$.error=new J1(H,"Error");return}if(Z.callee in C1){let Q=C1[Z.callee];if(typeof Q==="function"){let H=Z.arguments.map((K)=>r(K,$));return Q(...H)}}if(!$.resolver(Z.callee)){if(Z.callee in A4)throw Error(A4[Z.callee]);throw Error(`Unknown function: ${Z.callee}`)}throw Error(`Atom calls in expressions not yet supported: ${Z.callee}`)}case"methodCall":{let X=r(Z.object,$);if(Z.optional&&(X===null||X===void 0))return;let Q=Z.method;if(i7(Q),X===null||X===void 0)throw Error(`Cannot call method '${Q}' on ${X}`);let H=X[Q];if(typeof H!=="function")throw Error(`'${Q}' is not a function`);let K=Z.arguments.map((z)=>r(z,$)),Y=H.apply(X,K);if($.fuel&&A$.has(Q)){let z=0;if(typeof Y==="string")z=Y.length*p7;else if(Array.isArray(Y))z=Y.length*n7;else if(typeof Y==="object"&&Y!==null)z=Object.keys(Y).length*n7;if($.fuel.current-=z,$.fuel.current<=0){$.error=new J1("Out of Fuel",`expr.${Q}`);return}}return Y}default:throw Error(`Unknown expression type: ${Z.$expr}`)}}function v(Z,$,X,Q,H={}){let{docs:K="",timeoutMs:Y=1000,cost:z=1}=typeof H==="string"?{docs:H}:H;return{op:Z,inputSchema:$,outputSchema:X,exec:async(J,W)=>{let{op:U,result:_,...L}=J;if(W.error)return;let q=W.trace?{...W.state}:null,A=W.fuel.current,B,M;try{let F=W.costOverrides?.[Z],R=F!==void 0?F:z,w=typeof R==="function"?R(L,W):R;if((W.fuel.current-=w)<=0){W.error=new J1("Out of Fuel",Z);return}let C,P=async()=>Q(J,W);if(B=Y>0?await Promise.race([P(),new Promise((O,k)=>{C=setTimeout(()=>k(Error(`Atom '${Z}' timed out`)),Y)})]).finally(()=>clearTimeout(C)):await P(),J.result){if(W.consts.has(J.result))throw Error(`Cannot reassign const variable '${J.result}'`);if(B!==void 0&&X&&!z6(B,X)){W.error=new J1(`Output validation failed for '${Z}'`,Z);return}if(W.state[J.result]=B,J.resultConst)W.consts.add(J.result)}}catch(F){M=F.message||String(F),W.error=new J1(M,Z,F)}finally{if(W.trace&&q){let F=q$(q,W.state);W.trace.push({op:Z,input:L,stateDiff:F,result:B,error:M,fuelBefore:A,fuelAfter:W.fuel.current,timestamp:new Date().toISOString()})}}},docs:K,timeoutMs:Y,cost:z,create:(J)=>({op:Z,...J})}}var U1=v("seq",I.object({steps:I.array(I.any)}),void 0,async({steps:Z},$)=>{for(let X of Z){if($.output!==void 0)return;if($.error)return;let Q=$.resolver(X.op);if(!Q)throw Error(`Unknown Atom: ${X.op}`);await Q.exec(X,$)}},{docs:"Sequence",timeoutMs:0,cost:0.1}),I$=v("if",I.object({condition:I.any,then:I.array(I.any),else:I.array(I.any).optional}),void 0,async(Z,$)=>{if(r(Z.condition,$))await U1.exec({op:"seq",steps:Z.then},$);else if(Z.else)await U1.exec({op:"seq",steps:Z.else},$)},{docs:"If/Else",timeoutMs:0,cost:0.1}),R$=v("while",I.object({condition:I.any,body:I.array(I.any)}),void 0,async(Z,$)=>{while(r(Z.condition,$)){if($.signal?.aborted)throw Error("Execution aborted");if(($.fuel.current-=0.1)<=0)throw Error("Out of Fuel");if(await U1.exec({op:"seq",steps:Z.body},$),$.output!==void 0)return}},{docs:"While Loop",timeoutMs:0,cost:0.1}),B$=v("return",void 0,I.any,async(Z,$)=>{if($.error)return $.output=$.error,$.error;if("value"in Z){let Q=E(Z.value,$);if(Q!==void 0&&Q!==null&&!z$(Q)&&(typeof Q!=="object"||Array.isArray(Q))){let H=new J1(`Agent must return an object, got ${Array.isArray(Q)?"array":typeof Q}`,"return");return $.error=H,$.output=H,H}return $.output=Q,Q}let X={};if(Z.schema?.properties){for(let Q of Object.keys(Z.schema.properties))X[Q]=$.state[Q];if(Z.filter!==!1){let Q=a7(X,Z.schema);if(!(Q instanceof Error))X=Q}}return $.output=X,X},{docs:"Return",cost:0.1}),w$=v("try",I.object({try:I.array(I.any),catch:I.array(I.any).optional,catchParam:I.string.optional}),void 0,async(Z,$)=>{if(await U1.exec({op:"seq",steps:Z.try},$),$.error&&Z.catch){let X=Z.catchParam||"error";$.state[X]=$.error.message,$.state.errorOp=$.error.op,$.error=void 0,await U1.exec({op:"seq",steps:Z.catch},$)}},{docs:"Try/Catch",timeoutMs:0,cost:0.1}),j$=v("Error",I.object({args:I.array(I.any).optional}),void 0,async(Z,$)=>{let X=Z.args?.[0]??"Error";$.error=new J1(String(X),"Error")},{docs:"Trigger error flow",cost:0.1}),M$=v("varSet",I.object({key:I.string,value:I.any}),void 0,async({key:Z,value:$},X)=>{if(X.consts.has(Z))throw Error(`Cannot reassign const variable '${Z}'`);X.state[Z]=E($,X)},{docs:"Set Variable",cost:0.1}),F$=v("constSet",I.object({key:I.string,value:I.any}),void 0,async({key:Z,value:$},X)=>{if(X.consts.has(Z))throw Error(`Cannot reassign const variable '${Z}'`);if(Z in X.state)throw Error(`Cannot redeclare variable '${Z}' as const`);X.state[Z]=E($,X),X.consts.add(Z)},{docs:"Set Const Variable (immutable)",cost:0.1}),P$=v("varGet",I.object({key:I.string}),I.any,async({key:Z},$)=>{return E(Z,$)},{docs:"Get Variable",cost:0.1}),V$=v("varsImport",I.object({keys:I.union([I.array(I.string),I.record(I.string)])}),void 0,async({keys:Z},$)=>{if(Array.isArray(Z))for(let X of Z)$.state[X]=E({$kind:"arg",path:X},$);else for(let[X,Q]of Object.entries(Z))$.state[X]=E({$kind:"arg",path:Q},$)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:0.2}),C$=v("varsLet",I.record(I.any),void 0,async(Z,$)=>{for(let X of Object.keys(Z)){if(X==="op"||X==="result")continue;$.state[X]=E(Z[X],$)}},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:0.1}),O$=v("varsExport",I.object({keys:I.union([I.array(I.string),I.record(I.string)])}),I.record(I.any),async({keys:Z},$)=>{let X={};if(Array.isArray(Z))for(let Q of Z)X[Q]=E(Q,$);else for(let[Q,H]of Object.entries(Z))X[Q]=E(H,$);return X},{docs:"Export variables from the current scope, with optional renaming.",cost:0.2}),N$=v("scope",I.object({steps:I.array(I.any)}),void 0,async({steps:Z},$)=>{let X=T1($);if(await U1.exec({op:"seq",steps:Z},X),X.output!==void 0)$.output=X.output},{docs:"Create new scope",timeoutMs:0,cost:0.1}),E$=v("map",I.object({items:I.array(I.any),as:I.string,steps:I.array(I.any)}),I.array(I.any),async({items:Z,as:$,steps:X},Q)=>{let H=[],K=E(Z,Q);if(!Array.isArray(K))throw Error("map: items is not an array");for(let Y of K){if(Q.signal?.aborted)throw Error("Execution aborted");let z=T1(Q);z.state[$]=Y,await U1.exec({op:"seq",steps:X},z),H.push(z.state.result??null)}return H},{docs:"Map Array",timeoutMs:0,cost:1}),S$=v("filter",I.object({items:I.array(I.any),as:I.string,condition:I.any}),I.array(I.any),async({items:Z,as:$,condition:X},Q)=>{let H=[],K=E(Z,Q);if(!Array.isArray(K))throw Error("filter: items is not an array");for(let Y of K){if(Q.signal?.aborted)throw Error("Execution aborted");let z=T1(Q);if(z.state[$]=Y,r(X,z))H.push(Y)}return H},{docs:"Filter Array",timeoutMs:0,cost:1}),T$=v("reduce",I.object({items:I.array(I.any),as:I.string,accumulator:I.string,initial:I.any,steps:I.array(I.any)}),I.any,async({items:Z,as:$,accumulator:X,initial:Q,steps:H},K)=>{let Y=E(Z,K),z=E(Q,K);if(!Array.isArray(Y))throw Error("reduce: items is not an array");let G=z;for(let J of Y){if(K.signal?.aborted)throw Error("Execution aborted");let W=T1(K);W.state[$]=J,W.state[X]=G,await U1.exec({op:"seq",steps:H},W),G=W.state.result??G}return G},{docs:"Reduce Array",timeoutMs:0,cost:1}),k$=v("find",I.object({items:I.array(I.any),as:I.string,condition:I.any}),I.any,async({items:Z,as:$,condition:X},Q)=>{let H=E(Z,Q);if(!Array.isArray(H))throw Error("find: items is not an array");for(let K of H){if(Q.signal?.aborted)throw Error("Execution aborted");let Y=T1(Q);if(Y.state[$]=K,r(X,Y))return K}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),g$=v("push",I.object({list:I.array(I.any),item:I.any}),I.array(I.any),async({list:Z,item:$},X)=>{let Q=E(Z,X),H=E($,X);if(Array.isArray(Q))Q.push(H);return Q},{docs:"Push to Array",cost:1}),b$=v("len",I.object({list:I.any}),I.number,async({list:Z},$)=>{let X=E(Z,$);return Array.isArray(X)||typeof X==="string"?X.length:0},{docs:"Length",cost:1}),v$=v("split",I.object({str:I.string,sep:I.string}),I.array(I.string),async({str:Z,sep:$},X)=>E(Z,X).split(E($,X)),{docs:"Split String",cost:1}),f$=v("join",I.object({list:I.array(I.string),sep:I.string}),I.string,async({list:Z,sep:$},X)=>E(Z,X).join(E($,X)),{docs:"Join String",cost:1}),y$=v("template",I.object({tmpl:I.string,vars:I.record(I.any)}),I.string,async({tmpl:Z,vars:$},X)=>{return E(Z,X).replace(/\{\{(\w+)\}\}/g,(H,K)=>String(E($[K],X)??""))},{docs:"String Template",cost:1}),h$=v("regexMatch",I.object({pattern:I.string,value:I.any}),I.boolean,async({pattern:Z,value:$},X)=>{if(U$(Z))throw Error(`Suspicious regex pattern rejected (potential ReDoS): ${Z}`);let Q=E($,X);return new RegExp(Z).test(Q)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),x$=v("pick",I.object({obj:I.record(I.any),keys:I.array(I.string)}),I.record(I.any),async({obj:Z,keys:$},X)=>{let Q=E(Z,X),H=E($,X),K={};if(Q&&Array.isArray(H))H.forEach((Y)=>K[Y]=Q[Y]);return K},{docs:"Pick Keys",cost:1}),u$=v("omit",I.object({obj:I.record(I.any),keys:I.array(I.string)}),I.record(I.any),async({obj:Z,keys:$},X)=>{let Q=E(Z,X),H=new Set(E($,X)),K={};if(Q)Object.keys(Q).forEach((Y)=>{if(!H.has(Y))K[Y]=Q[Y]});return K},{docs:"Omit Keys",cost:1}),d$=v("merge",I.object({a:I.record(I.any),b:I.record(I.any)}),I.record(I.any),async({a:Z,b:$},X)=>({...E(Z,X),...E($,X)}),{docs:"Merge Objects",cost:1}),l$=v("keys",I.object({obj:I.record(I.any)}),I.array(I.string),async({obj:Z},$)=>Object.keys(E(Z,$)??{}),{docs:"Object Keys",cost:1}),c7=10,o7="X-Agent-Depth";function m$(Z,$){try{let Q=new URL(Z).hostname.toLowerCase();for(let H of $){let K=H.toLowerCase();if(K.startsWith("*.")){let Y=K.slice(1);if(Q.endsWith(Y)||Q===K.slice(2))return!0}else if(Q===K)return!0}return!1}catch{return!1}}var i$=v("httpFetch",I.object({url:I.string,method:I.string.optional,headers:I.record(I.string).optional,body:I.any.optional,responseType:I.string.optional}),I.any,async(Z,$)=>{let X=E(Z.url,$),Q=E(Z.method,$),H=E(Z.headers,$)||{},K=E(Z.body,$),Y=E(Z.responseType,$),z=$.context?.requestDepth??0;if(z>=c7)throw Error(`Agent request depth exceeded (max ${c7}). This prevents recursive agent loops.`);if($.capabilities.fetch)return $.capabilities.fetch(X,{method:Q,headers:{...H,[o7]:String(z+1)},body:K,signal:$.signal,responseType:Y});let G=$.context?.allowedFetchDomains;if(G){if(!m$(X,G))throw Error(`Fetch blocked: domain not in allowlist. Allowed: ${G.join(", ")}`)}else{if(L$(X))throw Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let W=new URL(X).hostname.toLowerCase();if(W!=="localhost"&&W!=="127.0.0.1"&&W!=="[::1]")throw Error("Fetch blocked: no allowedFetchDomains configured. Set ctx.context.allowedFetchDomains or provide a custom fetch capability.")}catch(J){if(J.message.includes("allowedFetchDomains"))throw J;throw Error(`Invalid URL: ${X}`)}}if(typeof globalThis.fetch==="function"){let J=await globalThis.fetch(X,{method:Q,headers:{...H,[o7]:String(z+1)},body:K?JSON.stringify(K):void 0,signal:$.signal});if(Y==="dataUrl"){let U=await J.arrayBuffer(),_=new Uint8Array(U),L="";for(let B=0;B<_.length;B++)L+=String.fromCharCode(_[B]);let q=btoa(L);return`data:${J.headers.get("content-type")||"application/octet-stream"};base64,${q}`}let W=J.headers.get("content-type");if(Y==="json"||W&&W.includes("application/json"))return J.json();return J.text()}throw Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:30000,cost:5}),p$=v("storeGet",I.object({key:I.string}),I.any,async({key:Z},$)=>{let X=E(Z,$);return $.capabilities.store?.get(X)},{docs:"Store Get",cost:5}),n$=v("storeSet",I.object({key:I.string,value:I.any}),void 0,async({key:Z,value:$},X)=>{let Q=E(Z,X),H=E($,X);return X.capabilities.store?.set(Q,H)},{docs:"Store Set",cost:5}),c$=v("storeQuery",I.object({query:I.any}),I.array(I.any),async({query:Z},$)=>$.capabilities.store?.query?.(E(Z,$))??[],{docs:"Store Query",cost:5}),o$=v("storeVectorSearch",I.object({collection:I.string.optional,vector:I.array(I.number),k:I.number.optional}),I.array(I.any),async({collection:Z,vector:$,k:X},Q)=>Q.capabilities.store?.vectorSearch?.(E(Z,Q),E($,Q),E(X,Q))??[],{docs:"Vector Search",cost:(Z,$)=>5+(E(Z.k,$)??5)}),s$=v("llmPredict",I.object({prompt:I.string,options:I.any.optional}),I.string,async({prompt:Z,options:$},X)=>{if(!X.capabilities.llm?.predict)throw Error("Capability 'llm.predict' missing");return X.capabilities.llm.predict(E(Z,X),E($,X))},{docs:"LLM Predict",timeoutMs:120000,cost:100}),a$=v("agentRun",I.object({agentId:I.any,input:I.any}),I.any,async({agentId:Z,input:$},X)=>{let Q=E(Z,X),H=E($,X),K=H;if(H&&typeof H==="object"&&!Array.isArray(H)){K={};for(let z in H)K[z]=E(H[z],X)}if(J6(Q)){let z=W6(Q),G={...X,args:K,state:{},consts:new Set,output:void 0,error:void 0},J=X.resolver("seq");if(!J)throw Error("seq atom not found");if(await J.exec(z,G),G.error)throw Error(G.error.message||"Sub-agent failed");return G.output}if(Q&&typeof Q==="object"&&"op"in Q){let z={...X,args:K,state:{},consts:new Set,output:void 0,error:void 0},G=X.resolver("seq");if(!G)throw Error("seq atom not found");if(await G.exec(Q,z),z.error)throw Error(z.error.message||"Sub-agent failed");return z.output}if(!X.capabilities.agent?.run)throw Error("Capability 'agent.run' missing");let Y=await X.capabilities.agent.run(Q,K);if(Y&&typeof Y==="object"&&"fuelUsed"in Y&&typeof Y.fuelUsed==="number"){if(Y.error)throw Error(Y.error.message||"Sub-agent failed");return Y.result}return Y},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),r$=v("transpileCode",I.object({code:I.string}),I.any,async({code:Z},$)=>{if(!$.capabilities.code?.transpile)throw Error("Capability 'code.transpile' missing. Enable code transpilation by providing the code capability.");let X=E(Z,$);try{return $.capabilities.code.transpile(X)}catch(Q){throw Error(`Code transpilation failed: ${Q.message}`)}},{docs:"Transpile AsyncJS code to AST",cost:1}),s7=10,t$=v("runCode",I.object({code:I.string,args:I.record(I.any).optional}),I.any,async({code:Z,args:$},X)=>{let Q=X.runCodeDepth??0;if(Q>=s7)throw Error(`runCode recursion limit exceeded (max ${s7}). This prevents infinite loops from dynamically generated code calling runCode.`);if(!X.capabilities.code?.transpile)throw Error("Capability 'code.transpile' missing. Enable dynamic code execution by providing the code capability.");let H=E(Z,X),K=$?E($,X):{},Y;try{Y=X.capabilities.code.transpile(H)}catch(G){throw Error(`Code transpilation failed: ${G.message}`)}if(Y.op!=="seq")throw Error("Transpiled code must be a seq node");let z=T1(X);if(z.args=K,z.output=void 0,z.runCodeDepth=Q+1,await U1.exec(Y,z),z.error){X.error=z.error;return}return z.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),e$=v("jsonParse",I.object({str:I.string}),I.any,async({str:Z},$)=>JSON.parse(E(Z,$)),{docs:"Parse JSON",cost:1}),ZX=v("jsonStringify",I.object({value:I.any}),I.string,async({value:Z},$)=>JSON.stringify(E(Z,$)),{docs:"Stringify JSON",cost:1}),$X=v("xmlParse",I.object({str:I.string}),I.any,async({str:Z},$)=>{if(!$.capabilities.xml?.parse)throw Error("Capability 'xml.parse' missing");return $.capabilities.xml.parse(E(Z,$))},{docs:"Parse XML",cost:1}),XX=v("memoize",I.object({key:I.string.optional,steps:I.array(I.any)}),I.any,async({key:Z,steps:$},X)=>{if(!X.memo)X.memo=new Map;let Q=E(Z,X)??await _6.exec({value:$,algorithm:"SHA-256"},X);if(X.memo.has(Q))return X.memo.get(Q);let H=T1(X);await U1.exec({op:"seq",steps:$},H);let K=H.output??H.state.result;return X.memo.set(Q,K),K},{docs:"Memoize steps result in memory",cost:1}),QX=v("cache",I.object({key:I.string.optional,steps:I.array(I.any),ttlMs:I.number.optional}),I.any,async({key:Z,steps:$,ttlMs:X},Q)=>{if(!Q.capabilities.store)throw Error("Capability 'store' missing for caching");let K=`cache:${E(Z,Q)??await _6.exec({value:$,algorithm:"SHA-256"},Q)}`,Y=await Q.capabilities.store.get(K);if(Y)if(typeof Y==="object"&&Y._exp){if(Date.now()<Y._exp)return Y.val}else return Y;let z=T1(Q);await U1.exec({op:"seq",steps:$},z);let G=z.output??z.state.result,J=Date.now()+(X??86400000);if((Q.fuel.current-=5)<=0)throw Error("Out of Fuel");return await Q.capabilities.store.set(K,{val:G,_exp:J}),G},{docs:"Cache steps result in store with TTL",cost:5}),HX=v("random",I.object({min:I.number.optional,max:I.number.optional,format:I.string.optional,length:I.number.optional}),I.any,async({min:Z,max:$,format:X,length:Q},H)=>{let K=E(X,H)??"float",Y=E(Q,H)??10,z=E(Z,H)??0,G=E($,H)??1;if(K==="base36"){let L="";if(typeof crypto<"u"&&crypto.getRandomValues){let q=new Uint8Array(Y);crypto.getRandomValues(q);for(let A=0;A<Y;A++)L+="0123456789abcdefghijklmnopqrstuvwxyz"[q[A]%36]}else for(let q=0;q<Y;q++)L+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(Math.floor(Math.random()*36));return L}let J;if(typeof crypto<"u"&&crypto.getRandomValues){let _=new Uint32Array(1);crypto.getRandomValues(_),J=_[0]/4294967296}else J=Math.random();let W=G-z,U=J*W+z;if(K==="integer")return Math.floor(U);return U},{docs:"Generate Random",cost:1}),KX=v("uuid",void 0,I.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let Z=new Uint8Array(16);crypto.getRandomValues(Z),Z[6]=Z[6]&15|64,Z[8]=Z[8]&63|128;let $=Array.from(Z,(X)=>X.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(Z)=>{let $=Math.random()*16|0;return(Z==="x"?$:$&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),_6=v("hash",I.object({value:I.any,algorithm:I.string.optional}),I.string,async({value:Z,algorithm:$},X)=>{let Q=typeof Z==="string"?Z:JSON.stringify(E(Z,X)),H=E($,X)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let z=new TextEncoder().encode(Q),G=await crypto.subtle.digest(H,z);return Array.from(new Uint8Array(G)).map((W)=>W.toString(16).padStart(2,"0")).join("")}let K=0;for(let Y=0;Y<Q.length;Y++){let z=Q.charCodeAt(Y);K=(K<<5)-K+z,K|=0}return String(K)},{docs:"Hash a value",cost:1}),YX=v("consoleLog",I.object({message:I.any}),void 0,async({message:Z},$)=>{let X=E(Z,$);if($.trace)$.trace.push({op:"console.log",input:{message:X},stateDiff:{},result:X,fuelBefore:$.fuel.current,fuelAfter:$.fuel.current,timestamp:new Date().toISOString()})},{docs:"Log to trace",cost:0.1}),zX=v("consoleWarn",I.object({message:I.any}),void 0,async({message:Z},$)=>{let X=E(Z,$),Q=typeof X==="string"?X:JSON.stringify(X);if(!$.warnings)$.warnings=[];if($.warnings.push(Q),$.trace)$.trace.push({op:"console.warn",input:{message:X},stateDiff:{},result:X,fuelBefore:$.fuel.current,fuelAfter:$.fuel.current,timestamp:new Date().toISOString()})},{docs:"Add warning",cost:0.1}),GX=v("consoleError",I.object({message:I.any}),void 0,async({message:Z},$)=>{let X=E(Z,$),Q=typeof X==="string"?X:JSON.stringify(X);$.error=new J1(Q,"console.error")},{docs:"Emit error and stop",cost:0.1}),JX=v("storeProcedure",I.object({ast:I.any,ttl:I.number.optional,maxSize:I.number.optional}),I.string,async({ast:Z,ttl:$,maxSize:X},Q)=>{let H=E(Z,Q),K=$?E($,Q):G$,Y=X?E(X,Q):J$;if(!H||typeof H!=="object"||!H.op)throw Error('Invalid AST: must be an object with an "op" property');let z=JSON.stringify(H);if(z.length>Y)throw Error(`AST too large: ${z.length} bytes exceeds limit of ${Y} bytes. Consider reducing AST size or using a shorter TTL.`);let G=W$(),J=Date.now();return $0.set(G,{ast:H,createdAt:J,expiresAt:J+K}),G},{docs:"Store an AST and return a token for later execution",cost:1}),WX=v("releaseProcedure",I.object({token:I.string}),I.boolean,async({token:Z},$)=>{let X=E(Z,$);return $0.delete(X)},{docs:"Release a stored procedure by token",cost:0.1}),_X=v("clearExpiredProcedures",void 0,I.number,async()=>{let Z=Date.now(),$=0;for(let[X,Q]of $0)if(Z>Q.expiresAt)$0.delete(X),$++;return $},{docs:"Clear all expired procedures and return count",cost:0.5}),R4={seq:U1,if:I$,while:R$,return:B$,try:w$,Error:j$,varSet:M$,constSet:F$,varGet:P$,varsImport:V$,varsLet:C$,varsExport:O$,scope:N$,map:E$,filter:S$,reduce:T$,find:k$,push:g$,len:b$,split:v$,join:f$,template:y$,regexMatch:h$,pick:x$,omit:u$,merge:d$,keys:l$,httpFetch:i$,storeGet:p$,storeSet:n$,storeQuery:c$,storeVectorSearch:o$,llmPredict:s$,agentRun:a$,transpileCode:r$,runCode:t$,jsonParse:e$,jsonStringify:ZX,xmlParse:$X,memoize:XX,cache:QX,random:HX,uuid:KX,hash:_6,consoleLog:YX,consoleWarn:zX,consoleError:GX,storeProcedure:JX,releaseProcedure:WX,clearExpiredProcedures:_X};var LX=new Set(["true","false","null","undefined","and","or","not"]);function UX(Z,$){let X=Z.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),Q=[],H=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,K;while((K=H.exec(X))!==null)Q.push(K[1]);let z=[...new Set(Q)].filter((G)=>!LX.has(G)&&!(G in $)&&!new RegExp(`\\b${G}\\s*\\(`).test(X));if(z.length>0)console.warn(`[Agent99 Builder] Condition "${Z}" references variables not in vars mapping: ${z.join(", ")}. Add them to vars or use AsyncJS syntax (ajs\`...\`) which handles this automatically.`)}function B4(Z,$){UX(Z,$);let X=qX(Z),Q=X8(X,0,$);if(Q.pos<X.length){let H=X.slice(Q.pos).join(" ");throw Error(`Unsupported condition syntax near '${H}' in: ${Z}
432
+ Supported: comparisons, &&, ||, !, arithmetic, member access (a.b), literals`)}return Q.node}function qX(Z){let $=[],X=0;while(X<Z.length){while(X<Z.length&&/\s/.test(Z[X]))X++;if(X>=Z.length)break;if(Z[X]==='"'||Z[X]==="'"){let Q=Z[X++],H="";while(X<Z.length&&Z[X]!==Q)if(Z[X]==="\\"&&X+1<Z.length)X++,H+=Z[X++];else H+=Z[X++];X++,$.push(JSON.stringify(H));continue}if(Z.slice(X,X+2).match(/^(&&|\|\||==|!=|>=|<=)$/)){$.push(Z.slice(X,X+2)),X+=2;continue}if("+-*/%><!().?:[]".includes(Z[X])){$.push(Z[X]),X++;continue}if(/\d/.test(Z[X])){let Q="";while(X<Z.length&&/[\d.]/.test(Z[X]))Q+=Z[X++];$.push(Q);continue}if(/[a-zA-Z_]/.test(Z[X])){let Q="";while(X<Z.length&&/[a-zA-Z0-9_]/.test(Z[X]))Q+=Z[X++];$.push(Q);continue}X++}return $}function X8(Z,$,X){return DX(Z,$,X)}function DX(Z,$,X){let{node:Q,pos:H}=t7(Z,$,X);while(Z[H]==="||"){H++;let{node:K,pos:Y}=t7(Z,H,X);Q={$expr:"logical",op:"||",left:Q,right:K},H=Y}return{node:Q,pos:H}}function t7(Z,$,X){let{node:Q,pos:H}=e7(Z,$,X);while(Z[H]==="&&"){H++;let{node:K,pos:Y}=e7(Z,H,X);Q={$expr:"logical",op:"&&",left:Q,right:K},H=Y}return{node:Q,pos:H}}function e7(Z,$,X){let{node:Q,pos:H}=Z8(Z,$,X),K=["==","!=",">","<",">=","<="];while(K.includes(Z[H])){let Y=Z[H++],{node:z,pos:G}=Z8(Z,H,X);Q={$expr:"binary",op:Y,left:Q,right:z},H=G}return{node:Q,pos:H}}function Z8(Z,$,X){let{node:Q,pos:H}=$8(Z,$,X);while(Z[H]==="+"||Z[H]==="-"){let K=Z[H++],{node:Y,pos:z}=$8(Z,H,X);Q={$expr:"binary",op:K,left:Q,right:Y},H=z}return{node:Q,pos:H}}function $8(Z,$,X){let{node:Q,pos:H}=L6(Z,$,X);while(Z[H]==="*"||Z[H]==="/"||Z[H]==="%"){let K=Z[H++],{node:Y,pos:z}=L6(Z,H,X);Q={$expr:"binary",op:K,left:Q,right:Y},H=z}return{node:Q,pos:H}}function L6(Z,$,X){if(Z[$]==="!"||Z[$]==="-"){let Q=Z[$++],{node:H,pos:K}=L6(Z,$,X);return{node:{$expr:"unary",op:Q,argument:H},pos:K}}return AX(Z,$,X)}function AX(Z,$,X){let Q=Z[$];if(Q==="("){let{node:H,pos:K}=X8(Z,$+1,X);return{node:H,pos:K+1}}if(Q&&Q.startsWith('"'))return{node:{$expr:"literal",value:JSON.parse(Q)},pos:$+1};if(Q&&/^\d/.test(Q))return{node:{$expr:"literal",value:parseFloat(Q)},pos:$+1};if(Q==="true")return{node:{$expr:"literal",value:!0},pos:$+1};if(Q==="false")return{node:{$expr:"literal",value:!1},pos:$+1};if(Q==="null")return{node:{$expr:"literal",value:null},pos:$+1};if(Q&&/^[a-zA-Z_]/.test(Q)){let H={$expr:"ident",name:Q},K=$+1;while(Z[K]==="."){K++;let Y=Z[K++];H={$expr:"member",object:H,property:Y}}return{node:H,pos:K}}return{node:{$expr:"literal",value:null},pos:$+1}}class H1{steps=[];atoms;proxy;constructor(Z){return this.atoms=Z,this.proxy=new Proxy(this,{get:($,X,Q)=>{if(X in $)return $[X];if(typeof X==="string"&&X in $.atoms)return(H)=>{let K=$.atoms[X];return $.add(K.create(H)),Q};return}}),this.proxy}add(Z){return this.steps.push(Z),this.proxy}as(Z){if(this.steps.length===0)throw Error("No step to capture");let $=this.steps[this.steps.length-1];return $.result=Z,this.proxy}step(Z){return this.add(Z)}return(Z){let $=this.atoms.return;if(!$)throw Error("Atom 'return' not found");let X=Z.schema??Z;return this.add($.create({schema:X}))}toJSON(){return{op:"seq",steps:[...this.steps]}}varsImport(Z){return this.add(this.atoms.varsImport.create({keys:Z}))}varsExport(Z){return this.add(this.atoms.varsExport.create({keys:Z}))}if(Z,$,X,Q){let H=new H1(this.atoms);X(H);let K;if(Q){let G=new H1(this.atoms);Q(G),K=G.steps}let Y=B4(Z,$),z=this.atoms.if;return this.add(z.create({condition:Y,then:H.steps,else:K}))}while(Z,$,X){let Q=new H1(this.atoms);X(Q);let H=B4(Z,$),K=this.atoms.while;return this.add(K.create({condition:H,body:Q.steps}))}scope(Z){let $=new H1(this.atoms);Z($);let X=this.atoms.scope;return this.add(X.create({steps:$.steps}))}map(Z,$,X){let Q=new H1(this.atoms);X(Q);let H=this.atoms.map;return this.add(H.create({items:Z,as:$,steps:Q.steps}))}filter(Z,$,X,Q={}){let H=B4(X,Q),K=this.atoms.filter;return this.add(K.create({items:Z,as:$,condition:H}))}find(Z,$,X,Q={}){let H=B4(X,Q),K=this.atoms.find;return this.add(K.create({items:Z,as:$,condition:H}))}reduce(Z,$,X,Q,H){let K=new H1(this.atoms);H(K);let Y=this.atoms.reduce;return this.add(Y.create({items:Z,as:$,accumulator:X,initial:Q,steps:K.steps}))}memoize(Z,$){let X=new H1(this.atoms);Z(X);let Q=this.atoms.memoize;return this.add(Q.create({key:$,steps:X.steps}))}cache(Z,$,X){let Q=new H1(this.atoms);Z(Q);let H=this.atoms.cache;return this.add(H.create({key:$,steps:Q.steps,ttlMs:X}))}try(Z){let $=new H1(this.atoms);Z.try($);let X;if(Z.catch){let H=new H1(this.atoms);Z.catch(H),X=H.steps}let Q=this.atoms.try;return this.add(Q.create({try:$.steps,catch:X}))}}var IX={take(Z){return new H1(R4)},custom(Z){return new H1(Z)},args(Z){return{$kind:"arg",path:Z}},val(Z){return Z}},sH=IX;import{validate as RX}from"tosijs-schema";function P0(Z,$={}){let{ast:X,returnType:Q,originalSource:H,requiredParams:K}=F1(Z,{filename:$.filename,colonShorthand:!0,vmTarget:!0}),Y=h0(X,$.filename),{ast:z,signature:G,warnings:J}=U0(Y,H,Q,$,K);return{ast:z,signature:G,warnings:J}}var BX=10;class U6{atoms;constructor(Z={}){this.atoms={...R4,...Z}}get builder(){return new H1(this.atoms)}get Agent(){return new H1(this.atoms)}get A99(){return this.Agent}resolve(Z){return this.atoms[Z]}getTools(Z="all"){let $=Object.values(this.atoms);if(Array.isArray(Z))$=$.filter((X)=>Z.includes(X.op));else if(Z==="flow"){let X=["seq","if","while","return","try","varSet","varGet","scope"];$=$.filter((Q)=>X.includes(Q.op))}return $.map((X)=>({type:"function",function:{name:X.op,description:X.docs,parameters:X.inputSchema?.schema??{}}}))}async run(Z,$={},X={}){let Q;if(typeof Z==="string")if(J6(Z))Q=W6(Z);else try{Q=P0(Z).ast}catch(L){throw Error(`AJS transpilation failed: ${L.message}`)}else Q=Z;let H=X.fuel??1000,K=X.timeoutMs??H*BX,Y=X.capabilities??{},z=[];if(!Y.store){let L=new Map,q=!1;Y.store={get:async(A)=>{if(!q)q=!0,z.push("Using default in-memory store (not suitable for production)");return L.get(A)},set:async(A,B)=>{if(!q)q=!0,z.push("Using default in-memory store (not suitable for production)");L.set(A,B)}}}let G=new AbortController,J=setTimeout(()=>G.abort(),K);if(X.signal)X.signal.addEventListener("abort",()=>G.abort());let W={fuel:{current:H},args:$,state:{},consts:new Set,capabilities:Y,resolver:(L)=>this.resolve(L),output:void 0,signal:G.signal,costOverrides:X.costOverrides,context:X.context,warnings:z};if(X.trace)W.trace=[];if(Q.op!=="seq")throw Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let U=Q.inputSchema;if(U&&!RX($,U)){let L=new J1("Input validation failed: args do not match expected schema","vm.run");return{result:L,error:L,fuelUsed:0,trace:W.trace,warnings:z.length>0?z:void 0}}try{await Promise.race([this.resolve("seq")?.exec(Q,W),new Promise((L,q)=>{if(G.signal.addEventListener("abort",()=>{q(Error(`Execution timeout after ${K}ms (fuel: ${H}). Consider increasing fuel or optimizing your agent.`))}),G.signal.aborted)q(Error(`Execution timeout after ${K}ms (fuel: ${H}). Consider increasing fuel or optimizing your agent.`))})])}catch(L){if(L.message?.includes("timeout")||L.message?.includes("aborted")||G.signal.aborted)W.error=new J1(`Execution timeout after ${K}ms (fuel: ${H}). Consider increasing fuel or optimizing your agent.`,"vm.run");else throw L}finally{clearTimeout(J)}if(W.error&&W.output===void 0)W.output=W.error;let _=[...z,...W.warnings??[]];return{result:W.output,error:W.error,fuelUsed:H-W.fuel.current,trace:W.trace,warnings:_.length>0?_:void 0}}}var wX=null,Q8=()=>wX??=new U6;function i1(Z){if(!Z||typeof Z!=="object")return;if(Array.isArray(Z)){for(let $ of Z)i1($);return}if(Z.op==="return"&&"value"in Z)Z.value={__result:Z.value};if(Z.steps)i1(Z.steps);if(Z.then)i1(Z.then);if(Z.else)i1(Z.else);if(Z.body)i1(Z.body)}async function jX(Z){let{code:$,context:X={},fuel:Q=1000,timeoutMs:H,capabilities:K={}}=Z,Y=Q8(),G=/\breturn\b/.test($)?`function __eval() { ${$} }`:`function __eval() { return (${$}) }`;try{let{ast:J}=P0(G);i1(J);let W=await Y.run(J,X,{fuel:Q,timeoutMs:H,capabilities:K}),U=W.result;return{result:U&&typeof U==="object"&&"__result"in U?U.__result:U,fuelUsed:W.fuelUsed,error:W.error?{message:W.error.message||String(W.error)}:void 0}}catch(J){return{result:void 0,fuelUsed:Q,error:{message:J.message||String(J)}}}}async function MX(Z){let{body:$,params:X=[],fuel:Q=1000,timeoutMs:H,capabilities:K={}}=Z,Y=Q8(),G=`function __safeFn(${X.join(", ")}) { ${$} }`,{ast:J}=P0(G);return i1(J),async(...W)=>{let U={};for(let _=0;_<X.length;_++)U[X[_]]=W[_];try{let _=await Y.run(J,U,{fuel:Q,timeoutMs:H,capabilities:K}),L=_.result;return{result:L&&typeof L==="object"&&"__result"in L?L.__result:L,fuelUsed:_.fuelUsed,error:_.error?{message:_.error.message||String(_.error)}:void 0}}catch(_){return{result:void 0,fuelUsed:Q,error:{message:_.message||String(_)}}}}}function j4(Z,$={}){let{ast:X,returnType:Q,originalSource:H,requiredParams:K}=F1(Z,{filename:$.filename,colonShorthand:!0,vmTarget:!0}),Y=h0(X,$.filename),{ast:z,signature:G,warnings:J}=U0(Y,H,Q,$,K);return{ast:z,signature:G,warnings:J}}function UK(Z,...$){if(typeof Z==="string")return j4(Z).ast;let X=Z.reduce((Q,H,K)=>Q+H+($[K]!==void 0?String($[K]):""),"");return j4(X).ast}function DK(Z,$,...X){if(typeof Z==="string")return M0(Z,$);let Q=$!==void 0?[$,...X]:X,H=Z.reduce((K,Y,z)=>K+Y+(Q[z]!==void 0?String(Q[z]):""),"");return M0(H)}async function AK(Z,$={},X){let Q=X??await U4(),H=await Q.getTranspile(Z);if(H)return{ast:H.ast,signature:H.signature,warnings:H.warnings};let K=j4(Z,$);return Q.setTranspile(Z,{ast:K.ast,signature:K.signature,warnings:K.warnings}),K}async function IK(Z,$={},X){let Q=X??await U4(),H=await Q.getTJS(Z);if(H)return{code:H.code,types:H.types,metadata:H.types,testRunner:H.testRunner,testCount:H.testCount,warnings:H.warnings};let K=M0(Z,$);return Q.setTJS(Z,{code:K.code,types:K.types,testRunner:K.testRunner,testCount:K.testCount,warnings:K.warnings}),K}function RK(Z,$,X){let{ast:Q,signature:H}=j4(Z),K=async(Y)=>{return(await $.run(Q,Y,X)).result};return K.signature=H,K.ast=Q,K}function BK(Z){return Object.entries(Z).map(([$,X])=>{let Q=X.signature,H={},K=[];for(let[Y,z]of Object.entries(Q.parameters)){if(H[Y]=w4(z.type),z.description)H[Y].description=z.description;if(z.required)K.push(Y)}return{type:"function",function:{name:Q.name||$,description:Q.description,parameters:{type:"object",properties:H,required:K}}}})}function w4(Z){switch(Z.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:Z.items?w4(Z.items):{}};case"object":if(!Z.shape)return{type:"object"};return{type:"object",properties:Object.fromEntries(Object.entries(Z.shape).map(([$,X])=>[$,w4(X)]))};case"union":if(!Z.members)return{};return{anyOf:Z.members.map(w4)};case"any":default:return{}}}import{s as h}from"tosijs-schema";var H8=v("storeVectorize",h.object({text:h.string,model:h.string.optional}),h.array(h.number),async({text:Z},$)=>{let X=$.capabilities.vector;if(!X)throw Error("Capability 'vector' missing. Ensure vector battery is loaded.");let Q=E(Z,$);return X.embed(Q)},{docs:"Generate embeddings using vector battery",cost:20}),K8=v("storeCreateCollection",h.object({collection:h.string,dimension:h.number.optional}),void 0,async({collection:Z,dimension:$},X)=>{let Q=X.capabilities.store;if(!Q?.createCollection)throw Error("Capability 'store' missing or does not support createCollection.");let H=E(Z,X),K=E($,X);return Q.createCollection(H,void 0,K)},{docs:"Create a vector store collection",cost:5}),Y8=v("storeVectorAdd",h.object({collection:h.string,doc:h.any}),void 0,async({collection:Z,doc:$},X)=>{let Q=X.capabilities.store;if(!Q?.vectorAdd)throw Error("Capability 'store' missing or does not support vectorAdd.");let H=E(Z,X),K=E($,X);return Q.vectorAdd(H,K)},{docs:"Add a document to a vector store collection",cost:5}),z8=v("storeSearch",h.object({collection:h.string,queryVector:h.array(h.number),k:h.number.optional,filter:h.record(h.any).optional}),h.array(h.any),async({collection:Z,queryVector:$,k:X,filter:Q},H)=>{let K=H.capabilities.store;if(!K?.vectorSearch)throw Error("Capability 'store' missing or does not support vectorSearch.");let Y=E(Z,H),z=E($,H),G=E(X,H)??5,J=E(Q,H);return K.vectorSearch(Y,z,G,J)},{docs:"Search vector store",cost:(Z,$)=>5+(E(Z.k,$)??5)}),G8=v("llmPredictBattery",h.object({system:h.string.optional,user:h.string,tools:h.array(h.any).optional,responseFormat:h.any.optional}),h.object({role:h.string.optional,content:h.string.optional,tool_calls:h.array(h.any).optional}),async({system:Z,user:$,tools:X,responseFormat:Q},H)=>{let K=H.capabilities.llmBattery;if(!K?.predict)throw Error("Capability 'llmBattery' missing or invalid.");let Y=E(Z,H)??"You are a helpful agent.",z=E($,H),G=E(X,H),J=E(Q,H);return K.predict(Y,z,G,J)},{docs:"Generate completion using LLM battery",cost:100}),J8=v("llmVision",h.object({system:h.string.optional,prompt:h.string,images:h.array(h.string),responseFormat:h.any.optional}),h.object({role:h.string.optional,content:h.string.optional,tool_calls:h.array(h.any).optional}),async({system:Z,prompt:$,images:X,responseFormat:Q},H)=>{let K=H.capabilities.llmBattery;if(!K?.predict)throw Error("Capability 'llmBattery' missing or invalid.");let Y=E(Z,H)??"You analyze images accurately and concisely.",z=E($,H),G=E(X,H)??[],J=E(Q,H);return K.predict(Y,{text:z,images:G},void 0,J)},{docs:"Analyze images using a vision model",timeoutMs:120000,cost:150});var dK={storeCreateCollection:K8,storeSearch:z8,storeVectorAdd:Y8,storeVectorize:H8,llmPredictBattery:G8,llmVision:J8};var W8=new Map,M4=new Map;function FX(Z,$){if(Z.length!==$.length)throw Error("Vectors must have the same length for cosine similarity.");let X=0,Q=0,H=0;for(let K=0;K<Z.length;K++)X+=Z[K]*$[K],Q+=Z[K]*Z[K],H+=$[K]*$[K];if(Q=Math.sqrt(Q),H=Math.sqrt(H),Q===0||H===0)return 0;return X/(Q*H)}function q6(){return{async get(Z){return W8.get(Z)},async set(Z,$){W8.set(Z,$)},async createCollection(Z,$,X){if(M4.has(Z))console.warn(`Collection '${Z}' already exists. Overwriting.`);M4.set(Z,[])},async vectorAdd(Z,$){let X=M4.get(Z);if(!X)throw Error(`Collection '${Z}' not found. Create it first.`);if(!$.embedding||!Array.isArray($.embedding))throw Error("Document must have an 'embedding' property that is an array of numbers.");X.push($)},async vectorSearch(Z,$,X=5){let Q=M4.get(Z);if(!Q)throw Error(`Collection '${Z}' not found. Create it first.`);let H=Q.map((K)=>({doc:K,score:FX($,K.embedding)}));return H.sort((K,Y)=>Y.score-K.score),H.slice(0,X).map((K)=>K.doc)}}}function PX(Z){if(typeof Z==="string")return{role:"user",content:Z};let $=[{type:"text",text:Z.text}];for(let X of Z.images||[])$.push({type:"image_url",image_url:{url:X}});return{role:"user",content:$}}var VX="http://localhost:1234/v1";function _8(Z,$=VX){return{async predict(X,Q,H,K){try{let Y=K?Z.getStructuredLLM():Z.getLLM(),z=[{role:"system",content:X},PX(Q)],G=await fetch(`${$}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Y.id,messages:z,temperature:0.7,tools:H,response_format:K})});if(!G.ok)throw Error(`LLM Error: ${G.status} ${G.statusText}`);return(await G.json()).choices[0]?.message??{content:""}}catch(Y){if(Y.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw Y}},async embed(X){try{let Q=Z.getEmbedding(),H=await fetch(`${$}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Q.id,input:X})});if(!H.ok)throw Error(`Embedding Error: ${H.status}`);return(await H.json()).data[0]?.embedding??[]}catch(Q){if(Q.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw Q}}}}var V0=typeof window<"u"&&typeof window.localStorage<"u";async function NX(Z){try{if(V0){let $=window.localStorage.getItem(".models.cache.json");if(!$)return null;let X=JSON.parse($);if(X.baseUrl!==Z)return null;if(Date.now()-X.timestamp>86400000)return null;return X.models}else{let $=await import("node:fs/promises"),Q=(await Promise.resolve().then(() => (I6(),A6))).join(process.cwd(),".models.cache.json");try{let H=await $.readFile(Q,"utf-8"),K=JSON.parse(H);if(K.baseUrl!==Z)return null;if(Date.now()-K.timestamp>86400000)return null;return K.models}catch{return null}}}catch($){return console.warn("⚠️ Error reading model cache:",$),null}}async function EX(Z,$){let X={timestamp:Date.now(),baseUrl:Z,models:$};try{if(V0)window.localStorage.setItem(".models.cache.json",JSON.stringify(X));else{let Q=await import("node:fs/promises"),K=(await Promise.resolve().then(() => (I6(),A6))).join(process.cwd(),".models.cache.json");await Q.writeFile(K,JSON.stringify(X,null,2))}}catch(Q){console.error("❌ Error writing model cache:",Q)}}var C0=async(Z,$)=>{let X=new AbortController,Q=setTimeout(()=>X.abort(),60000);try{let H=await fetch(Z,{...$,signal:X.signal});return clearTimeout(Q),H}catch(H){throw clearTimeout(Q),H}};async function SX(Z,$){try{let X={type:"json_schema",json_schema:{name:"test",strict:!1,schema:{type:"object",properties:{status:{type:"string"}}}}},Q=await C0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"system",content:"You respond in JSON."},{role:"user",content:'Return JSON: {"status": "ok"}'}],response_format:X,max_tokens:20})});if(!Q.ok){if(Q.status===400)return TX(Z,$);return{ok:!1,msg:`HTTP ${Q.status}`}}let H=await Q.json();return JSON.parse(H.choices[0].message.content),{ok:!0,msg:"OK (Schema)"}}catch(X){return{ok:!1,msg:X.message||"Error"}}}async function TX(Z,$){try{if((await C0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:'JSON: {"a":1}'}],response_format:{type:"json_object"},max_tokens:10})})).ok)return{ok:!0,msg:"OK (Legacy Mode)"};return{ok:!1,msg:"Not Supported"}}catch{return{ok:!1,msg:"Legacy Fail"}}}async function kX(Z,$){try{return(await C0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:"hi"}],max_tokens:1})})).ok}catch{return!1}}async function gX(Z,$){try{let X=await C0(`${Z}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,input:"test"})});if(!X.ok)return null;return(await X.json()).data[0]?.embedding?.length??null}catch{return null}}var bX="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";async function vX(Z,$){try{return(await C0(`${Z}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:$,messages:[{role:"user",content:[{type:"text",text:"What color is this?"},{type:"image_url",image_url:{url:bX}}]}],max_tokens:10})})).ok}catch{return!1}}async function V8(Z){let $=await NX(Z),X=[];try{let Y=await fetch(`${Z}/models`);if(!Y.ok)throw Error("Could not connect");X=(await Y.json()).data.map((G)=>G.id).sort()}catch(Y){if($)return console.log("⚠️ LM Studio unavailable, using cached model audit."),$;return console.error("❌ Failed to connect to LM Studio."),[]}if($){let Y=$.map((z)=>z.id).sort();if(JSON.stringify(X)===JSON.stringify(Y))return console.log("✅ Using cached model audit."),$;console.log("\uD83D\uDD0D Model list changed. Re-running audit...")}console.log("\uD83D\uDD0D Scanning models (this may take a moment)...");let Q=[],H=X.map((Y)=>({id:Y})),K;if(!V0)K=await import("node:readline");for(let Y of H){if(!V0&&K)K.cursorTo(process.stdout,0),process.stdout.write(`\uD83D\uDC49 Testing: ${Y.id}...`),K.clearLine(process.stdout,1);let z="Unknown",G=!1,J=!1,W="",U=void 0,_=await kX(Z,Y.id),L=await gX(Z,Y.id);if(L)U=L;if(_){z="LLM";let q=await SX(Z,Y.id);if(G=q.ok,J=await vX(Z,Y.id),W=G?q.msg:`Fail: ${q.msg}`,J)W+=" +Vision"}else if(L)z="Embedding",W=`OK (Dim: ${L})`;else W="LLM Fail";Q.push({id:Y.id,type:z,structuredOutput:G,vision:J,dimension:U,status:W})}if(!V0&&K)K.cursorTo(process.stdout,0),K.clearLine(process.stdout,0);return console.log(`
433
+ `),console.table(Q),await EX(Z,Q),console.log("\uD83D\uDCDD Audit results saved to cache."),Q}var fX="http://localhost:1234/v1";class R6{baseUrl;models=[];defaultLLM=null;defaultEmbedding=null;defaultStructuredLLM=null;constructor(Z=fX){this.baseUrl=Z}async audit(){this.models=await V8(this.baseUrl),this.selectDefaults()}selectDefaults(){if(this.defaultEmbedding=this.models.find((Z)=>Z.type==="Embedding")||null,this.defaultLLM=this.models.find((Z)=>Z.type==="LLM")||null,this.defaultStructuredLLM=this.models.find((Z)=>Z.type==="LLM"&&Z.structuredOutput)||null,!this.defaultEmbedding)console.warn("⚠️ No embedding model found.");if(!this.defaultLLM)console.warn("⚠️ No LLM found.");if(!this.defaultStructuredLLM)console.warn("⚠️ No LLM with structured output support found.")}getModels(){return this.models}_setDefaultModel(Z,$,X,Q){let H=this.models.find((K)=>K.id===Z&&X(K));if(!H)throw Error(`Model '${Z}' not found or is not ${Q}.`);this[$]=H}setDefaultLLM(Z){this._setDefaultModel(Z,"defaultLLM",($)=>$.type==="LLM","an LLM")}setDefaultEmbedding(Z){this._setDefaultModel(Z,"defaultEmbedding",($)=>$.dimension!==void 0,"an embedding model")}setDefaultStructuredLLM(Z){this._setDefaultModel(Z,"defaultStructuredLLM",($)=>$.type==="LLM"&&$.structuredOutput,"a structured-output LLM")}getLLM(){if(!this.defaultLLM)throw Error("No LLM available.");return this.defaultLLM}getEmbedding(){if(!this.defaultEmbedding)throw Error("No embedding model available.");return this.defaultEmbedding}getStructuredLLM(){if(!this.defaultStructuredLLM)throw Error("No structured-output LLM available.");return this.defaultStructuredLLM}}var yX=typeof window<"u",hX=yX&&window.location.protocol==="https:",O0=null,B6=null,C8=!1;async function xX(){if(C8)return{localModels:O0,llm:B6};if(C8=!0,hX)return console.log("\uD83D\uDCE1 HTTPS detected - local LLM endpoints disabled. Use HTTP for local LLM support."),{localModels:null,llm:null};try{O0=new R6,await O0.audit(),B6=_8(O0)}catch(Z){console.warn("⚠️ Could not connect to local LLM:",Z)}return{localModels:O0,llm:B6}}async function uX(){let{localModels:Z,llm:$}=await xX();return{vector:$?{embed:$.embed}:void 0,store:q6(),llmBattery:$,models:Z}}async function rK(){return uX()}var tK={store:q6(),llmBattery:null,vector:void 0,models:null};function dX(Z){if(typeof Z!=="string")return!1;let $=new Date(Z);return!isNaN($.getTime())&&Z.includes("T")}function lX(){return new Date().toISOString()}function X0(Z,$,X,Q=0,H=0,K=0,Y=0){return new Date(Date.UTC(Z,$-1,X,Q,H,K,Y)).toISOString()}function O8(Z){let $=new Date(Z);if(isNaN($.getTime()))throw Error(`Invalid date string: ${Z}`);return $.toISOString()}function mX(Z){try{return O8(Z)}catch{return null}}function N0(Z,$){let X=new Date(Z);return X.setTime(X.getTime()+$),X.toISOString()}function iX(Z,$){return N0(Z,$*1000)}function pX(Z,$){return N0(Z,$*60*1000)}function nX(Z,$){return N0(Z,$*60*60*1000)}function N8(Z,$){return N0(Z,$*24*60*60*1000)}function cX(Z,$){return N8(Z,$*7)}function oX(Z,$){let X=new Date(Z),Q=X.getUTCMonth()+$;if(X.setUTCMonth(Q),X.getUTCMonth()!==(Q%12+12)%12)X.setUTCDate(0);return X.toISOString()}function sX(Z,$){let X=new Date(Z),Q=X.getUTCDate();if(X.setUTCFullYear(X.getUTCFullYear()+$),X.getUTCDate()!==Q)X.setUTCDate(0);return X.toISOString()}function k1(Z,$){return new Date(Z).getTime()-new Date($).getTime()}function aX(Z,$){return Math.floor(k1(Z,$)/1000)}function rX(Z,$){return Math.floor(k1(Z,$)/60000)}function tX(Z,$){return Math.floor(k1(Z,$)/3600000)}function eX(Z,$){return Math.floor(k1(Z,$)/86400000)}function Q0(Z){return new Date(Z).getUTCFullYear()}function P4(Z){return new Date(Z).getUTCMonth()+1}function w6(Z){return new Date(Z).getUTCDate()}function ZQ(Z){return new Date(Z).getUTCHours()}function $Q(Z){return new Date(Z).getUTCMinutes()}function XQ(Z){return new Date(Z).getUTCSeconds()}function QQ(Z){return new Date(Z).getUTCMilliseconds()}function HQ(Z){let $=new Date(Z).getUTCDay();return $===0?7:$}function V4(Z,$,X){let Q=new Date(Z),H={timeZone:$,...X};return new Intl.DateTimeFormat(void 0,H).format(Q)}function KQ(Z,$){return V4(Z,$,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}function YQ(Z,$){return V4(Z,$,{year:"numeric",month:"short",day:"numeric"})}function zQ(Z,$){return V4(Z,$,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function GQ(Z){return Z.slice(0,10)}function E8(Z,$){return k1(Z,$)<0}function S8(Z,$){return k1(Z,$)>0}function JQ(Z,$){return k1(Z,$)===0}function WQ(Z,$){return E8(Z,$)?Z:$}function _Q(Z,$){return S8(Z,$)?Z:$}function LQ(Z){return X0(Q0(Z),P4(Z),w6(Z))}function UQ(Z){return X0(Q0(Z),P4(Z),w6(Z),23,59,59,999)}function qQ(Z){return X0(Q0(Z),P4(Z),1)}function DQ(Z){let $=new Date(Z);return $.setUTCMonth($.getUTCMonth()+1,0),$.setUTCHours(23,59,59,999),$.toISOString()}function AQ(Z){return X0(Q0(Z),1,1)}function IQ(Z){return X0(Q0(Z),12,31,23,59,59,999)}var H0={isValid:dX,now:lX,from:X0,parse:O8,tryParse:mX,addMilliseconds:N0,addSeconds:iX,addMinutes:pX,addHours:nX,addDays:N8,addWeeks:cX,addMonths:oX,addYears:sX,diff:k1,diffSeconds:aX,diffMinutes:rX,diffHours:tX,diffDays:eX,year:Q0,month:P4,day:w6,hour:ZQ,minute:$Q,second:XQ,millisecond:QQ,dayOfWeek:HQ,toLocal:V4,format:KQ,formatDate:YQ,formatTime:zQ,toDate:GQ,isBefore:E8,isAfter:S8,isEqual:JQ,min:WQ,max:_Q,startOfDay:LQ,endOfDay:UQ,startOfMonth:qQ,endOfMonth:DQ,startOfYear:AQ,endOfYear:IQ};function j6(Z){if(typeof Z!=="string")return!1;if(!/^\d{4}-\d{2}-\d{2}$/.test(Z))return!1;let $=parseInt(Z.slice(0,4),10),X=parseInt(Z.slice(5,7),10),Q=parseInt(Z.slice(8,10),10);if(X<1||X>12)return!1;if(Q<1)return!1;let H=[31,28,31,30,31,30,31,31,30,31,30,31],K=X===2&&($%4===0&&$%100!==0||$%400===0)?29:H[X-1];return Q<=K}function RQ(){return H0.toDate(H0.now())}function BQ(Z){let $=new Date;return new Intl.DateTimeFormat("en-CA",{timeZone:Z,year:"numeric",month:"2-digit",day:"2-digit"}).format($)}function q1(Z,$,X){let Q=String(Z).padStart(4,"0"),H=String($).padStart(2,"0"),K=String(X).padStart(2,"0"),Y=`${Q}-${H}-${K}`;if(!j6(Y))throw Error(`Invalid date: ${Z}-${$}-${X}`);return Y}function T8(Z){if(/^\d{4}-\d{2}-\d{2}$/.test(Z)){if(!j6(Z))throw Error(`Invalid date: ${Z}`);return Z}let $=new Date(Z);if(isNaN($.getTime()))throw Error(`Invalid date string: ${Z}`);let X=$.getUTCFullYear(),Q=$.getUTCMonth()+1,H=$.getUTCDate();return q1(X,Q,H)}function wQ(Z){try{return T8(Z)}catch{return null}}function C4(Z,$){let X=g8(Z);return H0.toDate(H0.addDays(X,$))}function jQ(Z,$){return C4(Z,$*7)}function MQ(Z,$){let X=Y1(Z),Q=g1(Z),H=M6(Z),K=X*12+(Q-1)+$,Y=Math.floor(K/12),z=K%12+1,G=E0(Y,z),J=Math.min(H,G);return q1(Y,z,J)}function FQ(Z,$){let X=Y1(Z),Q=g1(Z),H=M6(Z),K=X+$,Y=E0(K,Q),z=Math.min(H,Y);return q1(K,Q,z)}function k8(Z,$){let Q=new Date(Z+"T00:00:00Z").getTime(),H=new Date($+"T00:00:00Z").getTime();return Math.round((Q-H)/86400000)}function PQ(Z,$){let X=Y1(Z),Q=g1(Z),H=Y1($),K=g1($);return(X-H)*12+(Q-K)}function VQ(Z,$){return Y1(Z)-Y1($)}function Y1(Z){return parseInt(Z.slice(0,4),10)}function g1(Z){return parseInt(Z.slice(5,7),10)}function M6(Z){return parseInt(Z.slice(8,10),10)}function F6(Z){let $=new Date(Z+"T00:00:00Z").getUTCDay();return $===0?7:$}function CQ(Z){let $=new Date(Z+"T00:00:00Z"),X=$.getUTCDay()||7;$.setUTCDate($.getUTCDate()+4-X);let Q=new Date(Date.UTC($.getUTCFullYear(),0,1));return Math.ceil((($.getTime()-Q.getTime())/86400000+1)/7)}function OQ(Z){let $=q1(Y1(Z),1,1);return k8(Z,$)+1}function P6(Z){return Math.ceil(g1(Z)/3)}function V6(Z){return Z%4===0&&Z%100!==0||Z%400===0}function E0(Z,$){let X=[31,28,31,30,31,30,31,31,30,31,30,31];if($===2&&V6(Z))return 29;return X[$-1]}function NQ(Z){return V6(Z)?366:365}function g8(Z){return Z+"T00:00:00.000Z"}function EQ(Z){return Math.floor(new Date(Z+"T00:00:00Z").getTime()/1000)}function SQ(Z){let $=new Date(Z*1000);return q1($.getUTCFullYear(),$.getUTCMonth()+1,$.getUTCDate())}function C6(Z,$){let X=new Date(Z+"T00:00:00Z"),Q={timeZone:"UTC",...$};return new Intl.DateTimeFormat(void 0,Q).format(X)}function TQ(Z){return C6(Z,{year:"numeric",month:"long",day:"numeric"})}function kQ(Z){return C6(Z,{year:"numeric",month:"short",day:"numeric"})}function gQ(Z,$){return Z<$}function bQ(Z,$){return Z>$}function vQ(Z,$){return Z===$}function fQ(Z,$){return Z<$?Z:$}function yQ(Z,$){return Z>$?Z:$}function hQ(Z,$,X){return Z>=$&&Z<=X}function xQ(Z){return q1(Y1(Z),g1(Z),1)}function uQ(Z){let $=Y1(Z),X=g1(Z);return q1($,X,E0($,X))}function dQ(Z){let X=(P6(Z)-1)*3+1;return q1(Y1(Z),X,1)}function lQ(Z){let X=P6(Z)*3;return q1(Y1(Z),X,E0(Y1(Z),X))}function mQ(Z){return q1(Y1(Z),1,1)}function iQ(Z){return q1(Y1(Z),12,31)}function pQ(Z){let $=F6(Z);return C4(Z,-($-1))}function nQ(Z){let $=F6(Z);return C4(Z,7-$)}var cQ={isValid:j6,today:RQ,todayIn:BQ,from:q1,parse:T8,tryParse:wQ,addDays:C4,addWeeks:jQ,addMonths:MQ,addYears:FQ,diff:k8,diffMonths:PQ,diffYears:VQ,year:Y1,month:g1,day:M6,dayOfWeek:F6,weekOfYear:CQ,dayOfYear:OQ,quarter:P6,isLeapYear:V6,daysInMonth:E0,daysInYear:NQ,toTimestamp:g8,toUnix:EQ,fromUnix:SQ,format:C6,formatLong:TQ,formatShort:kQ,isBefore:gQ,isAfter:bQ,isEqual:vQ,min:fQ,max:yQ,isBetween:hQ,startOfMonth:xQ,endOfMonth:uQ,startOfQuarter:dQ,endOfQuarter:lQ,startOfYear:mQ,endOfYear:iQ,startOfWeek:pQ,endOfWeek:nQ};export{$X as xmlParse,s4 as wrap,R$ as whileLoop,o$ as vectorSearch,C$ as varsLet,V$ as varsImport,O$ as varsExport,M$ as varSet,P$ as varGet,o4 as validateArgs,KX as uuid,b4 as typeToString,o1 as typeOf,t1 as typeDescriptorToTS,w$ as tryCatch,AK as transpileWithCache,M0 as transpileToJS,r$ as transpileCode,j4 as transpile,U0 as transformFunction,IK as tjsWithCache,DK as tjs,PZ as testUtils,y$ as template,P7 as stripTjsPreamble,Y4 as stripModuleSyntax,n$ as storeSet,c$ as storeQuery,JX as storeProcedure,p$ as storeGet,v$ as split,Z$ as setGlobalCache,U1 as seq,N$ as scope,h1 as runtime,t$ as runCode,B$ as ret,E as resolveValue,W6 as resolveProcedureToken,WX as releaseProcedure,T7 as registerWasmBlock,h$ as regexMatch,T$ as reduce,HX as random,g$ as push,$0 as procedureStore,y0 as preprocess,x$ as pick,H7 as parseReturnType,O1 as parseParameter,F1 as parse,u$ as omit,d$ as merge,XX as memoize,E$ as map,c8 as lookupVariable,s$ as llmPredict,Q$ as lint,b$ as len,l$ as keys,ZX as jsonStringify,e$ as jsonParse,f$ as join,h4 as isValidUrl,x4 as isValidTimestamp,u4 as isValidLegalDate,N1 as isRuntimeType,J6 as isProcedureToken,P1 as isError,z$ as isAgentError,S7 as instantiateWasm,a4 as installRuntime,G1 as inferTypeFromValue,I$ as iff,r5 as hashSourceSync,L4 as hashSource,_6 as hash,BK as getToolDefinitions,q6 as getStoreCapabilityDefault,rK as getStandardCapabilities,o as getLocation,_8 as getLLMCapability,U4 as getGlobalCache,uX as getBatteries,Y$ as generateDocsMarkdown,m7 as generateDocs,E5 as generateDTS,s5 as fromTS,k$ as find,S$ as filter,i$ as fetch,f4 as extractTests,W0 as extractTDoc,B1 as extractLiteralValue,W7 as expectFunction,r as evaluateExpr,j$ as errorAtom,j1 as error,uZ as emitRuntimeWrapper,v as defineAtom,T1 as createChildScope,_1 as createChildContext,RK as createAgent,R4 as coreAtoms,F$ as constSet,zX as consoleWarn,YX as consoleLog,GX as consoleError,_5 as compileWasmBlocks,J4 as compileToWasm,_X as clearExpiredProcedures,x1 as checkType,QX as cache,C1 as builtins,dK as batteryAtoms,tK as batteries,J7 as assertFunction,UK as ajs,a$ as agentRun,t0 as Union,H1 as TypedBuilder,n8 as TypeError,t as Type,c as TranspileError,d4 as TimestampType,H0 as Timestamp,s0 as TUuid,o0 as TUrl,d0 as TString,$4 as TRecord,p0 as TPositiveInt,Z4 as TPair,l0 as TNumber,n0 as TNonEmptyString,K1 as TJS_VERSION,i0 as TInteger,c0 as TEmail,m0 as TBoolean,e0 as TArray,z1 as SyntaxError,a5 as Schema,MX as SafeFunction,G6 as PROCEDURE_TOKEN_PREFIX,r0 as Optional,a0 as Nullable,K6 as MetadataCache,R6 as LocalModels,l4 as LegalDateType,cQ as LegalDate,n1 as Generic,q0 as FunctionPredicate,jX as Eval,X4 as Enum,G$ as DEFAULT_PROCEDURE_TTL,J$ as DEFAULT_MAX_AST_SIZE,U6 as AgentVM,J1 as AgentError,IX as Agent,sH as A99};
432
434
 
433
- //# debugId=409E5B199E0ACB7364756E2164756E21
435
+ //# debugId=FD43EBDED79FDDE964756E2164756E21