tjs-lang 0.2.7 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/demo/docs.json +15 -15
- package/demo/src/tjs-playground.ts +18 -27
- package/dist/index.js +108 -160
- package/dist/index.js.map +6 -6
- package/dist/src/lang/emitters/js.d.ts +34 -2
- package/dist/src/lang/index.d.ts +1 -1
- package/dist/tjs-full.js +108 -160
- package/dist/tjs-full.js.map +6 -6
- package/dist/tjs-transpiler.js +87 -55
- package/dist/tjs-transpiler.js.map +5 -4
- package/docs/docs.json +792 -0
- package/docs/index.js +1962 -1875
- package/docs/index.js.map +7 -7
- package/package.json +1 -1
- package/src/lang/emitters/js.ts +154 -4
- package/src/lang/index.ts +0 -3
- package/src/lang/lang.test.ts +38 -19
- package/src/lang/roundtrip.test.ts +155 -0
- package/src/lang/wasm.test.ts +20 -0
- package/src/lang/wasm.ts +143 -0
package/dist/tjs-transpiler.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),Z=this.line-1,
|
|
3
|
-
`)}}function
|
|
4
|
-
`)$="normal";K++;continue;case"block-comment":if(Z+=W,W==="*"&&F==="/"){Z+=F,K+=2,$="normal";continue}K++;continue;case"regex":if(Z+=W,W==="\\"&&K+1<X.length){Z+=F,K+=2;continue}if(W==="["){K++;while(K<X.length&&X[K]!=="]")if(Z+=X[K],X[K]==="\\"&&K+1<X.length)Z+=X[K+1],K+=2;else K++;if(K<X.length)Z+=X[K],K++;continue}if(W==="/"){K++;while(K<X.length&&/[gimsuy]/.test(X[K]))Z+=X[K],K++;$="normal";continue}K++;continue;case"normal":if(Q.length>0){if(W==="{")Q[Q.length-1]++;else if(W==="}"){if(Q[Q.length-1]--,Q[Q.length-1]===0){Q.pop(),Z+=W,K++,$="template-string";continue}}}if(W==="'"){Z+=W,K++,$="single-string";continue}if(W==='"'){Z+=W,K++,$="double-string";continue}if(W==="`"){Z+=W,K++,$="template-string";continue}if(W==="/"&&F==="/"){Z+=W+F,K+=2,$="line-comment";continue}if(W==="/"&&F==="*"){Z+=W+F,K+=2,$="block-comment";continue}if(W==="/"){let B=Z.trimEnd();if(!B[B.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(B)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(B)){Z+=W,K++,$="regex";continue}}break}if(W==="{"){z++,Z+=W,K++;continue}if(W==="}"){z--;let B=G[G.length-1];if(B&&z===B.braceDepth)G.pop();Z+=W,K++;continue}let D=X.slice(K).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(D){let B=D[0].slice(0,-1);Z+=B,K+=B.length,G.push({type:"class-body",braceDepth:z});continue}let A=X.slice(K).match(/^function\s+(\w+)\s*\(/);if(A){let B=A[1],I=A[0].length,O=X[K+I],w=null,R=K+I;if(O==="?"||O==="!")if(w=O,R++,w==="!")Y.unsafeFunctions.add(B);else Y.safeFunctions.add(B);Z+=`function ${B}(`,K=R;let M=U6(X,K,"(",")");if(!M){Z+=X[K],K++;continue}let{content:P,endPos:j}=M;K=j;let b=C6(P,Y,!0);Z+=b+")";let T=K;while(T<X.length&&/\s/.test(X[T]))T++;let V=X.slice(T,T+2);if(V==="->"||V==="-?"||V==="-!"){T+=2;while(T<X.length&&/\s/.test(X[T]))T++;let S=F6(X,T);if(S){let{type:o,endPos:x}=S;if(H===void 0){if(H=o,V==="-?")J="safe";else if(V==="-!")J="unsafe"}K=x}}continue}let L=X.slice(K).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/);if(L&&U()){let B=L[1],I=L[0].length,O=K+I;Z+=B+"(",K=O;let w=U6(X,K,"(",")");if(!w){Z+=X[K],K++;continue}let{content:R,endPos:M}=w;K=M;let P=C6(R,Y,!0);Z+=P+")";let j=K;while(j<X.length&&/\s/.test(X[j]))j++;if(X.slice(j,j+2)==="->"){j+=2;while(j<X.length&&/\s/.test(X[j]))j++;let T=F6(X,j);if(T)K=T.endPos}else if(X[j]===":"){j++;while(j<X.length&&/\s/.test(X[j]))j++;let T=F6(X,j);if(T)K=T.endPos}continue}if(X[K]==="("){let B=U6(X,K+1,"(",")");if(!B){Z+=X[K],K++;continue}let{content:I,endPos:O}=B,w=O;while(w<X.length&&/\s/.test(X[w]))w++;let R,M=X.slice(w,w+2);if(M==="->"||M==="-?"||M==="-!"){w+=2;while(w<X.length&&/\s/.test(X[w]))w++;let P=F6(X,w);if(P){R=P.type,w=P.endPos;while(w<X.length&&/\s/.test(X[w]))w++}}if(X.slice(w,w+2)==="=>"){let P=null,j=I,b=I.trimStart();if(b.startsWith("?")&&(b.length===1||/\s/.test(b[1])))P="?",j=b.slice(1);else if(b.startsWith("!")&&(b.length===1||/\s/.test(b[1])))P="!",j=b.slice(1);let T=C6(j,Y,!1);Z+=`(${P==="?"?"/* safe */ ":P==="!"?"/* unsafe */ ":""}${T})`,K=O;while(K<w&&/\s/.test(X[K]))Z+=X[K],K++;if(R)K=w}else{let P=N6(I,Y);Z+=`(${P.source})`,K=O}continue}Z+=X[K],K++}return{source:Z,returnType:H,returnSafety:J}}function U6(X,Y,Z,K){let H=1,J=Y,$=!1,Q="";while(J<X.length&&H>0){let G=X[J];if(!$&&(G==="'"||G==='"'||G==="`"))$=!0,Q=G;else if($&&G===Q&&X[J-1]!=="\\")$=!1;else if(!$){if(G===Z)H++;else if(G===K)H--}J++}if(H!==0)return null;return{content:X.slice(Y,J-1),endPos:J}}function t0(X,Y){let Z=Y;while(Z<X.length&&/\s/.test(X[Z]))Z++;if(Z>=X.length)return null;let K=Z,H=X[Z];if(H==="{"||H==="["){let $=H==="{"?"}":"]",Q=U6(X,Z+1,H,$);if(!Q)return null;return{value:X.slice(K,Q.endPos),endPos:Q.endPos}}if(H==="'"||H==='"'||H==="`"){Z++;while(Z<X.length){if(X[Z]===H&&X[Z-1]!=="\\")return Z++,{value:X.slice(K,Z),endPos:Z};Z++}return null}if(/[-+\d]/.test(H)){while(Z<X.length&&/[\d.eE+-]/.test(X[Z]))Z++;return{value:X.slice(K,Z),endPos:Z}}let J=X.slice(Z).match(/^(true|false|null|undefined)\b/);if(J)return{value:J[1],endPos:Z+J[1].length};return null}function H6(X){return X.replace(/(?<!\|)\|(?!\|)/g," || ")}function F6(X,Y){let Z=Y,K=0,H=!1,J="",$=!1,Q=(G)=>({type:H6(X.slice(Y,G).trim()),endPos:G});while(Z<X.length){let G=X[Z];if(!H&&(G==="'"||G==='"'||G==="`")){H=!0,J=G,$=!0,Z++;continue}if(H){if(G===J&&X[Z-1]!=="\\"){if(H=!1,Z++,K===0){let z=Z;while(z<X.length&&/\s/.test(X[z]))z++;if(X[z]==="{"){if(!X.slice(z+1).match(/^\s*(\w+)\s*:/))return Q(Z)}if(X[z]!=="|"&&X[z]!=="&")return Q(Z)}continue}Z++;continue}if(G==="{"||G==="["||G==="("){K++,$=!0,Z++;continue}if(G==="}"||G==="]"||G===")"){if(K--,K===0){Z++;let z=Z;while(z<X.length&&/\s/.test(X[z]))z++;if(X[z]==="|"||X[z]==="&")continue;return Q(Z)}Z++;continue}if(K===0&&G==="{"){if($)return Q(Z);if(X.slice(Z+1).match(/^\s*(\w+)\s*:/)){K++,$=!0,Z++;continue}return Q(Z)}if(K===0&&(G==="|"||G==="&")){if(Z++,Z<X.length&&X[Z]==="|")Z++;while(Z<X.length&&/\s/.test(X[Z]))Z++;continue}if(K===0&&(/\d/.test(G)||G==="-"&&/\d/.test(X[Z+1]))){let z=Z;if(X[z]==="-")z++;while(z<X.length&&/\d/.test(X[z]))z++;if(z<X.length&&X[z]==="."&&/\d/.test(X[z+1])){z++;while(z<X.length&&/\d/.test(X[z]))z++}if(z<X.length&&(X[z]==="e"||X[z]==="E")){if(z++,z<X.length&&(X[z]==="+"||X[z]==="-"))z++;while(z<X.length&&/\d/.test(X[z]))z++}$=!0,Z=z;while(Z<X.length&&/\s/.test(X[Z]))Z++;if(Z<X.length&&X[Z]==="{")return{type:H6(X.slice(Y,z).trim()),endPos:z};if(X[Z]!=="|"&&X[Z]!=="&")return{type:H6(X.slice(Y,z).trim()),endPos:z};continue}if(K===0&&/[a-zA-Z_]/.test(G)){let z=Z;while(z<X.length&&/\w/.test(X[z]))z++;$=!0,Z=z;while(Z<X.length&&/\s/.test(X[Z]))Z++;if(Z<X.length&&X[Z]==="{"){if(!X.slice(Z+1).match(/^\s*(\w+)\s*:/)){let U=z;while(U>Y&&/\s/.test(X[U-1]))U--;return{type:H6(X.slice(Y,U).trim()),endPos:z}}}if(X[Z]!=="|"&&X[Z]!=="&")return{type:H6(X.slice(Y,z).trim()),endPos:z};continue}Z++}if($)return Q(Z);return null}function C6(X,Y,Z){let K=N6(X,{originalSource:X,requiredParams:Y.requiredParams,unsafeFunctions:Y.unsafeFunctions,safeFunctions:Y.safeFunctions}).source,H=B6(K),J=!1,$=new Set,Q=(z)=>{if(Z&&/^\w+$/.test(z)){if($.has(z))throw Error(`Duplicate parameter name '${z}'`);$.add(z)}};return H.map((z)=>{let _=z.trim();if(!_)return z;if(Z&&_.startsWith("{")&&_.endsWith("}")){let F=_.slice(1,-1);return`{ ${W0(F,Y)} }`}if(Z&&_.startsWith("[")&&_.endsWith("]")){let F=_.slice(1,-1);return`[ ${W0(F,Y)} ]`}let U=_.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(U){let[,F,D]=U;return Q(F),J=!0,`${F} = ${D}`}if(!r0(_)){let F=_.match(/^(\w+)\s*=/);if(F)Q(F[1]);return J=!0,z}let W=e0(_);if(W!==-1){let F=_.slice(0,W).trim(),D=_.slice(W+1).trim();if(Q(F),J&&Z&&/^\w+$/.test(F))throw Error(`Required parameter '${F}' cannot follow optional parameter`);if(Z&&/^\w+$/.test(F))Y.requiredParams.add(F);return`${F} = ${D}`}return z}).join(",")}function W0(X,Y){return B6(X).map((H)=>{let J=H.trim();if(!J)return H;let $=J.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if($){let[,z,_]=$;Y.requiredParams.add(z);let U=D6(_);return`${z} = ${U}`}let Q=J.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(Q){let[,z,_]=Q;Y.requiredParams.add(z);let U=A6(_);return`${z} = ${U}`}let G=J.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(G){let[,z,_]=G;return Y.requiredParams.add(z),`${z} = ${_}`}return H}).join(", ")}function D6(X){let Y=X.slice(1,-1).trim();return`{ ${B6(Y).map((H)=>{let J=H.trim();if(!J)return H;let $=J.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if($){let[,U,W]=$;return`${U}: ${D6(W)}`}let Q=J.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(Q){let[,U,W]=Q;return`${U}: ${D6(W)}`}let G=J.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(G){let[,U,W]=G;return`${U}: ${A6(W)}`}let z=J.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(z){let[,U,W]=z;return`${U}: ${A6(W)}`}let _=J.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(_){let[,U,W]=_;return`${U}: ${W}`}return H}).join(", ")} }`}function A6(X){let Y=X.slice(1,-1).trim();return`[ ${B6(Y).map((H)=>{let J=H.trim();if(!J)return H;if(J.startsWith("{")&&J.endsWith("}"))return D6(J);if(J.startsWith("[")&&J.endsWith("]"))return A6(J);return H}).join(", ")} ]`}function r0(X){let Y=0,Z=!1,K=!1,H=!1,J="";for(let $=0;$<X.length;$++){let Q=X[$];if(!H&&(Q==="'"||Q==='"'||Q==="`")){H=!0,J=Q;continue}if(H){if(Q===J&&X[$-1]!=="\\")H=!1;continue}if(Q==="("||Q==="{"||Q==="[")Y++;else if(Q===")"||Q==="}"||Q==="]")Y--;else if(Y===0){if(Q===":")Z=!0;if(Q==="="&&X[$+1]!==">")K=!0}}return Z&&!K}function e0(X){let Y=0,Z=!1,K="";for(let H=0;H<X.length;H++){let J=X[H];if(!Z&&(J==="'"||J==='"'||J==="`")){Z=!0,K=J;continue}if(Z){if(J===K&&X[H-1]!=="\\")Z=!1;continue}if(J==="("||J==="{"||J==="[")Y++;else if(J===")"||J==="}"||J==="]")Y--;else if(Y===0&&J===":")return H}return-1}function q6(X,Y={}){let Z=X,K,H=new Set,J=new Set,$=new Set,Q={tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1},G=X.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);if(G)K=G[2],X=X.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1");let z=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsStandard|TjsSafeEval)\b/,_;while(_=X.match(z)){let L=_[2];if(L==="TjsStrict")Q.tjsEquals=!0,Q.tjsClass=!0,Q.tjsDate=!0,Q.tjsNoeval=!0,Q.tjsStandard=!0;else if(L==="TjsEquals")Q.tjsEquals=!0;else if(L==="TjsClass")Q.tjsClass=!0;else if(L==="TjsDate")Q.tjsDate=!0;else if(L==="TjsNoeval")Q.tjsNoeval=!0;else if(L==="TjsStandard")Q.tjsStandard=!0;else if(L==="TjsSafeEval")Q.tjsSafeEval=!0;X=X.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${L}\\s*`),"$1")}if(Q.tjsStandard)X=$1(X);if(X=H1(X),Q.tjsEquals&&!Y.vmTarget)X=J1(X);X=G1(X),X=W1(X),X=_1(X),X=F1(X),X=D1(X);let{source:U,returnType:W,returnSafety:F}=N6(X,{originalSource:Z,requiredParams:H,unsafeFunctions:J,safeFunctions:$});X=U,X=X1(X);let D=Z1(X);X=D.source;let A=A1(X,Y.dangerouslySkipTests);if(X=A.source,Q.tjsClass)X=q1(X);if(Q.tjsDate)X=B1(X);if(Q.tjsNoeval)X=L1(X);return{source:X,returnType:W,returnSafety:F,moduleSafety:K,tjsModes:Q,originalSource:Z,requiredParams:H,unsafeFunctions:J,safeFunctions:$,wasmBlocks:D.blocks,tests:A.tests,testErrors:A.errors}}function X1(X){let Y="",Z=0;while(Z<X.length){let K=X.slice(Z).match(/^\btry\s*\{/);if(K){let J=Z+K[0].length-1+1,$=1,Q=J;while(Q<X.length&&$>0){let z=X[Q];if(z==="{")$++;else if(z==="}")$--;Q++}if($!==0){Y+=X[Z],Z++;continue}if(X.slice(Q).match(/^\s*(catch|finally)\b/))Y+=X.slice(Z,Q),Z=Q;else{let z=X.slice(J,Q-1);Y+=`try {${z}} catch (__try_err) { return { $error: true, message: __try_err?.message || String(__try_err), op: 'try', cause: __try_err, stack: globalThis.__tjs?.getStack?.() } }`,Z=Q}}else Y+=X[Z],Z++}return Y}function Z1(X){let Y=[],Z="",K=0,H=0;while(K<X.length){let J=X.slice(K).match(/^\bwasm\s*\{/);if(J){let $=K,Q=K+J[0].length,G=1,z=Q;while(z<X.length&&G>0){let M=X[z];if(M==="{")G++;else if(M==="}")G--;z++}if(G!==0){Z+=X[K],K++;continue}let _=X.slice(Q,z-1),U,W=z,F=X.slice(z).match(/^\s*fallback\s*\{/);if(F){let M=z+F[0].length;G=1;let P=M;while(P<X.length&&G>0){let j=X[P];if(j==="{")G++;else if(j==="}")G--;P++}if(G===0)U=X.slice(M,P-1),W=P}let A=Y1(_).map((M)=>{let P=K1(X,$,M);return P?`${M}: ${P}`:M}),L={id:`__tjs_wasm_${H}`,body:_,fallback:U,captures:A,start:$,end:W};Y.push(L);let B=U??_,I=A.map((M)=>M.split(":")[0].trim()),O=I.length>0?I.join(", "):"",w=I.length>0?`globalThis.${L.id}(${O})`:`globalThis.${L.id}()`,R=`(globalThis.${L.id} ? ${w} : (() => {${B}})())`;Z+=R,K=W,H++}else Z+=X[K],K++}return{source:Z,blocks:Y}}function Y1(X){let Y=X.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),Z=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,K=new Set,H;while((H=Z.exec(Y))!==null)K.add(H[1]);let J=new Set,$=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((H=$.exec(Y))!==null)J.add(H[1]);let Q=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((H=Q.exec(Y))!==null)J.add(H[1]);let G=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"]),z=[];for(let _ of K)if(!J.has(_)&&!G.has(_))z.push(_);return z.sort()}function K1(X,Y,Z){let K=X.slice(0,Y),H=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,J=K.match(H);if(!J){let $=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,Q=K.match($);if(!Q)return;return _0(Q[1],Z)}return _0(J[1],Z)}function _0(X,Y){let Z=X.split(",").map((K)=>K.trim());for(let K of Z){let H=K.match(new RegExp(`^${Y}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(H)return H[1];let J=K.match(new RegExp(`^${Y}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(J)return J[1]}return}function B6(X){let Y=[],Z="",K=0,H=!1,J=!1,$=0;while($<X.length){let Q=X[$],G=X[$+1];if(!J&&Q==="/"&&G==="/"){H=!0,Z+="//",$+=2;continue}if(!H&&Q==="/"&&G==="*"){J=!0,Z+="/*",$+=2;continue}if(H&&Q===`
|
|
5
|
-
`){
|
|
6
|
-
`),J=[];for(let $=0;$<
|
|
7
|
-
`)}function
|
|
8
|
-
`)
|
|
9
|
-
`,$);if(Q===-1)Q=X.length;let G=X.slice($,Q).trim();if(G){let z=
|
|
10
|
-
`),
|
|
11
|
-
`);return Z.description=
|
|
12
|
-
${
|
|
13
|
-
`.repeat(B),J=A;continue}}}H+=X[J],J++}return{source:H,tests:Z,errors:K}}function q1(X){let Y=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,Z="",K=0,H;while((H=Y.exec(X))!==null){let J=H[1],$=H[2]||"",Q=H.index,G=Q+H[0].length-1,z=1,_=G+1;while(_<X.length&&z>0){let U=X[_];if(U==="{")z++;else if(U==="}")z--;_++}if(z===0){let U=_,W=X.slice(G,U);Z+=X.slice(K,Q),Z+=`let ${J} = class ${J}${$} ${W}; `,Z+=`${J} = new Proxy(${J}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,K=U}}return Z+=X.slice(K),Z}function B1(X){let Y=[{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:Z,message:K}of Y)if(Z.test(X))throw Error(K);return X}function L1(X){if(/(?<![A-Za-z_$])\beval\s*\(/.test(X))throw Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(X))throw Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return X}import{parseExpressionAt as w1}from"acorn";function y(X){switch(X.type){case"Literal":{let Y=X.value;if(Y===null)return{kind:"null"};if(typeof Y==="string")return{kind:"string"};if(typeof Y==="number")return{kind:"number"};if(typeof Y==="boolean")return{kind:"boolean"};return{kind:"any"}}case"ArrayExpression":{let Y=X.elements;if(Y.length===0)return{kind:"array",items:{kind:"any"}};return{kind:"array",items:y(Y[0])}}case"ObjectExpression":{let Y=X.properties,Z={};for(let K of Y)if(K.type==="Property"&&K.key.type==="Identifier"){let H=K.key.name;Z[H]=y(K.value)}return{kind:"object",shape:Z}}case"LogicalExpression":{let{operator:Y,left:Z,right:K}=X;if(Y==="||"){let H=y(Z),J=y(K);if(J.kind==="null")return{...H,nullable:!0};if(H.kind==="null")return{...J,nullable:!0};return{kind:"union",members:[H,J]}}if(Y==="&&")return y(K);if(Y==="??")return y(K);return{kind:"any"}}case"Identifier":{if(X.name==="undefined")return{kind:"undefined"};return{kind:"any"}}case"UnaryExpression":{if(X.operator==="-"&&X.argument.type==="Literal"){if(typeof X.argument.value==="number")return{kind:"number"}}return{kind:"any"}}default:return{kind:"any"}}}function n(X,Y){if(X.type==="Identifier")return{name:X.name,type:{kind:"any"},required:!0};if(X.type==="AssignmentPattern"){let{left:Z,right:K}=X;if(Z.type!=="Identifier")throw new C("Only simple parameter names are supported",N(X));let H=Z.name,J=Y?.has(H)??!1,$=y(K),Q=i(K);return{name:H,type:$,required:J,default:J?null:Q,example:Q,loc:{start:X.start,end:X.end}}}if(X.type==="ObjectPattern"){let Z=X.properties,K={},H={};for(let J of Z)if(J.type==="Property"){let $=J.key.type==="Identifier"?J.key.name:String(J.key.value);if(J.value.type==="Identifier")K[$]={kind:"any"},H[$]={name:$,type:{kind:"any"},required:!0};else if(J.value.type==="AssignmentPattern"){let Q=n(J.value,Y),G=Y?.has($)??!1;K[$]=Q.type,H[$]={name:$,type:Q.type,required:G,default:G?null:Q.example,example:Q.example}}}return{name:"__destructured__",type:{kind:"object",shape:K,destructuredParams:H},required:!0}}throw new C(`Unsupported parameter pattern: ${X.type}`,N(X))}function i(X){switch(X.type){case"Literal":return X.value;case"ArrayExpression":return X.elements.map((Y)=>Y?i(Y):null);case"ObjectExpression":{let Y={};for(let Z of X.properties)if(Z.type==="Property"&&Z.key.type==="Identifier")Y[Z.key.name]=i(Z.value);return Y}case"UnaryExpression":if(X.operator==="-"){let Y=i(X.argument);return typeof Y==="number"?-Y:void 0}return;case"LogicalExpression":{let{operator:Y,left:Z,right:K}=X;if(Y==="&&"){if(Z.type==="Literal"&&Z.value===null)return null}if(Y==="||")return i(Z)??i(K);if(Y==="??")return i(Z)??i(K);return}default:return}}function A0(X){try{let Y=w1(X,0,{ecmaVersion:2022});return y(Y)}catch{return{kind:"any"}}}function S6(X){switch(X.kind){case"string":return X.nullable?"string | null":"string";case"number":return X.nullable?"number | null":"number";case"boolean":return X.nullable?"boolean | null":"boolean";case"null":return"null";case"any":return"any";case"array":{let Y=X.items?S6(X.items):"any";return X.nullable?`${Y}[] | null`:`${Y}[]`}case"object":{if(!X.shape||Object.keys(X.shape).length===0)return X.nullable?"object | null":"object";let Y=Object.entries(X.shape).map(([Z,K])=>`${Z}: ${S6(K)}`).join(", ");return X.nullable?`{ ${Y} } | null`:`{ ${Y} }`}case"union":return X.members?.map(S6).join(" | ")||"any";default:return"any"}}function L6(X){switch(X.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:X.items?L6(X.items):{}};case"object":if(X.shape){let Y={};for(let[Z,K]of Object.entries(X.shape))Y[Z]=L6(K);return{type:"object",properties:Y,additionalProperties:!1}}return{type:"object"};case"union":if(X.members)return{oneOf:X.members.map(L6)};return{};default:return{}}}function I1(X){let Y={},Z=[];for(let[K,H]of Object.entries(X))if(Y[K]=L6(H.type),H.required)Z.push(K);return{type:"object",properties:Y,required:Z.length>0?Z:void 0,additionalProperties:!1}}function k6(X,Y,Z,K={},H){let J=$6(Y,X),$=new Map;for(let L of X.params){let B=n(L,H);if(B.name==="__destructured__"&&B.type.kind==="object"&&B.type.destructuredParams)for(let[I,O]of Object.entries(B.type.destructuredParams))$.set(I,{...O,description:J.params[I]});else B.description=J.params[B.name],$.set(B.name,B)}let Q;if(Z)Q=A0(Z);let G={depth:0,locals:new Map,parameters:$,atoms:new Set(Object.keys(K.atoms||{})),warnings:[],source:Y,filename:K.filename||"<source>",options:K},z=h(X.body,G),_=[],U=[],W=[];for(let[L,B]of $.entries())if(B.required)U.push(L);else if(B.default!==void 0)W.push({name:L,defaultValue:B.default});else U.push(L);if(U.length>0)_.push({op:"varsImport",keys:U});for(let{name:L,defaultValue:B}of W)_.push({op:"varsImport",keys:[L]}),_.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:L},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:L,value:B}]});_.push(...z);let F=Object.fromEntries($),D={name:X.id?.name||"anonymous",description:J.description,parameters:F,returns:Q},A=I1(F);return{ast:{op:"seq",steps:_,inputSchema:A},signature:D,warnings:G.warnings}}function h(X,Y){let Z=[];for(let K of X.body){let H=J6(K,Y);if(H)if(Array.isArray(H))Z.push(...H);else Z.push(H)}return Z}function J6(X,Y){switch(X.type){case"VariableDeclaration":return R1(X,Y);case"ExpressionStatement":return O1(X,Y);case"IfStatement":return P1(X,Y);case"WhileStatement":return j1(X,Y);case"ForOfStatement":return E1(X,Y);case"TryStatement":return V1(X,Y);case"ReturnStatement":return T1(X,Y);case"ThrowStatement":throw new C("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",N(X),Y.source,Y.filename);case"BlockStatement":return{op:"scope",steps:h(X,f(Y))};case"EmptyStatement":return null;default:throw new C(`Unsupported statement type: ${X.type}`,N(X),Y.source,Y.filename)}}function R1(X,Y){let Z=[],K=X.kind==="const",H=K?"constSet":"varSet";for(let J of X.declarations){if(J.id.type!=="Identifier")throw new C("Only simple variable names are supported",N(J),Y.source,Y.filename);let $=J.id.name;if(J.init){let{step:Q,resultVar:G}=s(J.init,Y,$,K);if(Q)Z.push(Q);else if(G!==$)Z.push({op:H,key:$,value:G});let z=y(J.init);Y.locals.set($,z)}else{if(K)throw new C("const declarations must be initialized",N(J),Y.source,Y.filename);Z.push({op:"varSet",key:$,value:null}),Y.locals.set($,{kind:"any",nullable:!0})}}return Z}function O1(X,Y){let Z=X.expression;if(Z.type==="AssignmentExpression")return M1(Z,Y);if(Z.type==="CallExpression"){let{step:K,resultVar:H}=s(Z,Y);if(K)return K;if(H)return{op:"varSet",key:"_",value:H};return null}return Y.warnings.push({message:"Expression statement has no effect",line:N(X).line,column:N(X).column}),null}function M1(X,Y){if(X.left.type!=="Identifier")throw new C("Only simple variable assignment is supported",N(X),Y.source,Y.filename);let Z=X.left.name,{step:K,resultVar:H}=s(X.right,Y,Z);if(K)return K;return{op:"varSet",key:Z,value:H}}function P1(X,Y){let Z=E(X.test,Y),K=X.consequent.type==="BlockStatement"?h(X.consequent,f(Y)):[J6(X.consequent,Y)].filter(Boolean),H;if(X.alternate)H=X.alternate.type==="BlockStatement"?h(X.alternate,f(Y)):[J6(X.alternate,Y)].filter(Boolean);return{op:"if",condition:Z,then:K,...H&&{else:H}}}function j1(X,Y){let Z=E(X.test,Y),K=X.body.type==="BlockStatement"?h(X.body,f(Y)):[J6(X.body,Y)].filter(Boolean);return{op:"while",condition:Z,body:K}}function E1(X,Y){let Z;if(X.left.type==="VariableDeclaration"){let $=X.left.declarations[0];if($.id.type!=="Identifier")throw new C("Only simple variable names are supported in for...of",N(X.left),Y.source,Y.filename);Z=$.id.name}else if(X.left.type==="Identifier")Z=X.left.name;else throw new C("Unsupported for...of left-hand side",N(X.left),Y.source,Y.filename);let K=g(X.right,Y),H=f(Y);H.locals.set(Z,{kind:"any"});let J=X.body.type==="BlockStatement"?h(X.body,H):[J6(X.body,H)].filter(Boolean);return{op:"map",items:K,as:Z,steps:J}}function V1(X,Y){let Z=h(X.block,f(Y)),K,H;if(X.handler){let J=f(Y);if(X.handler.param?.type==="Identifier")H=X.handler.param.name,J.locals.set(H,{kind:"any"});K=h(X.handler.body,J)}return{op:"try",try:Z,...K&&{catch:K},...H&&{catchParam:H}}}function T1(X,Y){if(!X.argument)return{op:"return",value:{}};let{step:Z,resultVar:K}=s(X.argument,Y,"__returnVal__");if(Z)return[Z,{op:"return",value:K}];return{op:"return",value:g(X.argument,Y)}}var B0=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),C1=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),Q6=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),N1=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 S1(X){if(X.callee.type==="Identifier"){let Y=X.callee.name;return C1.has(Y)||Q6.has(Y)}if(X.callee.type==="MemberExpression"){let Y=X.callee;if(Y.object.type==="Identifier"){let Z=Y.object.name;if(B0.has(Z)||Q6.has(Z))return!0}if(Y.property.type==="Identifier"){let Z=Y.property.name;if(N1.has(Z))return!0}}return!1}function k1(X){if(X.object.type==="Identifier"){let Y=X.object.name;return B0.has(Y)||Q6.has(Y)}return!1}var q0={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 g1(X){if(X.callee.type==="Identifier"){let Y=X.callee.name;if(Q6.has(Y))return q0[Y]||`${Y} is not available in AsyncJS.`}if(X.callee.type==="MemberExpression"){let Y=X.callee;if(Y.object.type==="Identifier"){let Z=Y.object.name;if(Q6.has(Z))return q0[Z]||`${Z} is not available in AsyncJS.`}}return null}function L0(X){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."}[X]||" Use factory functions or object literals instead."}function s(X,Y,Z,K){let H=K?"constSet":"varSet";if(X.type==="ChainExpression")return s(X.expression,Y,Z,K);if(X.type==="NewExpression"){let $=X,Q="constructor";if($.callee.type==="Identifier")Q=$.callee.name;let G=L0(Q);throw new C(`The 'new' keyword is not supported in AsyncJS.${G}`,N(X),Y.source,Y.filename)}if(X.type==="CallExpression"){let $=g1(X);if($)throw new C($,N(X),Y.source,Y.filename)}if(X.type==="CallExpression"&&S1(X)){let $=E(X,Y);if(Z)return{step:{op:H,key:Z,value:$},resultVar:Z};return{step:null,resultVar:$}}if(X.type==="MemberExpression"&&k1(X)){let $=E(X,Y);if(Z)return{step:{op:H,key:Z,value:$},resultVar:Z};return{step:null,resultVar:$}}if(X.type==="CallExpression")return b1(X,Y,Z,K);if(X.type==="TemplateLiteral")return f1(X,Y,Z,K);if(X.type==="BinaryExpression"||X.type==="LogicalExpression"||X.type==="UnaryExpression"){let $=E(X,Y);if(Z)return{step:{op:H,key:Z,value:$},resultVar:Z};return{step:null,resultVar:$}}return{step:null,resultVar:g(X,Y)}}function b1(X,Y,Z,K){let H,J=!1,$;if(X.callee.type==="Identifier")H=X.callee.name;else if(X.callee.type==="MemberExpression"){let G=X.callee;if(G.property.type==="Identifier")H=G.property.name,J=!0,$=g(G.object,Y);else throw new C("Computed method names are not supported",N(X),Y.source,Y.filename)}else throw new C("Only named function calls are supported",N(X),Y.source,Y.filename);if(J)return v1(H,$,X.arguments,Y,Z,K);if(H==="console"&&X.callee.type==="MemberExpression");let Q=y1(X,Y);return{step:{op:H,...Q,...Z&&{result:Z},...Z&&K&&{resultConst:!0}},resultVar:Z}}function v1(X,Y,Z,K,H,J){switch(X){case"map":if(Z.length>0&&(Z[0].type==="ArrowFunctionExpression"||Z[0].type==="FunctionExpression")){let $=Z[0],Q=$.params[0],G=Q?.type==="Identifier"?Q.name:"item",z=f(K);z.locals.set(G,{kind:"any"});let _;if($.body.type==="BlockStatement")_=h($.body,z);else{let{step:U,resultVar:W}=s($.body,z,"result");_=U?[U]:[{op:"varSet",key:"result",value:W}]}return{step:{op:"map",items:Y,as:G,steps:_,...H&&{result:H},...H&&J&&{resultConst:!0}},resultVar:H}}break;case"filter":if(Z.length>0&&(Z[0].type==="ArrowFunctionExpression"||Z[0].type==="FunctionExpression")){let $=Z[0],Q=$.params[0],G=Q?.type==="Identifier"?Q.name:"item",z=f(K);z.locals.set(G,{kind:"any"});let _;if($.body.type==="BlockStatement")throw new C("filter callback must be an expression, not a block",N(Z[0]),K.source,K.filename);else _=E($.body,z);return{step:{op:"filter",items:Y,as:G,condition:_,...H&&{result:H},...H&&J&&{resultConst:!0}},resultVar:H}}break;case"find":if(Z.length>0&&(Z[0].type==="ArrowFunctionExpression"||Z[0].type==="FunctionExpression")){let $=Z[0],Q=$.params[0],G=Q?.type==="Identifier"?Q.name:"item",z=f(K);z.locals.set(G,{kind:"any"});let _;if($.body.type==="BlockStatement")throw new C("find callback must be an expression, not a block",N(Z[0]),K.source,K.filename);else _=E($.body,z);return{step:{op:"find",items:Y,as:G,condition:_,...H&&{result:H},...H&&J&&{resultConst:!0}},resultVar:H}}break;case"reduce":if(Z.length>=2&&(Z[0].type==="ArrowFunctionExpression"||Z[0].type==="FunctionExpression")){let $=Z[0],Q=$.params[0],G=$.params[1],z=Q?.type==="Identifier"?Q.name:"acc",_=G?.type==="Identifier"?G.name:"item",U=f(K);U.locals.set(z,{kind:"any"}),U.locals.set(_,{kind:"any"});let W;if($.body.type==="BlockStatement")W=h($.body,U);else{let{step:D,resultVar:A}=s($.body,U,"result");W=D?[D]:[{op:"varSet",key:"result",value:A}]}let F=g(Z[1],K);return{step:{op:"reduce",items:Y,as:_,accumulator:z,initial:F,steps:W,...H&&{result:H},...H&&J&&{resultConst:!0}},resultVar:H}}break;case"slice":break;case"push":return{step:{op:"push",list:Y,item:g(Z[0],K),...H&&{result:H},...H&&J&&{resultConst:!0}},resultVar:H};case"join":return{step:{op:"join",list:Y,sep:Z.length>0?g(Z[0],K):"",...H&&{result:H},...H&&J&&{resultConst:!0}},resultVar:H};case"split":return{step:{op:"split",str:Y,sep:Z.length>0?g(Z[0],K):"",...H&&{result:H},...H&&J&&{resultConst:!0}},resultVar:H}}return K.warnings.push({message:`Unknown method '${X}' - treating as atom call`,line:0,column:0}),{step:{op:X,receiver:Y,args:Z.map(($)=>g($,K)),...H&&{result:H},...H&&J&&{resultConst:!0}},resultVar:H}}function f1(X,Y,Z,K){let H="",J={};for(let $=0;$<X.quasis.length;$++)if(H+=X.quasis[$].value.cooked||X.quasis[$].value.raw,$<X.expressions.length){let Q=X.expressions[$],G=`_${$}`;J[G]=g(Q,Y),H+=`{{${G}}}`}return{step:{op:"template",tmpl:H,vars:J,...Z&&{result:Z},...Z&&K&&{resultConst:!0}},resultVar:Z}}function E(X,Y){switch(X.type){case"Literal":return{$expr:"literal",value:X.value};case"Identifier":return{$expr:"ident",name:X.name};case"MemberExpression":{let Z=X,K=E(Z.object,Y),H=Z.optional===!0;if(Z.computed){let $=Z.property;if($.type==="Literal")return{$expr:"member",object:K,property:String($.value),computed:!0,...H&&{optional:!0}};throw new C("Computed member access with variables not yet supported",N(X),Y.source,Y.filename)}let J=Z.property.name;return{$expr:"member",object:K,property:J,...H&&{optional:!0}}}case"ChainExpression":return E(X.expression,Y);case"BinaryExpression":{let Z=X;return{$expr:"binary",op:Z.operator,left:E(Z.left,Y),right:E(Z.right,Y)}}case"LogicalExpression":{let Z=X;return{$expr:"logical",op:Z.operator,left:E(Z.left,Y),right:E(Z.right,Y)}}case"UnaryExpression":{let Z=X;return{$expr:"unary",op:Z.operator,argument:E(Z.argument,Y)}}case"ConditionalExpression":{let Z=X;return{$expr:"conditional",test:E(Z.test,Y),consequent:E(Z.consequent,Y),alternate:E(Z.alternate,Y)}}case"ArrayExpression":return{$expr:"array",elements:X.elements.filter((K)=>K!==null).map((K)=>E(K,Y))};case"ObjectExpression":{let Z=X,K=[];for(let H of Z.properties)if(H.type==="Property"){let J=H.key.type==="Identifier"?H.key.name:String(H.key.value);K.push({key:J,value:E(H.value,Y)})}return{$expr:"object",properties:K}}case"CallExpression":{let Z=X;if(Z.callee.type==="MemberExpression"){let K=Z.callee,H=K.property.type==="Identifier"?K.property.name:String(K.property.value),J=K.optional===!0||Z.optional===!0;return{$expr:"methodCall",object:E(K.object,Y),method:H,arguments:Z.arguments.map(($)=>E($,Y)),...J&&{optional:!0}}}if(Z.callee.type==="Identifier")return{$expr:"call",callee:Z.callee.name,arguments:Z.arguments.map((H)=>E(H,Y))};throw new C("Complex function calls in expressions should be lifted to statements",N(X),Y.source,Y.filename)}case"NewExpression":{let Z=X,K="constructor";if(Z.callee.type==="Identifier")K=Z.callee.name;let H=L0(K);throw new C(`The 'new' keyword is not supported in AsyncJS.${H}`,N(X),Y.source,Y.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",N(X),Y.source,Y.filename);default:throw new C(`Unsupported expression type in condition: ${X.type}`,N(X),Y.source,Y.filename)}}function g(X,Y){switch(X.type){case"Literal":return X.value;case"Identifier":return X.name;case"MemberExpression":{let Z=X;if(Z.optional===!0)return E(X,Y);let H=g(Z.object,Y);if(H&&typeof H==="object"&&H.$expr){let $=Z.computed?String(Z.property.value):Z.property.name;return{$expr:"member",object:H,property:$,...Z.computed&&{computed:!0}}}if(Z.computed)return`${H}[${g(Z.property,Y)}]`;let J=Z.property.name;if(typeof H==="string")return`${H}.${J}`;if(H&&H.$kind==="arg")return{$kind:"arg",path:`${H.path}.${J}`};return`${H}.${J}`}case"ChainExpression":return g(X.expression,Y);case"ArrayExpression":return X.elements.map((Z)=>Z?g(Z,Y):null);case"ObjectExpression":{let Z={};for(let K of X.properties)if(K.type==="Property"){let H=K.key.type==="Identifier"?K.key.name:String(K.key.value);Z[H]=g(K.value,Y)}return Z}case"TemplateLiteral":return E(X,Y);case"CallExpression":return E(X,Y);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return E(X,Y);default:return null}}function y1(X,Y){if(X.arguments.length===1&&X.arguments[0].type==="ObjectExpression"){let Z=X.arguments[0],K={};for(let H of Z.properties)if(H.type==="Property"){let J=H.key.type==="Identifier"?H.key.name:String(H.key.value);K[J]=g(H.value,Y)}return K}return{args:X.arguments.map((Z)=>g(Z,Y))}}import{parseExpressionAt as l1}from"acorn";function x1(X,Y){let Z=Y;while(Z>0&&X[Z-1]!==`
|
|
14
|
-
`)Z--;if(X.slice(Z,
|
|
1
|
+
var q1=(X,K)=>()=>(K||X((K={exports:{}}).exports,K),K.exports);var X1=q1((dX,t8)=>{t8.exports={name:"tjs-lang",version:"0.2.8",description:"Type-safe JavaScript dialect with runtime validation, sandboxed VM execution, and AI agent orchestration. Transpiles TypeScript to validated JS with fuel-metered execution for untrusted code.",keywords:["typescript","transpiler","runtime-validation","type-safety","sandbox","virtual-machine","wasm-alternative","ai-agents","llm","orchestration","security","fuel-metering","capability-based","json-ast","untrusted-code"],license:"Apache-2.0",main:"./dist/index.js",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"],sideEffects:!1,repository:{type:"git",url:"https://github.com/tonioloewald/tjs-lang.git"},devDependencies:{"@codemirror/lang-javascript":"^6.2.4","@codemirror/state":"^6.5.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-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 functions:deploy && firebase deploy --only hosting",start:"bun run build:demo && bun run dev"},dependencies:{"@codemirror/lang-css":"^6.3.1","@codemirror/lang-html":"^6.4.11","@codemirror/lang-markdown":"^6.5.0","@codemirror/theme-one-dark":"^6.1.3",acorn:"^8.15.0",firebase:"^10.12.0","tosijs-schema":"^1.2.0"}}});import*as O6 from"acorn";class T extends Error{line;column;source;filename;constructor(X,K,Z,H){let Y=`${H||"<source>"}:${K.line}:${K.column}`;super(`${X} at ${Y}`);this.name="TranspileError",this.line=K.line,this.column=K.column,this.source=Z,this.filename=H}}class r extends T{constructor(X,K,Z,H){super(X,K,Z,H);this.name="SyntaxError"}formatWithContext(X=2){if(!this.source)return this.message;let K=this.source.split(`
|
|
2
|
+
`),Z=this.line-1,H=Math.max(0,Z-X),Y=Math.min(K.length-1,Z+X),J=[],$=String(Y+1).length;for(let Q=H;Q<=Y;Q++){let G=String(Q+1).padStart($),z=Q===Z?">":" ";if(J.push(`${z} ${G} | ${K[Q]}`),Q===Z){let D=" ".repeat($+4+this.column);J.push(`${D}^ ${this.message.split(" at ")[0]}`)}}return J.join(`
|
|
3
|
+
`)}}function m(X){return{depth:X.depth+1,locals:new Map,parent:X,parameters:X.parameters,atoms:X.atoms,warnings:X.warnings,source:X.source,filename:X.filename,options:X.options}}function k(X){if(X.loc)return{line:X.loc.start.line,column:X.loc.start.column};return{line:1,column:0}}function p0(X,K){let Z="",H=0,Y,J,$="normal",Q=[],G=[{type:"top-level",braceDepth:0}],z=0,D=()=>G[G.length-1]?.type||"top-level",F=()=>{let _=G[G.length-1];return _?.type==="class-body"&&z===_.braceDepth+1};while(H<X.length){let _=X[H],q=X[H+1];switch($){case"single-string":if(Z+=_,_==="\\"&&H+1<X.length){Z+=q,H+=2;continue}if(_==="'")$="normal";H++;continue;case"double-string":if(Z+=_,_==="\\"&&H+1<X.length){Z+=q,H+=2;continue}if(_==='"')$="normal";H++;continue;case"template-string":if(Z+=_,_==="\\"&&H+1<X.length){Z+=q,H+=2;continue}if(_==="$"&&q==="{"){Z+=q,H+=2,Q.push(1),$="normal";continue}if(_==="`")$="normal";H++;continue;case"line-comment":if(Z+=_,_===`
|
|
4
|
+
`)$="normal";H++;continue;case"block-comment":if(Z+=_,_==="*"&&q==="/"){Z+=q,H+=2,$="normal";continue}H++;continue;case"regex":if(Z+=_,_==="\\"&&H+1<X.length){Z+=q,H+=2;continue}if(_==="["){H++;while(H<X.length&&X[H]!=="]")if(Z+=X[H],X[H]==="\\"&&H+1<X.length)Z+=X[H+1],H+=2;else H++;if(H<X.length)Z+=X[H],H++;continue}if(_==="/"){H++;while(H<X.length&&/[gimsuy]/.test(X[H]))Z+=X[H],H++;$="normal";continue}H++;continue;case"normal":if(Q.length>0){if(_==="{")Q[Q.length-1]++;else if(_==="}"){if(Q[Q.length-1]--,Q[Q.length-1]===0){Q.pop(),Z+=_,H++,$="template-string";continue}}}if(_==="'"){Z+=_,H++,$="single-string";continue}if(_==='"'){Z+=_,H++,$="double-string";continue}if(_==="`"){Z+=_,H++,$="template-string";continue}if(_==="/"&&q==="/"){Z+=_+q,H+=2,$="line-comment";continue}if(_==="/"&&q==="*"){Z+=_+q,H+=2,$="block-comment";continue}if(_==="/"){let w=Z.trimEnd();if(!w[w.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(w)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(w)){Z+=_,H++,$="regex";continue}}break}if(_==="{"){z++,Z+=_,H++;continue}if(_==="}"){z--;let w=G[G.length-1];if(w&&z===w.braceDepth)G.pop();Z+=_,H++;continue}let U=X.slice(H).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(U){let w=U[0].slice(0,-1);Z+=w,H+=w.length,G.push({type:"class-body",braceDepth:z});continue}let A=X.slice(H).match(/^function\s+(\w+)\s*\(/);if(A){let w=A[1],B=A[0].length,P=X[H+B],L=null,M=H+B;if(P==="?"||P==="!")if(L=P,M++,L==="!")K.unsafeFunctions.add(w);else K.safeFunctions.add(w);Z+=`function ${w}(`,H=M;let j=E0(X,H,"(",")");if(!j){Z+=X[H],H++;continue}let{content:V,endPos:E}=j;H=E;let h=i0(V,K,!0);Z+=h+")";let S=H;while(S<X.length&&/\s/.test(X[S]))S++;let i=X.slice(S,S+2);if(i==="->"||i==="-?"||i==="-!"){S+=2;while(S<X.length&&/\s/.test(X[S]))S++;let O=V0(X,S);if(O){let{type:g,endPos:X0}=O;if(Y===void 0){if(Y=g,i==="-?")J="safe";else if(i==="-!")J="unsafe"}H=X0}}continue}let I=X.slice(H).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/);if(I&&F()){let w=I[1],B=I[0].length,P=H+B;Z+=w+"(",H=P;let L=E0(X,H,"(",")");if(!L){Z+=X[H],H++;continue}let{content:M,endPos:j}=L;H=j;let V=i0(M,K,!0);Z+=V+")";let E=H;while(E<X.length&&/\s/.test(X[E]))E++;if(X.slice(E,E+2)==="->"){E+=2;while(E<X.length&&/\s/.test(X[E]))E++;let S=V0(X,E);if(S)H=S.endPos}else if(X[E]===":"){E++;while(E<X.length&&/\s/.test(X[E]))E++;let S=V0(X,E);if(S)H=S.endPos}continue}if(X[H]==="("){let w=E0(X,H+1,"(",")");if(!w){Z+=X[H],H++;continue}let{content:B,endPos:P}=w,L=P;while(L<X.length&&/\s/.test(X[L]))L++;let M,j=X.slice(L,L+2);if(j==="->"||j==="-?"||j==="-!"){L+=2;while(L<X.length&&/\s/.test(X[L]))L++;let V=V0(X,L);if(V){M=V.type,L=V.endPos;while(L<X.length&&/\s/.test(X[L]))L++}}if(X.slice(L,L+2)==="=>"){let V=null,E=B,h=B.trimStart();if(h.startsWith("?")&&(h.length===1||/\s/.test(h[1])))V="?",E=h.slice(1);else if(h.startsWith("!")&&(h.length===1||/\s/.test(h[1])))V="!",E=h.slice(1);let S=i0(E,K,!1);Z+=`(${V==="?"?"/* safe */ ":V==="!"?"/* unsafe */ ":""}${S})`,H=P;while(H<L&&/\s/.test(X[H]))Z+=X[H],H++;if(M)H=L}else{let V=p0(B,K);Z+=`(${V.source})`,H=P}continue}Z+=X[H],H++}return{source:Z,returnType:Y,returnSafety:J}}function E0(X,K,Z,H){let Y=1,J=K,$=!1,Q="";while(J<X.length&&Y>0){let G=X[J];if(!$&&(G==="'"||G==='"'||G==="`"))$=!0,Q=G;else if($&&G===Q&&X[J-1]!=="\\")$=!1;else if(!$){if(G===Z)Y++;else if(G===H)Y--}J++}if(Y!==0)return null;return{content:X.slice(K,J-1),endPos:J}}function U1(X,K){let Z=K;while(Z<X.length&&/\s/.test(X[Z]))Z++;if(Z>=X.length)return null;let H=Z,Y=X[Z];if(Y==="{"||Y==="["){let $=Y==="{"?"}":"]",Q=E0(X,Z+1,Y,$);if(!Q)return null;return{value:X.slice(H,Q.endPos),endPos:Q.endPos}}if(Y==="'"||Y==='"'||Y==="`"){Z++;while(Z<X.length){if(X[Z]===Y&&X[Z-1]!=="\\")return Z++,{value:X.slice(H,Z),endPos:Z};Z++}return null}if(/[-+\d]/.test(Y)){while(Z<X.length&&/[\d.eE+-]/.test(X[Z]))Z++;return{value:X.slice(H,Z),endPos:Z}}let J=X.slice(Z).match(/^(true|false|null|undefined)\b/);if(J)return{value:J[1],endPos:Z+J[1].length};return null}function F0(X){return X.replace(/(?<!\|)\|(?!\|)/g," || ")}function V0(X,K){let Z=K,H=0,Y=!1,J="",$=!1,Q=(G)=>({type:F0(X.slice(K,G).trim()),endPos:G});while(Z<X.length){let G=X[Z];if(!Y&&(G==="'"||G==='"'||G==="`")){Y=!0,J=G,$=!0,Z++;continue}if(Y){if(G===J&&X[Z-1]!=="\\"){if(Y=!1,Z++,H===0){let z=Z;while(z<X.length&&/\s/.test(X[z]))z++;if(X[z]==="{"){if(!X.slice(z+1).match(/^\s*(\w+)\s*:/))return Q(Z)}if(X[z]!=="|"&&X[z]!=="&")return Q(Z)}continue}Z++;continue}if(G==="{"||G==="["||G==="("){H++,$=!0,Z++;continue}if(G==="}"||G==="]"||G===")"){if(H--,H===0){Z++;let z=Z;while(z<X.length&&/\s/.test(X[z]))z++;if(X[z]==="|"||X[z]==="&")continue;return Q(Z)}Z++;continue}if(H===0&&G==="{"){if($)return Q(Z);if(X.slice(Z+1).match(/^\s*(\w+)\s*:/)){H++,$=!0,Z++;continue}return Q(Z)}if(H===0&&(G==="|"||G==="&")){if(Z++,Z<X.length&&X[Z]==="|")Z++;while(Z<X.length&&/\s/.test(X[Z]))Z++;continue}if(H===0&&(/\d/.test(G)||G==="-"&&/\d/.test(X[Z+1]))){let z=Z;if(X[z]==="-")z++;while(z<X.length&&/\d/.test(X[z]))z++;if(z<X.length&&X[z]==="."&&/\d/.test(X[z+1])){z++;while(z<X.length&&/\d/.test(X[z]))z++}if(z<X.length&&(X[z]==="e"||X[z]==="E")){if(z++,z<X.length&&(X[z]==="+"||X[z]==="-"))z++;while(z<X.length&&/\d/.test(X[z]))z++}$=!0,Z=z;while(Z<X.length&&/\s/.test(X[Z]))Z++;if(Z<X.length&&X[Z]==="{")return{type:F0(X.slice(K,z).trim()),endPos:z};if(X[Z]!=="|"&&X[Z]!=="&")return{type:F0(X.slice(K,z).trim()),endPos:z};continue}if(H===0&&/[a-zA-Z_]/.test(G)){let z=Z;while(z<X.length&&/\w/.test(X[z]))z++;$=!0,Z=z;while(Z<X.length&&/\s/.test(X[Z]))Z++;if(Z<X.length&&X[Z]==="{"){if(!X.slice(Z+1).match(/^\s*(\w+)\s*:/)){let F=z;while(F>K&&/\s/.test(X[F-1]))F--;return{type:F0(X.slice(K,F).trim()),endPos:z}}}if(X[Z]!=="|"&&X[Z]!=="&")return{type:F0(X.slice(K,z).trim()),endPos:z};continue}Z++}if($)return Q(Z);return null}function i0(X,K,Z){let H=p0(X,{originalSource:X,requiredParams:K.requiredParams,unsafeFunctions:K.unsafeFunctions,safeFunctions:K.safeFunctions}).source,Y=S0(H),J=!1,$=new Set,Q=(z)=>{if(Z&&/^\w+$/.test(z)){if($.has(z))throw Error(`Duplicate parameter name '${z}'`);$.add(z)}};return Y.map((z)=>{let D=z.trim();if(!D)return z;if(Z&&D.startsWith("{")&&D.endsWith("}")){let q=D.slice(1,-1);return`{ ${E6(q,K)} }`}if(Z&&D.startsWith("[")&&D.endsWith("]")){let q=D.slice(1,-1);return`[ ${E6(q,K)} ]`}let F=D.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(F){let[,q,U]=F;return Q(q),J=!0,`${q} = ${U}`}if(!A1(D)){let q=D.match(/^(\w+)\s*=/);if(q)Q(q[1]);return J=!0,z}let _=w1(D);if(_!==-1){let q=D.slice(0,_).trim(),U=D.slice(_+1).trim();if(Q(q),J&&Z&&/^\w+$/.test(q))throw Error(`Required parameter '${q}' cannot follow optional parameter`);if(Z&&/^\w+$/.test(q))K.requiredParams.add(q);return`${q} = ${U}`}return z}).join(",")}function E6(X,K){return S0(X).map((Y)=>{let J=Y.trim();if(!J)return Y;let $=J.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if($){let[,z,D]=$;K.requiredParams.add(z);let F=C0(D);return`${z} = ${F}`}let Q=J.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(Q){let[,z,D]=Q;K.requiredParams.add(z);let F=N0(D);return`${z} = ${F}`}let G=J.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(G){let[,z,D]=G;return K.requiredParams.add(z),`${z} = ${D}`}return Y}).join(", ")}function C0(X){let K=X.slice(1,-1).trim();return`{ ${S0(K).map((Y)=>{let J=Y.trim();if(!J)return Y;let $=J.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if($){let[,F,_]=$;return`${F}: ${C0(_)}`}let Q=J.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(Q){let[,F,_]=Q;return`${F}: ${C0(_)}`}let G=J.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(G){let[,F,_]=G;return`${F}: ${N0(_)}`}let z=J.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(z){let[,F,_]=z;return`${F}: ${N0(_)}`}let D=J.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(D){let[,F,_]=D;return`${F}: ${_}`}return Y}).join(", ")} }`}function N0(X){let K=X.slice(1,-1).trim();return`[ ${S0(K).map((Y)=>{let J=Y.trim();if(!J)return Y;if(J.startsWith("{")&&J.endsWith("}"))return C0(J);if(J.startsWith("[")&&J.endsWith("]"))return N0(J);return Y}).join(", ")} ]`}function A1(X){let K=0,Z=!1,H=!1,Y=!1,J="";for(let $=0;$<X.length;$++){let Q=X[$];if(!Y&&(Q==="'"||Q==='"'||Q==="`")){Y=!0,J=Q;continue}if(Y){if(Q===J&&X[$-1]!=="\\")Y=!1;continue}if(Q==="("||Q==="{"||Q==="[")K++;else if(Q===")"||Q==="}"||Q==="]")K--;else if(K===0){if(Q===":")Z=!0;if(Q==="="&&X[$+1]!==">")H=!0}}return Z&&!H}function w1(X){let K=0,Z=!1,H="";for(let Y=0;Y<X.length;Y++){let J=X[Y];if(!Z&&(J==="'"||J==='"'||J==="`")){Z=!0,H=J;continue}if(Z){if(J===H&&X[Y-1]!=="\\")Z=!1;continue}if(J==="("||J==="{"||J==="[")K++;else if(J===")"||J==="}"||J==="]")K--;else if(K===0&&J===":")return Y}return-1}function O0(X,K={}){let Z=X,H,Y=new Set,J=new Set,$=new Set,Q={tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1},G=X.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);if(G)H=G[2],X=X.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1");let z=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsStandard|TjsSafeEval)\b/,D;while(D=X.match(z)){let I=D[2];if(I==="TjsStrict")Q.tjsEquals=!0,Q.tjsClass=!0,Q.tjsDate=!0,Q.tjsNoeval=!0,Q.tjsStandard=!0;else if(I==="TjsEquals")Q.tjsEquals=!0;else if(I==="TjsClass")Q.tjsClass=!0;else if(I==="TjsDate")Q.tjsDate=!0;else if(I==="TjsNoeval")Q.tjsNoeval=!0;else if(I==="TjsStandard")Q.tjsStandard=!0;else if(I==="TjsSafeEval")Q.tjsSafeEval=!0;X=X.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${I}\\s*`),"$1")}if(Q.tjsStandard)X=P1(X);if(X=M1(X),Q.tjsEquals&&!K.vmTarget)X=j1(X);X=C1(X),X=N1(X),X=O1(X),X=S1(X),X=k1(X);let{source:F,returnType:_,returnSafety:q}=p0(X,{originalSource:Z,requiredParams:Y,unsafeFunctions:J,safeFunctions:$});X=F,X=R1(X);let U=I1(X);X=U.source;let A=g1(X,K.dangerouslySkipTests);if(X=A.source,Q.tjsClass)X=v1(X);if(Q.tjsDate)X=b1(X);if(Q.tjsNoeval)X=f1(X);return{source:X,returnType:_,returnSafety:q,moduleSafety:H,tjsModes:Q,originalSource:Z,requiredParams:Y,unsafeFunctions:J,safeFunctions:$,wasmBlocks:U.blocks,tests:A.tests,testErrors:A.errors}}function R1(X){let K="",Z=0;while(Z<X.length){let H=X.slice(Z).match(/^\btry\s*\{/);if(H){let J=Z+H[0].length-1+1,$=1,Q=J;while(Q<X.length&&$>0){let z=X[Q];if(z==="{")$++;else if(z==="}")$--;Q++}if($!==0){K+=X[Z],Z++;continue}if(X.slice(Q).match(/^\s*(catch|finally)\b/))K+=X.slice(Z,Q),Z=Q;else{let z=X.slice(J,Q-1);K+=`try {${z}} catch (__try_err) { return { $error: true, message: __try_err?.message || String(__try_err), op: 'try', cause: __try_err, stack: globalThis.__tjs?.getStack?.() } }`,Z=Q}}else K+=X[Z],Z++}return K}function I1(X){let K=[],Z="",H=0,Y=0;while(H<X.length){let J=X.slice(H).match(/^\bwasm\s*\{/);if(J){let $=H,Q=H+J[0].length,G=1,z=Q;while(z<X.length&&G>0){let j=X[z];if(j==="{")G++;else if(j==="}")G--;z++}if(G!==0){Z+=X[H],H++;continue}let D=X.slice(Q,z-1),F,_=z,q=X.slice(z).match(/^\s*fallback\s*\{/);if(q){let j=z+q[0].length;G=1;let V=j;while(V<X.length&&G>0){let E=X[V];if(E==="{")G++;else if(E==="}")G--;V++}if(G===0)F=X.slice(j,V-1),_=V}let A=B1(D).map((j)=>{let V=L1(X,$,j);return V?`${j}: ${V}`:j}),I={id:`__tjs_wasm_${Y}`,body:D,fallback:F,captures:A,start:$,end:_};K.push(I);let w=F??D,B=A.map((j)=>j.split(":")[0].trim()),P=B.length>0?B.join(", "):"",L=B.length>0?`globalThis.${I.id}(${P})`:`globalThis.${I.id}()`,M=`(globalThis.${I.id} ? ${L} : (() => {${w}})())`;Z+=M,H=_,Y++}else Z+=X[H],H++}return{source:Z,blocks:K}}function B1(X){let K=X.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),Z=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,H=new Set,Y;while((Y=Z.exec(K))!==null)H.add(Y[1]);let J=new Set,$=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((Y=$.exec(K))!==null)J.add(Y[1]);let Q=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;while((Y=Q.exec(K))!==null)J.add(Y[1]);let G=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"]),z=[];for(let D of H)if(!J.has(D)&&!G.has(D))z.push(D);return z.sort()}function L1(X,K,Z){let H=X.slice(0,K),Y=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,J=H.match(Y);if(!J){let $=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,Q=H.match($);if(!Q)return;return C6(Q[1],Z)}return C6(J[1],Z)}function C6(X,K){let Z=X.split(",").map((H)=>H.trim());for(let H of Z){let Y=H.match(new RegExp(`^${K}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(Y)return Y[1];let J=H.match(new RegExp(`^${K}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(J)return J[1]}return}function S0(X){let K=[],Z="",H=0,Y=!1,J=!1,$=0;while($<X.length){let Q=X[$],G=X[$+1];if(!J&&Q==="/"&&G==="/"){Y=!0,Z+="//",$+=2;continue}if(!Y&&Q==="/"&&G==="*"){J=!0,Z+="/*",$+=2;continue}if(Y&&Q===`
|
|
5
|
+
`){Y=!1,Z+=Q,$++;continue}if(J&&Q==="*"&&G==="/"){J=!1,Z+="*/",$+=2;continue}if(Y||J){Z+=Q,$++;continue}if(Q==="("||Q==="{"||Q==="[")H++,Z+=Q;else if(Q===")"||Q==="}"||Q==="]")H--,Z+=Q;else if(Q===","&&H===0)K.push(Z),Z="";else Z+=Q;$++}if(Z.trim())K.push(Z);return K}function M1(X){let Z=new RegExp(`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")\\s+IsNot\\s+([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,"g");X=X.replace(Z,"IsNot($1, $2)");let H=new RegExp(`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")\\s+Is\\s+([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,"g");return X=X.replace(H,"Is($1, $2)"),X}function P1(X){let K=/^[\s]*[([/+\-`]/,Z=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,H=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,Y=X.split(`
|
|
6
|
+
`),J=[];for(let $=0;$<Y.length;$++){let Q=Y[$],G=$>0?Y[$-1]:"";if($>0&&K.test(Q)){let z=G.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!Z.test(z)&&!H.test(z)){let D=Q.match(/^(\s*)/),F=D?D[1]:"",_=Q.slice(F.length);J.push(F+";"+_);continue}}J.push(Q)}return J.join(`
|
|
7
|
+
`)}function j1(X){let K=[],Z=0,H="normal",Y=[];while(Z<X.length){let $=X[Z],Q=X[Z+1];switch(H){case"single-string":if($==="\\"&&Z+1<X.length){Z+=2;continue}if($==="'")H="normal";Z++;continue;case"double-string":if($==="\\"&&Z+1<X.length){Z+=2;continue}if($==='"')H="normal";Z++;continue;case"template-string":if($==="\\"&&Z+1<X.length){Z+=2;continue}if($==="$"&&Q==="{"){Z+=2,Y.push(1),H="normal";continue}if($==="`")H="normal";Z++;continue;case"line-comment":if($===`
|
|
8
|
+
`)H="normal";Z++;continue;case"block-comment":if($==="*"&&Q==="/"){Z+=2,H="normal";continue}Z++;continue;case"regex":if($==="\\"&&Z+1<X.length){Z+=2;continue}if($==="["){Z++;while(Z<X.length&&X[Z]!=="]")if(X[Z]==="\\"&&Z+1<X.length)Z+=2;else Z++;if(Z<X.length)Z++;continue}if($==="/"){Z++;while(Z<X.length&&/[gimsuy]/.test(X[Z]))Z++;H="normal";continue}Z++;continue;case"normal":if(Y.length>0){if($==="{")Y[Y.length-1]++;else if($==="}"){if(Y[Y.length-1]--,Y[Y.length-1]===0){Y.pop(),Z++,H="template-string";continue}}}if($==="'"){Z++,H="single-string";continue}if($==='"'){Z++,H="double-string";continue}if($==="`"){Z++,H="template-string";continue}if($==="/"&&Q==="/"){Z+=2,H="line-comment";continue}if($==="/"&&Q==="*"){Z+=2,H="block-comment";continue}if($==="/"){let G=Z-1;while(G>=0&&/\s/.test(X[G]))G--;let z=G>=0?X[G]:"";if(!z||/[=(!,;:{[&|?+\-*%<>~^]/.test(z)||G>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(X.slice(Math.max(0,G-10),G+1))){Z++,H="regex";continue}}if($==="="&&Q==="="&&X[Z+2]!=="="&&X[Z-1]!=="!"){K.push({pos:Z,op:"=="}),Z+=2;continue}if($==="!"&&Q==="="&&X[Z+2]!=="="){K.push({pos:Z,op:"!="}),Z+=2;continue}break}Z++}if(K.length===0)return X;let J=X;for(let $=K.length-1;$>=0;$--){let{pos:Q,op:G}=K[$],z=G==="=="?"Is":"IsNot",D=V1(J,Q),F=E1(J,Q+2),_=J.slice(D,Q).trim(),q=J.slice(Q+2,F).trim();if(_&&q){let U=J.slice(0,D),A=J.slice(F),w=/[a-zA-Z0-9_$]$/.test(U)?" ":"";J=`${U}${w}${z}(${_}, ${q})${A}`}}return J}function V1(X,K){let Z=K-1;while(Z>=0&&/\s/.test(X[Z]))Z--;if(Z<0)return 0;let H=0,Y=!1,J="";while(Z>=0){let $=X[Z],Q=Z>0?X[Z-1]:"";if(Y){if($===J&&Q!=="\\")Y=!1;Z--;continue}if(($==='"'||$==="'"||$==="`")&&Q!=="\\"){Y=!0,J=$,Z--;continue}if($===")"||$==="]"){H++,Z--;continue}if($==="("||$==="["){if(H>0){H--,Z--;continue}return Z+1}if(H>0){Z--;continue}if($===";"||$==="{"||$==="}")return Z+1;if(/[a-z]/.test($)){let G=Z+1,z=Z;while(z>0&&/[a-z]/i.test(X[z-1]))z--;let D=X.slice(z,G),F=z>0?X[z-1]:"";if(!/[a-zA-Z0-9_$]/.test(F)){if(["return","throw","case","typeof","void","delete","await","yield","new"].includes(D))return G}}if($===">"&&Q==="=")return Z+1;if($==="="&&Q!=="="&&Q!=="!"&&Q!=="<"&&Q!==">")return Z+1;if($==="&"&&Q==="&")return Z+1;if($==="|"&&Q==="|")return Z+1;if($==="?"||$===":")return Z+1;if($===",")return Z+1;Z--}return 0}function E1(X,K){let Z=K;while(Z<X.length&&/\s/.test(X[Z]))Z++;if(Z>=X.length)return X.length;let H=0,Y=!1,J="";while(Z<X.length){let $=X[Z],Q=Z+1<X.length?X[Z+1]:"";if(Y){if($===J&&X[Z-1]!=="\\")Y=!1;Z++;continue}if(($==='"'||$==="'"||$==="`")&&X[Z-1]!=="\\"){Y=!0,J=$,Z++;continue}if($==="("||$==="["||$==="{"){H++,Z++;continue}if($===")"||$==="]"||$==="}"){if(H>0){H--,Z++;continue}return Z}if(H>0){Z++;continue}if($===";")return Z;if($==="&"&&Q==="&")return Z;if($==="|"&&Q==="|")return Z;if($==="?")return Z;if($===":")return Z;if($===",")return Z;if(($==="="||$==="!")&&Q==="="&&X[Z+2]!=="=")return Z;Z++}return X.length}function C1(X){let K="",Z=0;while(Z<X.length){let H=X.slice(Z).match(/^\bType\s+([A-Z][a-zA-Z0-9_]*)\s*/);if(H){let Y=H[1],J=Z+H[0].length,$=Y,Q=!1,G=X.slice(J).match(/^(['"`])([^]*?)\1\s*/);if(G){let _=J+G[0].length,q=X[_],U=q===void 0||_>=X.length||q!=="="&&q!=="{";if(q==="="||q==="{")$=G[2],Q=!0,J=_;else if(U){let A=G[0].trim(),I=G[0].slice(A.length);K+=`const ${Y} = Type('${Y}', ${A})${I}`,Z=_;continue}}let z,D=J,F=X.slice(J).match(/^=\s*/);if(F){J+=F[0].length;let _=X.slice(J).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(_){z=_[0],J+=_[0].length,D=J;let q=X.slice(J).match(/^\s*/);if(q)J+=q[0].length}}if(X[J]==="{"){let _=J+1,q=1,U=_;while(U<X.length&&q>0){let M=X[U];if(M==="{")q++;else if(M==="}")q--;U++}if(q!==0){K+=X[Z],Z++;continue}let A=X.slice(_,U-1).trim(),I=U,w=A.match(/description\s*:\s*(['"`])([^]*?)\1/);if(w&&!Q)$=w[2];let B,P=A.match(/example\s*:\s*/);if(P){let M=P.index+P[0].length,j=U1(A,M);if(j)B=j.value.trim()}let L=A.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(L&&B){let M=L[1].trim(),j=L[2].trim(),V=z?`, ${z}`:"";K+=`const ${Y} = Type('${$}', (${M}) => { if (!globalThis.__tjs?.validate(${M}, globalThis.__tjs?.infer(${B}))) return false; ${j} }, ${B}${V})`}else if(L){let M=L[1].trim(),j=L[2].trim(),V=z?`, undefined, ${z}`:"";K+=`const ${Y} = Type('${$}', (${M}) => { ${j} }${V})`}else if(B){let M=z?`, ${z}`:"";K+=`const ${Y} = Type('${$}', undefined, ${B}${M})`}else if(z)K+=`const ${Y} = Type('${$}', ${z})`;else K+=`const ${Y} = Type('${$}')`;Z=I;continue}else if(z){K+=`const ${Y} = Type('${$}', ${z})`,Z=D;continue}else if(!G){let _=X.slice(J).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(_){let q=_[0];K+=`const ${Y} = Type('${Y}', ${q})`,Z=J+_[0].length;continue}}}K+=X[Z],Z++}return K}function N1(X){let K="",Z=0;while(Z<X.length){let H=X.slice(Z).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(H){let Y=H[1],J=H[2],Q=Z+H[0].length-1+1,G=1,z=Q;while(z<X.length&&G>0){let I=X[z];if(I==="{")G++;else if(I==="}")G--;z++}if(G!==0){K+=X[Z],Z++;continue}let D=X.slice(Q,z-1).trim(),F=z,_=J.split(",").map((I)=>{let w=I.trim().split("=").map((B)=>B.trim());if(w.length===2)return`['${w[0]}', ${w[1]}]`;return`'${w[0]}'`}),q=D.match(/description\s*:\s*(['"`])([^]*?)\1/),U=D.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),A=q?q[2]:Y;if(U){let I=U[1].trim().split(",").map((M)=>M.trim()),w=U[2].trim(),B=I[0]||"x",P=I.slice(1),L=P.map((M)=>`check${M}`);P.forEach((M,j)=>{w=w.replace(new RegExp(`\\b${M}\\s*\\(`,"g"),`${L[j]}(`)}),K+=`const ${Y} = Generic([${_.join(", ")}], (${B}, ${L.join(", ")}) => { ${w} }, '${A}')`}else K+=`const ${Y} = Generic([${_.join(", ")}], () => true, '${A}')`;Z=F;continue}K+=X[Z],Z++}return K}function O1(X){let K="",Z=0;while(Z<X.length){let H=X.slice(Z).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(H){let Y=H[1],J=H[3],$=Z+H[0].length;if(X[$]==="{"){let Q=$+1,G=1,z=Q;while(z<X.length&&G>0){let q=X[z];if(q==="{")G++;else if(q==="}")G--;z++}if(G!==0){K+=X[Z],Z++;continue}let D=X.slice(Q,z-1).trim(),F=z,_=N6(D);K+=`const ${Y} = Union('${J}', [${_.join(", ")}])`,Z=F;continue}else{let Q=X.indexOf(`
|
|
9
|
+
`,$);if(Q===-1)Q=X.length;let G=X.slice($,Q).trim();if(G){let z=N6(G);K+=`const ${Y} = Union('${J}', [${z.join(", ")}])`,Z=Q;continue}}}K+=X[Z],Z++}return K}function N6(X){let K=[],Z=X.split("|").map((H)=>H.trim());for(let H of Z){if(!H)continue;K.push(H)}return K}function S1(X){let K="",Z=0;while(Z<X.length){let H=X.slice(Z).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(H){let Y=H[1],J=H[3],Q=Z+H[0].length-1+1,G=1,z=Q;while(z<X.length&&G>0){let U=X[z];if(U==="{")G++;else if(U==="}")G--;z++}if(G!==0){K+=X[Z],Z++;continue}let D=X.slice(Q,z-1).trim(),F=z,q=T1(D).map(([U,A])=>`${U}: ${A}`).join(", ");K+=`const ${Y} = Enum('${J}', { ${q} })`,Z=F;continue}K+=X[Z],Z++}return K}function T1(X){let K=[],Z=0,H=X.split(/[\n,]/).map((Y)=>Y.trim()).filter((Y)=>Y&&!Y.startsWith("//"));for(let Y of H){let J=Y.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(J){let $=J[1],Q=J[2]?.trim();if(Q!==void 0){K.push([$,Q]);let G=Number(Q);if(!isNaN(G))Z=G+1}else K.push([$,String(Z)]),Z++}}return K}function k1(X){return X.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(K,Z)=>{return K.replace(Z,`const ${Z}`)})}function Z0(X,K={}){let{filename:Z="<source>",colonShorthand:H=!0,vmTarget:Y=!1}=K,{source:J,returnType:$,returnSafety:Q,moduleSafety:G,originalSource:z,requiredParams:D,unsafeFunctions:F,safeFunctions:_,wasmBlocks:q,tests:U,testErrors:A}=H?O0(X,{vmTarget:Y}):{source:X,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:X,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[]};try{return{ast:O6.parse(J,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:$,returnSafety:Q,moduleSafety:G,originalSource:z,requiredParams:D,unsafeFunctions:F,safeFunctions:_,wasmBlocks:q,tests:U,testErrors:A}}catch(I){let w=I.loc||{line:1,column:0};throw new r(I.message.replace(/\s*\(\d+:\d+\)$/,""),w,z,Z)}}function S6(X,K){for(let H of X.body){if(H.type==="ImportDeclaration")throw new r("Imports are not supported. All atoms must be registered with the VM.",H.loc?.start||{line:1,column:0},void 0,K);if(H.type==="ExportNamedDeclaration"||H.type==="ExportDefaultDeclaration")throw new r("Exports are not supported. The function is automatically exported.",H.loc?.start||{line:1,column:0},void 0,K);if(H.type==="ClassDeclaration")throw new r("Classes are not supported. Agent99 uses functional composition.",H.loc?.start||{line:1,column:0},void 0,K)}let Z=X.body.filter((H)=>H.type==="FunctionDeclaration");if(Z.length===0)throw new r("Source must contain a function declaration",{line:1,column:0},void 0,K);if(Z.length>1){let H=Z[1];throw new r("Only a single function per agent is allowed",H.loc?.start||{line:1,column:0},void 0,K)}return Z[0]}function q0(X,K){let Z={params:{}};if(!K.loc)return Z;let H=X.substring(0,K.start),Y=[...H.matchAll(/\/\*#([\s\S]*?)\*\//g)];if(Y.length>0){let D=Y[Y.length-1],F=H.substring(D.index+D[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(F)){let _=D[1],q=_.split(`
|
|
10
|
+
`),U=q.filter((A)=>A.trim().length>0).reduce((A,I)=>{let w=I.match(/^(\s*)/)?.[1].length||0;return Math.min(A,w)},1/0);if(U>0&&U<1/0)_=q.map((A)=>A.slice(U)).join(`
|
|
11
|
+
`);return Z.description=_.trim(),Z}}let J=H.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!J)return Z;let $=J[0],Q=$.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);if(Q)Z.description=Q[1].trim();let G=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,z;while((z=G.exec($))!==null)Z.params[z[1]]=z[2].trim();return Z}function g1(X,K=!1){let Z=[],H=[],Y="",J=0;while(J<X.length){let $=X.slice(J).match(/^\btest\s+/);if($){let Q=J,G=J+$[0].length,z,D=X.slice(G).match(/^(['"`])([^]*?)\1\s*/);if(D)z=D[2],G+=D[0].length;if(X[G]==="{"){let F=G+1,_=1,q=F;while(q<X.length&&_>0){let U=X[q];if(U==="{")_++;else if(U==="}")_--;q++}if(_===0){let U=X.slice(F,q-1).trim(),A=q;if(Z.push({description:z,body:U,start:Q,end:A}),!K)try{Function(U)()}catch(B){let P=z||`test at position ${Q}`;H.push(`Test failed: ${P}
|
|
12
|
+
${B.message||B}`)}let w=(X.slice(Q,A).match(/\n/g)||[]).length;Y+=`
|
|
13
|
+
`.repeat(w),J=A;continue}}}Y+=X[J],J++}return{source:Y,tests:Z,errors:H}}function v1(X){let K=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,Z="",H=0,Y;while((Y=K.exec(X))!==null){let J=Y[1],$=Y[2]||"",Q=Y.index,G=Q+Y[0].length-1,z=1,D=G+1;while(D<X.length&&z>0){let F=X[D];if(F==="{")z++;else if(F==="}")z--;D++}if(z===0){let F=D,_=X.slice(G,F);Z+=X.slice(H,Q),Z+=`let ${J} = class ${J}${$} ${_}; `,Z+=`${J} = new Proxy(${J}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,H=F}}return Z+=X.slice(H),Z}function b1(X){let K=[{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:Z,message:H}of K)if(Z.test(X))throw Error(H);return X}function f1(X){if(/(?<![A-Za-z_$])\beval\s*\(/.test(X))throw Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(X))throw Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return X}import{parseExpressionAt as y1}from"acorn";function d(X){switch(X.type){case"Literal":{let K=X.value;if(K===null)return{kind:"null"};if(typeof K==="string")return{kind:"string"};if(typeof K==="number")return{kind:"number"};if(typeof K==="boolean")return{kind:"boolean"};return{kind:"any"}}case"ArrayExpression":{let K=X.elements;if(K.length===0)return{kind:"array",items:{kind:"any"}};return{kind:"array",items:d(K[0])}}case"ObjectExpression":{let K=X.properties,Z={};for(let H of K)if(H.type==="Property"&&H.key.type==="Identifier"){let Y=H.key.name;Z[Y]=d(H.value)}return{kind:"object",shape:Z}}case"LogicalExpression":{let{operator:K,left:Z,right:H}=X;if(K==="||"){let Y=d(Z),J=d(H);if(J.kind==="null")return{...Y,nullable:!0};if(Y.kind==="null")return{...J,nullable:!0};return{kind:"union",members:[Y,J]}}if(K==="&&")return d(H);if(K==="??")return d(H);return{kind:"any"}}case"Identifier":{if(X.name==="undefined")return{kind:"undefined"};return{kind:"any"}}case"UnaryExpression":{if(X.operator==="-"&&X.argument.type==="Literal"){if(typeof X.argument.value==="number")return{kind:"number"}}return{kind:"any"}}default:return{kind:"any"}}}function e(X,K){if(X.type==="Identifier")return{name:X.name,type:{kind:"any"},required:!0};if(X.type==="AssignmentPattern"){let{left:Z,right:H}=X;if(Z.type!=="Identifier")throw new T("Only simple parameter names are supported",k(X));let Y=Z.name,J=K?.has(Y)??!1,$=d(H),Q=t(H);return{name:Y,type:$,required:J,default:J?null:Q,example:Q,loc:{start:X.start,end:X.end}}}if(X.type==="ObjectPattern"){let Z=X.properties,H={},Y={};for(let J of Z)if(J.type==="Property"){let $=J.key.type==="Identifier"?J.key.name:String(J.key.value);if(J.value.type==="Identifier")H[$]={kind:"any"},Y[$]={name:$,type:{kind:"any"},required:!0};else if(J.value.type==="AssignmentPattern"){let Q=e(J.value,K),G=K?.has($)??!1;H[$]=Q.type,Y[$]={name:$,type:Q.type,required:G,default:G?null:Q.example,example:Q.example}}}return{name:"__destructured__",type:{kind:"object",shape:H,destructuredParams:Y},required:!0}}throw new T(`Unsupported parameter pattern: ${X.type}`,k(X))}function t(X){switch(X.type){case"Literal":return X.value;case"ArrayExpression":return X.elements.map((K)=>K?t(K):null);case"ObjectExpression":{let K={};for(let Z of X.properties)if(Z.type==="Property"&&Z.key.type==="Identifier")K[Z.key.name]=t(Z.value);return K}case"UnaryExpression":if(X.operator==="-"){let K=t(X.argument);return typeof K==="number"?-K:void 0}return;case"LogicalExpression":{let{operator:K,left:Z,right:H}=X;if(K==="&&"){if(Z.type==="Literal"&&Z.value===null)return null}if(K==="||")return t(Z)??t(H);if(K==="??")return t(Z)??t(H);return}default:return}}function T6(X){try{let K=y1(X,0,{ecmaVersion:2022});return d(K)}catch{return{kind:"any"}}}function n0(X){switch(X.kind){case"string":return X.nullable?"string | null":"string";case"number":return X.nullable?"number | null":"number";case"boolean":return X.nullable?"boolean | null":"boolean";case"null":return"null";case"any":return"any";case"array":{let K=X.items?n0(X.items):"any";return X.nullable?`${K}[] | null`:`${K}[]`}case"object":{if(!X.shape||Object.keys(X.shape).length===0)return X.nullable?"object | null":"object";let K=Object.entries(X.shape).map(([Z,H])=>`${Z}: ${n0(H)}`).join(", ");return X.nullable?`{ ${K} } | null`:`{ ${K} }`}case"union":return X.members?.map(n0).join(" | ")||"any";default:return"any"}}function T0(X){switch(X.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:X.items?T0(X.items):{}};case"object":if(X.shape){let K={};for(let[Z,H]of Object.entries(X.shape))K[Z]=T0(H);return{type:"object",properties:K,additionalProperties:!1}}return{type:"object"};case"union":if(X.members)return{oneOf:X.members.map(T0)};return{};default:return{}}}function h1(X){let K={},Z=[];for(let[H,Y]of Object.entries(X))if(K[H]=T0(Y.type),Y.required)Z.push(H);return{type:"object",properties:K,required:Z.length>0?Z:void 0,additionalProperties:!1}}function c0(X,K,Z,H={},Y){let J=q0(K,X),$=new Map;for(let I of X.params){let w=e(I,Y);if(w.name==="__destructured__"&&w.type.kind==="object"&&w.type.destructuredParams)for(let[B,P]of Object.entries(w.type.destructuredParams))$.set(B,{...P,description:J.params[B]});else w.description=J.params[w.name],$.set(w.name,w)}let Q;if(Z)Q=T6(Z);let G={depth:0,locals:new Map,parameters:$,atoms:new Set(Object.keys(H.atoms||{})),warnings:[],source:K,filename:H.filename||"<source>",options:H},z=p(X.body,G),D=[],F=[],_=[];for(let[I,w]of $.entries())if(w.required)F.push(I);else if(w.default!==void 0)_.push({name:I,defaultValue:w.default});else F.push(I);if(F.length>0)D.push({op:"varsImport",keys:F});for(let{name:I,defaultValue:w}of _)D.push({op:"varsImport",keys:[I]}),D.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:I},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:I,value:w}]});D.push(...z);let q=Object.fromEntries($),U={name:X.id?.name||"anonymous",description:J.description,parameters:q,returns:Q},A=h1(q);return{ast:{op:"seq",steps:D,inputSchema:A},signature:U,warnings:G.warnings}}function p(X,K){let Z=[];for(let H of X.body){let Y=U0(H,K);if(Y)if(Array.isArray(Y))Z.push(...Y);else Z.push(Y)}return Z}function U0(X,K){switch(X.type){case"VariableDeclaration":return x1(X,K);case"ExpressionStatement":return m1(X,K);case"IfStatement":return l1(X,K);case"WhileStatement":return u1(X,K);case"ForOfStatement":return i1(X,K);case"TryStatement":return p1(X,K);case"ReturnStatement":return n1(X,K);case"ThrowStatement":throw new T("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",k(X),K.source,K.filename);case"BlockStatement":return{op:"scope",steps:p(X,m(K))};case"EmptyStatement":return null;default:throw new T(`Unsupported statement type: ${X.type}`,k(X),K.source,K.filename)}}function x1(X,K){let Z=[],H=X.kind==="const",Y=H?"constSet":"varSet";for(let J of X.declarations){if(J.id.type!=="Identifier")throw new T("Only simple variable names are supported",k(J),K.source,K.filename);let $=J.id.name;if(J.init){let{step:Q,resultVar:G}=K0(J.init,K,$,H);if(Q)Z.push(Q);else if(G!==$)Z.push({op:Y,key:$,value:G});let z=d(J.init);K.locals.set($,z)}else{if(H)throw new T("const declarations must be initialized",k(J),K.source,K.filename);Z.push({op:"varSet",key:$,value:null}),K.locals.set($,{kind:"any",nullable:!0})}}return Z}function m1(X,K){let Z=X.expression;if(Z.type==="AssignmentExpression")return d1(Z,K);if(Z.type==="CallExpression"){let{step:H,resultVar:Y}=K0(Z,K);if(H)return H;if(Y)return{op:"varSet",key:"_",value:Y};return null}return K.warnings.push({message:"Expression statement has no effect",line:k(X).line,column:k(X).column}),null}function d1(X,K){if(X.left.type!=="Identifier")throw new T("Only simple variable assignment is supported",k(X),K.source,K.filename);let Z=X.left.name,{step:H,resultVar:Y}=K0(X.right,K,Z);if(H)return H;return{op:"varSet",key:Z,value:Y}}function l1(X,K){let Z=N(X.test,K),H=X.consequent.type==="BlockStatement"?p(X.consequent,m(K)):[U0(X.consequent,K)].filter(Boolean),Y;if(X.alternate)Y=X.alternate.type==="BlockStatement"?p(X.alternate,m(K)):[U0(X.alternate,K)].filter(Boolean);return{op:"if",condition:Z,then:H,...Y&&{else:Y}}}function u1(X,K){let Z=N(X.test,K),H=X.body.type==="BlockStatement"?p(X.body,m(K)):[U0(X.body,K)].filter(Boolean);return{op:"while",condition:Z,body:H}}function i1(X,K){let Z;if(X.left.type==="VariableDeclaration"){let $=X.left.declarations[0];if($.id.type!=="Identifier")throw new T("Only simple variable names are supported in for...of",k(X.left),K.source,K.filename);Z=$.id.name}else if(X.left.type==="Identifier")Z=X.left.name;else throw new T("Unsupported for...of left-hand side",k(X.left),K.source,K.filename);let H=f(X.right,K),Y=m(K);Y.locals.set(Z,{kind:"any"});let J=X.body.type==="BlockStatement"?p(X.body,Y):[U0(X.body,Y)].filter(Boolean);return{op:"map",items:H,as:Z,steps:J}}function p1(X,K){let Z=p(X.block,m(K)),H,Y;if(X.handler){let J=m(K);if(X.handler.param?.type==="Identifier")Y=X.handler.param.name,J.locals.set(Y,{kind:"any"});H=p(X.handler.body,J)}return{op:"try",try:Z,...H&&{catch:H},...Y&&{catchParam:Y}}}function n1(X,K){if(!X.argument)return{op:"return",value:{}};let{step:Z,resultVar:H}=K0(X.argument,K,"__returnVal__");if(Z)return[Z,{op:"return",value:H}];return{op:"return",value:f(X.argument,K)}}var g6=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),c1=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),A0=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),o1=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 s1(X){if(X.callee.type==="Identifier"){let K=X.callee.name;return c1.has(K)||A0.has(K)}if(X.callee.type==="MemberExpression"){let K=X.callee;if(K.object.type==="Identifier"){let Z=K.object.name;if(g6.has(Z)||A0.has(Z))return!0}if(K.property.type==="Identifier"){let Z=K.property.name;if(o1.has(Z))return!0}}return!1}function a1(X){if(X.object.type==="Identifier"){let K=X.object.name;return g6.has(K)||A0.has(K)}return!1}var k6={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 r1(X){if(X.callee.type==="Identifier"){let K=X.callee.name;if(A0.has(K))return k6[K]||`${K} is not available in AsyncJS.`}if(X.callee.type==="MemberExpression"){let K=X.callee;if(K.object.type==="Identifier"){let Z=K.object.name;if(A0.has(Z))return k6[Z]||`${Z} is not available in AsyncJS.`}}return null}function v6(X){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."}[X]||" Use factory functions or object literals instead."}function K0(X,K,Z,H){let Y=H?"constSet":"varSet";if(X.type==="ChainExpression")return K0(X.expression,K,Z,H);if(X.type==="NewExpression"){let $=X,Q="constructor";if($.callee.type==="Identifier")Q=$.callee.name;let G=v6(Q);throw new T(`The 'new' keyword is not supported in AsyncJS.${G}`,k(X),K.source,K.filename)}if(X.type==="CallExpression"){let $=r1(X);if($)throw new T($,k(X),K.source,K.filename)}if(X.type==="CallExpression"&&s1(X)){let $=N(X,K);if(Z)return{step:{op:Y,key:Z,value:$},resultVar:Z};return{step:null,resultVar:$}}if(X.type==="MemberExpression"&&a1(X)){let $=N(X,K);if(Z)return{step:{op:Y,key:Z,value:$},resultVar:Z};return{step:null,resultVar:$}}if(X.type==="CallExpression")return t1(X,K,Z,H);if(X.type==="TemplateLiteral")return X8(X,K,Z,H);if(X.type==="BinaryExpression"||X.type==="LogicalExpression"||X.type==="UnaryExpression"){let $=N(X,K);if(Z)return{step:{op:Y,key:Z,value:$},resultVar:Z};return{step:null,resultVar:$}}return{step:null,resultVar:f(X,K)}}function t1(X,K,Z,H){let Y,J=!1,$;if(X.callee.type==="Identifier")Y=X.callee.name;else if(X.callee.type==="MemberExpression"){let G=X.callee;if(G.property.type==="Identifier")Y=G.property.name,J=!0,$=f(G.object,K);else throw new T("Computed method names are not supported",k(X),K.source,K.filename)}else throw new T("Only named function calls are supported",k(X),K.source,K.filename);if(J)return e1(Y,$,X.arguments,K,Z,H);if(Y==="console"&&X.callee.type==="MemberExpression");let Q=Z8(X,K);return{step:{op:Y,...Q,...Z&&{result:Z},...Z&&H&&{resultConst:!0}},resultVar:Z}}function e1(X,K,Z,H,Y,J){switch(X){case"map":if(Z.length>0&&(Z[0].type==="ArrowFunctionExpression"||Z[0].type==="FunctionExpression")){let $=Z[0],Q=$.params[0],G=Q?.type==="Identifier"?Q.name:"item",z=m(H);z.locals.set(G,{kind:"any"});let D;if($.body.type==="BlockStatement")D=p($.body,z);else{let{step:F,resultVar:_}=K0($.body,z,"result");D=F?[F]:[{op:"varSet",key:"result",value:_}]}return{step:{op:"map",items:K,as:G,steps:D,...Y&&{result:Y},...Y&&J&&{resultConst:!0}},resultVar:Y}}break;case"filter":if(Z.length>0&&(Z[0].type==="ArrowFunctionExpression"||Z[0].type==="FunctionExpression")){let $=Z[0],Q=$.params[0],G=Q?.type==="Identifier"?Q.name:"item",z=m(H);z.locals.set(G,{kind:"any"});let D;if($.body.type==="BlockStatement")throw new T("filter callback must be an expression, not a block",k(Z[0]),H.source,H.filename);else D=N($.body,z);return{step:{op:"filter",items:K,as:G,condition:D,...Y&&{result:Y},...Y&&J&&{resultConst:!0}},resultVar:Y}}break;case"find":if(Z.length>0&&(Z[0].type==="ArrowFunctionExpression"||Z[0].type==="FunctionExpression")){let $=Z[0],Q=$.params[0],G=Q?.type==="Identifier"?Q.name:"item",z=m(H);z.locals.set(G,{kind:"any"});let D;if($.body.type==="BlockStatement")throw new T("find callback must be an expression, not a block",k(Z[0]),H.source,H.filename);else D=N($.body,z);return{step:{op:"find",items:K,as:G,condition:D,...Y&&{result:Y},...Y&&J&&{resultConst:!0}},resultVar:Y}}break;case"reduce":if(Z.length>=2&&(Z[0].type==="ArrowFunctionExpression"||Z[0].type==="FunctionExpression")){let $=Z[0],Q=$.params[0],G=$.params[1],z=Q?.type==="Identifier"?Q.name:"acc",D=G?.type==="Identifier"?G.name:"item",F=m(H);F.locals.set(z,{kind:"any"}),F.locals.set(D,{kind:"any"});let _;if($.body.type==="BlockStatement")_=p($.body,F);else{let{step:U,resultVar:A}=K0($.body,F,"result");_=U?[U]:[{op:"varSet",key:"result",value:A}]}let q=f(Z[1],H);return{step:{op:"reduce",items:K,as:D,accumulator:z,initial:q,steps:_,...Y&&{result:Y},...Y&&J&&{resultConst:!0}},resultVar:Y}}break;case"slice":break;case"push":return{step:{op:"push",list:K,item:f(Z[0],H),...Y&&{result:Y},...Y&&J&&{resultConst:!0}},resultVar:Y};case"join":return{step:{op:"join",list:K,sep:Z.length>0?f(Z[0],H):"",...Y&&{result:Y},...Y&&J&&{resultConst:!0}},resultVar:Y};case"split":return{step:{op:"split",str:K,sep:Z.length>0?f(Z[0],H):"",...Y&&{result:Y},...Y&&J&&{resultConst:!0}},resultVar:Y}}return H.warnings.push({message:`Unknown method '${X}' - treating as atom call`,line:0,column:0}),{step:{op:X,receiver:K,args:Z.map(($)=>f($,H)),...Y&&{result:Y},...Y&&J&&{resultConst:!0}},resultVar:Y}}function X8(X,K,Z,H){let Y="",J={};for(let $=0;$<X.quasis.length;$++)if(Y+=X.quasis[$].value.cooked||X.quasis[$].value.raw,$<X.expressions.length){let Q=X.expressions[$],G=`_${$}`;J[G]=f(Q,K),Y+=`{{${G}}}`}return{step:{op:"template",tmpl:Y,vars:J,...Z&&{result:Z},...Z&&H&&{resultConst:!0}},resultVar:Z}}function N(X,K){switch(X.type){case"Literal":return{$expr:"literal",value:X.value};case"Identifier":return{$expr:"ident",name:X.name};case"MemberExpression":{let Z=X,H=N(Z.object,K),Y=Z.optional===!0;if(Z.computed){let $=Z.property;if($.type==="Literal")return{$expr:"member",object:H,property:String($.value),computed:!0,...Y&&{optional:!0}};throw new T("Computed member access with variables not yet supported",k(X),K.source,K.filename)}let J=Z.property.name;return{$expr:"member",object:H,property:J,...Y&&{optional:!0}}}case"ChainExpression":return N(X.expression,K);case"BinaryExpression":{let Z=X;return{$expr:"binary",op:Z.operator,left:N(Z.left,K),right:N(Z.right,K)}}case"LogicalExpression":{let Z=X;return{$expr:"logical",op:Z.operator,left:N(Z.left,K),right:N(Z.right,K)}}case"UnaryExpression":{let Z=X;return{$expr:"unary",op:Z.operator,argument:N(Z.argument,K)}}case"ConditionalExpression":{let Z=X;return{$expr:"conditional",test:N(Z.test,K),consequent:N(Z.consequent,K),alternate:N(Z.alternate,K)}}case"ArrayExpression":return{$expr:"array",elements:X.elements.filter((H)=>H!==null).map((H)=>N(H,K))};case"ObjectExpression":{let Z=X,H=[];for(let Y of Z.properties)if(Y.type==="Property"){let J=Y.key.type==="Identifier"?Y.key.name:String(Y.key.value);H.push({key:J,value:N(Y.value,K)})}return{$expr:"object",properties:H}}case"CallExpression":{let Z=X;if(Z.callee.type==="MemberExpression"){let H=Z.callee,Y=H.property.type==="Identifier"?H.property.name:String(H.property.value),J=H.optional===!0||Z.optional===!0;return{$expr:"methodCall",object:N(H.object,K),method:Y,arguments:Z.arguments.map(($)=>N($,K)),...J&&{optional:!0}}}if(Z.callee.type==="Identifier")return{$expr:"call",callee:Z.callee.name,arguments:Z.arguments.map((Y)=>N(Y,K))};throw new T("Complex function calls in expressions should be lifted to statements",k(X),K.source,K.filename)}case"NewExpression":{let Z=X,H="constructor";if(Z.callee.type==="Identifier")H=Z.callee.name;let Y=v6(H);throw new T(`The 'new' keyword is not supported in AsyncJS.${Y}`,k(X),K.source,K.filename)}case"TemplateLiteral":throw new T("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",k(X),K.source,K.filename);default:throw new T(`Unsupported expression type in condition: ${X.type}`,k(X),K.source,K.filename)}}function f(X,K){switch(X.type){case"Literal":return X.value;case"Identifier":return X.name;case"MemberExpression":{let Z=X;if(Z.optional===!0)return N(X,K);let Y=f(Z.object,K);if(Y&&typeof Y==="object"&&Y.$expr){let $=Z.computed?String(Z.property.value):Z.property.name;return{$expr:"member",object:Y,property:$,...Z.computed&&{computed:!0}}}if(Z.computed)return`${Y}[${f(Z.property,K)}]`;let J=Z.property.name;if(typeof Y==="string")return`${Y}.${J}`;if(Y&&Y.$kind==="arg")return{$kind:"arg",path:`${Y.path}.${J}`};return`${Y}.${J}`}case"ChainExpression":return f(X.expression,K);case"ArrayExpression":return X.elements.map((Z)=>Z?f(Z,K):null);case"ObjectExpression":{let Z={};for(let H of X.properties)if(H.type==="Property"){let Y=H.key.type==="Identifier"?H.key.name:String(H.key.value);Z[Y]=f(H.value,K)}return Z}case"TemplateLiteral":return N(X,K);case"CallExpression":return N(X,K);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return N(X,K);default:return null}}function Z8(X,K){if(X.arguments.length===1&&X.arguments[0].type==="ObjectExpression"){let Z=X.arguments[0],H={};for(let Y of Z.properties)if(Y.type==="Property"){let J=Y.key.type==="Identifier"?Y.key.name:String(Y.key.value);H[J]=f(Y.value,K)}return H}return{args:X.arguments.map((Z)=>f(Z,K))}}import{parseExpressionAt as P8}from"acorn";function K8(X,K){let Z=K;while(Z>0&&X[Z-1]!==`
|
|
14
|
+
`)Z--;if(X.slice(Z,K).includes("//"))return!0;let Y=0,J=!1;while(Y<K)if(!J&&X.slice(Y,Y+2)==="/*")J=!0,Y+=2;else if(J&&X.slice(Y,Y+2)==="*/")J=!1,Y+=2;else Y++;return J}function H8(X){let K=[],Z=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{([\s\S]*?)\}\s*\*\/|\/\*test\s*\{([\s\S]*?)\}\s*\*\//g,H;while((H=Z.exec(X))!==null){let Y=H[2]||`embedded test ${K.length+1}`,J=(H[3]||H[4]||"").trim();K.push({description:Y,body:J,line:o0(X,H.index)})}return K}function s0(X){let K=[],Z=[],H=H8(X);K.push(...H);let Y=/test\s+(['"`])([^'"`]*)\1\s*\{|test\s*\(\s*(['"`])([^'"`]*)\3\s*\)\s*\{|test\s*\{/g,J=/mock\s*\{/g,$=X,Q,G=[];while((Q=Y.exec(X))!==null){let _=Q.index;if(K8(X,_))continue;let q=Q[2]||Q[4]||`test ${K.length+1}`,U=Q.index+Q[0].length,A=b6(X,U-1);if(A===-1)continue;let I=X.slice(U,A).trim();K.push({description:q,body:I,line:o0(X,_)}),G.push({start:_,end:A+1,desc:q})}let z=[];while((Q=J.exec(X))!==null){let _=Q.index,q=Q.index+Q[0].length,U=b6(X,q-1);if(U===-1)continue;let A=X.slice(q,U).trim();Z.push({body:A,line:o0(X,_)}),z.push({start:_,end:U+1})}let D=[...G,...z].sort((_,q)=>q.start-_.start);for(let _ of D)$=$.slice(0,_.start)+$.slice(_.end);$=$.replace(/\n\s*\n\s*\n/g,`
|
|
15
15
|
|
|
16
|
-
`).trim();let
|
|
17
|
-
`).length}function
|
|
16
|
+
`).trim();let F=Y8(K,Z);return{code:$,tests:K,mocks:Z,testRunner:F}}function b6(X,K){let Z=0,H=null,Y=!1;for(let J=K;J<X.length;J++){let $=X[J];if(Y){Y=!1;continue}if($==="\\"){Y=!0;continue}if(!H&&($==='"'||$==="'"||$==="`")){H=$;continue}if(H===$){H=null;continue}if(H)continue;if($==="{")Z++;if($==="}"){if(Z--,Z===0)return J}}return-1}function o0(X,K){return X.slice(0,K).split(`
|
|
17
|
+
`).length}function Y8(X,K){if(X.length===0)return"// No tests defined";let Z=K.map((Y)=>Y.body).join(`
|
|
18
18
|
`);return`(async () => {
|
|
19
19
|
const __results = []
|
|
20
20
|
|
|
21
|
-
${X.map((
|
|
22
|
-
// Test ${J+1}: ${
|
|
21
|
+
${X.map((Y,J)=>`
|
|
22
|
+
// Test ${J+1}: ${Y.description}
|
|
23
23
|
try {
|
|
24
24
|
${Z}
|
|
25
25
|
await (async () => {
|
|
26
|
-
${
|
|
26
|
+
${Y.body}
|
|
27
27
|
})()
|
|
28
|
-
__results.push({ description: ${JSON.stringify(
|
|
28
|
+
__results.push({ description: ${JSON.stringify(Y.description)}, passed: true })
|
|
29
29
|
} catch (__e) {
|
|
30
|
-
__results.push({ description: ${JSON.stringify(
|
|
30
|
+
__results.push({ description: ${JSON.stringify(Y.description)}, passed: false, error: __e.message })
|
|
31
31
|
}`).join(`
|
|
32
32
|
`)}
|
|
33
33
|
|
|
@@ -37,13 +37,13 @@ const __failed = __results.filter(r => !r.passed).length
|
|
|
37
37
|
|
|
38
38
|
// Return summary
|
|
39
39
|
return { passed: __passed, failed: __failed, results: __results }
|
|
40
|
-
})()`.trim()}var
|
|
40
|
+
})()`.trim()}var f6=`
|
|
41
41
|
function assert(condition, message) {
|
|
42
42
|
if (!condition) {
|
|
43
43
|
throw new Error(message || 'Assertion failed')
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
|
-
`,
|
|
46
|
+
`,y6=`
|
|
47
47
|
function expect(actual) {
|
|
48
48
|
const deepEqual = (a, b) => {
|
|
49
49
|
if (a === b) return true
|
|
@@ -134,43 +134,45 @@ function expect(actual) {
|
|
|
134
134
|
}
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
|
-
|
|
138
|
-
`+
|
|
139
|
-
`):null}let $=Object.entries(Y.params);if($.length===0)return null;for(let[Q]of $)K.push(`if (${Q} instanceof Error) return ${Q};`);for(let[Q,G]of $){let z=`${H}${X}.${Q}`,_=O0(Q,G.type);if(_){let U=G.type.kind;if(G.required)K.push(`if (${_}) return __tjs.typeError('${z}', '${U}', ${Q});`);else K.push(`if (${Q} !== undefined && ${_}) return __tjs.typeError('${z}', '${U}', ${Q});`)}}return K.length>0?K.join(`
|
|
140
|
-
`):null}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
${
|
|
149
|
-
${
|
|
150
|
-
|
|
137
|
+
`,$8=f6+`
|
|
138
|
+
`+y6;import*as h6 from"acorn";var l={i32:127,i64:126,f32:125,f64:124,v128:123,funcref:112,externref:111,void:64},w0={custom:0,type:1,import:2,function:3,table:4,memory:5,global:6,export:7,start:8,element:9,code:10,data:11},W={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},J8=Object.fromEntries(Object.entries(W).map(([X,K])=>[K,X.replace(/_/g,".")]));function C(X){let K=[];do{let Z=X&127;if(X>>>=7,X!==0)Z|=128;K.push(Z)}while(X!==0);return K}function B0(X){let K=[],Z=!0;while(Z){let H=X&127;if(X>>=7,X===0&&(H&64)===0||X===-1&&(H&64)!==0)Z=!1;else H|=128;K.push(H)}return K}function Q8(X){let K=new ArrayBuffer(4);return new Float32Array(K)[0]=X,[...new Uint8Array(K)]}function u(X){let K=new ArrayBuffer(8);return new Float64Array(K)[0]=X,[...new Uint8Array(K)]}function a0(X){let K=new TextEncoder().encode(X);return[...C(K.length),...K]}function R0(X,K){return[X,...C(K.length),...K]}function I0(X,K){let Z=0,H=0,Y=K;while(Y<X.length){let J=X[Y];if(Z|=(J&127)<<H,Y++,(J&128)===0)break;H+=7}return[Z,Y-K]}function z8(X,K){let Z=new ArrayBuffer(8),H=new Uint8Array(Z);for(let Y=0;Y<8;Y++)H[Y]=X[K+Y];return new Float64Array(Z)[0]}function G8(X,K,Z){let H=[],Y=1,J=()=>" ".repeat(Y),$=K.map((z,D)=>`(param $${z.name} ${z.type})`).join(" "),Q=Z.map((z,D)=>`(local $L${K.length+D} ${z})`).join(" ");if(H.push(`(func (export "compute") ${$} (result f64)`),Q)H.push(` ${Q}`);let G=0;while(G<X.length){let z=X[G],D=J8[z]||`unknown(0x${z.toString(16)})`;if(G++,z===W.local_get||z===W.local_set||z===W.local_tee){let[F,_]=I0(X,G);G+=_;let q=F<K.length?`$${K[F].name}`:`$L${F}`;H.push(`${J()}${D} ${q}`)}else if(z===W.br||z===W.br_if){let[F,_]=I0(X,G);G+=_,H.push(`${J()}${D} ${F}`)}else if(z===W.i32_const){let[F,_]=I0(X,G);G+=_,H.push(`${J()}i32.const ${F}`)}else if(z===W.f64_const){let F=z8(X,G);G+=8,H.push(`${J()}f64.const ${F}`)}else if(z===W.block||z===W.loop){let F=X[G];G++,H.push(`${J()}${D}${F===l.void?"":` (result ${F===l.f64?"f64":"i32"})`}`),Y++}else if(z===W.if){let F=X[G];G++,H.push(`${J()}if${F===l.void?"":` (result ${F===l.f64?"f64":"i32"})`}`),Y++}else if(z===W.else)Y--,H.push(`${J()}else`),Y++;else if(z===W.end)Y=Math.max(1,Y-1),H.push(`${J()}end`);else if(z===W.f64_load||z===W.f64_store||z===W.f32_load||z===W.f32_store||z===W.i32_load||z===W.i32_store){let[F,_]=I0(X,G);G+=_;let[q,U]=I0(X,G);G+=U,H.push(`${J()}${D}${q?` offset=${q}`:""}`)}else H.push(`${J()}${D}`)}return H.push(")"),H.join(`
|
|
139
|
+
`)}var g0={Int8Array:{elementType:"i32",bytesPerElement:1,loadOp:W.i32_load8_s,storeOp:W.i32_store8},Uint8Array:{elementType:"i32",bytesPerElement:1,loadOp:W.i32_load8_u,storeOp:W.i32_store8},Uint8ClampedArray:{elementType:"i32",bytesPerElement:1,loadOp:W.i32_load8_u,storeOp:W.i32_store8},Int16Array:{elementType:"i32",bytesPerElement:2,loadOp:W.i32_load16_s,storeOp:W.i32_store16},Uint16Array:{elementType:"i32",bytesPerElement:2,loadOp:W.i32_load16_u,storeOp:W.i32_store16},Int32Array:{elementType:"i32",bytesPerElement:4,loadOp:W.i32_load,storeOp:W.i32_store},Uint32Array:{elementType:"i32",bytesPerElement:4,loadOp:W.i32_load,storeOp:W.i32_store},Float32Array:{elementType:"f32",bytesPerElement:4,loadOp:W.f32_load,storeOp:W.f32_store},Float64Array:{elementType:"f64",bytesPerElement:8,loadOp:W.f64_load,storeOp:W.f64_store}};function W8(X){let K={params:X,locals:new Map,nextLocalIndex:X.length,localTypes:[],warnings:[],errors:[],loopDepth:0,needsMathImports:new Set,needsMemory:!1,hasReturn:!1,wat:[],watIndent:1};return X.forEach((Z,H)=>{K.locals.set(Z.name,{index:H,type:Z.type})}),K}function k0(X,K,Z){if(X.locals.has(K))return X.errors.push(`Duplicate local declaration: ${K}`),X.locals.get(K).index;let H=X.nextLocalIndex++;return X.locals.set(K,{index:H,type:Z}),X.localTypes.push(Z),H}function H0(X,K){return X.locals.get(K)}function W0(X,K){switch(X.type){case"ExpressionStatement":{let Z=X.expression;return[...b(Z,K),W.drop]}case"ReturnStatement":{let Z=X;if(K.hasReturn=!0,!Z.argument)return[W.return];let H=b(Z.argument,K),Y=y(Z.argument,K);if(Y==="i32")H.push(W.f64_convert_i32_s);else if(Y==="f32")H.push(W.f64_promote_f32);return H.push(W.return),H}case"VariableDeclaration":{let Z=X,H=[];for(let Y of Z.declarations){if(Y.id.type!=="Identifier"){K.errors.push("Destructuring not supported in WASM blocks");continue}let J=Y.id.name,$="f64";if(Y.init)$=y(Y.init,K);let Q=k0(K,J,$);if(Y.init)H.push(...b(Y.init,K)),H.push(W.local_set,...C(Q))}return H}case"ForStatement":return _8(X,K);case"IfStatement":return D8(X,K);case"BlockStatement":{let Z=X,H=[];for(let Y of Z.body)H.push(...W0(Y,K));return H}default:return K.errors.push(`Unsupported statement type: ${X.type}`),[]}}function _8(X,K){let Z=[];if(X.init)if(X.init.type==="VariableDeclaration")Z.push(...W0(X.init,K));else Z.push(...b(X.init,K));if(Z.push(W.block,l.void),Z.push(W.loop,l.void),X.test)Z.push(...b(X.test,K)),Z.push(W.i32_eqz),Z.push(W.br_if,1);if(K.loopDepth++,X.body)Z.push(...W0(X.body,K));if(K.loopDepth--,X.update)Z.push(...b(X.update,K)),Z.push(W.drop);return Z.push(W.br,0),Z.push(W.end),Z.push(W.end),Z}function D8(X,K){let Z=[];if(Z.push(...b(X.test,K)),Z.push(W.if,l.void),Z.push(...W0(X.consequent,K)),X.alternate)Z.push(W.else),Z.push(...W0(X.alternate,K));return Z.push(W.end),Z}function y(X,K){switch(X.type){case"Literal":{let Z=X;if(typeof Z.value==="number"){if(Z.raw&&(Z.raw.includes(".")||Z.raw.includes("e")))return"f64";if(Number.isInteger(Z.value)&&Z.value>=-2147483648&&Z.value<=2147483647)return"i32";return"f64"}return"f64"}case"Identifier":return H0(K,X.name)?.type??"f64";case"BinaryExpression":case"AssignmentExpression":{let Z=X;if(["<",">","<=",">=","==","!=","===","!=="].includes(Z.operator))return"i32";if(["|","&","^","<<",">>",">>>"].includes(Z.operator))return"i32";let H=y(Z.left,K),Y=y(Z.right,K);if(H==="f64"||Y==="f64")return"f64";if(H==="f32"||Y==="f32")return"f32";return"i32"}case"UnaryExpression":{let Z=X;if(Z.operator==="!")return"i32";return y(Z.argument,K)}case"MemberExpression":{let Z=X;if(Z.object.type==="Identifier"){if(H0(K,Z.object.name)){let Y=K.params.find((J)=>J.name===Z.object.name);if(Y?.arrayType){let J=g0[Y.arrayType];if(J)return J.elementType}}}return"f64"}case"CallExpression":{let Z=X;if(Z.callee.type==="MemberExpression"){let H=Z.callee;if(H.object.type==="Identifier"&&H.object.name==="Math")return"f64"}return"f64"}default:return"f64"}}function b(X,K){switch(X.type){case"Literal":{let Z=X;if(typeof Z.value==="number"){let H=y(X,K);if(H==="i32")return[W.i32_const,...B0(Z.value|0)];else if(H==="f32")return[W.f32_const,...Q8(Z.value)];else return[W.f64_const,...u(Z.value)]}return K.errors.push(`Unsupported literal type: ${typeof Z.value}`),[W.f64_const,...u(0)]}case"Identifier":{let Z=X.name,H=H0(K,Z);if(H)return[W.local_get,...C(H.index)];return K.errors.push(`Unknown identifier: ${Z}`),[W.f64_const,...u(0)]}case"BinaryExpression":return F8(X,K);case"UnaryExpression":return q8(X,K);case"AssignmentExpression":return U8(X,K);case"UpdateExpression":return A8(X,K);case"MemberExpression":return w8(X,K);case"CallExpression":return I8(X,K);case"SequenceExpression":{let Z=X,H=[];for(let Y=0;Y<Z.expressions.length;Y++)if(H.push(...b(Z.expressions[Y],K)),Y<Z.expressions.length-1)H.push(W.drop);return H}default:return K.errors.push(`Unsupported expression type: ${X.type}`),[W.f64_const,...u(0)]}}function F8(X,K){let Z=b(X.left,K),H=b(X.right,K),Y=y(X,K),J=y(X.left,K),$=y(X.right,K),Q=["<",">","<=",">=","==","===","!=","!=="].includes(X.operator),G;if(J==="f64"||$==="f64")G="f64";else if(J==="f32"||$==="f32")G="f32";else G="i32";if(!Q&&Y==="f64")G="f64";let z=Z,D=H;if(G==="f64"){if(J==="i32")z=[...Z,W.f64_convert_i32_s];else if(J==="f32")z=[...Z,W.f64_promote_f32];if($==="i32")D=[...H,W.f64_convert_i32_s];else if($==="f32")D=[...H,W.f64_promote_f32]}else if(G==="f32"){if(J==="i32")z=[...Z,W.f32_convert_i32_s];if($==="i32")D=[...H,W.f32_convert_i32_s]}let _={"+":{i32:W.i32_add,f32:W.f32_add,f64:W.f64_add},"-":{i32:W.i32_sub,f32:W.f32_sub,f64:W.f64_sub},"*":{i32:W.i32_mul,f32:W.f32_mul,f64:W.f64_mul},"/":{i32:W.i32_div_s,f32:W.f32_div,f64:W.f64_div},"%":{i32:W.i32_rem_s},"<":{i32:W.i32_lt_s,f32:W.f32_lt,f64:W.f64_lt},">":{i32:W.i32_gt_s,f32:W.f32_gt,f64:W.f64_gt},"<=":{i32:W.i32_le_s,f32:W.f32_le,f64:W.f64_le},">=":{i32:W.i32_ge_s,f32:W.f32_ge,f64:W.f64_ge},"==":{i32:W.i32_eq,f32:W.f32_eq,f64:W.f64_eq},"===":{i32:W.i32_eq,f32:W.f32_eq,f64:W.f64_eq},"!=":{i32:W.i32_ne,f32:W.f32_ne,f64:W.f64_ne},"!==":{i32:W.i32_ne,f32:W.f32_ne,f64:W.f64_ne},"|":{i32:W.i32_or},"&":{i32:W.i32_and},"^":{i32:W.i32_xor},"<<":{i32:W.i32_shl},">>":{i32:W.i32_shr_s},">>>":{i32:W.i32_shr_u}}[X.operator];if(!_)return K.errors.push(`Unsupported operator: ${X.operator}`),[W.f64_const,...u(0)];let q=_[G]??_.f64??_.i32;if(q===void 0)return K.errors.push(`Operator ${X.operator} not supported for type ${G}`),[W.f64_const,...u(0)];return[...z,...D,q]}function q8(X,K){let Z=b(X.argument,K),H=y(X.argument,K);switch(X.operator){case"-":if(H==="i32")return[W.i32_const,0,...Z,W.i32_sub];else if(H==="f32")return[...Z,W.f32_neg];else return[...Z,W.f64_neg];case"!":return[...Z,W.i32_eqz];case"~":return[...Z,W.i32_const,...B0(-1),W.i32_xor];default:return K.errors.push(`Unsupported unary operator: ${X.operator}`),Z}}function U8(X,K){if(X.left.type==="MemberExpression")return R8(X.left,X.right,X.operator,K);if(X.left.type!=="Identifier")return K.errors.push("Assignment target must be identifier or array element"),[];let Z=X.left.name,H=H0(K,Z);if(!H)return K.errors.push(`Unknown variable: ${Z}`),[];let Y=[];if(X.operator==="="){Y.push(...b(X.right,K));let J=y(X.right,K);if(H.type==="f64"&&J==="i32")Y.push(W.f64_convert_i32_s);else if(H.type==="f64"&&J==="f32")Y.push(W.f64_promote_f32);else if(H.type==="i32"&&J==="f64")Y.push(W.i32_trunc_f64_s);else if(H.type==="i32"&&J==="f32")Y.push(W.i32_trunc_f32_s);else if(H.type==="f32"&&J==="i32")Y.push(W.f32_convert_i32_s);else if(H.type==="f32"&&J==="f64")Y.push(W.f32_demote_f64)}else{let J=y(X.right,K),$=H.type;if(J==="f64"||H.type==="f64")$="f64";else if(J==="f32"||H.type==="f32")$="f32";if(Y.push(W.local_get,...C(H.index)),$==="f64"&&H.type==="i32")Y.push(W.f64_convert_i32_s);else if($==="f64"&&H.type==="f32")Y.push(W.f64_promote_f32);else if($==="f32"&&H.type==="i32")Y.push(W.f32_convert_i32_s);if(Y.push(...b(X.right,K)),$==="f64"&&J==="i32")Y.push(W.f64_convert_i32_s);else if($==="f64"&&J==="f32")Y.push(W.f64_promote_f32);else if($==="f32"&&J==="i32")Y.push(W.f32_convert_i32_s);let Q=X.operator.slice(0,-1),z={"+":{i32:W.i32_add,f32:W.f32_add,f64:W.f64_add},"-":{i32:W.i32_sub,f32:W.f32_sub,f64:W.f64_sub},"*":{i32:W.i32_mul,f32:W.f32_mul,f64:W.f64_mul},"/":{i32:W.i32_div_s,f32:W.f32_div,f64:W.f64_div}}[Q]?.[$];if(!z)return K.errors.push(`Unsupported compound assignment: ${X.operator}`),[];if(Y.push(z),H.type==="i32"&&$==="f64")Y.push(W.i32_trunc_f64_s);else if(H.type==="i32"&&$==="f32")Y.push(W.i32_trunc_f32_s);else if(H.type==="f32"&&$==="f64")Y.push(W.f32_demote_f64)}return Y.push(W.local_tee,...C(H.index)),Y}function A8(X,K){if(X.argument.type!=="Identifier")return K.errors.push("Update expression argument must be identifier"),[];let Z=X.argument.name,H=H0(K,Z);if(!H)return K.errors.push(`Unknown variable: ${Z}`),[];let Y=[],J=H.type==="i32";if(X.prefix){if(Y.push(W.local_get,...C(H.index)),J)Y.push(W.i32_const,1),Y.push(X.operator==="++"?W.i32_add:W.i32_sub);else Y.push(W.f64_const,...u(1)),Y.push(X.operator==="++"?W.f64_add:W.f64_sub);Y.push(W.local_tee,...C(H.index))}else{if(Y.push(W.local_get,...C(H.index)),Y.push(W.local_get,...C(H.index)),J)Y.push(W.i32_const,1),Y.push(X.operator==="++"?W.i32_add:W.i32_sub);else Y.push(W.f64_const,...u(1)),Y.push(X.operator==="++"?W.f64_add:W.f64_sub);Y.push(W.local_set,...C(H.index))}return Y}function w8(X,K){if(X.object.type!=="Identifier")return K.errors.push("Array access requires identifier"),[];let Z=X.object.name,H=K.params.find((z)=>z.name===Z);if(!H?.isArray||!H.arrayType)return K.errors.push(`${Z} is not a typed array parameter`),[];let Y=g0[H.arrayType];if(!Y)return K.errors.push(`Unknown array type: ${H.arrayType}`),[];K.needsMemory=!0;let J=[],$=H0(K,Z);if(!$)return K.errors.push(`Unknown array: ${Z}`),[];if(J.push(W.local_get,...C($.index)),!X.computed||!X.property)return K.errors.push("Array access requires computed index"),[];let Q=b(X.property,K),G=y(X.property,K);if(J.push(...Q),G==="f64")J.push(W.i32_trunc_f64_s);if(Y.bytesPerElement>1)J.push(W.i32_const,...B0(Y.bytesPerElement)),J.push(W.i32_mul);return J.push(W.i32_add),J.push(Y.loadOp,0,0),J}function R8(X,K,Z,H){if(X.object.type!=="Identifier")return H.errors.push("Array store requires identifier"),[];let Y=X.object.name,J=H.params.find((U)=>U.name===Y);if(!J?.isArray||!J.arrayType)return H.errors.push(`${Y} is not a typed array parameter`),[];let $=g0[J.arrayType];if(!$)return H.errors.push(`Unknown array type: ${J.arrayType}`),[];H.needsMemory=!0;let Q=[],G=H0(H,Y);if(!G)return[];if(!X.computed||!X.property)return H.errors.push("Array store requires computed index"),[];let z=b(X.property,H),D=y(X.property,H),F=()=>{let U=[];if(U.push(W.local_get,...C(G.index)),U.push(...z),D==="f64")U.push(W.i32_trunc_f64_s);if($.bytesPerElement>1)U.push(W.i32_const,...B0($.bytesPerElement)),U.push(W.i32_mul);return U.push(W.i32_add),U};if(Z==="=")Q.push(...b(K,H));else{let U=k0(H,`__addr_${H.nextLocalIndex}`,"i32");Q.push(...F()),Q.push(W.local_tee,...C(U)),Q.push($.loadOp,0,0),Q.push(...b(K,H));let A=y(K,H);if($.elementType==="f32"&&A==="f64")Q.push(W.f32_demote_f64);else if($.elementType==="f64"&&A==="f32")Q.push(W.f64_promote_f32);else if($.elementType==="f32"&&A==="i32")Q.push(W.f32_convert_i32_s);else if($.elementType==="f64"&&A==="i32")Q.push(W.f64_convert_i32_s);else if($.elementType==="i32"&&A==="f64")Q.push(W.i32_trunc_f64_s);else if($.elementType==="i32"&&A==="f32")Q.push(W.i32_trunc_f32_s);let I=Z.slice(0,-1),w={"+":$.elementType==="i32"?W.i32_add:$.elementType==="f32"?W.f32_add:W.f64_add,"-":$.elementType==="i32"?W.i32_sub:$.elementType==="f32"?W.f32_sub:W.f64_sub,"*":$.elementType==="i32"?W.i32_mul:$.elementType==="f32"?W.f32_mul:W.f64_mul};Q.push(w[I]??W.f64_add);let B=k0(H,`__val_${H.nextLocalIndex}`,$.elementType);return Q.push(W.local_set,...C(B)),Q.push(W.local_get,...C(U)),Q.push(W.local_get,...C(B)),Q.push($.storeOp,0,0),Q.push(W.local_get,...C(B)),Q}let _=y(K,H);if($.elementType==="f32"&&_==="f64")Q.push(W.f32_demote_f64);else if($.elementType==="f64"&&_==="f32")Q.push(W.f64_promote_f32);else if($.elementType==="i32"&&_==="f64")Q.push(W.i32_trunc_f64_s);let q=k0(H,`__tmp_${H.nextLocalIndex}`,$.elementType);if(Q.push(W.local_set,...C(q)),Q.push(W.local_get,...C(G.index)),Q.push(...z),D==="f64")Q.push(W.i32_trunc_f64_s);if($.bytesPerElement>1)Q.push(W.i32_const,...B0($.bytesPerElement)),Q.push(W.i32_mul);return Q.push(W.i32_add),Q.push(W.local_get,...C(q)),Q.push($.storeOp,0,0),Q.push(W.local_get,...C(q)),Q}function I8(X,K){if(X.callee.type==="MemberExpression"){let Z=X.callee;if(Z.object.type==="Identifier"&&Z.object.name==="Math"&&Z.property.type==="Identifier"){let H=Z.property.name;return B8(H,X.arguments,K)}}return K.errors.push(`Unsupported function call: ${X.callee.type}`),[W.f64_const,...u(0)]}function B8(X,K,Z){let H=[];for(let Q of K){H.push(...b(Q,Z));let G=y(Q,Z);if(G==="i32")H.push(W.f64_convert_i32_s);else if(G==="f32")H.push(W.f64_promote_f32)}let J={abs:W.f64_abs,ceil:W.f64_ceil,floor:W.f64_floor,trunc:W.f64_trunc,sqrt:W.f64_sqrt,min:W.f64_min,max:W.f64_max}[X];if(J!==void 0)return H.push(J),H;if(["sin","cos","tan","asin","acos","atan","atan2","exp","log","pow"].includes(X))return Z.needsMathImports.add(X),Z.errors.push(`Math.${X} requires JS import (not yet implemented)`),[W.f64_const,...u(0)];return Z.errors.push(`Unknown Math method: ${X}`),[W.f64_const,...u(0)]}function L8(X){let K=X.split(":").map((J)=>J.trim()),Z=K[0];if(K.length===1)return{name:Z,type:"f64"};let H=K[1];if(g0[H])return{name:Z,type:"i32",isArray:!0,arrayType:H};return{name:Z,type:{i32:"i32",i64:"i64",f32:"f32",f64:"f64",number:"f64",int:"i32"}[H]??"f64"}}function M8(X,K,Z,H,Y){let J=[0,97,115,109,1,0,0,0],$=X.map((B)=>l[B.type]),Q=Y?[1,l.f64]:[0],G=R0(w0.type,[1,96,...C(X.length),...$,...Q]),z=[],D=[];if(H)D=R0(w0.import,[1,...a0("env"),...a0("memory"),2,0,1]);let F=R0(w0.function,[1,0]),_=R0(w0.export,[1,...a0("compute"),0,0]),q=[];if(Z.length>0){let B=Z[0],P=1;for(let L=1;L<Z.length;L++)if(Z[L]===B)P++;else q.push([...C(P),l[B]]),B=Z[L],P=1;q.push([...C(P),l[B]])}let A=[...[...C(q.length),...q.flat()],...K,W.end],I=R0(w0.code,[1,...C(A.length),...A]),w=[...J,...G];if(D.length>0)w.push(...D);return w.push(...F,..._,...I),w}function x6(X){try{let K=X.captures.map(L8),Z;try{let z=`function __wasm__(${K.map((D)=>D.name).join(", ")}) { ${X.body} }`;Z=h6.parse(z,{ecmaVersion:2022})}catch(z){return{bytes:new Uint8Array,warnings:[],success:!1,error:`Parse error: ${z.message}`}}let Y=Z.body[0].body.body,J=W8(K),$=[];for(let z of Y)$.push(...W0(z,J));if(J.errors.length>0)return{bytes:new Uint8Array,warnings:J.warnings,success:!1,error:J.errors.join("; ")};let Q=M8(K,$,J.localTypes,J.needsMemory,J.hasReturn),G=G8($,K,J.localTypes);return{bytes:new Uint8Array(Q),warnings:J.warnings,success:!0,needsMemory:J.needsMemory,wat:G}}catch(K){return{bytes:new Uint8Array,warnings:[],success:!1,error:K.message}}}function j8(X,K,Z,H){let Y=[],J=q0(K,X),$={},Q=!1,G,z;if(X.params.length===1&&(X.params[0].type==="ObjectPattern"||X.params[0].type==="AssignmentPattern"&&X.params[0].left.type==="ObjectPattern")){Q=!0;let _=X.params[0],q=_.type==="ObjectPattern"?_:_.left,U=e(q,Z);if(U.type.kind==="object"&&U.type.destructuredParams){G={},z=new Set;for(let[A,I]of Object.entries(U.type.destructuredParams))if($[A]={...I,description:J.params[A]},G[A]=I.type,I.required)z.add(A)}}else for(let _ of X.params)if(_.type==="Identifier"){let q=e(_,Z);$[_.name]={...q,required:Z.has(_.name),description:J.params[_.name]}}else if(_.type==="AssignmentPattern"&&_.left.type==="Identifier"){let q=e(_,Z);$[_.left.name]={...q,required:Z.has(_.left.name),description:J.params[_.left.name]}}else if(_.type==="ObjectPattern"){let q=e(_,Z);if(q.type.kind==="object"&&q.type.destructuredParams)for(let[U,A]of Object.entries(q.type.destructuredParams))$[U]={...A,description:J.params[U]}}let D;if(H)try{let _=P8(H,0,{ecmaVersion:2022});D=d(_)}catch{D={kind:"any"},Y.push(`Could not parse return type: ${H}`)}return{types:{name:X.id?.name||"anonymous",params:$,returns:D,description:J.description,isDestructuredParam:Q,destructuredShape:G,destructuredRequired:z},warnings:Y}}function V8(X,K,Z){let H=[],Y=Z?`${Z}:`:"",J=Z?`${Z}:${X}`:X;if(H.push(`__tjs.pushStack('${J}');`),K.isDestructuredParam&&K.destructuredShape){let Q=K.destructuredShape,G=K.destructuredRequired||new Set,z=Object.keys(Q);if(z.length===0)return null;for(let D of z)H.push(`if (${D} instanceof Error) return ${D};`);for(let[D,F]of Object.entries(Q)){let _=G.has(D),q=`${Y}${X}.${D}`,U=m6(D,F);if(U){let A=F.kind;if(_)H.push(`if (${U}) return __tjs.typeError('${q}', '${A}', ${D});`);else H.push(`if (${D} !== undefined && ${U}) return __tjs.typeError('${q}', '${A}', ${D});`)}}return H.length>0?H.join(`
|
|
140
|
+
`):null}let $=Object.entries(K.params);if($.length===0)return null;for(let[Q]of $)H.push(`if (${Q} instanceof Error) return ${Q};`);for(let[Q,G]of $){let z=`${Y}${X}.${Q}`,D=m6(Q,G.type);if(D){let F=G.type.kind;if(G.required)H.push(`if (${D}) return __tjs.typeError('${z}', '${F}', ${Q});`);else H.push(`if (${Q} !== undefined && ${D}) return __tjs.typeError('${z}', '${F}', ${Q});`)}}return H.length>0?H.join(`
|
|
141
|
+
`):null}function E8(X,K){let H=new RegExp(`function\\s+${K}\\s*\\([^)]*\\)\\s*(-[>?!])\\s*`,"g").exec(X);if(!H)return null;let Y=X.slice(H.index+H[0].length);return u6(Y)}function C8(X,K){let H=new RegExp(`function\\s+${K}\\s*\\([^)]*\\)\\s*-([>?!])`,"g").exec(X);if(!H)return;let Y=H[1];if(Y==="?")return"safe";if(Y==="!")return"unsafe";return}function N8(X){let K=X.match(/^\/\*\s*tjs\s*<-\s*([^*]+?)\s*\*\//);return K?K[1].trim():void 0}function O8(X,K){let Z=new RegExp(`\\/\\*\\s*line\\s+(\\d+)\\s*\\*\\/\\s*(?:async\\s+)?function\\s+${K}\\s*\\(`,"m"),H=X.match(Z);return H?parseInt(H[1],10):void 0}function v0(X,K={}){let{filename:Z="<source>",runTests:H=!0,debug:Y=!1,resolvedImports:J={}}=K,$=[],G=N8(X)||Z,{code:z,tests:D,mocks:F,testRunner:_}=s0(X),{ast:q,originalSource:U,requiredParams:A,unsafeFunctions:I}=Z0(z,{filename:Z,colonShorthand:!0}),w=S8(q),B=O0(z),P={},L=[];for(let O of w){let g=O.id?.name||"anonymous",X0=E8(z,g),{types:a,warnings:z1}=j8(O,U,A,X0);$.push(...z1),P[g]=a;let j6=B.moduleSafety==="none"||I.has(g),G1=B.safeFunctions.has(g),W1=C8(z,g),_1=O8(X,g),u0={file:G,line:_1??O.loc?.start.line??0,column:O.loc?.start.column??0},D1=T8(g,a,{unsafe:j6,safe:G1,returnSafety:W1},{debug:Y,source:u0});if(L.push({position:O.end,text:`
|
|
142
|
+
${D1}`}),!j6){let F1=`${u0.file}:${u0.line}`,V6=V8(g,a,F1);if(V6&&O.body&&O.body.start!==void 0)L.push({position:O.body.start+1,text:`
|
|
143
|
+
${V6}
|
|
144
|
+
`})}}L.sort((O,g)=>g.position-O.position);let M=B.source;for(let{position:O,text:g}of L)M=M.slice(0,O)+g+M.slice(O);let j=M.includes("__tjs.typeError("),V=M.includes("Is("),E=M.includes("IsNot("),h=B.tjsModes.tjsSafeEval;if(j||V||E||h){let O=`const __tjs = globalThis.__tjs?.createRuntime?.() ?? globalThis.__tjs;
|
|
145
|
+
`;if(V||E){let g=[V&&"Is",E&&"IsNot"].filter(Boolean).join(", ");O+=`const { ${g} } = __tjs ?? {};
|
|
146
|
+
`}M=O+M}if(h)M=`import { Eval, SafeFunction } from 'tjs-lang';
|
|
147
|
+
`+M;let S;if(H){let O=b8(X);S=f8(D,F,O,M,J);let g=S.filter((X0)=>!X0.passed);if(g.length>0&&H===!0){let X0=g.map((a)=>{if(a.isSignatureTest)return` Function signature example is inconsistent:
|
|
148
|
+
${a.error}`;return` Test '${a.description}' failed:
|
|
149
|
+
${a.error}`});throw Error(`Transpile-time test failures:
|
|
150
|
+
${X0.join(`
|
|
151
|
+
`)}`)}}if(H==="only")return{code:"",types:P,metadata:P,testResults:S,testCount:S?.length};let i;if(B.wasmBlocks.length>0){i=[];let O=x8(B.wasmBlocks);if(O.code)M=O.code+`
|
|
152
|
+
`+M;i=O.results}return{code:M,types:P,metadata:P,warnings:$.length>0?$:void 0,testRunner:D.length>0?_:void 0,testCount:D.length>0?D.length:void 0,testResults:S,wasmCompiled:i}}function S8(X){let K=[];for(let Z of X.body)if(Z.type==="FunctionDeclaration")K.push(Z);else if(Z.type==="ExportNamedDeclaration"&&Z.declaration?.type==="FunctionDeclaration")K.push(Z.declaration);else if(Z.type==="ExportDefaultDeclaration"&&Z.declaration?.type==="FunctionDeclaration")K.push(Z.declaration);return K}function M0(X){let K={kind:X.kind};if(X.nullable)K.nullable=!0;if(X.items)K.items=M0(X.items);if(X.shape)K.shape=Object.fromEntries(Object.entries(X.shape).map(([Z,H])=>[Z,M0(H)]));if(X.members)K.members=X.members.map(M0);return K}function T8(X,K,Z={},H={}){let Y={};for(let[$,Q]of Object.entries(K.params)){if(Y[$]={type:M0(Q.type),required:Q.required},Q.default!==void 0)Y[$].default=Q.default;if(Q.description)Y[$].description=Q.description}let J={params:Y};if(K.returns){if(J.returns={type:M0(K.returns)},Z.returnSafety==="safe")J.safeReturn=!0;else if(Z.returnSafety==="unsafe")J.unsafeReturn=!0}if(K.description)J.description=K.description;if(Z.unsafe)J.unsafe=!0;if(Z.safe)J.safe=!0;if(H.source){let{file:$,line:Q}=H.source;J.source=`${$}:${Q}`}return`${X}.__tjs = ${JSON.stringify(J,null,2)}`}function m6(X,K){switch(K.kind){case"string":return`typeof ${X} !== 'string'`;case"number":return`typeof ${X} !== 'number'`;case"boolean":return`typeof ${X} !== 'boolean'`;case"null":return`${X} !== null`;case"undefined":return`${X} !== undefined`;case"array":return`!Array.isArray(${X})`;case"object":return`(typeof ${X} !== 'object' || ${X} === null || Array.isArray(${X}))`;case"any":return null;default:return null}}function k8(X,K,Z=0.000000001){if(X===K)return!0;if(typeof X==="number"&&typeof K==="number"){if(!Number.isInteger(X)||!Number.isInteger(K)){let H=Math.abs(X-K),Y=Math.max(Math.abs(X),Math.abs(K),1);return H/Y<Z}}return!1}function r0(X,K){if(X===K)return!0;if(k8(X,K))return!0;if(X===null||K===null)return X===K;if(X===void 0||K===void 0)return X===K;if(typeof X!==typeof K)return!1;if(typeof X!=="object")return!1;if(Array.isArray(X)&&Array.isArray(K)){if(X.length!==K.length)return!1;return X.every((Y,J)=>r0(Y,K[J]))}if(Array.isArray(X)!==Array.isArray(K))return!1;let Z=Object.keys(X),H=Object.keys(K);if(Z.length!==H.length)return!1;return Z.every((Y)=>r0(X[Y],K[Y]))}function t0(X,K,Z=""){if(K===null){if(X===null)return{matches:!0};return{matches:!1,error:`Expected null at '${Z}', got ${Y0(X)}`}}if(K===void 0){if(X===void 0)return{matches:!0};return{matches:!1,error:`Expected undefined at '${Z}', got ${Y0(X)}`}}if(typeof K==="number"){if(typeof X==="number")return{matches:!0};return{matches:!1,error:`Expected number at '${Z}', got ${Y0(X)}`}}if(typeof K==="string"){if(typeof X==="string")return{matches:!0};return{matches:!1,error:`Expected string at '${Z}', got ${Y0(X)}`}}if(typeof K==="boolean"){if(typeof X==="boolean")return{matches:!0};return{matches:!1,error:`Expected boolean at '${Z}', got ${Y0(X)}`}}if(Array.isArray(K)){if(!Array.isArray(X))return{matches:!1,error:`Expected array at '${Z}', got ${Y0(X)}`};if(K.length===0)return{matches:!0};let H=K[0];for(let Y=0;Y<X.length;Y++){let J=t0(X[Y],H,`${Z}[${Y}]`);if(!J.matches)return J}return{matches:!0}}if(typeof K==="object"&&K!==null){if(typeof X!=="object"||X===null||Array.isArray(X))return{matches:!1,error:`Expected object at '${Z}', got ${Y0(X)}`};for(let H of Object.keys(K)){let Y=Z?`${Z}.${H}`:H;if(!(H in X))return{matches:!1,error:`Missing property '${Y}'`};let J=t0(X[H],K[H],Y);if(!J.matches)return J}return{matches:!0}}if(X===K)return{matches:!0};return{matches:!1,error:`Type mismatch at '${Z}'`}}function Y0(X){if(X===null)return"null";if(X===void 0)return"undefined";if(Array.isArray(X))return"array";return typeof X}function L0(X,K=0){if(X===null)return"null";if(X===void 0)return"undefined";if(typeof X==="string")return JSON.stringify(X);if(typeof X==="number")return String(X);if(typeof X==="boolean")return String(X);if(Array.isArray(X)){if(X.length===0)return"[]";if(X.length<=3)return`[${X.map((Z)=>L0(Z,K)).join(", ")}]`;return`[${X.slice(0,3).map((Z)=>L0(Z,K)).join(", ")}, ...]`}if(typeof X==="object"){let Z=Object.entries(X);if(Z.length===0)return"{}";let H=(G)=>/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(G)?G:JSON.stringify(G);if(Z.length<=2)return`{${Z.map(([z,D])=>`${H(z)}: ${L0(D,K)}`).join(", ")}}`;let Y=" ".repeat(K+1),J=" ".repeat(K),$=Z.slice(0,8).map(([G,z])=>`${Y}${H(G)}: ${L0(z,K+1)}`).join(`,
|
|
151
153
|
`),Q=Z.length>8?`,
|
|
152
|
-
${
|
|
154
|
+
${Y}...`:"";return`{
|
|
153
155
|
${$}${Q}
|
|
154
|
-
${J}}`}return String(X)}function
|
|
156
|
+
${J}}`}return String(X)}function g8(X){let K=X.replace(/\/\*[\s\S]*?\*\//g,(Z)=>{let H=Z.split(`
|
|
155
157
|
`).length-1;return`
|
|
156
|
-
`.repeat(
|
|
157
|
-
`)}function
|
|
158
|
-
`).length;if(Q==="-!")continue;let z=Z.slice(
|
|
159
|
-
`),z=X.map((
|
|
160
|
-
// Test ${A}: ${
|
|
158
|
+
`.repeat(H)});return K=K.replace(/\/\/[^\n]*/g,""),K}function d6(X){let K=X.replace(/^import\s+.*?from\s+['"][^'"]+['"];?\s*$/gm,"");return K=K.replace(/^import\s+['"][^'"]+['"];?\s*$/gm,""),K=K.replace(/^export\s+default\s+/gm,""),K=K.replace(/^export\s+/gm,""),K}function l6(X){let K=X.replace(/^const __tjs = globalThis\.__tjs\?\.createRuntime\?\.\(\) \?\? globalThis\.__tjs;\n?/m,"");return K=K.replace(/^const \{ (?:Is|IsNot|Is, IsNot) \} = __tjs \?\? \{\};\n?/m,""),K}function v8(X){if(Object.keys(X).length===0)return"";let K=[];for(let[Z,H]of Object.entries(X)){let Y=d6(H);Y=l6(Y),K.push(`// Resolved import: ${Z}`),K.push(Y)}return K.join(`
|
|
159
|
+
`)}function b8(X){let K=[],Z=g8(X),H=/function\s+(\w+)\s*\(([^)]*)\)\s*(-[>?])\s*/g,Y;while((Y=H.exec(Z))!==null){let J=Y[1],$=Y[2],Q=Y[3],G=Z.slice(0,Y.index).split(`
|
|
160
|
+
`).length;if(Q==="-!")continue;let z=Z.slice(Y.index+Y[0].length),D=u6(z);if(!D)continue;let F=y8($);if($.trim()&&F.length===0)continue;try{let _=Function(`return ${D}`)(),q=F.map((U)=>Function(`return ${U}`)());K.push({funcName:J,args:q,expected:_,line:G})}catch{}}return K}function f8(X,K,Z,H,Y={}){let J=[];if(X.length===0&&Z.length===0)return J;let $=d6(H);$=l6($);let Q=v8(Y),G=K.map((U)=>U.body).join(`
|
|
161
|
+
`),z=X.map((U,A)=>`
|
|
162
|
+
// Test ${A}: ${U.description}
|
|
161
163
|
try {
|
|
162
|
-
${
|
|
164
|
+
${U.body}
|
|
163
165
|
__testResults.push({ idx: ${A}, passed: true });
|
|
164
166
|
} catch (e) {
|
|
165
167
|
__testResults.push({ idx: ${A}, passed: false, error: e.message || String(e) });
|
|
166
168
|
}
|
|
167
169
|
`).join(`
|
|
168
|
-
`),
|
|
169
|
-
// Signature test ${A}: ${
|
|
170
|
+
`),D=Z.map((U,A)=>`
|
|
171
|
+
// Signature test ${A}: ${U.funcName}
|
|
170
172
|
try {
|
|
171
|
-
const __actual = ${
|
|
172
|
-
const __expected = ${JSON.stringify(
|
|
173
|
-
const __typeResult = __typeMatches(__actual, __expected, '${
|
|
173
|
+
const __actual = ${U.funcName}(${U.args.map((I)=>JSON.stringify(I)).join(", ")});
|
|
174
|
+
const __expected = ${JSON.stringify(U.expected)};
|
|
175
|
+
const __typeResult = __typeMatches(__actual, __expected, '${U.funcName}');
|
|
174
176
|
if (__typeResult.matches) {
|
|
175
177
|
__sigTestResults.push({ idx: ${A}, passed: true });
|
|
176
178
|
} else {
|
|
@@ -180,7 +182,7 @@ ${J}}`}return String(X)}function r1(X){let Y=X.replace(/\/\*[\s\S]*?\*\//g,(Z)=>
|
|
|
180
182
|
__sigTestResults.push({ idx: ${A}, passed: false, error: e.message || String(e) });
|
|
181
183
|
}
|
|
182
184
|
`).join(`
|
|
183
|
-
`),
|
|
185
|
+
`),q=`
|
|
184
186
|
${"\n const __saved_tjs = globalThis.__tjs;\n const __stub_tjs = { version: '0.0.0', pushStack: () => {}, typeError: (path, expected, value) => new Error(`Type error at ${path}: expected ${expected}`), createRuntime: function() { return this; } };\n globalThis.__tjs = __stub_tjs;\n "}
|
|
185
187
|
const __testResults = [];
|
|
186
188
|
const __sigTestResults = [];
|
|
@@ -216,17 +218,47 @@ ${J}}`}return String(X)}function r1(X){let Y=X.replace(/\/\*[\s\S]*?\*\//g,(Z)=>
|
|
|
216
218
|
${z}
|
|
217
219
|
|
|
218
220
|
// Run signature tests
|
|
219
|
-
${
|
|
221
|
+
${D}
|
|
220
222
|
|
|
221
223
|
} finally {
|
|
222
224
|
${"globalThis.__tjs = __saved_tjs;"}
|
|
223
225
|
}
|
|
224
226
|
return { testResults: __testResults, sigTestResults: __sigTestResults };
|
|
225
|
-
`;try{let D=Function("__deepEqual","__format","__typeMatches",F),{testResults:A,sigTestResults:L}=D(v6,z6,f6);for(let B of A){let I=X[B.idx];J.push({description:I.description,passed:B.passed,error:B.error,line:I.line})}for(let B of L){let I=Z[B.idx];J.push({description:`${I.funcName} signature example`,passed:B.passed,error:B.error,isSignatureTest:!0,line:I.line})}}catch(D){for(let A of X)J.push({description:A.description,passed:!1,error:`Module execution failed: ${D.message}`,line:A.line});for(let A of Z)J.push({description:`${A.funcName} signature example`,passed:!1,error:`Module execution failed: ${D.message}`,isSignatureTest:!0,line:A.line})}return J}function j0(X){let Y="",Z=0,K=!1;for(let J=0;J<X.length;J++){let $=X[J];if($==="{"||$==="["||$==="("){if($==="{"&&Z===0&&K)break;Z++,Y+=$,K=!0}else if($==="}"||$==="]"||$===")")Z--,Y+=$;else if(!/\s/.test($))Y+=$,K=!0;else Y+=$}return Y.trim()||null}function Y5(X){if(!X.trim())return[];let Y=[],Z=K5(X);for(let K of Z){let H=K.match(/(?:\(\s*[?!]\s*)?(\w+)\s*[:=]\s*(.+?)(?:\))?$/);if(H)Y.push(H[2].trim());else return[]}return Y}function K5(X){let Y=[],Z="",K=0;for(let H of X){if(H==="("||H==="["||H==="{")K++;else if(H===")"||H==="]"||H==="}")K--;else if(H===","&&K===0){Y.push(Z.trim()),Z="";continue}Z+=H}if(Z.trim())Y.push(Z.trim());return Y}function R6(X,Y={}){let{ast:Z,returnType:K,originalSource:H,requiredParams:J}=c(X,{filename:Y.filename,colonShorthand:!0,vmTarget:!0}),$=D0(Z,Y.filename),{ast:Q,signature:G,warnings:z}=k6($,H,K,Y,J);return{ast:Q,signature:G,warnings:z}}function H5(X,...Y){if(typeof X==="string")return R6(X).ast;let Z=X.reduce((K,H,J)=>K+H+(Y[J]!==void 0?String(Y[J]):""),"");return R6(Z).ast}function $5(X,Y,Z){let{ast:K,signature:H}=R6(X),J=async($)=>{return(await Y.run(K,$,Z)).result};return J.signature=H,J.ast=K,J}function I6(X){switch(X.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:X.items?I6(X.items):{}};case"object":if(!X.shape)return{type:"object"};return{type:"object",properties:Object.fromEntries(Object.entries(X.shape).map(([Y,Z])=>[Y,I6(Z)]))};case"union":if(!X.members)return{};return{anyOf:X.members.map(I6)};case"any":default:return{}}}function J5(X){return Object.entries(X).map(([Y,Z])=>{let K=Z.signature,H={},J=[];for(let[$,Q]of Object.entries(K.parameters)){if(H[$]=I6(Q.type),Q.description)H[$].description=Q.description;if(Q.required)J.push($)}return{type:"function",function:{name:Y,description:K.description,parameters:{type:"object",properties:H,required:J}}}})}function Q5(X,Y,...Z){if(typeof X==="string")return w6(X,Y);let K=Y!==void 0?[Y,...Z]:Z,H=X.reduce((J,$,Q)=>J+$+(K[Q]!==void 0?String(K[Q]):""),"");return w6(H)}import{s as E0}from"tosijs-schema";function V0(X){if(X===null)return"null";if(X===void 0)return"undefined";if(Array.isArray(X))return"array";return typeof X}function O6(X){return E0.infer(X)}function y6(X){return O6(X)}y6.type=V0;y6.infer=O6;var z5=new Proxy(y6,{get(X,Y){if(Y==="type")return V0;if(Y==="infer")return O6;return E0[Y]},apply(X,Y,Z){return O6(Z[0])}});function M6(X,Y,Z,K,H){if(!Z)Z=q;(function J($,Q,G){var z=G||$.type;if(Z[z]($,Q,J),Y[z])Y[z]($,Q)})(X,K,H)}function T0(X,Y,Z,K,H){var J=[];if(!Z)Z=q;(function $(Q,G,z){var _=z||Q.type,U=Q!==J[J.length-1];if(U)J.push(Q);if(Z[_](Q,G,$),Y[_])Y[_](Q,G||J,J);if(U)J.pop()})(X,K,H)}function x6(X,Y,Z){Z(X,Y)}function t(X,Y,Z){}var q={};q.Program=q.BlockStatement=q.StaticBlock=function(X,Y,Z){for(var K=0,H=X.body;K<H.length;K+=1){var J=H[K];Z(J,Y,"Statement")}};q.Statement=x6;q.EmptyStatement=t;q.ExpressionStatement=q.ParenthesizedExpression=q.ChainExpression=function(X,Y,Z){return Z(X.expression,Y,"Expression")};q.IfStatement=function(X,Y,Z){if(Z(X.test,Y,"Expression"),Z(X.consequent,Y,"Statement"),X.alternate)Z(X.alternate,Y,"Statement")};q.LabeledStatement=function(X,Y,Z){return Z(X.body,Y,"Statement")};q.BreakStatement=q.ContinueStatement=t;q.WithStatement=function(X,Y,Z){Z(X.object,Y,"Expression"),Z(X.body,Y,"Statement")};q.SwitchStatement=function(X,Y,Z){Z(X.discriminant,Y,"Expression");for(var K=0,H=X.cases;K<H.length;K+=1){var J=H[K];Z(J,Y)}};q.SwitchCase=function(X,Y,Z){if(X.test)Z(X.test,Y,"Expression");for(var K=0,H=X.consequent;K<H.length;K+=1){var J=H[K];Z(J,Y,"Statement")}};q.ReturnStatement=q.YieldExpression=q.AwaitExpression=function(X,Y,Z){if(X.argument)Z(X.argument,Y,"Expression")};q.ThrowStatement=q.SpreadElement=function(X,Y,Z){return Z(X.argument,Y,"Expression")};q.TryStatement=function(X,Y,Z){if(Z(X.block,Y,"Statement"),X.handler)Z(X.handler,Y);if(X.finalizer)Z(X.finalizer,Y,"Statement")};q.CatchClause=function(X,Y,Z){if(X.param)Z(X.param,Y,"Pattern");Z(X.body,Y,"Statement")};q.WhileStatement=q.DoWhileStatement=function(X,Y,Z){Z(X.test,Y,"Expression"),Z(X.body,Y,"Statement")};q.ForStatement=function(X,Y,Z){if(X.init)Z(X.init,Y,"ForInit");if(X.test)Z(X.test,Y,"Expression");if(X.update)Z(X.update,Y,"Expression");Z(X.body,Y,"Statement")};q.ForInStatement=q.ForOfStatement=function(X,Y,Z){Z(X.left,Y,"ForInit"),Z(X.right,Y,"Expression"),Z(X.body,Y,"Statement")};q.ForInit=function(X,Y,Z){if(X.type==="VariableDeclaration")Z(X,Y);else Z(X,Y,"Expression")};q.DebuggerStatement=t;q.FunctionDeclaration=function(X,Y,Z){return Z(X,Y,"Function")};q.VariableDeclaration=function(X,Y,Z){for(var K=0,H=X.declarations;K<H.length;K+=1){var J=H[K];Z(J,Y)}};q.VariableDeclarator=function(X,Y,Z){if(Z(X.id,Y,"Pattern"),X.init)Z(X.init,Y,"Expression")};q.Function=function(X,Y,Z){if(X.id)Z(X.id,Y,"Pattern");for(var K=0,H=X.params;K<H.length;K+=1){var J=H[K];Z(J,Y,"Pattern")}Z(X.body,Y,X.expression?"Expression":"Statement")};q.Pattern=function(X,Y,Z){if(X.type==="Identifier")Z(X,Y,"VariablePattern");else if(X.type==="MemberExpression")Z(X,Y,"MemberPattern");else Z(X,Y)};q.VariablePattern=t;q.MemberPattern=x6;q.RestElement=function(X,Y,Z){return Z(X.argument,Y,"Pattern")};q.ArrayPattern=function(X,Y,Z){for(var K=0,H=X.elements;K<H.length;K+=1){var J=H[K];if(J)Z(J,Y,"Pattern")}};q.ObjectPattern=function(X,Y,Z){for(var K=0,H=X.properties;K<H.length;K+=1){var J=H[K];if(J.type==="Property"){if(J.computed)Z(J.key,Y,"Expression");Z(J.value,Y,"Pattern")}else if(J.type==="RestElement")Z(J.argument,Y,"Pattern")}};q.Expression=x6;q.ThisExpression=q.Super=q.MetaProperty=t;q.ArrayExpression=function(X,Y,Z){for(var K=0,H=X.elements;K<H.length;K+=1){var J=H[K];if(J)Z(J,Y,"Expression")}};q.ObjectExpression=function(X,Y,Z){for(var K=0,H=X.properties;K<H.length;K+=1){var J=H[K];Z(J,Y)}};q.FunctionExpression=q.ArrowFunctionExpression=q.FunctionDeclaration;q.SequenceExpression=function(X,Y,Z){for(var K=0,H=X.expressions;K<H.length;K+=1){var J=H[K];Z(J,Y,"Expression")}};q.TemplateLiteral=function(X,Y,Z){for(var K=0,H=X.quasis;K<H.length;K+=1){var J=H[K];Z(J,Y)}for(var $=0,Q=X.expressions;$<Q.length;$+=1){var G=Q[$];Z(G,Y,"Expression")}};q.TemplateElement=t;q.UnaryExpression=q.UpdateExpression=function(X,Y,Z){Z(X.argument,Y,"Expression")};q.BinaryExpression=q.LogicalExpression=function(X,Y,Z){Z(X.left,Y,"Expression"),Z(X.right,Y,"Expression")};q.AssignmentExpression=q.AssignmentPattern=function(X,Y,Z){Z(X.left,Y,"Pattern"),Z(X.right,Y,"Expression")};q.ConditionalExpression=function(X,Y,Z){Z(X.test,Y,"Expression"),Z(X.consequent,Y,"Expression"),Z(X.alternate,Y,"Expression")};q.NewExpression=q.CallExpression=function(X,Y,Z){if(Z(X.callee,Y,"Expression"),X.arguments)for(var K=0,H=X.arguments;K<H.length;K+=1){var J=H[K];Z(J,Y,"Expression")}};q.MemberExpression=function(X,Y,Z){if(Z(X.object,Y,"Expression"),X.computed)Z(X.property,Y,"Expression")};q.ExportNamedDeclaration=q.ExportDefaultDeclaration=function(X,Y,Z){if(X.declaration)Z(X.declaration,Y,X.type==="ExportNamedDeclaration"||X.declaration.id?"Statement":"Expression");if(X.source)Z(X.source,Y,"Expression")};q.ExportAllDeclaration=function(X,Y,Z){if(X.exported)Z(X.exported,Y);Z(X.source,Y,"Expression")};q.ImportDeclaration=function(X,Y,Z){for(var K=0,H=X.specifiers;K<H.length;K+=1){var J=H[K];Z(J,Y)}Z(X.source,Y,"Expression")};q.ImportExpression=function(X,Y,Z){Z(X.source,Y,"Expression")};q.ImportSpecifier=q.ImportDefaultSpecifier=q.ImportNamespaceSpecifier=q.Identifier=q.PrivateIdentifier=q.Literal=t;q.TaggedTemplateExpression=function(X,Y,Z){Z(X.tag,Y,"Expression"),Z(X.quasi,Y,"Expression")};q.ClassDeclaration=q.ClassExpression=function(X,Y,Z){return Z(X,Y,"Class")};q.Class=function(X,Y,Z){if(X.id)Z(X.id,Y,"Pattern");if(X.superClass)Z(X.superClass,Y,"Expression");Z(X.body,Y)};q.ClassBody=function(X,Y,Z){for(var K=0,H=X.body;K<H.length;K+=1){var J=H[K];Z(J,Y)}};q.MethodDefinition=q.PropertyDefinition=q.Property=function(X,Y,Z){if(X.computed)Z(X.key,Y,"Expression");if(X.value)Z(X.value,Y,"Expression")};var W5={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function _5(X,Y={}){let Z={...W5,...Y},K=[],H;try{H=c(X,{filename:Z.filename,colonShorthand:!0}).ast}catch($){return{diagnostics:[{severity:"error",message:$.message,line:$.loc?.line,column:$.loc?.column,rule:"parse-error"}],valid:!1}}let J=[C0()];if(T0(H,{FunctionDeclaration($,Q,G){let z=C0();J.push(z);for(let _ of $.params)F5(z,_,"parameter");if($.id)(J[J.length-2]||J[0]).declarations.set($.id.name,{node:$.id,kind:"function",used:!1})},VariableDeclaration($){let Q=J[J.length-1];for(let G of $.declarations)if(G.id.type==="Identifier")Q.declarations.set(G.id.name,{node:G.id,kind:$.kind,used:!1})}}),M6(H,{Identifier($){for(let Q=J.length-1;Q>=0;Q--){let G=J[Q].declarations.get($.name);if(G){G.used=!0;break}}}}),Z.unusedVariables)for(let $ of J)for(let[Q,G]of $.declarations){if(Q.startsWith("_"))continue;if(!G.used&&G.kind!=="function")K.push({severity:"warning",message:`'${Q}' is declared but never used`,line:G.node.loc?.start?.line,column:G.node.loc?.start?.column,rule:"no-unused-vars"})}if(Z.unreachableCode)M6(H,{BlockStatement($){let Q=!1;for(let G of $.body){if(Q){K.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")Q=!0}}});if(Z.noExplicitNew)M6(H,{NewExpression($){let Q="class";if($.callee.type==="Identifier")Q=$.callee.name;else if($.callee.type==="MemberExpression"){if($.callee.property.type==="Identifier")Q=$.callee.property.name}K.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${Q}(...) instead of new ${Q}(...)`,line:$.loc?.start?.line,column:$.loc?.start?.column,rule:"no-explicit-new"})}});return{diagnostics:K,valid:K.filter(($)=>$.severity==="error").length===0}}function C0(){return{declarations:new Map}}function F5(X,Y,Z){if(Y.type==="Identifier")X.declarations.set(Y.name,{node:Y,kind:Z,used:!1});else if(Y.type==="AssignmentPattern"&&Y.left.type==="Identifier")X.declarations.set(Y.left.name,{node:Y.left,kind:Z,used:!1})}import{validate as y0,s as E6}from"tosijs-schema";import{validate as h6,s as P6}from"tosijs-schema";function r(X){return X!==null&&typeof X==="object"&&"__runtimeType"in X&&X.__runtimeType===!0}function N0(X){return X!==null&&typeof X==="object"&&"schema"in X&&typeof X.schema==="object"}function U5(X){return X!==null&&typeof X==="object"&&"type"in X&&typeof X.type==="string"}function k(X,Y,Z,K){let H,J,$,Q=Z,G=K;if(typeof X==="string")if(H=X,typeof Y==="function"){if(J=Y,Q!==void 0)$=P6.infer(Q)}else if(Y===void 0&&Q!==void 0)$=P6.infer(Q);else if(N0(Y))$=Y;else if(U5(Y))$=Y;else if(Y!==void 0)Q=Y,G=Q,$=P6.infer(Q);else throw Error("Type(description) requires a predicate, schema, or example");else{if(N0(X))$=X;else $=X;H=D5($)}return{description:H,check:(_)=>{if(J)return J(_);if($)return h6(_,$);return!1},schema:$,predicate:J,example:Q,default:G,__runtimeType:!0}}function D5(X){let Y=X?.schema??X;if(Y&&typeof Y==="object"&&"type"in Y){let Z=Y;switch(Z.type){case"string":if(Z.format)return`string (${Z.format})`;if(Z.pattern)return`string matching ${Z.pattern}`;if(Z.minLength!==void 0&&Z.maxLength!==void 0)return`string (${Z.minLength}-${Z.maxLength} chars)`;return"string";case"number":case"integer":if(Z.minimum!==void 0&&Z.maximum!==void 0)return`${Z.type} (${Z.minimum}-${Z.maximum})`;if(Z.minimum!==void 0)return`${Z.type} >= ${Z.minimum}`;if(Z.maximum!==void 0)return`${Z.type} <= ${Z.maximum}`;return Z.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var d6=k("string",(X)=>typeof X==="string"),m6=k("number",(X)=>typeof X==="number"),l6=k("boolean",(X)=>typeof X==="boolean"),u6=k("integer",(X)=>typeof X==="number"&&Number.isInteger(X)),p6=k("positive integer",(X)=>typeof X==="number"&&Number.isInteger(X)&&X>0),i6=k("non-empty string",(X)=>typeof X==="string"&&X.length>0),n6=k("email address",(X)=>typeof X==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X)),S0=(X)=>{try{return new URL(X),!0}catch{return!1}},o6=k("URL",(X)=>typeof X==="string"&&S0(X)),c6=k("UUID",(X)=>typeof X==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(X)),k0=(X)=>{let Y=new Date(X);return!isNaN(Y.getTime())&&X.includes("T")},g0=(X)=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(X))return!1;let Y=new Date(X+"T00:00:00Z");return!isNaN(Y.getTime())},b0=k("ISO 8601 timestamp",(X)=>typeof X==="string"&&k0(X)),v0=k("date (YYYY-MM-DD)",(X)=>typeof X==="string"&&g0(X));function s6(X){return k(`${X.description} or null`,(Y)=>Y===null||X.check(Y))}function a6(X){return k(`${X.description} (optional)`,(Y)=>Y===null||Y===void 0||X.check(Y))}function t6(X,Y,...Z){if(typeof X==="string"&&Array.isArray(Y)){let J=X,$=Y,Q=new Set($);return{description:J,check:(z)=>Q.has(z),__runtimeType:!0,values:$}}let K=[];if(r(X))K.push(X);if(r(Y))K.push(Y);K.push(...Z);let H=K.map((J)=>J.description).join(" | ");return k(H,(J)=>K.some(($)=>$.check(J)))}function r6(X){return k(`array of ${X.description}`,(Y)=>Array.isArray(Y)&&Y.every((Z)=>X.check(Z)))}function A5(X){if(r(X))return(Z)=>X.check(Z);if(X&&typeof X==="object"&&"schema"in X)return(Z)=>h6(Z,X);let Y=P6.infer(X);return(Z)=>h6(Z,Y)}function W6(X,Y,Z){let K=[],H=[];for(let $ of X)if(typeof $==="string")K.push($),H.push(void 0);else K.push($[0]),H.push($[1]);let J=(...$)=>{let Q=K.map((z,_)=>{let U=_<$.length?$[_]:H[_];if(U===void 0)return()=>!0;return A5(U)}),G=Z;return K.forEach((z,_)=>{let U=_<$.length?$[_]:H[_],W="any";if(r(U))W=U.description;else if(U!==void 0)W=typeof U==="string"?"string":JSON.stringify(U);G=G.replace(new RegExp(`\\b${z}\\b`,"g"),W)}),k(G,(z)=>Y(z,...Q))};return J.params=K,J.description=Z,J}var e6=W6(["T","U"],(X,Y,Z)=>Array.isArray(X)&&X.length===2&&Y(X[0])&&Z(X[1]),"Pair<T, U>"),X0=W6(["V"],(X,Y)=>typeof X==="object"&&X!==null&&!Array.isArray(X)&&Object.values(X).every(Y),"Record<string, V>");function Z0(X,Y){let Z=Object.values(Y),K=new Set(Z),H=Object.keys(Y),J={};for(let[Q,G]of Object.entries(Y))J[G]=Q;return{description:X,check:(Q)=>K.has(Q),__runtimeType:!0,members:Y,names:J,values:Z,keys:H}}var B5=f0(),m=B5.version;function V6(X){let[Y=0,Z=0,K=0]=X.split(".").map(Number);return{major:Y,minor:Z,patch:K}}function Y0(X,Y){let Z=V6(X),K=V6(Y);if(Z.major!==K.major)return Z.major<K.major?-1:1;if(Z.minor!==K.minor)return Z.minor<K.minor?-1:1;if(Z.patch!==K.patch)return Z.patch<K.patch?-1:1;return 0}function K0(X,Y){let Z=V6(X),K=V6(Y);return Z.major===K.major}class Z6 extends Error{path;expected;actual;callStack;constructor(X,Y,Z,K,H){super(X);if(this.name="MonadicError",this.path=Y,this.expected=Z,this.actual=K,this.callStack=H,Error.captureStackTrace)Error.captureStackTrace(this,Z6)}}function L5(X,Y,Z){let K=Z===null?"null":typeof Z,H=v.debug?d0():void 0;return new Z6(`Expected ${Y} for '${X}', got ${K}`,X,Y,K,H)}function x0(X){return X instanceof Z6}var H0={debug:!1,safety:"inputs",requireReturnTypes:!1,maxStackSize:100},v={...H0},u=[],K6=0;function w5(){K6++}function I5(){if(K6>0)K6--}function R5(){return K6>0}function O5(X){v={...v,...X}}function M5(){return{...v}}function h0(X){if(v.debug&&X){u.push(X);let Y=v.maxStackSize??100;while(u.length>Y)u.shift()}}function j6(){if(v.debug)u.pop()}function d0(){return[...u]}function P5(){v={...H0},u.length=0,K6=0}function _6(X,Y){if(X!==null&&typeof X==="object"&&typeof X.Equals==="function")return X.Equals(Y);if(Y!==null&&typeof Y==="object"&&typeof Y.Equals==="function")return Y.Equals(X);if(X===Y)return!0;if((X===null||X===void 0)&&(Y===null||Y===void 0))return!0;if(X===null||X===void 0||Y===null||Y===void 0)return!1;if(typeof X!==typeof Y)return!1;if(typeof X!=="object")return!1;if(Array.isArray(X)&&Array.isArray(Y)){if(X.length!==Y.length)return!1;return X.every((H,J)=>_6(H,Y[J]))}if(Array.isArray(X)!==Array.isArray(Y))return!1;let Z=Object.keys(X),K=Object.keys(Y);if(Z.length!==K.length)return!1;return Z.every((H)=>_6(X[H],Y[H]))}function m0(X,Y){return!_6(X,Y)}function l(X){return X!==null&&typeof X==="object"&&X.$error===!0}function d(X,Y){let Z={$error:!0,message:X,...Y};if(v.debug&&u.length>0){let K=Y?.path?[...u,Y.path]:[...u];Z.stack=K}return Z}function $0(X,Y){if(X.length===0)return d("Unknown error");if(X.length===1)return X[0];let Z=X.map((H)=>{if(H.path){let J=H.path.split(".");return J[J.length-1]}return"unknown"}).join(", "),K=`Multiple parameter errors in ${Y||"function"}: ${Z}`;return d(K,{path:Y,errors:X})}function Y6(X){if(X===null)return"null";if(X===void 0)return"undefined";if(Array.isArray(X))return"array";let Y=typeof X;if(Y!=="object")return Y;let Z=X.constructor?.name;if(Z&&Z!=="Object")return Z;return"object"}function l0(X,Y){if(X===null||X===void 0)return!1;if(typeof X!=="object"&&typeof X!=="function")return!1;let Z=X;while(Z!==null){if(Z.constructor?.name===Y)return!0;Z=Object.getPrototypeOf(Z)}return!1}function X6(X,Y,Z){if(l(X))return X;if(typeof Y==="object"&&Y!==null&&"check"in Y){if(Y.check(X))return null;return d(`Expected ${Y.description} but got ${Y6(X)}`,{path:Z,expected:Y.description,actual:Y6(X)})}let K=Y6(X);if(Y==="any")return null;if(Y===K)return null;if(Y==="number"&&K==="number")return null;if(Y==="integer"&&K==="number"&&Number.isInteger(X))return null;if(Y==="object"&&K==="object")return null;return d(`Expected ${Y} but got ${K}`,{path:Z,expected:Y,actual:K})}function J0(X,Y,Z){for(let[K,H]of Object.entries(Y.params)){let J=X[K];if(l(J))return J;if(H.required&&J===void 0){let Q=typeof H.type==="string"?H.type:H.type.description;return d(`Missing required parameter '${K}'`,{path:Z?`${Z}.${K}`:K,expected:Q,actual:"undefined",loc:H.loc})}if(J===void 0)continue;let $=X6(J,H.type,Z?`${Z}.${K}`:K);if($){if(H.loc)$.loc=H.loc;return $}}return null}function Q0(X,Y){if(X.__tjs=Y,!(Y.safe||Y.safeReturn||v.safety!=="none"&&!Y.unsafe||Y.returns&&v.safety==="all"&&!Y.unsafeReturn))return X;let K=!!Y.returns,H=!!Y.unsafe,J=!!Y.safe,$=!!Y.unsafeReturn,Q=!!Y.safeReturn,G=Object.entries(Y.params),z=G.length,_=X.name||Y.name||"anonymous",U=function(...W){if(K6>0)return X.apply(this,W);let F=J||!H&&v.safety!=="none",D=K&&(Q||!$&&v.safety==="all");if(!F&&!D)return X.apply(this,W);if(W.length>0&&l(W[0]))return W[0];if(F){let A=W.length===1&&typeof W[0]==="object"&&W[0]!==null&&!Array.isArray(W[0]),L=[];if(!A)for(let B=0;B<z;B++){let[I,O]=G[B],w=W[B];if(l(w)){L.push(w);continue}if(O.required&&w===void 0){L.push(d(`Missing required parameter '${I}'`,{path:`${_}.${I}`,expected:typeof O.type==="string"?O.type:O.type?.description||"value",actual:"undefined",loc:O.loc}));continue}if(w!==void 0){let R=X6(w,O.type,`${_}.${I}`);if(R){if(O.loc)R.loc=O.loc;L.push(R)}}}else{let B=W[0];for(let I=0;I<z;I++){let[O,w]=G[I],R=B[O];if(l(R)){L.push(R);continue}if(w.required&&R===void 0){L.push(d(`Missing required parameter '${O}'`,{path:`${_}.${O}`,expected:typeof w.type==="string"?w.type:w.type?.description||"value",actual:"undefined",loc:w.loc}));continue}if(R!==void 0){let M=X6(R,w.type,`${_}.${O}`);if(M){if(w.loc)M.loc=w.loc;L.push(M)}}}}if(L.length>0)return $0(L,_)}h0(_);try{let A=X.apply(this,W);if(D&&Y.returns&&!l(A)){let L=X6(A,Y.returns.type,`${_}()`);if(L)return j6(),L}return j6(),A}catch(A){return j6(),d(A.message||String(A),{path:_,cause:A})}};return Object.defineProperty(U,"name",{value:X.name}),U.__tjs=Y,U}function u0(X){let Y=new Proxy(X,{construct(Z,K,H){return Reflect.construct(Z,K,H)},apply(Z,K,H){return Reflect.construct(Z,H)}});Object.defineProperty(Y,"name",{value:X.name});for(let Z of Object.getOwnPropertyNames(X))if(Z!=="length"&&Z!=="name"&&Z!=="prototype")Object.defineProperty(Y,Z,Object.getOwnPropertyDescriptor(X,Z));return Y}function j5(){let X={...v},Y=[],Z=0;function K(D){X={...X,...D}}function H(){return{...X}}function J(D){if(X.debug&&D){Y.push(D);let A=X.maxStackSize??100;while(Y.length>A)Y.shift()}}function $(){if(X.debug)Y.pop()}function Q(){return[...Y]}function G(){X={...H0},Y.length=0,Z=0}function z(){Z++}function _(){if(Z>0)Z--}function U(){return Z>0}function W(D,A,L){let B=L===null?"null":typeof L,I=X.debug?Q():void 0;return new Z6(`Expected ${A} for '${D}', got ${B}`,D,A,B,I)}function F(D,A){let L={$error:!0,message:D,...A};if(X.debug&&Y.length>0){let B=A?.path?[...Y,A.path]:[...Y];L.stack=B}return L}return{version:m,MonadicError:Z6,typeError:W,isMonadicError:x0,isError:l,error:F,composeErrors:$0,typeOf:Y6,isNativeType:l0,checkType:X6,validateArgs:J0,wrap:Q0,wrapClass:u0,compareVersions:Y0,versionsCompatible:K0,configure:K,getConfig:H,pushStack:J,popStack:$,getStack:Q,resetRuntime:G,enterUnsafe:z,exitUnsafe:_,isUnsafeMode:U,validate:y0,infer:E6.infer.bind(E6),Type:k,isRuntimeType:r,Union:t6,Generic:W6,Enum:Z0,Nullable:s6,Optional:a6,TArray:r6,TString:d6,TNumber:m6,TBoolean:l6,TInteger:u6,TPositiveInt:p6,TNonEmptyString:i6,TEmail:n6,TUrl:o6,TUuid:c6,TPair:e6,TRecord:X0,Is:_6,IsNot:m0}}var e={version:m,MonadicError:Z6,typeError:L5,isMonadicError:x0,isError:l,error:d,composeErrors:$0,typeOf:Y6,isNativeType:l0,checkType:X6,validateArgs:J0,wrap:Q0,wrapClass:u0,compareVersions:Y0,versionsCompatible:K0,configure:O5,getConfig:M5,pushStack:h0,popStack:j6,getStack:d0,resetRuntime:P5,enterUnsafe:w5,exitUnsafe:I5,isUnsafeMode:R5,createRuntime:j5,validate:y0,infer:E6.infer.bind(E6),Type:k,isRuntimeType:r,Union:t6,Generic:W6,Enum:Z0,Nullable:s6,Optional:a6,TArray:r6,TString:d6,TNumber:m6,TBoolean:l6,TInteger:u6,TPositiveInt:p6,TNonEmptyString:i6,TEmail:n6,TUrl:o6,TUuid:c6,Timestamp:b0,LegalDate:v0,TPair:e6,TRecord:X0,Is:_6,IsNot:m0};function E5(){let X=globalThis;if(X.__tjs){let Y=X.__tjs.version;if(typeof Y!=="string")return X.__tjs=e,e;let Z=Y0(m,Y);if(Z===0)return X.__tjs;if(K0(m,Y))if(Z>0)console.info(`TJS runtime: upgrading ${Y} → ${m}`),X.__tjs=e;else console.info(`TJS runtime: keeping ${Y} (newer than ${m})`);else if(console.warn(`TJS runtime version conflict: ${Y} vs ${m} (major version mismatch)`),Z>0)console.warn(`Upgrading to ${m} - check for breaking changes`),X.__tjs=e;return X.__tjs}return X.__tjs=e,e}function V5(X){return`
|
|
227
|
+
`;try{let U=Function("__deepEqual","__format","__typeMatches",q),{testResults:A,sigTestResults:I}=U(r0,L0,t0);for(let w of A){let B=X[w.idx];J.push({description:B.description,passed:w.passed,error:w.error,line:B.line})}for(let w of I){let B=Z[w.idx];J.push({description:`${B.funcName} signature example`,passed:w.passed,error:w.error,isSignatureTest:!0,line:B.line})}}catch(U){for(let A of X)J.push({description:A.description,passed:!1,error:`Module execution failed: ${U.message}`,line:A.line});for(let A of Z)J.push({description:`${A.funcName} signature example`,passed:!1,error:`Module execution failed: ${U.message}`,isSignatureTest:!0,line:A.line})}return J}function u6(X){let K="",Z=0,H=!1;for(let J=0;J<X.length;J++){let $=X[J];if($==="{"||$==="["||$==="("){if($==="{"&&Z===0&&H)break;Z++,K+=$,H=!0}else if($==="}"||$==="]"||$===")")Z--,K+=$;else if(!/\s/.test($))K+=$,H=!0;else K+=$}return K.trim()||null}function y8(X){if(!X.trim())return[];let K=[],Z=h8(X);for(let H of Z){let Y=H.match(/(?:\(\s*[?!]\s*)?(\w+)\s*[:=]\s*(.+?)(?:\))?$/);if(Y)K.push(Y[2].trim());else return[]}return K}function h8(X){let K=[],Z="",H=0;for(let Y of X){if(Y==="("||Y==="["||Y==="{")H++;else if(Y===")"||Y==="]"||Y==="}")H--;else if(Y===","&&H===0){K.push(Z.trim()),Z="";continue}Z+=Y}if(Z.trim())K.push(Z.trim());return K}function x8(X){let K=[],Z=[];for(let $ of X){let Q=x6($);if(Q.success){let G=btoa(String.fromCharCode(...Q.bytes));Z.push({id:$.id,base64:G,captures:$.captures,needsMemory:Q.needsMemory??!1,wat:Q.wat??""}),K.push({id:$.id,success:!0,byteLength:Q.bytes.length})}else K.push({id:$.id,success:!1,error:Q.error})}if(Z.length===0)return{code:"",results:K};let H=Z.map(($)=>{let Q=$.wat.split(`
|
|
228
|
+
`).map((G)=>` * ${G}`);return`/**
|
|
229
|
+
* WASM: ${$.id}
|
|
230
|
+
${Q.join(`
|
|
231
|
+
`)}
|
|
232
|
+
*/`}).join(`
|
|
233
|
+
`),Y=Z.map(($)=>`{id:${JSON.stringify($.id)},b64:${JSON.stringify($.base64)},c:${JSON.stringify($.captures)},m:${$.needsMemory}}`).join(",");return{code:`${H}
|
|
234
|
+
;(async()=>{
|
|
235
|
+
const __wasmBlocks=[${Y}];
|
|
236
|
+
const __b64ToBytes=s=>{const b=atob(s),a=new Uint8Array(b.length);for(let i=0;i<b.length;i++)a[i]=b.charCodeAt(i);return a};
|
|
237
|
+
const __parseType=c=>{const m=c.match(/^(\\w+)\\s*:\\s*(\\w+)$/);if(!m)return{n:c,t:'f64',a:false};const[,n,ts]=m;const at={Float32Array:'f32',Float64Array:'f64',Int32Array:'i32',Uint8Array:'i32'};if(at[ts])return{n,t:'i32',a:true,at:ts};return{n,t:'f64',a:false}};
|
|
238
|
+
for(const{id,b64,c,m}of __wasmBlocks){
|
|
239
|
+
const bytes=__b64ToBytes(b64);
|
|
240
|
+
const params=c.map(__parseType);
|
|
241
|
+
const hasArrays=params.some(p=>p.a);
|
|
242
|
+
let mem;if(m)mem=new WebAssembly.Memory({initial:256});
|
|
243
|
+
const imp=mem?{env:{memory:mem}}:{};
|
|
244
|
+
const inst=await WebAssembly.instantiate(await WebAssembly.compile(bytes),imp);
|
|
245
|
+
const compute=inst.exports.compute;
|
|
246
|
+
if(!hasArrays){globalThis[id]=compute;continue}
|
|
247
|
+
globalThis[id]=function(...args){
|
|
248
|
+
const mv=new Uint8Array(mem.buffer);let off=0;const ptrs=[];
|
|
249
|
+
for(let i=0;i<params.length;i++){const p=params[i],a=args[i];
|
|
250
|
+
if(p.a&&a?.buffer){const ab=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);mv.set(ab,off);ptrs.push(off);off+=ab.length;off=(off+7)&~7}
|
|
251
|
+
else ptrs.push(a)}
|
|
252
|
+
const r=compute(...ptrs);off=0;
|
|
253
|
+
for(let i=0;i<params.length;i++){const p=params[i],a=args[i];
|
|
254
|
+
if(p.a&&a?.buffer){const ab=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);ab.set(mv.slice(off,off+ab.length));off+=ab.length;off=(off+7)&~7}}
|
|
255
|
+
return r};
|
|
256
|
+
}})();
|
|
257
|
+
`.trim(),results:K}}function f0(X,K={}){let{ast:Z,returnType:H,originalSource:Y,requiredParams:J}=Z0(X,{filename:K.filename,colonShorthand:!0,vmTarget:!0}),$=S6(Z,K.filename),{ast:Q,signature:G,warnings:z}=c0($,Y,H,K,J);return{ast:Q,signature:G,warnings:z}}function m8(X,...K){if(typeof X==="string")return f0(X).ast;let Z=X.reduce((H,Y,J)=>H+Y+(K[J]!==void 0?String(K[J]):""),"");return f0(Z).ast}function d8(X,K,Z){let{ast:H,signature:Y}=f0(X),J=async($)=>{return(await K.run(H,$,Z)).result};return J.signature=Y,J.ast=H,J}function b0(X){switch(X.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:X.items?b0(X.items):{}};case"object":if(!X.shape)return{type:"object"};return{type:"object",properties:Object.fromEntries(Object.entries(X.shape).map(([K,Z])=>[K,b0(Z)]))};case"union":if(!X.members)return{};return{anyOf:X.members.map(b0)};case"any":default:return{}}}function l8(X){return Object.entries(X).map(([K,Z])=>{let H=Z.signature,Y={},J=[];for(let[$,Q]of Object.entries(H.parameters)){if(Y[$]=b0(Q.type),Q.description)Y[$].description=Q.description;if(Q.required)J.push($)}return{type:"function",function:{name:K,description:H.description,parameters:{type:"object",properties:Y,required:J}}}})}function u8(X,K,...Z){if(typeof X==="string")return v0(X,K);let H=K!==void 0?[K,...Z]:Z,Y=X.reduce((J,$,Q)=>J+$+(H[Q]!==void 0?String(H[Q]):""),"");return v0(Y)}import{s as i6}from"tosijs-schema";function p6(X){if(X===null)return"null";if(X===void 0)return"undefined";if(Array.isArray(X))return"array";return typeof X}function y0(X){return i6.infer(X)}function e0(X){return y0(X)}e0.type=p6;e0.infer=y0;var i8=new Proxy(e0,{get(X,K){if(K==="type")return p6;if(K==="infer")return y0;return i6[K]},apply(X,K,Z){return y0(Z[0])}});function h0(X,K,Z,H,Y){if(!Z)Z=R;(function J($,Q,G){var z=G||$.type;if(Z[z]($,Q,J),K[z])K[z]($,Q)})(X,H,Y)}function n6(X,K,Z,H,Y){var J=[];if(!Z)Z=R;(function $(Q,G,z){var D=z||Q.type,F=Q!==J[J.length-1];if(F)J.push(Q);if(Z[D](Q,G,$),K[D])K[D](Q,G||J,J);if(F)J.pop()})(X,H,Y)}function X6(X,K,Z){Z(X,K)}function $0(X,K,Z){}var R={};R.Program=R.BlockStatement=R.StaticBlock=function(X,K,Z){for(var H=0,Y=X.body;H<Y.length;H+=1){var J=Y[H];Z(J,K,"Statement")}};R.Statement=X6;R.EmptyStatement=$0;R.ExpressionStatement=R.ParenthesizedExpression=R.ChainExpression=function(X,K,Z){return Z(X.expression,K,"Expression")};R.IfStatement=function(X,K,Z){if(Z(X.test,K,"Expression"),Z(X.consequent,K,"Statement"),X.alternate)Z(X.alternate,K,"Statement")};R.LabeledStatement=function(X,K,Z){return Z(X.body,K,"Statement")};R.BreakStatement=R.ContinueStatement=$0;R.WithStatement=function(X,K,Z){Z(X.object,K,"Expression"),Z(X.body,K,"Statement")};R.SwitchStatement=function(X,K,Z){Z(X.discriminant,K,"Expression");for(var H=0,Y=X.cases;H<Y.length;H+=1){var J=Y[H];Z(J,K)}};R.SwitchCase=function(X,K,Z){if(X.test)Z(X.test,K,"Expression");for(var H=0,Y=X.consequent;H<Y.length;H+=1){var J=Y[H];Z(J,K,"Statement")}};R.ReturnStatement=R.YieldExpression=R.AwaitExpression=function(X,K,Z){if(X.argument)Z(X.argument,K,"Expression")};R.ThrowStatement=R.SpreadElement=function(X,K,Z){return Z(X.argument,K,"Expression")};R.TryStatement=function(X,K,Z){if(Z(X.block,K,"Statement"),X.handler)Z(X.handler,K);if(X.finalizer)Z(X.finalizer,K,"Statement")};R.CatchClause=function(X,K,Z){if(X.param)Z(X.param,K,"Pattern");Z(X.body,K,"Statement")};R.WhileStatement=R.DoWhileStatement=function(X,K,Z){Z(X.test,K,"Expression"),Z(X.body,K,"Statement")};R.ForStatement=function(X,K,Z){if(X.init)Z(X.init,K,"ForInit");if(X.test)Z(X.test,K,"Expression");if(X.update)Z(X.update,K,"Expression");Z(X.body,K,"Statement")};R.ForInStatement=R.ForOfStatement=function(X,K,Z){Z(X.left,K,"ForInit"),Z(X.right,K,"Expression"),Z(X.body,K,"Statement")};R.ForInit=function(X,K,Z){if(X.type==="VariableDeclaration")Z(X,K);else Z(X,K,"Expression")};R.DebuggerStatement=$0;R.FunctionDeclaration=function(X,K,Z){return Z(X,K,"Function")};R.VariableDeclaration=function(X,K,Z){for(var H=0,Y=X.declarations;H<Y.length;H+=1){var J=Y[H];Z(J,K)}};R.VariableDeclarator=function(X,K,Z){if(Z(X.id,K,"Pattern"),X.init)Z(X.init,K,"Expression")};R.Function=function(X,K,Z){if(X.id)Z(X.id,K,"Pattern");for(var H=0,Y=X.params;H<Y.length;H+=1){var J=Y[H];Z(J,K,"Pattern")}Z(X.body,K,X.expression?"Expression":"Statement")};R.Pattern=function(X,K,Z){if(X.type==="Identifier")Z(X,K,"VariablePattern");else if(X.type==="MemberExpression")Z(X,K,"MemberPattern");else Z(X,K)};R.VariablePattern=$0;R.MemberPattern=X6;R.RestElement=function(X,K,Z){return Z(X.argument,K,"Pattern")};R.ArrayPattern=function(X,K,Z){for(var H=0,Y=X.elements;H<Y.length;H+=1){var J=Y[H];if(J)Z(J,K,"Pattern")}};R.ObjectPattern=function(X,K,Z){for(var H=0,Y=X.properties;H<Y.length;H+=1){var J=Y[H];if(J.type==="Property"){if(J.computed)Z(J.key,K,"Expression");Z(J.value,K,"Pattern")}else if(J.type==="RestElement")Z(J.argument,K,"Pattern")}};R.Expression=X6;R.ThisExpression=R.Super=R.MetaProperty=$0;R.ArrayExpression=function(X,K,Z){for(var H=0,Y=X.elements;H<Y.length;H+=1){var J=Y[H];if(J)Z(J,K,"Expression")}};R.ObjectExpression=function(X,K,Z){for(var H=0,Y=X.properties;H<Y.length;H+=1){var J=Y[H];Z(J,K)}};R.FunctionExpression=R.ArrowFunctionExpression=R.FunctionDeclaration;R.SequenceExpression=function(X,K,Z){for(var H=0,Y=X.expressions;H<Y.length;H+=1){var J=Y[H];Z(J,K,"Expression")}};R.TemplateLiteral=function(X,K,Z){for(var H=0,Y=X.quasis;H<Y.length;H+=1){var J=Y[H];Z(J,K)}for(var $=0,Q=X.expressions;$<Q.length;$+=1){var G=Q[$];Z(G,K,"Expression")}};R.TemplateElement=$0;R.UnaryExpression=R.UpdateExpression=function(X,K,Z){Z(X.argument,K,"Expression")};R.BinaryExpression=R.LogicalExpression=function(X,K,Z){Z(X.left,K,"Expression"),Z(X.right,K,"Expression")};R.AssignmentExpression=R.AssignmentPattern=function(X,K,Z){Z(X.left,K,"Pattern"),Z(X.right,K,"Expression")};R.ConditionalExpression=function(X,K,Z){Z(X.test,K,"Expression"),Z(X.consequent,K,"Expression"),Z(X.alternate,K,"Expression")};R.NewExpression=R.CallExpression=function(X,K,Z){if(Z(X.callee,K,"Expression"),X.arguments)for(var H=0,Y=X.arguments;H<Y.length;H+=1){var J=Y[H];Z(J,K,"Expression")}};R.MemberExpression=function(X,K,Z){if(Z(X.object,K,"Expression"),X.computed)Z(X.property,K,"Expression")};R.ExportNamedDeclaration=R.ExportDefaultDeclaration=function(X,K,Z){if(X.declaration)Z(X.declaration,K,X.type==="ExportNamedDeclaration"||X.declaration.id?"Statement":"Expression");if(X.source)Z(X.source,K,"Expression")};R.ExportAllDeclaration=function(X,K,Z){if(X.exported)Z(X.exported,K);Z(X.source,K,"Expression")};R.ImportDeclaration=function(X,K,Z){for(var H=0,Y=X.specifiers;H<Y.length;H+=1){var J=Y[H];Z(J,K)}Z(X.source,K,"Expression")};R.ImportExpression=function(X,K,Z){Z(X.source,K,"Expression")};R.ImportSpecifier=R.ImportDefaultSpecifier=R.ImportNamespaceSpecifier=R.Identifier=R.PrivateIdentifier=R.Literal=$0;R.TaggedTemplateExpression=function(X,K,Z){Z(X.tag,K,"Expression"),Z(X.quasi,K,"Expression")};R.ClassDeclaration=R.ClassExpression=function(X,K,Z){return Z(X,K,"Class")};R.Class=function(X,K,Z){if(X.id)Z(X.id,K,"Pattern");if(X.superClass)Z(X.superClass,K,"Expression");Z(X.body,K)};R.ClassBody=function(X,K,Z){for(var H=0,Y=X.body;H<Y.length;H+=1){var J=Y[H];Z(J,K)}};R.MethodDefinition=R.PropertyDefinition=R.Property=function(X,K,Z){if(X.computed)Z(X.key,K,"Expression");if(X.value)Z(X.value,K,"Expression")};var n8={unusedVariables:!0,undefinedVariables:!0,unreachableCode:!0,noExplicitNew:!0};function c8(X,K={}){let Z={...n8,...K},H=[],Y;try{Y=Z0(X,{filename:Z.filename,colonShorthand:!0}).ast}catch($){return{diagnostics:[{severity:"error",message:$.message,line:$.loc?.line,column:$.loc?.column,rule:"parse-error"}],valid:!1}}let J=[c6()];if(n6(Y,{FunctionDeclaration($,Q,G){let z=c6();J.push(z);for(let D of $.params)o8(z,D,"parameter");if($.id)(J[J.length-2]||J[0]).declarations.set($.id.name,{node:$.id,kind:"function",used:!1})},VariableDeclaration($){let Q=J[J.length-1];for(let G of $.declarations)if(G.id.type==="Identifier")Q.declarations.set(G.id.name,{node:G.id,kind:$.kind,used:!1})}}),h0(Y,{Identifier($){for(let Q=J.length-1;Q>=0;Q--){let G=J[Q].declarations.get($.name);if(G){G.used=!0;break}}}}),Z.unusedVariables)for(let $ of J)for(let[Q,G]of $.declarations){if(Q.startsWith("_"))continue;if(!G.used&&G.kind!=="function")H.push({severity:"warning",message:`'${Q}' is declared but never used`,line:G.node.loc?.start?.line,column:G.node.loc?.start?.column,rule:"no-unused-vars"})}if(Z.unreachableCode)h0(Y,{BlockStatement($){let Q=!1;for(let G of $.body){if(Q){H.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")Q=!0}}});if(Z.noExplicitNew)h0(Y,{NewExpression($){let Q="class";if($.callee.type==="Identifier")Q=$.callee.name;else if($.callee.type==="MemberExpression"){if($.callee.property.type==="Identifier")Q=$.callee.property.name}H.push({severity:"warning",message:`Unnecessary 'new' keyword. In TJS, classes are callable without 'new': ${Q}(...) instead of new ${Q}(...)`,line:$.loc?.start?.line,column:$.loc?.start?.column,rule:"no-explicit-new"})}});return{diagnostics:H,valid:H.filter(($)=>$.severity==="error").length===0}}function c6(){return{declarations:new Map}}function o8(X,K,Z){if(K.type==="Identifier")X.declarations.set(K.name,{node:K,kind:Z,used:!1});else if(K.type==="AssignmentPattern"&&K.left.type==="Identifier")X.declarations.set(K.left.name,{node:K.left,kind:Z,used:!1})}import{validate as Z1,s as d0}from"tosijs-schema";import{validate as Z6,s as x0}from"tosijs-schema";function J0(X){return X!==null&&typeof X==="object"&&"__runtimeType"in X&&X.__runtimeType===!0}function o6(X){return X!==null&&typeof X==="object"&&"schema"in X&&typeof X.schema==="object"}function s8(X){return X!==null&&typeof X==="object"&&"type"in X&&typeof X.type==="string"}function v(X,K,Z,H){let Y,J,$,Q=Z,G=H;if(typeof X==="string")if(Y=X,typeof K==="function"){if(J=K,Q!==void 0)$=x0.infer(Q)}else if(K===void 0&&Q!==void 0)$=x0.infer(Q);else if(o6(K))$=K;else if(s8(K))$=K;else if(K!==void 0)Q=K,G=Q,$=x0.infer(Q);else throw Error("Type(description) requires a predicate, schema, or example");else{if(o6(X))$=X;else $=X;Y=a8($)}return{description:Y,check:(D)=>{if(J)return J(D);if($)return Z6(D,$);return!1},schema:$,predicate:J,example:Q,default:G,__runtimeType:!0}}function a8(X){let K=X?.schema??X;if(K&&typeof K==="object"&&"type"in K){let Z=K;switch(Z.type){case"string":if(Z.format)return`string (${Z.format})`;if(Z.pattern)return`string matching ${Z.pattern}`;if(Z.minLength!==void 0&&Z.maxLength!==void 0)return`string (${Z.minLength}-${Z.maxLength} chars)`;return"string";case"number":case"integer":if(Z.minimum!==void 0&&Z.maximum!==void 0)return`${Z.type} (${Z.minimum}-${Z.maximum})`;if(Z.minimum!==void 0)return`${Z.type} >= ${Z.minimum}`;if(Z.maximum!==void 0)return`${Z.type} <= ${Z.maximum}`;return Z.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var K6=v("string",(X)=>typeof X==="string"),H6=v("number",(X)=>typeof X==="number"),Y6=v("boolean",(X)=>typeof X==="boolean"),$6=v("integer",(X)=>typeof X==="number"&&Number.isInteger(X)),J6=v("positive integer",(X)=>typeof X==="number"&&Number.isInteger(X)&&X>0),Q6=v("non-empty string",(X)=>typeof X==="string"&&X.length>0),z6=v("email address",(X)=>typeof X==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X)),s6=(X)=>{try{return new URL(X),!0}catch{return!1}},G6=v("URL",(X)=>typeof X==="string"&&s6(X)),W6=v("UUID",(X)=>typeof X==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(X)),a6=(X)=>{let K=new Date(X);return!isNaN(K.getTime())&&X.includes("T")},r6=(X)=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(X))return!1;let K=new Date(X+"T00:00:00Z");return!isNaN(K.getTime())},t6=v("ISO 8601 timestamp",(X)=>typeof X==="string"&&a6(X)),e6=v("date (YYYY-MM-DD)",(X)=>typeof X==="string"&&r6(X));function _6(X){return v(`${X.description} or null`,(K)=>K===null||X.check(K))}function D6(X){return v(`${X.description} (optional)`,(K)=>K===null||K===void 0||X.check(K))}function F6(X,K,...Z){if(typeof X==="string"&&Array.isArray(K)){let J=X,$=K,Q=new Set($);return{description:J,check:(z)=>Q.has(z),__runtimeType:!0,values:$}}let H=[];if(J0(X))H.push(X);if(J0(K))H.push(K);H.push(...Z);let Y=H.map((J)=>J.description).join(" | ");return v(Y,(J)=>H.some(($)=>$.check(J)))}function q6(X){return v(`array of ${X.description}`,(K)=>Array.isArray(K)&&K.every((Z)=>X.check(Z)))}function r8(X){if(J0(X))return(Z)=>X.check(Z);if(X&&typeof X==="object"&&"schema"in X)return(Z)=>Z6(Z,X);let K=x0.infer(X);return(Z)=>Z6(Z,K)}function P0(X,K,Z){let H=[],Y=[];for(let $ of X)if(typeof $==="string")H.push($),Y.push(void 0);else H.push($[0]),Y.push($[1]);let J=(...$)=>{let Q=H.map((z,D)=>{let F=D<$.length?$[D]:Y[D];if(F===void 0)return()=>!0;return r8(F)}),G=Z;return H.forEach((z,D)=>{let F=D<$.length?$[D]:Y[D],_="any";if(J0(F))_=F.description;else if(F!==void 0)_=typeof F==="string"?"string":JSON.stringify(F);G=G.replace(new RegExp(`\\b${z}\\b`,"g"),_)}),v(G,(z)=>K(z,...Q))};return J.params=H,J.description=Z,J}var U6=P0(["T","U"],(X,K,Z)=>Array.isArray(X)&&X.length===2&&K(X[0])&&Z(X[1]),"Pair<T, U>"),A6=P0(["V"],(X,K)=>typeof X==="object"&&X!==null&&!Array.isArray(X)&&Object.values(X).every(K),"Record<string, V>");function w6(X,K){let Z=Object.values(K),H=new Set(Z),Y=Object.keys(K),J={};for(let[Q,G]of Object.entries(K))J[G]=Q;return{description:X,check:(Q)=>H.has(Q),__runtimeType:!0,members:K,names:J,values:Z,keys:Y}}var e8=X1(),c=e8.version;function l0(X){let[K=0,Z=0,H=0]=X.split(".").map(Number);return{major:K,minor:Z,patch:H}}function R6(X,K){let Z=l0(X),H=l0(K);if(Z.major!==H.major)return Z.major<H.major?-1:1;if(Z.minor!==H.minor)return Z.minor<H.minor?-1:1;if(Z.patch!==H.patch)return Z.patch<H.patch?-1:1;return 0}function I6(X,K){let Z=l0(X),H=l0(K);return Z.major===H.major}class G0 extends Error{path;expected;actual;callStack;constructor(X,K,Z,H,Y){super(X);if(this.name="MonadicError",this.path=K,this.expected=Z,this.actual=H,this.callStack=Y,Error.captureStackTrace)Error.captureStackTrace(this,G0)}}function XX(X,K,Z){let H=Z===null?"null":typeof Z,Y=x.debug?Y1():void 0;return new G0(`Expected ${K} for '${X}', got ${H}`,X,K,H,Y)}function K1(X){return X instanceof G0}var B6={debug:!1,safety:"inputs",requireReturnTypes:!1,maxStackSize:100},x={...B6},s=[],D0=0;function ZX(){D0++}function KX(){if(D0>0)D0--}function HX(){return D0>0}function YX(X){x={...x,...X}}function $X(){return{...x}}function H1(X){if(x.debug&&X){s.push(X);let K=x.maxStackSize??100;while(s.length>K)s.shift()}}function m0(){if(x.debug)s.pop()}function Y1(){return[...s]}function JX(){x={...B6},s.length=0,D0=0}function j0(X,K){if(X!==null&&typeof X==="object"&&typeof X.Equals==="function")return X.Equals(K);if(K!==null&&typeof K==="object"&&typeof K.Equals==="function")return K.Equals(X);if(X===K)return!0;if((X===null||X===void 0)&&(K===null||K===void 0))return!0;if(X===null||X===void 0||K===null||K===void 0)return!1;if(typeof X!==typeof K)return!1;if(typeof X!=="object")return!1;if(Array.isArray(X)&&Array.isArray(K)){if(X.length!==K.length)return!1;return X.every((Y,J)=>j0(Y,K[J]))}if(Array.isArray(X)!==Array.isArray(K))return!1;let Z=Object.keys(X),H=Object.keys(K);if(Z.length!==H.length)return!1;return Z.every((Y)=>j0(X[Y],K[Y]))}function $1(X,K){return!j0(X,K)}function o(X){return X!==null&&typeof X==="object"&&X.$error===!0}function n(X,K){let Z={$error:!0,message:X,...K};if(x.debug&&s.length>0){let H=K?.path?[...s,K.path]:[...s];Z.stack=H}return Z}function L6(X,K){if(X.length===0)return n("Unknown error");if(X.length===1)return X[0];let Z=X.map((Y)=>{if(Y.path){let J=Y.path.split(".");return J[J.length-1]}return"unknown"}).join(", "),H=`Multiple parameter errors in ${K||"function"}: ${Z}`;return n(H,{path:K,errors:X})}function _0(X){if(X===null)return"null";if(X===void 0)return"undefined";if(Array.isArray(X))return"array";let K=typeof X;if(K!=="object")return K;let Z=X.constructor?.name;if(Z&&Z!=="Object")return Z;return"object"}function J1(X,K){if(X===null||X===void 0)return!1;if(typeof X!=="object"&&typeof X!=="function")return!1;let Z=X;while(Z!==null){if(Z.constructor?.name===K)return!0;Z=Object.getPrototypeOf(Z)}return!1}function z0(X,K,Z){if(o(X))return X;if(typeof K==="object"&&K!==null&&"check"in K){if(K.check(X))return null;return n(`Expected ${K.description} but got ${_0(X)}`,{path:Z,expected:K.description,actual:_0(X)})}let H=_0(X);if(K==="any")return null;if(K===H)return null;if(K==="number"&&H==="number")return null;if(K==="integer"&&H==="number"&&Number.isInteger(X))return null;if(K==="object"&&H==="object")return null;return n(`Expected ${K} but got ${H}`,{path:Z,expected:K,actual:H})}function M6(X,K,Z){for(let[H,Y]of Object.entries(K.params)){let J=X[H];if(o(J))return J;if(Y.required&&J===void 0){let Q=typeof Y.type==="string"?Y.type:Y.type.description;return n(`Missing required parameter '${H}'`,{path:Z?`${Z}.${H}`:H,expected:Q,actual:"undefined",loc:Y.loc})}if(J===void 0)continue;let $=z0(J,Y.type,Z?`${Z}.${H}`:H);if($){if(Y.loc)$.loc=Y.loc;return $}}return null}function P6(X,K){if(X.__tjs=K,!(K.safe||K.safeReturn||x.safety!=="none"&&!K.unsafe||K.returns&&x.safety==="all"&&!K.unsafeReturn))return X;let H=!!K.returns,Y=!!K.unsafe,J=!!K.safe,$=!!K.unsafeReturn,Q=!!K.safeReturn,G=Object.entries(K.params),z=G.length,D=X.name||K.name||"anonymous",F=function(..._){if(D0>0)return X.apply(this,_);let q=J||!Y&&x.safety!=="none",U=H&&(Q||!$&&x.safety==="all");if(!q&&!U)return X.apply(this,_);if(_.length>0&&o(_[0]))return _[0];if(q){let A=_.length===1&&typeof _[0]==="object"&&_[0]!==null&&!Array.isArray(_[0]),I=[];if(!A)for(let w=0;w<z;w++){let[B,P]=G[w],L=_[w];if(o(L)){I.push(L);continue}if(P.required&&L===void 0){I.push(n(`Missing required parameter '${B}'`,{path:`${D}.${B}`,expected:typeof P.type==="string"?P.type:P.type?.description||"value",actual:"undefined",loc:P.loc}));continue}if(L!==void 0){let M=z0(L,P.type,`${D}.${B}`);if(M){if(P.loc)M.loc=P.loc;I.push(M)}}}else{let w=_[0];for(let B=0;B<z;B++){let[P,L]=G[B],M=w[P];if(o(M)){I.push(M);continue}if(L.required&&M===void 0){I.push(n(`Missing required parameter '${P}'`,{path:`${D}.${P}`,expected:typeof L.type==="string"?L.type:L.type?.description||"value",actual:"undefined",loc:L.loc}));continue}if(M!==void 0){let j=z0(M,L.type,`${D}.${P}`);if(j){if(L.loc)j.loc=L.loc;I.push(j)}}}}if(I.length>0)return L6(I,D)}H1(D);try{let A=X.apply(this,_);if(U&&K.returns&&!o(A)){let I=z0(A,K.returns.type,`${D}()`);if(I)return m0(),I}return m0(),A}catch(A){return m0(),n(A.message||String(A),{path:D,cause:A})}};return Object.defineProperty(F,"name",{value:X.name}),F.__tjs=K,F}function Q1(X){let K=new Proxy(X,{construct(Z,H,Y){return Reflect.construct(Z,H,Y)},apply(Z,H,Y){return Reflect.construct(Z,Y)}});Object.defineProperty(K,"name",{value:X.name});for(let Z of Object.getOwnPropertyNames(X))if(Z!=="length"&&Z!=="name"&&Z!=="prototype")Object.defineProperty(K,Z,Object.getOwnPropertyDescriptor(X,Z));return K}function QX(){let X={...x},K=[],Z=0;function H(U){X={...X,...U}}function Y(){return{...X}}function J(U){if(X.debug&&U){K.push(U);let A=X.maxStackSize??100;while(K.length>A)K.shift()}}function $(){if(X.debug)K.pop()}function Q(){return[...K]}function G(){X={...B6},K.length=0,Z=0}function z(){Z++}function D(){if(Z>0)Z--}function F(){return Z>0}function _(U,A,I){let w=I===null?"null":typeof I,B=X.debug?Q():void 0;return new G0(`Expected ${A} for '${U}', got ${w}`,U,A,w,B)}function q(U,A){let I={$error:!0,message:U,...A};if(X.debug&&K.length>0){let w=A?.path?[...K,A.path]:[...K];I.stack=w}return I}return{version:c,MonadicError:G0,typeError:_,isMonadicError:K1,isError:o,error:q,composeErrors:L6,typeOf:_0,isNativeType:J1,checkType:z0,validateArgs:M6,wrap:P6,wrapClass:Q1,compareVersions:R6,versionsCompatible:I6,configure:H,getConfig:Y,pushStack:J,popStack:$,getStack:Q,resetRuntime:G,enterUnsafe:z,exitUnsafe:D,isUnsafeMode:F,validate:Z1,infer:d0.infer.bind(d0),Type:v,isRuntimeType:J0,Union:F6,Generic:P0,Enum:w6,Nullable:_6,Optional:D6,TArray:q6,TString:K6,TNumber:H6,TBoolean:Y6,TInteger:$6,TPositiveInt:J6,TNonEmptyString:Q6,TEmail:z6,TUrl:G6,TUuid:W6,TPair:U6,TRecord:A6,Is:j0,IsNot:$1}}var Q0={version:c,MonadicError:G0,typeError:XX,isMonadicError:K1,isError:o,error:n,composeErrors:L6,typeOf:_0,isNativeType:J1,checkType:z0,validateArgs:M6,wrap:P6,wrapClass:Q1,compareVersions:R6,versionsCompatible:I6,configure:YX,getConfig:$X,pushStack:H1,popStack:m0,getStack:Y1,resetRuntime:JX,enterUnsafe:ZX,exitUnsafe:KX,isUnsafeMode:HX,createRuntime:QX,validate:Z1,infer:d0.infer.bind(d0),Type:v,isRuntimeType:J0,Union:F6,Generic:P0,Enum:w6,Nullable:_6,Optional:D6,TArray:q6,TString:K6,TNumber:H6,TBoolean:Y6,TInteger:$6,TPositiveInt:J6,TNonEmptyString:Q6,TEmail:z6,TUrl:G6,TUuid:W6,Timestamp:t6,LegalDate:e6,TPair:U6,TRecord:A6,Is:j0,IsNot:$1};function zX(){let X=globalThis;if(X.__tjs){let K=X.__tjs.version;if(typeof K!=="string")return X.__tjs=Q0,Q0;let Z=R6(c,K);if(Z===0)return X.__tjs;if(I6(c,K))if(Z>0)console.info(`TJS runtime: upgrading ${K} → ${c}`),X.__tjs=Q0;else console.info(`TJS runtime: keeping ${K} (newer than ${c})`);else if(console.warn(`TJS runtime version conflict: ${K} vs ${c} (major version mismatch)`),Z>0)console.warn(`Upgrading to ${c} - check for breaking changes`),X.__tjs=Q0;return X.__tjs}return X.__tjs=Q0,Q0}function GX(X){return`
|
|
226
258
|
// TJS runtime wrapper (skips unsafe functions)
|
|
227
259
|
if (typeof ${X}.__tjs === 'object' && !${X}.__tjs.unsafe && typeof globalThis.__tjs?.wrap === 'function') {
|
|
228
260
|
${X} = globalThis.__tjs.wrap(${X}, ${X}.__tjs)
|
|
229
261
|
}
|
|
230
|
-
`.trim()}export{
|
|
262
|
+
`.trim()}export{P6 as wrap,M6 as validateArgs,n0 as typeToString,_0 as typeOf,v0 as transpileToJS,f0 as transpile,c0 as transformFunction,u8 as tjs,$8 as testUtils,Q0 as runtime,O0 as preprocess,T6 as parseReturnType,e as parseParameter,Z0 as parse,c8 as lint,o as isError,zX as installRuntime,d as inferTypeFromValue,l8 as getToolDefinitions,s0 as extractTests,q0 as extractTDoc,t as extractLiteralValue,y6 as expectFunction,n as error,GX as emitRuntimeWrapper,d8 as createAgent,z0 as checkType,f6 as assertFunction,m8 as ajs,c as TJS_VERSION,i8 as Schema};
|
|
231
263
|
|
|
232
|
-
//# debugId=
|
|
264
|
+
//# debugId=86356C12F4E13E0F64756E2164756E21
|