tjs-lang 0.8.6 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tjs-eval.js CHANGED
@@ -25,7 +25,7 @@ ${S.join(`
25
25
  `)}
26
26
  return __tjs.typeError('${m}', 'no matching overload', __args)
27
27
  }
28
- `;p+=h}return{source:p,polymorphicNames:t}}function pt(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function mt(e,n=!1){let t=[],r=[],s="",o=0;for(;o<e.length;){let i=e.slice(o).match(/^\btest\s+/);if(i){let a=o,l=o+i[0].length,c,p=e.slice(l).match(/^(['"`])([^]*?)\1\s*/);if(p&&(c=p[2],l+=p[0].length),e[l]==="{"){let m=l+1,u=1,d=m,g=null,y=!1;for(;d<e.length&&u>0;){let w=e[d];if(y){y=!1,d++;continue}if(w==="\\"&&g){y=!0,d++;continue}if(g){w===g&&(g=null),d++;continue}if(w==="/"&&e[d+1]==="/"){let E=e.indexOf(`
28
+ `;p+=h}return{source:p,polymorphicNames:t}}function pt(e){let n=new Set,t=/\b(?:let|const|var|function|class)\s+([A-Z][a-zA-Z0-9_]*)/g;for(let r;r=t.exec(e);)n.add(r[1]);return e.replace(/(?<=^|[;\n{])(\s*)([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(r,s,o)=>n.has(o)?r:r.replace(o,`const ${o}`))}function mt(e,n=!1){let t=[],r=[],s="",o=0;for(;o<e.length;){let i=e.slice(o).match(/^\btest\s+/);if(i){let a=o,l=o+i[0].length,c,p=e.slice(l).match(/^(['"`])([^]*?)\1\s*/);if(p&&(c=p[2],l+=p[0].length),e[l]==="{"){let m=l+1,u=1,d=m,g=null,y=!1;for(;d<e.length&&u>0;){let w=e[d];if(y){y=!1,d++;continue}if(w==="\\"&&g){y=!0,d++;continue}if(g){w===g&&(g=null),d++;continue}if(w==="/"&&e[d+1]==="/"){let E=e.indexOf(`
29
29
  `,d);d=E===-1?e.length:E+1;continue}if(w==="/"&&e[d+1]==="*"){let E=e.indexOf("*/",d+2);d=E===-1?e.length:E+2;continue}if(w==="'"||w==='"'||w==="`"){g=w,d++;continue}w==="{"?u++:w==="}"&&u--,d++}if(u===0){let w=e.slice(m,d-1).trim(),E=d,S=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:c,body:w,start:a,end:E,line:S}),!n)try{new Function(w)()}catch($){let b=c||`test at line ${S}`;r.push(`Test failed: ${b} (line ${S})
30
30
  ${$.message||$}`)}let T=(e.slice(a,E).match(/\n/g)||[]).length;s+=`
31
31
  `.repeat(T),o=E;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function dt(e,n){let t=new Set,r=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,s,o=[];for(;(s=r.exec(e))!==null;){let a=s[1],l=s[2]?.trim()||"",c=s.index+s[0].length-1,p=se(e,c),m=e.slice(c,p);o.push({className:a,extendsClause:l,bodyStart:c,bodyEnd:p,body:m})}let i=e;for(let a=o.length-1;a>=0;a--){let{className:l,extendsClause:c,bodyStart:p,bodyEnd:m,body:u}=o[a],d=/\bconstructor\s*\(/g,g,y=[];for(;(g=d.exec(u))!==null;)y.push(g.index);if(y.length<2)continue;t.add(l);let w=[];for(let $=0;$<y.length;$++){let b=y[$],v=u.indexOf("(",b),j=1,A=v+1;for(;A<u.length&&j>0;)u[A]==="("&&j++,u[A]===")"&&j--,A++;let M=u.slice(v+1,A-1),C=A;for(;C<u.length&&u[C]!=="{";)C++;let R=se(u,C),L=u.slice(C+1,R-1);w.push({index:$+1,paramStr:M,bodyText:L,fullStart:b,fullEnd:R})}let E=u;for(let $=w.length-1;$>=1;$--){let b=w[$],v=b.fullStart;for(;v>0&&E[v-1]===" ";)v--;v>0&&E[v-1]===`
@@ -48,7 +48,7 @@ function ${l}$dispatch(t, a) {
48
48
  `&&(i="normal"),r++;continue;case"block-comment":if(t+=u,u==="*"&&d==="/"){t+=d,r+=2,i="normal";continue}r++;continue;case"regex":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}if(u==="["){for(r++;r<e.length&&e[r]!=="]";)t+=e[r],e[r]==="\\"&&r+1<e.length?(t+=e[r+1],r+=2):r++;r<e.length&&(t+=e[r],r++);continue}if(u==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)t+=e[r],r++;i="normal";continue}r++;continue;case"normal":if(a.length>0){if(u==="{")a[a.length-1]++;else if(u==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),t+=u,r++,i="template-string";continue}}if(u==="'"){t+=u,r++,i="single-string";continue}if(u==='"'){t+=u,r++,i="double-string";continue}if(u==="`"){t+=u,r++,i="template-string";continue}if(u==="/"&&d==="/"){t+=u+d,r+=2,i="line-comment";continue}if(u==="/"&&d==="*"){t+=u+d,r+=2,i="block-comment";continue}if(u==="/"){let h=t.trimEnd();if(!h[h.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(h)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(h)){t+=u,r++,i="regex";continue}}break}if(u==="{"){c++,t+=u,r++;continue}if(u==="}"){c--;let h=l[l.length-1];h&&c===h.braceDepth&&l.pop(),t+=u,r++;continue}let g=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(g){let h=g[0].slice(0,-1);t+=h,r+=h.length,l.push({type:"class-body",braceDepth:c});continue}let y=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(y){let h=y[1],T=y[0].length,$=e[r+T],b,v=r+T;($==="?"||$==="!")&&(b=$,v++,b==="!"?n.unsafeFunctions.add(h):n.safeFunctions.add(h)),t+=`function ${h}(`,r=v;let j=pe(e,r,"(",")");if(!j){t+=e[r],r++;continue}let{content:A,endPos:M}=j;r=M;let C=ke(A,n,!0);t+=C+")";let R=r;for(;R<e.length&&/\s/.test(e[R]);)R++;if(e[R]===":"){let ee=e.slice(R,R+2),te;for(ee===":?"||ee===":!"?(R+=2,te=ee===":?"?"safe":"unsafe"):R+=1;R<e.length&&/\s/.test(e[R]);)R++;let ne=Me(e,R);ne&&(s===void 0&&(s=ne.type,te&&(o=te)),r=ne.endPos)}let L=r;for(;L<e.length&&/\s/.test(e[L]);)L++;if(e[L]==="="&&e[L+1]===">")throw new _("Unexpected '=>' after function declaration. Function declarations use `function name(params) { body }`, not arrow syntax. Remove the `=>`.",J(n.originalSource,L),n.originalSource);continue}let w=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),E=(()=>{for(let h=t.length-1;h>=0;h--)if(!/\s/.test(t[h]))return t[h];return`
49
49
  `})(),S=E!=="="&&E!==","&&E!=="("&&E!=="["&&E!==">";if(w&&m()&&!S){let h=w[1].length;t+=e.slice(r,r+h),r+=h;continue}if(w&&m()&&S){let h=w[1],T=w[0].length,$=r+T;t+=h+"(",r=$;let b=pe(e,r,"(",")");if(!b){t+=e[r],r++;continue}let{content:v,endPos:j}=b;r=j;let A=ke(v,n,!0);t+=A+")";let M=r;for(;M<e.length&&/\s/.test(e[M]);)M++;if(e[M]===":"){let R=e.slice(M,M+2);for(R===":?"||R===":!"?M+=2:M++;M<e.length&&/\s/.test(e[M]);)M++;let L=Me(e,M);L&&(r=L.endPos)}let C=r;for(;C<e.length&&/\s/.test(e[C]);)C++;if(e[C]==="="&&e[C+1]===">")throw new _("Unexpected '=>' after method declaration. Methods use `name(params) { body }`, not arrow syntax. Remove the `=>`.",J(n.originalSource,C),n.originalSource);continue}if(e[r]==="("){let h=pe(e,r+1,"(",")");if(!h){t+=e[r],r++;continue}let T=h.content,$=h.endPos,b=$;for(;b<e.length&&/\s/.test(e[b]);)b++;let v;if(e[b]===":"){let j=e.slice(b,b+2);for(j===":?"||j===":!"?b+=2:b++;b<e.length&&/\s/.test(e[b]);)b++;let A=Me(e,b);if(A)for(v=A.type,b=A.endPos;b<e.length&&/\s/.test(e[b]);)b++}if(e.slice(b,b+2)==="=>"){let j=null,A=T,M=T.trimStart();M.startsWith("?")&&(M.length===1||/\s/.test(M[1]))?(j="?",A=M.slice(1)):M.startsWith("!")&&(M.length===1||/\s/.test(M[1]))&&(j="!",A=M.slice(1));let C=ke(A,n,!1);for(t+=`(${j==="?"?"/* safe */ ":j==="!"?"/* unsafe */ ":""}${C})`,r=$;r<b&&/\s/.test(e[r]);)t+=e[r],r++;v&&(r=b)}else{let j=ge(T,n);t+=`(${j.source})`,r=$}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:o}}function pe(e,n,t,r){let s=1,o=n,i=!1,a="";for(;o<e.length&&s>0;){let l=e[o];!i&&(l==="'"||l==='"'||l==="`")?(i=!0,a=l):i&&l===a&&e[o-1]!=="\\"?i=!1:i||(l===t?s++:l===r&&s--),o++}return s!==0?null:{content:e.slice(n,o-1),endPos:o}}function Et(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return null;let r=t,s=e[t];if(s==="{"||s==="["){let i=s==="{"?"}":"]",a=pe(e,t+1,s,i);return a?{value:e.slice(r,a.endPos),endPos:a.endPos}:null}if(s==="'"||s==='"'||s==="`"){for(t++;t<e.length;){if(e[t]===s&&e[t-1]!=="\\")return t++,{value:e.slice(r,t),endPos:t};t++}return null}if(/[-+\d]/.test(s)){for(;t<e.length&&/[\d.eE+-]/.test(e[t]);)t++;return{value:e.slice(r,t),endPos:t}}let o=e.slice(t).match(/^(true|false|null|undefined)\b/);return o?{value:o[1],endPos:t+o[1].length}:null}function ie(e){return e.replace(/(?<!\|)\|(?!\|)/g," || ")}function Me(e,n){let t=n,r=0,s=!1,o="",i=!1,a=l=>({type:ie(e.slice(n,l).trim()),endPos:l});for(;t<e.length;){let l=e[t];if(!s&&(l==="'"||l==='"'||l==="`")){s=!0,o=l,i=!0,t++;continue}if(s){if(l===o&&e[t-1]!=="\\"){if(s=!1,t++,r===0){let c=t;for(;c<e.length&&/\s/.test(e[c]);)c++;if(e[c]==="{"&&!e.slice(c+1).match(/^\s*(\w+)\s*:/)||e[c]!=="|"&&e[c]!=="&")return a(t)}continue}t++;continue}if(l==="{"||l==="["||l==="("){r++,i=!0,t++;continue}if(l==="}"||l==="]"||l===")"){if(r--,r===0){t++;let c=t;for(;c<e.length&&/\s/.test(e[c]);)c++;if(e[c]==="|"||e[c]==="&")continue;return a(t)}t++;continue}if(r===0&&l==="{"){if(i)return a(t);if(e.slice(t+1).match(/^\s*(\w+)\s*:/)){r++,i=!0,t++;continue}return a(t)}if(r===0&&(l==="|"||l==="&")){for(t++,t<e.length&&e[t]==="|"&&t++;t<e.length&&/\s/.test(e[t]);)t++;continue}if(r===0&&(/\d/.test(l)||l==="-"&&/\d/.test(e[t+1]))){let c=t;for(e[c]==="-"&&c++;c<e.length&&/\d/.test(e[c]);)c++;if(c<e.length&&e[c]==="."&&/\d/.test(e[c+1]))for(c++;c<e.length&&/\d/.test(e[c]);)c++;if(c<e.length&&(e[c]==="e"||e[c]==="E"))for(c++,c<e.length&&(e[c]==="+"||e[c]==="-")&&c++;c<e.length&&/\d/.test(e[c]);)c++;for(i=!0,t=c;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="{")return{type:ie(e.slice(n,c).trim()),endPos:c};if(e[t]!=="|"&&e[t]!=="&")return{type:ie(e.slice(n,c).trim()),endPos:c};continue}if(r===0&&/[a-zA-Z_]/.test(l)){let c=t;for(;c<e.length&&/\w/.test(e[c]);)c++;for(i=!0,t=c;t<e.length&&/\s/.test(e[t]);)t++;if(t<e.length&&e[t]==="("){r++,t++;continue}if(t<e.length&&e[t]==="{"&&!e.slice(t+1).match(/^\s*(\w+)\s*:/)){let m=c;for(;m>n&&/\s/.test(e[m-1]);)m--;return{type:ie(e.slice(n,m).trim()),endPos:c}}if(e[t]!=="|"&&e[t]!=="&")return{type:ie(e.slice(n,c).trim()),endPos:c};continue}t++}return i?a(t):null}function he(e){let n=[],t="",r=0,s=!1,o=!1,i=0;for(;i<e.length;){let a=e[i],l=e[i+1];if(!o&&a==="/"&&l==="/"){s=!0,t+="//",i+=2;continue}if(!s&&a==="/"&&l==="*"){o=!0,t+="/*",i+=2;continue}if(s&&a===`
50
50
  `){s=!1,t+=a,i++;continue}if(o&&a==="*"&&l==="/"){o=!1,t+="*/",i+=2;continue}if(s||o){t+=a,i++;continue}a==="("||a==="{"||a==="["?(r++,t+=a):a===")"||a==="}"||a==="]"?(r--,t+=a):a===","&&r===0?(n.push(t),t=""):t+=a,i++}return t.trim()&&n.push(t),n}function ke(e,n,t){let r=ge(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=he(r),o=!1,i=new Set,a=c=>{if(t&&/^\w+$/.test(c)){if(i.has(c))throw new Error(`Duplicate parameter name '${c}'`);i.add(c)}};return s.map(c=>{let p=c.trim();if(!p)return c;if(t&&p.startsWith("{")&&p.endsWith("}")){let d=p.slice(1,-1);return`{ ${Tt(d,n)} }`}if(t&&p.startsWith("[")&&p.endsWith("]")){let d=p.slice(1,-1);return`[ ${Tt(d,n)} ]`}if(p.startsWith("...")){let d=xt(p);return d!==-1?p.slice(0,d).trim():c}let m=p.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(m){let[,d,g]=m;return a(d),o=!0,`${d} = ${g}`}if(!ir(p)){let d=p.match(/^(\w+)\s*=/);return d&&a(d[1]),o=!0,c}let u=xt(p);if(u!==-1){let d=p.slice(0,u).trim(),g=p.slice(u+1).trim();return a(d),o&&t&&/^\w+$/.test(d),t&&/^\w+$/.test(d)&&n.requiredParams.add(d),`${d} = ${g}`}return c}).join(",")}function Tt(e,n){return he(e).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,c,p]=i;n.requiredParams.add(c);let m=me(p);return`${c} = ${m}`}let a=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,c,p]=a;n.requiredParams.add(c);let m=de(p);return`${c} = ${m}`}let l=o.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(l){let[,c,p]=l;return n.requiredParams.add(c),`${c} = ${p}`}return s}).join(", ")}function me(e){let n=e.slice(1,-1).trim();return`{ ${he(n).map(s=>{let o=s.trim();if(!o)return s;let i=o.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(i){let[,m,u]=i;return`${m}: ${me(u)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,m,u]=a;return`${m}: ${me(u)}`}let l=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(l){let[,m,u]=l;return`${m}: ${de(u)}`}let c=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(c){let[,m,u]=c;return`${m}: ${de(u)}`}let p=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(p){let[,m,u]=p;return`${m}: ${u}`}return s}).join(", ")} }`}function de(e){let n=e.slice(1,-1).trim();return`[ ${he(n).map(s=>{let o=s.trim();return o?o.startsWith("{")&&o.endsWith("}")?me(o):o.startsWith("[")&&o.endsWith("]")?de(o):s:s}).join(", ")} ]`}function ir(e){let n=0,t=!1,r=!1,s=!1,o="";for(let i=0;i<e.length;i++){let a=e[i];if(!s&&(a==="'"||a==='"'||a==="`")){s=!0,o=a;continue}if(s){a===o&&e[i-1]!=="\\"&&(s=!1);continue}a==="("||a==="{"||a==="["?n++:a===")"||a==="}"||a==="]"?n--:n===0&&(a===":"&&(t=!0),a==="="&&e[i+1]!==">"&&(r=!0))}return t&&!r}function xt(e){let n=0,t=!1,r="";for(let s=0;s<e.length;s++){let o=e[s];if(!t&&(o==="'"||o==='"'||o==="`")){t=!0,r=o;continue}if(t){o===r&&e[s-1]!=="\\"&&(t=!1);continue}if(o==="("||o==="{"||o==="[")n++;else if(o===")"||o==="}"||o==="]")n--;else if(n===0&&o===":")return s}return-1}function or(e){let n="",t=0;for(;t<e.length;){let r=e[t];if(r==="'"||r==='"'||r==="`"){let s=r;for(n+=r,t++;t<e.length&&e[t]!==s;)e[t]==="\\"&&(n+=e[t++]),t<e.length&&(n+=e[t++]);t<e.length&&(n+=e[t++]);continue}if(r==="/"&&e[t+1]==="*"){let s=e.indexOf("*/",t+2),o=s===-1?e.slice(t):e.slice(t,s+2);n+=o,t+=o.length;continue}if(r==="/"&&e[t+1]==="/"){let s=e.indexOf(`
51
- `,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function ar(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,a=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e),l=n.dialect==="js"?!0:n.dialect==="tjs"?!1:a||n.vmTarget,c=l?{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0,tjsSafeAssign:!0};l&&(r="none");let p=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);p&&(r=p[2],e=e.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1"));let m=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval|TjsSafeAssign)\b/,u;for(;u=e.match(m);){let M=u[2];M==="TjsStrict"?(c.tjsEquals=!0,c.tjsClass=!0,c.tjsDate=!0,c.tjsNoeval=!0,c.tjsNoVar=!0,c.tjsStandard=!0,c.tjsSafeAssign=!0):M==="TjsCompat"?(c.tjsEquals=!1,c.tjsClass=!1,c.tjsDate=!1,c.tjsNoeval=!1,c.tjsNoVar=!1,c.tjsStandard=!1,c.tjsSafeEval=!1,c.tjsSafeAssign=!1):M==="TjsEquals"?c.tjsEquals=!0:M==="TjsClass"?c.tjsClass=!0:M==="TjsDate"?c.tjsDate=!0:M==="TjsNoeval"?c.tjsNoeval=!0:M==="TjsNoVar"?c.tjsNoVar=!0:M==="TjsStandard"?c.tjsStandard=!0:M==="TjsSafeEval"?c.tjsSafeEval=!0:M==="TjsSafeAssign"&&(c.tjsSafeAssign=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${M}\\s*`),"$1")}e=or(e),c.tjsStandard&&(e=tt(e)),e=yt(e),e=St(e);let d=$t(e);e=d.source;let g=d.annotations,y=Xe(e);e=y.source,e=et(e),c.tjsEquals&&!n.vmTarget&&(e=nt(e)),e=rt(e),e=it(e),e=st(e),e=ot(e),e=at(e),e=pt(e);let w=Qe(e,{loader:n.moduleLoader,importerPath:n.filename});e=w.source;let{source:E,returnType:S,returnSafety:h}=ge(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=E;let T=lt(e);e=T.source,e=Ke(e);let $=ft(e,s);e=$.source;let b=Ye(e);e=b.source;let v=[...y.blocks,...w.blocks,...b.blocks],j=mt(e,n.dangerouslySkipTests);e=j.source;let A=dt(e,s);e=A.source;for(let M of A.polyCtorClasses)o.add(`${M}$dispatch`);return c.tjsClass&&(e=gt(e,A.polyCtorClasses)),c.tjsDate&&(e=ht(e)),c.tjsNoeval&&(e=wt(e)),c.tjsNoVar&&(e=bt(e)),e=ct(e,T.extensions),{source:e,returnType:S,returnSafety:h,moduleSafety:r,tjsModes:c,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:v,tests:j.tests,testErrors:j.errors,polymorphicNames:$.polymorphicNames,extensions:T.extensions,letAnnotations:g}}function At(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1,dialect:o}=n,{source:i,returnType:a,returnSafety:l,moduleSafety:c,originalSource:p,requiredParams:m,unsafeFunctions:u,safeFunctions:d,wasmBlocks:g,tests:y,testErrors:w,letAnnotations:E,tjsModes:S}=r?ar(e,{vmTarget:s,dialect:o,moduleLoader:n.moduleLoader,filename:n.filename}):{source:e,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:e,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[],letAnnotations:new Map,tjsModes:{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}};try{return{ast:vt.parse(i,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:a,returnSafety:l,moduleSafety:c,originalSource:p,requiredParams:m,unsafeFunctions:u,safeFunctions:d,wasmBlocks:g,tests:y,testErrors:w,letAnnotations:E,tjsModes:S}}catch(h){let T=h.loc||{line:1,column:0};throw new _(h.message.replace(/\s*\(\d+:\d+\)$/,""),T,p,t)}}function jt(e,n){for(let o of e.body){if(o.type==="ImportDeclaration")throw new _("Imports are not supported. All atoms must be registered with the VM.",o.loc?.start||{line:1,column:0},void 0,n);if(o.type==="ExportNamedDeclaration"||o.type==="ExportDefaultDeclaration")throw new _("Exports are not supported. The function is automatically exported.",o.loc?.start||{line:1,column:0},void 0,n);if(o.type==="ClassDeclaration")throw new _("Classes are not supported. Agent99 uses functional composition.",o.loc?.start||{line:1,column:0},void 0,n)}let t=e.body.filter(o=>o.type==="FunctionDeclaration");if(t.length===0)throw new _("Source must contain a function declaration",{line:1,column:0},void 0,n);let r=t[t.length-1],s=new Map;for(let o=0;o<t.length-1;o++){let i=t[o],a=i.id?.name;if(!a)throw new _("Helper function must have a name",i.loc?.start||{line:1,column:0},void 0,n);if(s.has(a))throw new _(`Duplicate helper function name: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);if(a===r.id?.name)throw new _(`Helper function cannot share a name with the entry function: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);s.set(a,i)}return{entry:r,helpers:s}}function Mt(e,n){let t={params:{}};if(!n.loc)return t;let r=e.substring(0,n.start),s=[...r.matchAll(/\/\*#([\s\S]*?)\*\//g)];if(s.length>0){let p=s[s.length-1],m=r.substring(p.index+p[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(m)){let u=p[1],d=u.split(`
51
+ `,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function ar(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,a=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e),l=n.dialect==="js"?!0:n.dialect==="tjs"?!1:a||n.vmTarget,c=l?{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0,tjsSafeAssign:!0};l&&(r="none");let p=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);p&&(r=p[2],e=e.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1"));let m=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval|TjsSafeAssign)\b/,u;for(;u=e.match(m);){let M=u[2];M==="TjsStrict"?(c.tjsEquals=!0,c.tjsClass=!0,c.tjsDate=!0,c.tjsNoeval=!0,c.tjsNoVar=!0,c.tjsStandard=!0,c.tjsSafeAssign=!0):M==="TjsCompat"?(c.tjsEquals=!1,c.tjsClass=!1,c.tjsDate=!1,c.tjsNoeval=!1,c.tjsNoVar=!1,c.tjsStandard=!1,c.tjsSafeEval=!1,c.tjsSafeAssign=!1):M==="TjsEquals"?c.tjsEquals=!0:M==="TjsClass"?c.tjsClass=!0:M==="TjsDate"?c.tjsDate=!0:M==="TjsNoeval"?c.tjsNoeval=!0:M==="TjsNoVar"?c.tjsNoVar=!0:M==="TjsStandard"?c.tjsStandard=!0:M==="TjsSafeEval"?c.tjsSafeEval=!0:M==="TjsSafeAssign"&&(c.tjsSafeAssign=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${M}\\s*`),"$1")}e=or(e),c.tjsStandard&&(e=tt(e)),e=yt(e),e=St(e);let d=$t(e);e=d.source;let g=d.annotations,y=Xe(e);e=y.source,e=et(e),c.tjsEquals&&!n.vmTarget&&(e=nt(e)),e=rt(e),e=it(e),e=st(e),e=ot(e),e=at(e),c.tjsSafeAssign&&(e=pt(e));let w=Qe(e,{loader:n.moduleLoader,importerPath:n.filename});e=w.source;let{source:E,returnType:S,returnSafety:h}=ge(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=E;let T=lt(e);e=T.source,e=Ke(e);let $=ft(e,s);e=$.source;let b=Ye(e);e=b.source;let v=[...y.blocks,...w.blocks,...b.blocks],j=mt(e,n.dangerouslySkipTests);e=j.source;let A=dt(e,s);e=A.source;for(let M of A.polyCtorClasses)o.add(`${M}$dispatch`);return c.tjsClass&&(e=gt(e,A.polyCtorClasses)),c.tjsDate&&(e=ht(e)),c.tjsNoeval&&(e=wt(e)),c.tjsNoVar&&(e=bt(e)),e=ct(e,T.extensions),{source:e,returnType:S,returnSafety:h,moduleSafety:r,tjsModes:c,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:v,tests:j.tests,testErrors:j.errors,polymorphicNames:$.polymorphicNames,extensions:T.extensions,letAnnotations:g}}function At(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1,dialect:o}=n,{source:i,returnType:a,returnSafety:l,moduleSafety:c,originalSource:p,requiredParams:m,unsafeFunctions:u,safeFunctions:d,wasmBlocks:g,tests:y,testErrors:w,letAnnotations:E,tjsModes:S}=r?ar(e,{vmTarget:s,dialect:o,moduleLoader:n.moduleLoader,filename:n.filename}):{source:e,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:e,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[],letAnnotations:new Map,tjsModes:{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}};try{return{ast:vt.parse(i,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:a,returnSafety:l,moduleSafety:c,originalSource:p,requiredParams:m,unsafeFunctions:u,safeFunctions:d,wasmBlocks:g,tests:y,testErrors:w,letAnnotations:E,tjsModes:S}}catch(h){let T=h.loc||{line:1,column:0};throw new _(h.message.replace(/\s*\(\d+:\d+\)$/,""),T,p,t)}}function jt(e,n){for(let o of e.body){if(o.type==="ImportDeclaration")throw new _("Imports are not supported. All atoms must be registered with the VM.",o.loc?.start||{line:1,column:0},void 0,n);if(o.type==="ExportNamedDeclaration"||o.type==="ExportDefaultDeclaration")throw new _("Exports are not supported. The function is automatically exported.",o.loc?.start||{line:1,column:0},void 0,n);if(o.type==="ClassDeclaration")throw new _("Classes are not supported. Agent99 uses functional composition.",o.loc?.start||{line:1,column:0},void 0,n)}let t=e.body.filter(o=>o.type==="FunctionDeclaration");if(t.length===0)throw new _("Source must contain a function declaration",{line:1,column:0},void 0,n);let r=t[t.length-1],s=new Map;for(let o=0;o<t.length-1;o++){let i=t[o],a=i.id?.name;if(!a)throw new _("Helper function must have a name",i.loc?.start||{line:1,column:0},void 0,n);if(s.has(a))throw new _(`Duplicate helper function name: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);if(a===r.id?.name)throw new _(`Helper function cannot share a name with the entry function: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);s.set(a,i)}return{entry:r,helpers:s}}function Mt(e,n){let t={params:{}};if(!n.loc)return t;let r=e.substring(0,n.start),s=[...r.matchAll(/(?<=^[ \t]*)\/\*#([\s\S]*?)\*\//gm)];if(s.length>0){let p=s[s.length-1],m=r.substring(p.index+p[0].length);if(/^(?:\s|\/\/[^\n]*)*$/.test(m)){let u=p[1],d=u.split(`
52
52
  `),g=d.filter(y=>y.trim().length>0).reduce((y,w)=>{let E=w.match(/^(\s*)/)?.[1].length||0;return Math.min(y,E)},1/0);return g>0&&g<1/0&&(u=d.map(y=>y.slice(g)).join(`
53
53
  `)),t.description=u.trim(),t}}let o=r.match(/\/\*\*[\s\S]*?\*\/\s*$/);if(!o)return t;let i=o[0],a=i.match(/\/\*\*\s*\n?\s*\*?\s*([^@\n][^\n]*)/m);a&&(t.description=a[1].trim());let l=/@param\s+(?:\{[^}]+\}\s+)?(\w+)\s*-?\s*(.*)/g,c;for(;(c=l.exec(i))!==null;)t.params[c[1]]=c[2].trim();return t}import{parseExpressionAt as lr}from"acorn";function U(e){switch(e.type){case"Literal":{let n=e.value;if(n===null)return{kind:"null"};if(typeof n=="string")return{kind:"string"};if(typeof n=="number"){let t=e.raw;return t&&t.includes(".")?{kind:"number"}:{kind:"integer"}}return typeof n=="boolean"?{kind:"boolean"}:{kind:"any"}}case"ArrayExpression":{let n=e.elements;if(n.length===0)return{kind:"array",items:{kind:"any"}};let t=n.filter(i=>i!=null).map(i=>U(i));if(t.length===0)return{kind:"array",items:{kind:"any"}};let r=new Map;for(let i of t){let a=JSON.stringify(i);r.has(a)||r.set(a,i)}let s=[...r.values()];return{kind:"array",items:s.length===1?s[0]:{kind:"union",members:s}}}case"ObjectExpression":{let n=e.properties,t={};for(let r of n)if(r.type==="Property"&&r.key.type==="Identifier"){let s=r.key.name;t[s]=U(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?U(t):n==="&&"||n==="??"?U(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=U(t),o=U(r);return o.kind==="null"?{...s,nullable:!0}:s.kind==="null"?{...o,nullable:!0}:{kind:"union",members:[s,o]}}return{kind:"any"}}case"Identifier":return e.name==="undefined"?{kind:"undefined"}:{kind:"any"};case"ArrowFunctionExpression":case"FunctionExpression":{let n=e,t=n.params.map(s=>cr(s)),r={kind:"any"};return n.type==="ArrowFunctionExpression"&&n.body&&n.body.type!=="BlockStatement"&&(r=U(n.body)),{kind:"function",params:t,returns:r}}case"UnaryExpression":{let n=e.operator,t=e.argument;if(n==="+"&&t.type==="Literal"&&typeof t.value=="number")return{kind:"non-negative-integer"};if(n==="-"&&t.type==="Literal"&&typeof t.value=="number"){let s=t.raw;return s&&s.includes(".")?{kind:"number"}:{kind:"integer"}}return{kind:"any"}}default:return{kind:"any"}}}function cr(e){return e.type==="Identifier"?{name:e.name,type:{kind:"any"}}:e.type==="AssignmentPattern"&&e.left?.type==="Identifier"?{name:e.left.name,type:U(e.right)}:e.type==="RestElement"&&e.argument?.type==="Identifier"?{name:`...${e.argument.name}`,type:{kind:"array",items:{kind:"any"}}}:{name:"?",type:{kind:"any"}}}function Ce(e,n){if(e.type==="Identifier")return{name:e.name,type:{kind:"any"},required:!0};if(e.type==="AssignmentPattern"){let{left:t,right:r}=e;if(t.type!=="Identifier")throw new P("Only simple parameter names are supported",I(e));let s=t.name,o=n?.has(s)??!1,i=U(r),a=V(r);return{name:s,type:i,required:o,default:o?null:a,example:a,loc:{start:e.start,end:e.end}}}if(e.type==="ObjectPattern"){let t=e.properties,r={},s={};for(let o of t)if(o.type==="Property"){let i=o.key.type==="Identifier"?o.key.name:String(o.key.value);if(o.value.type==="Identifier")r[i]={kind:"any"},s[i]={name:i,type:{kind:"any"},required:!0};else if(o.value.type==="AssignmentPattern"){let a=Ce(o.value,n),l=n?.has(i)??!1;r[i]=a.type,s[i]={name:i,type:a.type,required:l,default:l?null:a.example,example:a.example}}}return{name:"__destructured__",type:{kind:"object",shape:r,destructuredParams:s},required:!0}}throw new P(`Unsupported parameter pattern: ${e.type}`,I(e))}function V(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?V(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=V(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=V(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=V(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?V(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?V(t)??V(r):void 0}default:return}}function kt(e){try{let n=lr(e,0,{ecmaVersion:2022});return U(n)}catch{return{kind:"any"}}}function ye(e){switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"null":return{};case"undefined":return{};case"any":return{};case"array":return{type:"array",items:e.items?ye(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=ye(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(ye)}:{};default:return{}}}function ur(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=ye(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function Nt(e,n,t,r={},s,o){let i=Mt(n,e),a=new Map;for(let S of e.params){let h=Ce(S,s);if(h.name==="__destructured__"&&h.type.kind==="object"&&h.type.destructuredParams)for(let[T,$]of Object.entries(h.type.destructuredParams))a.set(T,{...$,description:i.params[T]});else h.description=i.params[h.name],a.set(h.name,h)}let l;t&&(l=kt(t));let c={depth:0,locals:new Map,parameters:a,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r,helpers:o,helperSteps:o?new Map:void 0,helperTransforming:o?new Set:void 0},p=W(e.body,c),m=[],u=[],d=[];for(let[S,h]of a.entries())h.required?u.push(S):h.default!==void 0?d.push({name:S,defaultValue:h.default}):u.push(S);u.length>0&&m.push({op:"varsImport",keys:u});for(let{name:S,defaultValue:h}of d)m.push({op:"varsImport",keys:[S]}),m.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:S},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:S,value:h}]});m.push(...p);let g=Object.fromEntries(a),y={name:e.id?.name||"anonymous",description:i.description,parameters:g,returns:l},w=ur(g),E=c.helperSteps&&c.helperSteps.size>0?Object.fromEntries(c.helperSteps):void 0;return{ast:{op:"seq",steps:m,inputSchema:w,...E&&{helpers:E}},signature:y,warnings:c.warnings}}function W(e,n){let t=[];for(let r of e.body){let s=oe(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function oe(e,n){switch(e.type){case"VariableDeclaration":return fr(e,n);case"ExpressionStatement":return pr(e,n);case"IfStatement":return dr(e,n);case"WhileStatement":return gr(e,n);case"ForOfStatement":return hr(e,n);case"TryStatement":return yr(e,n);case"ReturnStatement":return br(e,n);case"ThrowStatement":throw new P("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",I(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:W(e,q(n))};case"EmptyStatement":return null;default:throw new P(`Unsupported statement type: ${e.type}`,I(e),n.source,n.filename)}}function fr(e,n){let t=[],r=e.kind==="const",s=r?"constSet":"varSet";for(let o of e.declarations){if(o.id.type!=="Identifier")throw new P("Only simple variable names are supported",I(o),n.source,n.filename);let i=o.id.name;if(o.init){let{step:a,resultVar:l}=K(o.init,n,i,r);a?t.push(a):l!==i&&t.push({op:s,key:i,value:l});let c=U(o.init);n.locals.set(i,c)}else{if(r)throw new P("const declarations must be initialized",I(o),n.source,n.filename);t.push({op:"varSet",key:i,value:null}),n.locals.set(i,{kind:"any",nullable:!0})}}return t}function pr(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return mr(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=K(t,n);return r||(s?{op:"varSet",key:"_",value:s}:null)}return n.warnings.push({message:"Expression statement has no effect",line:I(e).line,column:I(e).column}),null}function mr(e,n){if(e.left.type!=="Identifier")throw new P("Only simple variable assignment is supported",I(e),n.source,n.filename);let t=e.left.name,{step:r,resultVar:s}=K(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function dr(e,n){let t=N(e.test,n),r=e.consequent.type==="BlockStatement"?W(e.consequent,q(n)):[oe(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?W(e.alternate,q(n)):[oe(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function gr(e,n){let t=N(e.test,n),r=e.body.type==="BlockStatement"?W(e.body,q(n)):[oe(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function hr(e,n){let t;if(e.left.type==="VariableDeclaration"){let i=e.left.declarations[0];if(i.id.type!=="Identifier")throw new P("Only simple variable names are supported in for...of",I(e.left),n.source,n.filename);t=i.id.name}else if(e.left.type==="Identifier")t=e.left.name;else throw new P("Unsupported for...of left-hand side",I(e.left),n.source,n.filename);let r=D(e.right,n),s=q(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?W(e.body,s):[oe(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function yr(e,n){let t=W(e.block,q(n)),r,s;if(e.handler){let o=q(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=W(e.handler.body,o)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function br(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=K(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:D(e.argument,n)}}var Rt=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),wr=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),ae=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),Sr=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 $r(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return wr.has(n)||ae.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Rt.has(t)||ae.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(Sr.has(t))return!0}}return!1}function Er(e){if(e.object.type==="Identifier"){let n=e.object.name;return Rt.has(n)||ae.has(n)}return!1}var Ct={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 Tr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(ae.has(n))return Ct[n]||`${n} is not available in AsyncJS.`}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(ae.has(t))return Ct[t]||`${t} is not available in AsyncJS.`}}return null}function Pt(e){return{Date:" Use Date() or Date('2024-01-15') instead - no 'new' needed.",Set:" Use Set([items]) instead - no 'new' needed.",Map:" Use plain objects instead of Map.",Array:" Use array literals like [1, 2, 3] instead.",Object:" Use object literals like { key: value } instead.",Error:" Return an error object like { error: 'message' } instead.",RegExp:" Use string methods or the regexMatch atom.",Promise:" Not needed - all operations are implicitly async.",WeakSet:" WeakSet is not available.",WeakMap:" WeakMap is not available."}[e]||" Use factory functions or object literals instead."}function K(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return K(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let l=Pt(a);throw new P(`The 'new' keyword is not supported in AsyncJS.${l}`,I(e),n.source,n.filename)}if(e.type==="CallExpression"){let i=Tr(e);if(i)throw new P(i,I(e),n.source,n.filename)}if(e.type==="CallExpression"&&$r(e)){let i=N(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="MemberExpression"&&Er(e)){let i=N(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="CallExpression")return xr(e,n,t,r);if(e.type==="TemplateLiteral")return jr(e,n,t,r);if(e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="UnaryExpression"){let i=N(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}return{step:null,resultVar:D(e,n)}}function xr(e,n,t,r){let s,o=!1,i;if(e.callee.type==="Identifier")s=e.callee.name;else if(e.callee.type==="MemberExpression"){let l=e.callee;if(l.property.type==="Identifier")s=l.property.name,o=!0,i=D(l.object,n);else throw new P("Computed method names are not supported",I(e),n.source,n.filename)}else throw new P("Only named function calls are supported",I(e),n.source,n.filename);if(o)return Ar(s,i,e.arguments,n,t,r);if(s==="console"&&e.callee.type,n.helpers?.has(s)){let l=vr(s,n,e),c=e.arguments.map(p=>D(p,n));if(c.length!==l.length)throw new P(`Helper '${s}' expects ${l.length} argument(s), got ${c.length}`,I(e),n.source,n.filename);return{step:{op:"callLocal",name:s,args:c,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}let a=Mr(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function vr(e,n,t){let r=n.helpers.get(e),s=[];for(let o of r.params){let i;if(o.type==="Identifier"?i=o:o.type==="AssignmentPattern"&&o.left?.type==="Identifier"&&(i=o.left),!i)throw new P(`Helper '${e}' parameters must be plain identifiers (optionally with an example value); destructuring is not supported`,o.loc?.start??I(t),n.source,n.filename);s.push(i.name)}if(n.helperSteps.has(e)||n.helperTransforming.has(e))return s;n.helperTransforming.add(e);try{let o={depth:0,locals:new Map,parameters:new Map(s.map(a=>[a,{name:a,type:{kind:"any"},required:!0}])),atoms:n.atoms,warnings:n.warnings,source:n.source,filename:n.filename,options:n.options,helpers:n.helpers,helperSteps:n.helperSteps,helperTransforming:n.helperTransforming},i=W(r.body,o);n.helperSteps.set(e,{steps:i,paramNames:s})}finally{n.helperTransforming.delete(e)}return s}function Ar(e,n,t,r,s,o){switch(e){case"map":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=q(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")p=W(i.body,c);else{let{step:m,resultVar:u}=K(i.body,c,"result");p=m?[m]:[{op:"varSet",key:"result",value:u}]}return{step:{op:"map",items:n,as:l,steps:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"filter":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=q(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new P("filter callback must be an expression, not a block",I(t[0]),r.source,r.filename);return p=N(i.body,c),{step:{op:"filter",items:n,as:l,condition:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"find":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=q(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new P("find callback must be an expression, not a block",I(t[0]),r.source,r.filename);return p=N(i.body,c),{step:{op:"find",items:n,as:l,condition:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"reduce":if(t.length>=2&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=i.params[1],c=a?.type==="Identifier"?a.name:"acc",p=l?.type==="Identifier"?l.name:"item",m=q(r);m.locals.set(c,{kind:"any"}),m.locals.set(p,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=W(i.body,m);else{let{step:g,resultVar:y}=K(i.body,m,"result");u=g?[g]:[{op:"varSet",key:"result",value:y}]}let d=D(t[1],r);return{step:{op:"reduce",items:n,as:p,accumulator:c,initial:d,steps:u,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"slice":break;case"push":return{step:{op:"push",list:n,item:D(t[0],r),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?D(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?D(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}return r.warnings.push({message:`Unknown method '${e}' - treating as atom call`,line:0,column:0}),{step:{op:e,receiver:n,args:t.map(i=>D(i,r)),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}function jr(e,n,t,r){let s="",o={};for(let i=0;i<e.quasis.length;i++)if(s+=e.quasis[i].value.cooked||e.quasis[i].value.raw,i<e.expressions.length){let a=e.expressions[i],l=`_${i}`;o[l]=D(a,n),s+=`{{${l}}}`}return{step:{op:"template",tmpl:s,vars:o,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function N(e,n){switch(e.type){case"Literal":return{$expr:"literal",value:e.value};case"Identifier":return{$expr:"ident",name:e.name};case"MemberExpression":{let t=e,r=N(t.object,n),s=t.optional===!0;if(t.computed){let i=t.property;return i.type==="Literal"?{$expr:"member",object:r,property:String(i.value),computed:!0,...s&&{optional:!0}}:{$expr:"member",object:r,property:N(i,n),computed:!0,...s&&{optional:!0}}}let o=t.property.name;return{$expr:"member",object:r,property:o,...s&&{optional:!0}}}case"ChainExpression":return N(e.expression,n);case"BinaryExpression":{let t=e;return{$expr:"binary",op:t.operator,left:N(t.left,n),right:N(t.right,n)}}case"LogicalExpression":{let t=e;return{$expr:"logical",op:t.operator,left:N(t.left,n),right:N(t.right,n)}}case"UnaryExpression":{let t=e;return{$expr:"unary",op:t.operator,argument:N(t.argument,n)}}case"ConditionalExpression":{let t=e;return{$expr:"conditional",test:N(t.test,n),consequent:N(t.consequent,n),alternate:N(t.alternate,n)}}case"ArrayExpression":return{$expr:"array",elements:e.elements.filter(r=>r!==null).map(r=>N(r,n))};case"ObjectExpression":{let t=e,r=[];for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r.push({key:o,value:N(s.value,n)})}return{$expr:"object",properties:r}}case"CallExpression":{let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,s=r.property.type==="Identifier"?r.property.name:String(r.property.value),o=r.optional===!0||t.optional===!0;return{$expr:"methodCall",object:N(r.object,n),method:s,arguments:t.arguments.map(i=>N(i,n)),...o&&{optional:!0}}}if(t.callee.type==="Identifier"){let r=t.callee.name;if(n.helpers?.has(r))throw new P(`Helper '${r}' cannot be called inside an expression. Assign its result to a variable first: const result = ${r}(...); then use result.`,I(e),n.source,n.filename);return{$expr:"call",callee:r,arguments:t.arguments.map(s=>N(s,n))}}throw new P("Complex function calls in expressions should be lifted to statements",I(e),n.source,n.filename)}case"NewExpression":{let t=e,r="constructor";t.callee.type==="Identifier"&&(r=t.callee.name);let s=Pt(r);throw new P(`The 'new' keyword is not supported in AsyncJS.${s}`,I(e),n.source,n.filename)}case"TemplateLiteral":throw new P("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",I(e),n.source,n.filename);default:throw new P(`Unsupported expression type in condition: ${e.type}`,I(e),n.source,n.filename)}}function D(e,n){switch(e.type){case"Literal":return e.value;case"Identifier":return e.name;case"MemberExpression":{let t=e;if(t.optional===!0)return N(e,n);let s=D(t.object,n);if(s&&typeof s=="object"&&s.$expr){let i=t.computed?String(t.property.value):t.property.name;return{$expr:"member",object:s,property:i,...t.computed&&{computed:!0}}}if(t.computed)return N(e,n);let o=t.property.name;return typeof s=="string"?`${s}.${o}`:s&&s.$kind==="arg"?{$kind:"arg",path:`${s.path}.${o}`}:`${s}.${o}`}case"ChainExpression":return D(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?D(t,n):null);case"ObjectExpression":{let t={};for(let r of e.properties)if(r.type==="Property"){let s=r.key.type==="Identifier"?r.key.name:String(r.key.value);t[s]=D(r.value,n)}return t}case"TemplateLiteral":return N(e,n);case"CallExpression":return N(e,n);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return N(e,n);default:return null}}function Mr(e,n){if(e.arguments.length===1&&e.arguments[0].type==="ObjectExpression"){let t=e.arguments[0],r={};for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r[o]=D(s.value,n)}return r}return{args:e.arguments.map(t=>D(t,n))}}function le(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=At(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),{entry:i,helpers:a}=jt(t,n.filename),{ast:l,signature:c,warnings:p}=Nt(i,s,r,n,o,a.size>0?a:void 0);return{ast:l,signature:c,warnings:p}}var Cr=6e4,be=class{atoms;_defaultRunTimeout;constructor(n={}){this.atoms={...ve,...n}}get defaultRunTimeout(){if(this._defaultRunTimeout===void 0){let n=0;for(let t of Object.values(this.atoms)){let r=t.timeoutMs??1e3;r>0&&r>n&&(n=r)}this._defaultRunTimeout=Math.max(Cr,n*2)}return this._defaultRunTimeout}get builder(){return new re(this.atoms)}get Agent(){return new re(this.atoms)}get A99(){return this.Agent}resolve(n){return this.atoms[n]}getTools(n="all"){let t=Object.values(this.atoms);if(Array.isArray(n))t=t.filter(r=>n.includes(r.op));else if(n==="flow"){let r=["seq","if","while","return","try","varSet","varGet","scope"];t=t.filter(s=>r.includes(s.op))}return t.map(r=>({type:"function",function:{name:r.op,description:r.docs,parameters:r.inputSchema?.schema??{}}}))}async run(n,t={},r={}){let s;if(typeof n=="string")if(Ee(n))s=Te(n);else try{s=le(n).ast}catch(g){throw new Error(`AJS transpilation failed: ${g.message}`,{cause:g})}else s=n;let o=r.fuel??1e3,i=r.timeoutMs??this.defaultRunTimeout,a=r.capabilities??{},l=[];if(!a.store){let g=new Map,y=!1;a.store={get:async w=>(y||(y=!0,l.push("Using default in-memory store (not suitable for production)")),g.get(w)),set:async(w,E)=>{y||(y=!0,l.push("Using default in-memory store (not suitable for production)")),g.set(w,E)}}}let c=new AbortController,p=setTimeout(()=>c.abort(),i);r.signal&&r.signal.addEventListener("abort",()=>c.abort());let m={fuel:{current:o},args:t,state:{},consts:new Set,capabilities:a,resolver:g=>this.resolve(g),output:void 0,signal:c.signal,costOverrides:r.costOverrides,timeoutOverrides:r.timeoutOverrides,context:r.context,warnings:l,helpers:s.helpers};if(r.trace&&(m.trace=[]),s.op!=="seq")throw new Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let u=s.inputSchema;if(u&&!kr(t,u)){let g=new O("Input validation failed: args do not match expected schema","vm.run");return{result:g,error:g,fuelUsed:0,trace:m.trace,warnings:l.length>0?l:void 0}}try{await Promise.race([this.resolve("seq")?.exec(s,m),new Promise((g,y)=>{c.signal.addEventListener("abort",()=>{y(new Error(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`))}),c.signal.aborted&&y(new Error(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`))})])}catch(g){if(g.message?.includes("timeout")||g.message?.includes("aborted")||c.signal.aborted)m.error=new O(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`,"vm.run");else throw g}finally{clearTimeout(p)}m.error&&m.output===void 0&&(m.output=m.error);let d=[...l,...m.warnings??[]];return{result:m.output,error:m.error,fuelUsed:o-m.fuel.current,trace:m.trace,warnings:d.length>0?d:void 0}}};var Nr=null,It=()=>Nr??=new be;function Y(e){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let n of e)Y(n);return}e.op==="return"&&"value"in e&&(e.value={__result:e.value}),e.steps&&Y(e.steps),e.then&&Y(e.then),e.else&&Y(e.else),e.body&&Y(e.body)}}async function us(e){let{code:n,context:t={},fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=It(),l=/\breturn\b/.test(n)?`function __eval() { ${n} }`:`function __eval() { return (${n}) }`;try{let{ast:c}=le(l);Y(c);let p=await i.run(c,t,{fuel:r,timeoutMs:s,capabilities:o}),m=p.result;return{result:m&&typeof m=="object"&&"__result"in m?m.__result:m,fuelUsed:p.fuelUsed,error:p.error?{message:p.error.message||String(p.error)}:void 0}}catch(c){return{result:void 0,fuelUsed:r,error:{message:c.message||String(c)}}}}async function fs(e){let{body:n,params:t=[],fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=It(),l=`function __safeFn(${t.join(", ")}) { ${n} }`,{ast:c}=le(l);return Y(c),async(...p)=>{let m={};for(let u=0;u<t.length;u++)m[t[u]]=p[u];try{let u=await i.run(c,m,{fuel:r,timeoutMs:s,capabilities:o}),d=u.result;return{result:d&&typeof d=="object"&&"__result"in d?d.__result:d,fuelUsed:u.fuelUsed,error:u.error?{message:u.error.message||String(u.error)}:void 0}}catch(u){return{result:void 0,fuelUsed:r,error:{message:u.message||String(u)}}}}}export{us as Eval,fs as SafeFunction};
54
54
  //# sourceMappingURL=tjs-eval.js.map