tjs-lang 0.7.8 → 0.8.1

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.
Files changed (62) hide show
  1. package/CLAUDE.md +14 -1
  2. package/CONTEXT.md +4 -0
  3. package/demo/docs.json +66 -696
  4. package/demo/src/ts-examples.ts +8 -8
  5. package/dist/eslint.config.d.ts +2 -0
  6. package/dist/index.js +137 -135
  7. package/dist/index.js.map +4 -4
  8. package/dist/src/lang/emitters/js-wasm.d.ts +5 -1
  9. package/dist/src/lang/emitters/js.d.ts +9 -0
  10. package/dist/src/lang/index.d.ts +1 -0
  11. package/dist/src/lang/module-loader.d.ts +125 -0
  12. package/dist/src/lang/parser-transforms.d.ts +79 -0
  13. package/dist/src/lang/parser-types.d.ts +33 -0
  14. package/dist/src/lang/wasm.d.ts +67 -1
  15. package/dist/tjs-batteries.js +2 -2
  16. package/dist/tjs-batteries.js.map +2 -2
  17. package/dist/tjs-eval.js +39 -37
  18. package/dist/tjs-eval.js.map +3 -3
  19. package/dist/tjs-from-ts.js +2 -2
  20. package/dist/tjs-from-ts.js.map +2 -2
  21. package/dist/tjs-lang.js +102 -102
  22. package/dist/tjs-lang.js.map +3 -3
  23. package/dist/tjs-vm.js +50 -48
  24. package/dist/tjs-vm.js.map +3 -3
  25. package/docs/README.md +2 -0
  26. package/docs/lm-studio-setup.md +143 -0
  27. package/docs/universal-endpoint.md +122 -0
  28. package/llms.txt +8 -2
  29. package/package.json +11 -6
  30. package/src/batteries/audit.ts +3 -3
  31. package/src/batteries/llm.ts +8 -3
  32. package/src/builder.ts +0 -3
  33. package/src/cli/commands/test.ts +1 -1
  34. package/src/lang/docs.test.ts +148 -1
  35. package/src/lang/docs.ts +49 -15
  36. package/src/lang/emitters/from-ts.ts +1 -1
  37. package/src/lang/emitters/js-wasm.ts +57 -65
  38. package/src/lang/emitters/js.ts +16 -2
  39. package/src/lang/features.test.ts +4 -3
  40. package/src/lang/index.ts +9 -0
  41. package/src/lang/linter.ts +1 -1
  42. package/src/lang/module-loader.test.ts +322 -0
  43. package/src/lang/module-loader.ts +418 -0
  44. package/src/lang/parser-params.ts +1 -1
  45. package/src/lang/parser-transforms.ts +339 -9
  46. package/src/lang/parser-types.ts +33 -0
  47. package/src/lang/parser.ts +43 -2
  48. package/src/lang/perf.test.ts +10 -4
  49. package/src/lang/runtime.ts +0 -1
  50. package/src/lang/wasm.test.ts +1293 -2
  51. package/src/lang/wasm.ts +470 -87
  52. package/src/linalg/index.tjs +119 -0
  53. package/src/linalg/linalg.test.ts +300 -0
  54. package/src/linalg/vector-search.bench.test.ts +416 -0
  55. package/src/types/Type.ts +6 -6
  56. package/src/use-cases/asymmetric-client-server.test.ts +0 -2
  57. package/src/use-cases/client-server.test.ts +1 -1
  58. package/src/use-cases/unbundled-imports.test.ts +0 -1
  59. package/src/vm/runtime.ts +3 -3
  60. package/src/vm/vm.ts +3 -1
  61. package/dist/examples/modules/dist/main.d.ts +0 -34
  62. package/dist/examples/modules/dist/math.d.ts +0 -120
package/dist/tjs-eval.js CHANGED
@@ -1,52 +1,54 @@
1
- import{s as f,validate as $e,filter as De}from"tosijs-schema";var ce=Symbol.for("tjs.equals");function fe(e,n){if(e!==null&&typeof e=="object"&&typeof e[ce]=="function")return e[ce](n);if(n!==null&&typeof n=="object"&&typeof n[ce]=="function")return n[ce](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(n);if(n!==null&&typeof n=="object"&&typeof n.Equals=="function")return n.Equals(e);if(e===n||e==null&&n==null)return!0;if(e==null||n===null||n===void 0||typeof e!=typeof n||typeof e!="object")return!1;if(Array.isArray(e)&&Array.isArray(n))return e.length!==n.length?!1:e.every((s,o)=>fe(s,n[o]));if(Array.isArray(e)!==Array.isArray(n))return!1;let t=Object.keys(e),r=Object.keys(n);return t.length!==r.length?!1:t.every(s=>fe(e[s],n[s]))}var F=class{$error=!0;message;op;cause;constructor(n,t,r){this.message=n,this.op=t,this.cause=r}toString(){return`AgentError[${this.op}]: ${this.message}`}toJSON(){return{$error:!0,message:this.message,op:this.op}}};function Pt(e){return e instanceof F||e&&e.$error===!0}var te=new Map,It=3600*1e3,Bt=100*1024,xe="proc_";function Te(e){return typeof e=="string"&&e.startsWith(xe)}function Ae(e){let n=te.get(e);if(!n)throw new Error(`Procedure not found: ${e}`);if(Date.now()>n.expiresAt)throw te.delete(e),new Error(`Procedure expired: ${e}`);return n.ast}function _t(){return typeof crypto<"u"&&crypto.randomUUID?xe+crypto.randomUUID():xe+Math.random().toString(36).slice(2)+Date.now().toString(36)}var Fe=new Set(["__proto__","constructor","prototype"]);function Re(e){if(Fe.has(e))throw new Error(`Security Error: Access to '${e}' is forbidden`)}var Ot=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function Dt(e){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;let t=n.hostname.toLowerCase();return!!(Ot.has(t)||t.endsWith(".internal")||t.endsWith(".local")||t==="169.254.169.254"||/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t))}catch{return!0}}function Ft(e){return!!(/\([^)]*[+*][^)]*\)[+*]/.test(e)||/\(([^|)]+)\|\1\)[+*]/.test(e)||/\(\.\*\)\+/.test(e)||/\(\.\+\)\+/.test(e)||/\(\[.*\]\+\)\+/.test(e))}function G(e){return{...e,state:Object.create(e.state)}}function Ut(e,n){let t={},r=new Set([...Object.keys(e),...Object.keys(n)]);for(let s of r){let o=e[s],i=n[s];i!==o&&(t[s]=i)}return t}function $(e,n){if(e&&typeof e=="object"&&e.$kind==="arg")return n.args[e.path];if(e&&typeof e=="object"&&e.$expr)return I(e,n);if(typeof e=="string"){if(e.startsWith("args.")&&!("args"in n.state))return n.args[e.replace("args.","")];if(e.includes(".")){let t=e.split(".");for(let s of t)if(Fe.has(s))throw new Error(`Security Error: Access to '${s}' is forbidden`);let r=n.state[t[0]];if(r!==void 0){for(let s=1;s<t.length;s++)r=r?.[t[s]];return r}}return e in n.state?n.state[e]:e}if(e&&typeof e=="object"&&!Array.isArray(e)&&e.constructor===Object){let t={};for(let r of Object.keys(e))t[r]=$(e[r],n);return t}return Array.isArray(e)?e.map(t=>$(t,n)):e}function Y(e,n,t){return new Proxy(n,{get(r,s){if(s in r)return r[s];let o=t?.[s];throw o?new Error(`${e}.${s} is not available. ${o}`):new Error(`${e}.${s} is not supported in AsyncJS. Check docs for available ${e} methods.`)}})}function ee(e){if(e===null)return{type:"null"};if(e===void 0)return{};if(typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string")return e;if(typeof e=="object"&&e!==null&&"schema"in e&&typeof e.schema=="object")return e.schema;let n=typeof e;if(n==="string")return{type:"string"};if(n==="number")return Number.isInteger(e)?{type:"integer"}:{type:"number"};if(n==="boolean")return{type:"boolean"};if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:ee(e[0])};if(n==="object"){let t={},r=[];for(let[s,o]of Object.entries(e))t[s]=ee(o),r.push(s);return{type:"object",properties:t,required:r}}return{}}var z={Math:Y("Math",{PI:Math.PI,E:Math.E,LN2:Math.LN2,LN10:Math.LN10,LOG2E:Math.LOG2E,LOG10E:Math.LOG10E,SQRT2:Math.SQRT2,SQRT1_2:Math.SQRT1_2,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc,sign:Math.sign,sqrt:Math.sqrt,cbrt:Math.cbrt,pow:Math.pow,exp:Math.exp,expm1:Math.expm1,log:Math.log,log2:Math.log2,log10:Math.log10,log1p:Math.log1p,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,hypot:Math.hypot,min:Math.min,max:Math.max,clz32:Math.clz32,imul:Math.imul,fround:Math.fround,random:()=>{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]/4294967296}return Math.random()}}),JSON:Y("JSON",{parse:e=>JSON.parse(e),stringify:(e,n,t)=>JSON.stringify(e,n,t)}),console:Y("console",{log:(...e)=>{},warn:(...e)=>{},error:(...e)=>{},info:(...e)=>{}},{table:"Use console.log with JSON.stringify for structured data.",dir:"Use console.log instead.",trace:"Stack traces are not available in AsyncJS."}),Array:Y("Array",{isArray:e=>Array.isArray(e),from:(e,n,t)=>Array.from(e,n,t),of:(...e)=>Array.of(...e)},{prototype:"Prototype access is not allowed."}),Object:Y("Object",{keys:e=>Object.keys(e),values:e=>Object.values(e),entries:e=>Object.entries(e),fromEntries:e=>Object.fromEntries(e),assign:(e,...n)=>Object.assign({},e,...n),hasOwn:(e,n)=>Object.hasOwn(e,n)},{prototype:"Prototype access is not allowed.",create:"Use object literals instead.",defineProperty:"Property descriptors are not supported.",getPrototypeOf:"Prototype access is not allowed.",setPrototypeOf:"Prototype modification is not allowed."}),String:Y("String",{fromCharCode:(...e)=>String.fromCharCode(...e),fromCodePoint:(...e)=>String.fromCodePoint(...e)}),Number:Y("Number",{isNaN:Number.isNaN,isFinite:Number.isFinite,isInteger:Number.isInteger,isSafeInteger:Number.isSafeInteger,parseFloat,parseInt,MAX_VALUE:Number.MAX_VALUE,MIN_VALUE:Number.MIN_VALUE,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,POSITIVE_INFINITY:Number.POSITIVE_INFINITY,NEGATIVE_INFINITY:Number.NEGATIVE_INFINITY,NaN:Number.NaN,EPSILON:Number.EPSILON}),parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,undefined:void 0,null:null,NaN:NaN,Infinity:1/0,filter:(e,n)=>{let t=ee(n),r=De(e,t);if(r instanceof Error)throw r;return r},Schema:{...f,response:(e,n)=>{let t=n?.schema!=null?n.schema:ee(n);return{type:"json_schema",json_schema:{name:e,strict:!0,schema:t}}},fromExample:e=>ee(e),isValid:(e,n)=>n?.schema!=null?$e(e,n):$e(e,ee(n))},Set:(e=[])=>{let n=[...new globalThis.Set(e)];return{add(t){return n.includes(t)||n.push(t),this},remove(t){let r=n.indexOf(t);return r!==-1&&n.splice(r,1),this},clear(){return n.length=0,this},has(t){return n.includes(t)},get size(){return n.length},toArray(){return[...n]},union(t){let r=t?.toArray?.()??t??[];return z.Set([...n,...r])},intersection(t){let r=t?.toArray?.()??t??[];return z.Set(n.filter(s=>r.includes(s)))},diff(t){let r=t?.toArray?.()??t??[];return z.Set(n.filter(s=>!r.includes(s)))},forEach(t){n.forEach(t)},map(t){return z.Set(n.map(t))},filter(t){return z.Set(n.filter(t))},toJSON(){return[...n]}}},Date:(()=>{let e=t=>({get value(){return t.toISOString()},get timestamp(){return t.getTime()},get year(){return t.getFullYear()},get month(){return t.getMonth()+1},get day(){return t.getDate()},get hours(){return t.getHours()},get minutes(){return t.getMinutes()},get seconds(){return t.getSeconds()},get dayOfWeek(){return t.getDay()},add({years:r=0,months:s=0,days:o=0,hours:i=0,minutes:a=0,seconds:l=0,ms:c=0}={}){let p=new globalThis.Date(t.getTime());return r&&p.setFullYear(p.getFullYear()+r),s&&p.setMonth(p.getMonth()+s),o&&p.setDate(p.getDate()+o),i&&p.setHours(p.getHours()+i),a&&p.setMinutes(p.getMinutes()+a),l&&p.setSeconds(p.getSeconds()+l),c&&p.setMilliseconds(p.getMilliseconds()+c),e(p)},diff(r,s="ms"){let o=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime(),i=t.getTime()-o;switch(s){case"seconds":return i/1e3;case"minutes":return i/6e4;case"hours":return i/36e5;case"days":return i/864e5;default:return i}},format(r="ISO"){return r==="ISO"?t.toISOString():r==="date"?t.toISOString().split("T")[0]:r==="time"?t.toISOString().split("T")[1].split(".")[0]:r.replace("YYYY",String(t.getFullYear())).replace("MM",String(t.getMonth()+1).padStart(2,"0")).replace("DD",String(t.getDate()).padStart(2,"0")).replace("HH",String(t.getHours()).padStart(2,"0")).replace("mm",String(t.getMinutes()).padStart(2,"0")).replace("ss",String(t.getSeconds()).padStart(2,"0"))},isBefore(r){let s=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime();return t.getTime()<s},isAfter(r){let s=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime();return t.getTime()>s},toString(){return t.toISOString()},toJSON(){return t.toISOString()}}),n=t=>{let r=t!==void 0?new globalThis.Date(t):new globalThis.Date;if(isNaN(r.getTime()))throw new Error(`Invalid date: ${t}`);return e(r)};return n.now=()=>globalThis.Date.now(),n.parse=t=>e(new globalThis.Date(t)),n})()},ue={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."},qt=.01,Pe=1e-4,Ie=.001,Lt=new Set(["concat","slice","map","filter","flatMap","flat","toReversed","toSorted","toSpliced","repeat","padStart","padEnd","split","join","replace","replaceAll","substring","substr","trim","trimStart","trimEnd","toLowerCase","toUpperCase","match","matchAll","parse","stringify"]);function I(e,n){if(e==null||typeof e!="object"||!("$expr"in e))return e;if(n.fuel&&(n.fuel.current-=qt,n.fuel.current<=0))throw new Error("Out of Fuel");switch(e.$expr){case"literal":return e.value;case"ident":{if(e.name in n.state)return n.state[e.name];if(e.name in n.args)return n.args[e.name];if(e.name in z)return z[e.name];if(e.name in ue)throw new Error(ue[e.name]);return}case"member":{let t=I(e.object,n);if(e.optional&&t==null)return;let r=typeof e.property=="object"&&e.property!==null?I(e.property,n):e.property;return Re(String(r)),t?.[r]}case"binary":{let t=I(e.left,n),r=I(e.right,n);switch(e.op){case"+":{let s=t+r;if(typeof s=="string"&&n.fuel&&(n.fuel.current-=s.length*Pe,n.fuel.current<=0)){n.error=new F("Out of Fuel","expr.concat");return}return s}case"-":return t-r;case"*":return t*r;case"/":return t/r;case"%":return t%r;case"**":return t**r;case">":return t>r;case"<":return t<r;case">=":return t>=r;case"<=":return t<=r;case"==":return fe(t,r);case"!=":return!fe(t,r);case"===":return t===r;case"!==":return t!==r;default:throw new Error(`Unknown binary operator: ${e.op}`)}}case"unary":{let t=I(e.argument,n);switch(e.op){case"!":return!t;case"-":return-t;case"+":return+t;case"typeof":return typeof t;default:throw new Error(`Unknown unary operator: ${e.op}`)}}case"logical":{let t=I(e.left,n);return e.op==="&&"?t&&I(e.right,n):e.op==="??"?t??I(e.right,n):t||I(e.right,n)}case"conditional":{let t=I(e.test,n);return I(t?e.consequent:e.alternate,n)}case"array":return e.elements.map(t=>I(t,n));case"object":{let t={};for(let r of e.properties)t[r.key]=I(r.value,n);return t}case"call":{if(e.callee==="Error"){let r=e.arguments.map(o=>I(o,n)),s=typeof r[0]=="string"?r[0]:"Error";n.error=new F(s,"Error");return}if(e.callee in z){let r=z[e.callee];if(typeof r=="function"){let s=e.arguments.map(o=>I(o,n));return r(...s)}}throw n.resolver(e.callee)?new Error(`Atom calls in expressions not yet supported: ${e.callee}`):e.callee in ue?new Error(ue[e.callee]):new Error(`Unknown function: ${e.callee}`)}case"methodCall":{let t=I(e.object,n);if(e.optional&&t==null)return;let r=e.method;if(Re(r),t==null)throw new Error(`Cannot call method '${r}' on ${t}`);let s=t[r];if(typeof s!="function")throw new Error(`'${r}' is not a function`);let o=e.arguments.map(a=>I(a,n)),i=s.apply(t,o);if(n.fuel&&Lt.has(r)){let a=0;if(typeof i=="string"?a=i.length*Pe:Array.isArray(i)?a=i.length*Ie:typeof i=="object"&&i!==null&&(a=Object.keys(i).length*Ie),n.fuel.current-=a,n.fuel.current<=0){n.error=new F("Out of Fuel",`expr.${r}`);return}}return i}default:throw new Error(`Unknown expression type: ${e.$expr}`)}}function v(e,n,t,r,s={}){let{docs:o="",timeoutMs:i=1e3,cost:a=1}=typeof s=="string"?{docs:s}:s;return{op:e,inputSchema:n,outputSchema:t,exec:async(c,p)=>{let{op:m,result:u,...d}=c;if(p.error)return;let g=p.trace?{...p.state}:null,b=p.fuel.current,h,w;try{let x=p.costOverrides?.[e],y=x!==void 0?x:a,T=typeof y=="function"?y(d,p):y;if((p.fuel.current-=T)<=0){p.error=new F("Out of Fuel",e);return}let A,E=async()=>r(c,p);if(h=i>0?await Promise.race([E(),new Promise((S,j)=>{A=setTimeout(()=>j(new Error(`Atom '${e}' timed out`)),i)})]).finally(()=>clearTimeout(A)):await E(),c.result){if(p.consts.has(c.result))throw new Error(`Cannot reassign const variable '${c.result}'`);if(h!==void 0&&t&&!$e(h,t)){p.error=new F(`Output validation failed for '${e}'`,e);return}p.state[c.result]=h,c.resultConst&&p.consts.add(c.result)}}catch(x){w=x.message||String(x),p.error=new F(w,e,x)}finally{if(p.trace&&g){let x=Ut(g,p.state);p.trace.push({op:e,input:d,stateDiff:x,result:h,error:w,fuelBefore:b,fuelAfter:p.fuel.current,timestamp:new Date().toISOString()})}}},docs:o,timeoutMs:i,cost:a,create:c=>({op:e,...c})}}var q=v("seq",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{for(let t of e){if(n.output!==void 0||n.error)return;let r=n.resolver(t.op);if(!r)throw new Error(`Unknown Atom: ${t.op}`);await r.exec(t,n)}},{docs:"Sequence",timeoutMs:0,cost:.1}),Wt=v("if",f.object({condition:f.any,then:f.array(f.any),else:f.array(f.any).optional}),void 0,async(e,n)=>{I(e.condition,n)?await q.exec({op:"seq",steps:e.then},n):e.else&&await q.exec({op:"seq",steps:e.else},n)},{docs:"If/Else",timeoutMs:0,cost:.1}),Vt=v("while",f.object({condition:f.any,body:f.array(f.any)}),void 0,async(e,n)=>{for(;I(e.condition,n);){if(n.signal?.aborted)throw new Error("Execution aborted");if((n.fuel.current-=.1)<=0)throw new Error("Out of Fuel");if(await q.exec({op:"seq",steps:e.body},n),n.output!==void 0||n.error)return}},{docs:"While Loop",timeoutMs:0,cost:.1}),zt=v("return",void 0,f.any,async(e,n)=>{if(n.error)return n.output=n.error,n.error;if("value"in e){let r=$(e.value,n);if(r!=null&&!Pt(r)&&(typeof r!="object"||Array.isArray(r))){let s=new F(`Agent must return an object, got ${Array.isArray(r)?"array":typeof r}`,"return");return n.error=s,n.output=s,s}return n.output=r,r}let t={};if(e.schema?.properties){for(let r of Object.keys(e.schema.properties))t[r]=n.state[r];if(e.filter!==!1){let r=De(t,e.schema);r instanceof Error||(t=r)}}return n.output=t,t},{docs:"Return",cost:.1}),Jt=v("try",f.object({try:f.array(f.any),catch:f.array(f.any).optional,catchParam:f.string.optional}),void 0,async(e,n)=>{if(await q.exec({op:"seq",steps:e.try},n),n.error&&e.catch){let t=e.catchParam||"error";n.state[t]=n.error.message,n.state.errorOp=n.error.op,n.error=void 0,await q.exec({op:"seq",steps:e.catch},n)}},{docs:"Try/Catch",timeoutMs:0,cost:.1}),Zt=v("Error",f.object({args:f.array(f.any).optional}),void 0,async(e,n)=>{let t=e.args?.[0]??"Error";n.error=new F(String(t),"Error")},{docs:"Trigger error flow",cost:.1}),Gt=v("varSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{if(t.consts.has(e))throw new Error(`Cannot reassign const variable '${e}'`);t.state[e]=$(n,t)},{docs:"Set Variable",cost:.1}),Ht=v("constSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{if(t.consts.has(e))throw new Error(`Cannot reassign const variable '${e}'`);if(e in t.state)throw new Error(`Cannot redeclare variable '${e}' as const`);t.state[e]=$(n,t),t.consts.add(e)},{docs:"Set Const Variable (immutable)",cost:.1}),Kt=v("varGet",f.object({key:f.string}),f.any,async({key:e},n)=>$(e,n),{docs:"Get Variable",cost:.1}),Yt=v("varsImport",f.object({keys:f.union([f.array(f.string),f.record(f.string)])}),void 0,async({keys:e},n)=>{if(Array.isArray(e))for(let t of e)n.state[t]=$({$kind:"arg",path:t},n);else for(let[t,r]of Object.entries(e))n.state[t]=$({$kind:"arg",path:r},n)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:.2}),Xt=v("varsLet",f.record(f.any),void 0,async(e,n)=>{for(let t of Object.keys(e))t==="op"||t==="result"||(n.state[t]=$(e[t],n))},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:.1}),Qt=v("varsExport",f.object({keys:f.union([f.array(f.string),f.record(f.string)])}),f.record(f.any),async({keys:e},n)=>{let t={};if(Array.isArray(e))for(let r of e)t[r]=$(r,n);else for(let[r,s]of Object.entries(e))t[r]=$(s,n);return t},{docs:"Export variables from the current scope, with optional renaming.",cost:.2}),en=v("scope",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{let t=G(n);await q.exec({op:"seq",steps:e},t),t.output!==void 0&&(n.output=t.output)},{docs:"Create new scope",timeoutMs:0,cost:.1}),tn=v("map",f.object({items:f.array(f.any),as:f.string,steps:f.array(f.any)}),f.array(f.any),async({items:e,as:n,steps:t},r)=>{let s=[],o=$(e,r);if(!Array.isArray(o))throw new Error("map: items is not an array");for(let i of o){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=i,await q.exec({op:"seq",steps:t},a),s.push(a.state.result??null)}return s},{docs:"Map Array",timeoutMs:0,cost:1}),nn=v("filter",f.object({items:f.array(f.any),as:f.string,condition:f.any}),f.array(f.any),async({items:e,as:n,condition:t},r)=>{let s=[],o=$(e,r);if(!Array.isArray(o))throw new Error("filter: items is not an array");for(let i of o){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=i,I(t,a)&&s.push(i)}return s},{docs:"Filter Array",timeoutMs:0,cost:1}),rn=v("reduce",f.object({items:f.array(f.any),as:f.string,accumulator:f.string,initial:f.any,steps:f.array(f.any)}),f.any,async({items:e,as:n,accumulator:t,initial:r,steps:s},o)=>{let i=$(e,o),a=$(r,o);if(!Array.isArray(i))throw new Error("reduce: items is not an array");let l=a;for(let c of i){if(o.signal?.aborted)throw new Error("Execution aborted");let p=G(o);p.state[n]=c,p.state[t]=l,await q.exec({op:"seq",steps:s},p),l=p.state.result??l}return l},{docs:"Reduce Array",timeoutMs:0,cost:1}),sn=v("find",f.object({items:f.array(f.any),as:f.string,condition:f.any}),f.any,async({items:e,as:n,condition:t},r)=>{let s=$(e,r);if(!Array.isArray(s))throw new Error("find: items is not an array");for(let o of s){if(r.signal?.aborted)throw new Error("Execution aborted");let i=G(r);if(i.state[n]=o,I(t,i))return o}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),on=v("push",f.object({list:f.array(f.any),item:f.any}),f.array(f.any),async({list:e,item:n},t)=>{let r=$(e,t),s=$(n,t);return Array.isArray(r)&&r.push(s),r},{docs:"Push to Array",cost:1}),an=v("len",f.object({list:f.any}),f.number,async({list:e},n)=>{let t=$(e,n);return Array.isArray(t)||typeof t=="string"?t.length:0},{docs:"Length",cost:1}),ln=v("split",f.object({str:f.string,sep:f.string}),f.array(f.string),async({str:e,sep:n},t)=>$(e,t).split($(n,t)),{docs:"Split String",cost:1}),cn=v("join",f.object({list:f.array(f.string),sep:f.string}),f.string,async({list:e,sep:n},t)=>$(e,t).join($(n,t)),{docs:"Join String",cost:1}),un=v("template",f.object({tmpl:f.string,vars:f.record(f.any)}),f.string,async({tmpl:e,vars:n},t)=>$(e,t).replace(/\{\{(\w+)\}\}/g,(s,o)=>String($(n[o],t)??"")),{docs:"String Template",cost:1}),fn=v("regexMatch",f.object({pattern:f.string,value:f.any}),f.boolean,async({pattern:e,value:n},t)=>{if(Ft(e))throw new Error(`Suspicious regex pattern rejected (potential ReDoS): ${e}`);let r=$(n,t);return new RegExp(e).test(r)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),pn=v("pick",f.object({obj:f.record(f.any),keys:f.array(f.string)}),f.record(f.any),async({obj:e,keys:n},t)=>{let r=$(e,t),s=$(n,t),o={};return r&&Array.isArray(s)&&s.forEach(i=>o[i]=r[i]),o},{docs:"Pick Keys",cost:1}),mn=v("omit",f.object({obj:f.record(f.any),keys:f.array(f.string)}),f.record(f.any),async({obj:e,keys:n},t)=>{let r=$(e,t),s=new Set($(n,t)),o={};return r&&Object.keys(r).forEach(i=>{s.has(i)||(o[i]=r[i])}),o},{docs:"Omit Keys",cost:1}),dn=v("merge",f.object({a:f.record(f.any),b:f.record(f.any)}),f.record(f.any),async({a:e,b:n},t)=>({...$(e,t),...$(n,t)}),{docs:"Merge Objects",cost:1}),gn=v("keys",f.object({obj:f.record(f.any)}),f.array(f.string),async({obj:e},n)=>Object.keys($(e,n)??{}),{docs:"Object Keys",cost:1}),Be=10,_e="X-Agent-Depth";function yn(e,n){try{let r=new URL(e).hostname.toLowerCase();for(let s of n){let o=s.toLowerCase();if(o.startsWith("*.")){let i=o.slice(1);if(r.endsWith(i)||r===o.slice(2))return!0}else if(r===o)return!0}return!1}catch{return!1}}var hn=v("httpFetch",f.object({url:f.string,method:f.string.optional,headers:f.record(f.string).optional,body:f.any.optional,responseType:f.string.optional}),f.any,async(e,n)=>{let t=$(e.url,n),r=$(e.method,n),s=$(e.headers,n)||{},o=$(e.body,n),i=$(e.responseType,n),a=n.context?.requestDepth??0;if(a>=Be)throw new Error(`Agent request depth exceeded (max ${Be}). This prevents recursive agent loops.`);if(n.capabilities.fetch)return n.capabilities.fetch(t,{method:r,headers:{...s,[_e]:String(a+1)},body:o,signal:n.signal,responseType:i});let l=n.context?.allowedFetchDomains;if(l){if(!yn(t,l))throw new Error(`Fetch blocked: domain not in allowlist. Allowed: ${l.join(", ")}`)}else{if(Dt(t))throw new Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let p=new URL(t).hostname.toLowerCase();if(p!=="localhost"&&p!=="127.0.0.1"&&p!=="[::1]")throw new Error("Fetch blocked: no allowedFetchDomains configured. Set ctx.context.allowedFetchDomains or provide a custom fetch capability.")}catch(c){throw c.message.includes("allowedFetchDomains")?c:new Error(`Invalid URL: ${t}`)}}if(typeof globalThis.fetch=="function"){let c=await globalThis.fetch(t,{method:r,headers:{...s,[_e]:String(a+1)},body:o?JSON.stringify(o):void 0,signal:n.signal});if(i==="dataUrl"){let m=await c.arrayBuffer(),u=new Uint8Array(m),d="";for(let h=0;h<u.length;h++)d+=String.fromCharCode(u[h]);let g=btoa(d);return`data:${c.headers.get("content-type")||"application/octet-stream"};base64,${g}`}let p=c.headers.get("content-type");return i==="json"||p&&p.includes("application/json")?c.json():c.text()}throw new Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:3e4,cost:5}),bn=v("storeGet",f.object({key:f.string}),f.any,async({key:e},n)=>{let t=$(e,n);return n.capabilities.store?.get(t)},{docs:"Store Get",cost:5}),wn=v("storeSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{let r=$(e,t),s=$(n,t);return t.capabilities.store?.set(r,s)},{docs:"Store Set",cost:5}),Sn=v("storeQuery",f.object({query:f.any}),f.array(f.any),async({query:e},n)=>n.capabilities.store?.query?.($(e,n))??[],{docs:"Store Query",cost:5}),En=v("storeVectorSearch",f.object({collection:f.string.optional,vector:f.array(f.number),k:f.number.optional}),f.array(f.any),async({collection:e,vector:n,k:t},r)=>r.capabilities.store?.vectorSearch?.($(e,r),$(n,r),$(t,r))??[],{docs:"Vector Search",cost:(e,n)=>5+($(e.k,n)??5)}),$n=v("llmPredict",f.object({prompt:f.string,options:f.any.optional}),f.string,async({prompt:e,options:n},t)=>{if(!t.capabilities.llm?.predict)throw new Error("Capability 'llm.predict' missing");return t.capabilities.llm.predict($(e,t),$(n,t))},{docs:"LLM Predict",timeoutMs:12e4,cost:100}),xn=v("agentRun",f.object({agentId:f.any,input:f.any}),f.any,async({agentId:e,input:n},t)=>{let r=$(e,t),s=$(n,t),o=s;if(s&&typeof s=="object"&&!Array.isArray(s)){o={};for(let a in s)o[a]=$(s[a],t)}if(Te(r)){let a=Ae(r),l={...t,args:o,state:{},consts:new Set,output:void 0,error:void 0},c=t.resolver("seq");if(!c)throw new Error("seq atom not found");if(await c.exec(a,l),l.error)throw new Error(l.error.message||"Sub-agent failed");return l.output}if(r&&typeof r=="object"&&"op"in r){let a={...t,args:o,state:{},consts:new Set,output:void 0,error:void 0},l=t.resolver("seq");if(!l)throw new Error("seq atom not found");if(await l.exec(r,a),a.error)throw new Error(a.error.message||"Sub-agent failed");return a.output}if(!t.capabilities.agent?.run)throw new Error("Capability 'agent.run' missing");let i=await t.capabilities.agent.run(r,o);if(i&&typeof i=="object"&&"fuelUsed"in i&&typeof i.fuelUsed=="number"){if(i.error)throw new Error(i.error.message||"Sub-agent failed");return i.result}return i},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),Tn=v("transpileCode",f.object({code:f.string}),f.any,async({code:e},n)=>{if(!n.capabilities.code?.transpile)throw new Error("Capability 'code.transpile' missing. Enable code transpilation by providing the code capability.");let t=$(e,n);try{return n.capabilities.code.transpile(t)}catch(r){throw new Error(`Code transpilation failed: ${r.message}`)}},{docs:"Transpile AsyncJS code to AST",cost:1}),Oe=10,An=v("runCode",f.object({code:f.string,args:f.record(f.any).optional}),f.any,async({code:e,args:n},t)=>{let r=t.runCodeDepth??0;if(r>=Oe)throw new Error(`runCode recursion limit exceeded (max ${Oe}). This prevents infinite loops from dynamically generated code calling runCode.`);if(!t.capabilities.code?.transpile)throw new Error("Capability 'code.transpile' missing. Enable dynamic code execution by providing the code capability.");let s=$(e,t),o=n?$(n,t):{},i;try{i=t.capabilities.code.transpile(s)}catch(l){throw new Error(`Code transpilation failed: ${l.message}`)}if(i.op!=="seq")throw new Error("Transpiled code must be a seq node");let a=G(t);if(a.args=o,a.output=void 0,a.runCodeDepth=r+1,await q.exec(i,a),a.error){t.error=a.error;return}return a.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),jn=v("jsonParse",f.object({str:f.string}),f.any,async({str:e},n)=>JSON.parse($(e,n)),{docs:"Parse JSON",cost:1}),vn=v("jsonStringify",f.object({value:f.any}),f.string,async({value:e},n)=>JSON.stringify($(e,n)),{docs:"Stringify JSON",cost:1}),Mn=v("xmlParse",f.object({str:f.string}),f.any,async({str:e},n)=>{if(!n.capabilities.xml?.parse)throw new Error("Capability 'xml.parse' missing");return n.capabilities.xml.parse($(e,n))},{docs:"Parse XML",cost:1}),kn=v("memoize",f.object({key:f.string.optional,steps:f.array(f.any)}),f.any,async({key:e,steps:n},t)=>{t.memo||(t.memo=new Map);let r=$(e,t)??await je.exec({value:n,algorithm:"SHA-256"},t);if(t.memo.has(r))return t.memo.get(r);let s=G(t);await q.exec({op:"seq",steps:n},s);let o=s.output??s.state.result;return t.memo.set(r,o),o},{docs:"Memoize steps result in memory",cost:1}),Cn=v("cache",f.object({key:f.string.optional,steps:f.array(f.any),ttlMs:f.number.optional}),f.any,async({key:e,steps:n,ttlMs:t},r)=>{if(!r.capabilities.store)throw new Error("Capability 'store' missing for caching");let o=`cache:${$(e,r)??await je.exec({value:n,algorithm:"SHA-256"},r)}`,i=await r.capabilities.store.get(o);if(i)if(typeof i=="object"&&i._exp){if(Date.now()<i._exp)return i.val}else return i;let a=G(r);await q.exec({op:"seq",steps:n},a);let l=a.output??a.state.result,c=Date.now()+(t??24*3600*1e3);if((r.fuel.current-=5)<=0)throw new Error("Out of Fuel");return await r.capabilities.store.set(o,{val:l,_exp:c}),l},{docs:"Cache steps result in store with TTL",cost:5}),Nn=v("random",f.object({min:f.number.optional,max:f.number.optional,format:f.string.optional,length:f.number.optional}),f.any,async({min:e,max:n,format:t,length:r},s)=>{let o=$(t,s)??"float",i=$(r,s)??10,a=$(e,s)??0,l=$(n,s)??1;if(o==="base36"){let u="0123456789abcdefghijklmnopqrstuvwxyz",d="";if(typeof crypto<"u"&&crypto.getRandomValues){let g=new Uint8Array(i);crypto.getRandomValues(g);for(let b=0;b<i;b++)d+=u[g[b]%36]}else for(let g=0;g<i;g++)d+=u.charAt(Math.floor(Math.random()*36));return d}let c;if(typeof crypto<"u"&&crypto.getRandomValues){let u=new Uint32Array(1);crypto.getRandomValues(u),c=u[0]/4294967296}else c=Math.random();let p=l-a,m=c*p+a;return o==="integer"?Math.floor(m):m},{docs:"Generate Random",cost:1}),Rn=v("uuid",void 0,f.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return(e==="x"?n:n&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),je=v("hash",f.object({value:f.any,algorithm:f.string.optional}),f.string,async({value:e,algorithm:n},t)=>{let r=typeof e=="string"?e:JSON.stringify($(e,t)),s=$(n,t)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let a=new TextEncoder().encode(r),l=await crypto.subtle.digest(s,a);return Array.from(new Uint8Array(l)).map(p=>p.toString(16).padStart(2,"0")).join("")}let o=0;for(let i=0;i<r.length;i++){let a=r.charCodeAt(i);o=(o<<5)-o+a,o|=0}return String(o)},{docs:"Hash a value",cost:1}),Pn=v("consoleLog",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=$(e,n);n.trace&&n.trace.push({op:"console.log",input:{message:t},stateDiff:{},result:t,fuelBefore:n.fuel.current,fuelAfter:n.fuel.current,timestamp:new Date().toISOString()})},{docs:"Log to trace",cost:.1}),In=v("consoleWarn",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=$(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.warnings||(n.warnings=[]),n.warnings.push(r),n.trace&&n.trace.push({op:"console.warn",input:{message:t},stateDiff:{},result:t,fuelBefore:n.fuel.current,fuelAfter:n.fuel.current,timestamp:new Date().toISOString()})},{docs:"Add warning",cost:.1}),Bn=v("consoleError",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=$(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.error=new F(r,"console.error")},{docs:"Emit error and stop",cost:.1}),_n=v("storeProcedure",f.object({ast:f.any,ttl:f.number.optional,maxSize:f.number.optional}),f.string,async({ast:e,ttl:n,maxSize:t},r)=>{let s=$(e,r),o=n?$(n,r):It,i=t?$(t,r):Bt;if(!s||typeof s!="object"||!s.op)throw new Error('Invalid AST: must be an object with an "op" property');let a=JSON.stringify(s);if(a.length>i)throw new Error(`AST too large: ${a.length} bytes exceeds limit of ${i} bytes. Consider reducing AST size or using a shorter TTL.`);let l=_t(),c=Date.now();return te.set(l,{ast:s,createdAt:c,expiresAt:c+o}),l},{docs:"Store an AST and return a token for later execution",cost:1}),On=v("releaseProcedure",f.object({token:f.string}),f.boolean,async({token:e},n)=>{let t=$(e,n);return te.delete(t)},{docs:"Release a stored procedure by token",cost:.1}),Dn=v("clearExpiredProcedures",void 0,f.number,async()=>{let e=Date.now(),n=0;for(let[t,r]of te)e>r.expiresAt&&(te.delete(t),n++);return n},{docs:"Clear all expired procedures and return count",cost:.5}),Ue={seq:q,if:Wt,while:Vt,return:zt,try:Jt,Error:Zt,varSet:Gt,constSet:Ht,varGet:Kt,varsImport:Yt,varsLet:Xt,varsExport:Qt,scope:en,map:tn,filter:nn,reduce:rn,find:sn,push:on,len:an,split:ln,join:cn,template:un,regexMatch:fn,pick:pn,omit:mn,merge:dn,keys:gn,httpFetch:hn,storeGet:bn,storeSet:wn,storeQuery:Sn,storeVectorSearch:En,llmPredict:$n,agentRun:xn,transpileCode:Tn,runCode:An,jsonParse:jn,jsonStringify:vn,xmlParse:Mn,memoize:kn,cache:Cn,random:Nn,uuid:Rn,hash:je,consoleLog:Pn,consoleWarn:In,consoleError:Bn,storeProcedure:_n,releaseProcedure:On,clearExpiredProcedures:Dn};var Fn=new Set(["true","false","null","undefined","and","or","not"]);function Un(e,n){let t=e.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),r=[],s=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,o;for(;(o=s.exec(t))!==null;)r.push(o[1]);let a=[...new Set(r)].filter(l=>!Fn.has(l)&&!(l in n)&&!new RegExp(`\\b${l}\\s*\\(`).test(t));a.length>0&&console.warn(`[Agent99 Builder] Condition "${e}" references variables not in vars mapping: ${a.join(", ")}. Add them to vars or use AsyncJS syntax (ajs\`...\`) which handles this automatically.`)}function pe(e,n){Un(e,n);let t=qn(e),r=ze(t,0,n);if(r.pos<t.length){let s=t.slice(r.pos).join(" ");throw new Error(`Unsupported condition syntax near '${s}' in: ${e}
2
- Supported: comparisons, &&, ||, !, arithmetic, member access (a.b), literals`)}return r.node}function qn(e){let n=[],t=0;for(;t<e.length;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)break;if(e[t]==='"'||e[t]==="'"){let r=e[t++],s="";for(;t<e.length&&e[t]!==r;)e[t]==="\\"&&t+1<e.length&&t++,s+=e[t++];t++,n.push(JSON.stringify(s));continue}if(e.slice(t,t+2).match(/^(&&|\|\||==|!=|>=|<=)$/)){n.push(e.slice(t,t+2)),t+=2;continue}if("+-*/%><!().?:[]".includes(e[t])){n.push(e[t]),t++;continue}if(/\d/.test(e[t])){let r="";for(;t<e.length&&/[\d.]/.test(e[t]);)r+=e[t++];n.push(r);continue}if(/[a-zA-Z_]/.test(e[t])){let r="";for(;t<e.length&&/[a-zA-Z0-9_]/.test(e[t]);)r+=e[t++];n.push(r);continue}t++}return n}function ze(e,n,t){return Ln(e,n,t)}function Ln(e,n,t){let{node:r,pos:s}=qe(e,n,t);for(;e[s]==="||";){s++;let{node:o,pos:i}=qe(e,s,t);r={$expr:"logical",op:"||",left:r,right:o},s=i}return{node:r,pos:s}}function qe(e,n,t){let{node:r,pos:s}=Le(e,n,t);for(;e[s]==="&&";){s++;let{node:o,pos:i}=Le(e,s,t);r={$expr:"logical",op:"&&",left:r,right:o},s=i}return{node:r,pos:s}}function Le(e,n,t){let{node:r,pos:s}=We(e,n,t),o=["==","!=",">","<",">=","<="];for(;o.includes(e[s]);){let i=e[s++],{node:a,pos:l}=We(e,s,t);r={$expr:"binary",op:i,left:r,right:a},s=l}return{node:r,pos:s}}function We(e,n,t){let{node:r,pos:s}=Ve(e,n,t);for(;e[s]==="+"||e[s]==="-";){let o=e[s++],{node:i,pos:a}=Ve(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function Ve(e,n,t){let{node:r,pos:s}=ve(e,n,t);for(;e[s]==="*"||e[s]==="/"||e[s]==="%";){let o=e[s++],{node:i,pos:a}=ve(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function ve(e,n,t){if(e[n]==="!"||e[n]==="-"){let r=e[n++],{node:s,pos:o}=ve(e,n,t);return{node:{$expr:"unary",op:r,argument:s},pos:o}}return Wn(e,n,t)}function Wn(e,n,t){let r=e[n];if(r==="("){let{node:s,pos:o}=ze(e,n+1,t);return{node:s,pos:o+1}}if(r&&r.startsWith('"'))return{node:{$expr:"literal",value:JSON.parse(r)},pos:n+1};if(r&&/^\d/.test(r))return{node:{$expr:"literal",value:parseFloat(r)},pos:n+1};if(r==="true")return{node:{$expr:"literal",value:!0},pos:n+1};if(r==="false")return{node:{$expr:"literal",value:!1},pos:n+1};if(r==="null")return{node:{$expr:"literal",value:null},pos:n+1};if(r&&/^[a-zA-Z_]/.test(r)){let s={$expr:"ident",name:r},o=n+1;for(;e[o]===".";){o++;let i=e[o++];s={$expr:"member",object:s,property:i}}return{node:s,pos:o}}return{node:{$expr:"literal",value:null},pos:n+1}}var re=class e{steps=[];atoms;proxy;constructor(n){return this.atoms=n,this.proxy=new Proxy(this,{get:(t,r,s)=>{if(r in t)return t[r];if(typeof r=="string"&&r in t.atoms)return o=>{let i=t.atoms[r];return t.add(i.create(o)),s}}}),this.proxy}add(n){return this.steps.push(n),this.proxy}as(n){if(this.steps.length===0)throw new Error("No step to capture");let t=this.steps[this.steps.length-1];return t.result=n,this.proxy}step(n){return this.add(n)}return(n){let t=this.atoms.return;if(!t)throw new Error("Atom 'return' not found");let r=n.schema??n;return this.add(t.create({schema:r}))}toJSON(){return{op:"seq",steps:[...this.steps]}}varsImport(n){return this.add(this.atoms.varsImport.create({keys:n}))}varsExport(n){return this.add(this.atoms.varsExport.create({keys:n}))}if(n,t,r,s){let o=new e(this.atoms);r(o);let i;if(s){let c=new e(this.atoms);s(c),i=c.steps}let a=pe(n,t),l=this.atoms.if;return this.add(l.create({condition:a,then:o.steps,else:i}))}while(n,t,r){let s=new e(this.atoms);r(s);let o=pe(n,t),i=this.atoms.while;return this.add(i.create({condition:o,body:s.steps}))}scope(n){let t=new e(this.atoms);n(t);let r=this.atoms.scope;return this.add(r.create({steps:t.steps}))}map(n,t,r){let s=new e(this.atoms);r(s);let o=this.atoms.map;return this.add(o.create({items:n,as:t,steps:s.steps}))}filter(n,t,r,s={}){let o=pe(r,s),i=this.atoms.filter;return this.add(i.create({items:n,as:t,condition:o}))}find(n,t,r,s={}){let o=pe(r,s),i=this.atoms.find;return this.add(i.create({items:n,as:t,condition:o}))}reduce(n,t,r,s,o){let i=new e(this.atoms);o(i);let a=this.atoms.reduce;return this.add(a.create({items:n,as:t,accumulator:r,initial:s,steps:i.steps}))}memoize(n,t){let r=new e(this.atoms);n(r);let s=this.atoms.memoize;return this.add(s.create({key:t,steps:r.steps}))}cache(n,t,r){let s=new e(this.atoms);n(s);let o=this.atoms.cache;return this.add(o.create({key:t,steps:s.steps,ttlMs:r}))}try(n){let t=new e(this.atoms);n.try(t);let r;if(n.catch){let o=new e(this.atoms);n.catch(o),r=o.steps}let s=this.atoms.try;return this.add(s.create({try:t.steps,catch:r}))}};import{validate as xr}from"tosijs-schema";import*as xt from"acorn";var P=class extends Error{line;column;source;filename;constructor(n,t,r,s){let o=`${s||"<source>"}:${t.line}:${t.column}`;super(`${n} at ${o}`),this.name="TranspileError",this.line=t.line,this.column=t.column,this.source=r,this.filename=s}},O=class extends P{constructor(n,t,r,s){super(n,t,r,s),this.name="SyntaxError"}formatWithContext(n=2){if(!this.source)return this.message;let t=this.source.split(`
1
+ import{s as f,validate as Ee,filter as De}from"tosijs-schema";var ce=Symbol.for("tjs.equals");function fe(e,n){if(e!==null&&typeof e=="object"&&typeof e[ce]=="function")return e[ce](n);if(n!==null&&typeof n=="object"&&typeof n[ce]=="function")return n[ce](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(n);if(n!==null&&typeof n=="object"&&typeof n.Equals=="function")return n.Equals(e);if(e===n||e==null&&n==null)return!0;if(e==null||n===null||n===void 0||typeof e!=typeof n||typeof e!="object")return!1;if(Array.isArray(e)&&Array.isArray(n))return e.length!==n.length?!1:e.every((s,o)=>fe(s,n[o]));if(Array.isArray(e)!==Array.isArray(n))return!1;let t=Object.keys(e),r=Object.keys(n);return t.length!==r.length?!1:t.every(s=>fe(e[s],n[s]))}var D=class{$error=!0;message;op;cause;constructor(n,t,r){this.message=n,this.op=t,this.cause=r}toString(){return`AgentError[${this.op}]: ${this.message}`}toJSON(){return{$error:!0,message:this.message,op:this.op}}};function It(e){return e instanceof D||e&&e.$error===!0}var Q=new Map,_t=3600*1e3,Ot=100*1024,xe="proc_";function Te(e){return typeof e=="string"&&e.startsWith(xe)}function je(e){let n=Q.get(e);if(!n)throw new Error(`Procedure not found: ${e}`);if(Date.now()>n.expiresAt)throw Q.delete(e),new Error(`Procedure expired: ${e}`);return n.ast}function Dt(){return typeof crypto<"u"&&crypto.randomUUID?xe+crypto.randomUUID():xe+Math.random().toString(36).slice(2)+Date.now().toString(36)}var Fe=new Set(["__proto__","constructor","prototype"]);function Re(e){if(Fe.has(e))throw new Error(`Security Error: Access to '${e}' is forbidden`)}var Ft=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function Ut(e){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;let t=n.hostname.toLowerCase();return!!(Ft.has(t)||t.endsWith(".internal")||t.endsWith(".local")||t==="169.254.169.254"||/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t))}catch{return!0}}function qt(e){return!!(/\([^)]*[+*][^)]*\)[+*]/.test(e)||/\(([^|)]+)\|\1\)[+*]/.test(e)||/\(\.\*\)\+/.test(e)||/\(\.\+\)\+/.test(e)||/\(\[.*\]\+\)\+/.test(e))}function G(e){return{...e,state:Object.create(e.state)}}function Lt(e,n){let t={},r=new Set([...Object.keys(e),...Object.keys(n)]);for(let s of r){let o=e[s],i=n[s];i!==o&&(t[s]=i)}return t}function T(e,n){if(e&&typeof e=="object"&&e.$kind==="arg")return n.args[e.path];if(e&&typeof e=="object"&&e.$expr)return B(e,n);if(typeof e=="string"){if(e.startsWith("args.")&&!("args"in n.state))return n.args[e.replace("args.","")];if(e.includes(".")){let t=e.split(".");for(let s of t)if(Fe.has(s))throw new Error(`Security Error: Access to '${s}' is forbidden`);let r=n.state[t[0]];if(r!==void 0){for(let s=1;s<t.length;s++)r=r?.[t[s]];return r}}return e in n.state?n.state[e]:e}if(e&&typeof e=="object"&&!Array.isArray(e)&&e.constructor===Object){let t={};for(let r of Object.keys(e))t[r]=T(e[r],n);return t}return Array.isArray(e)?e.map(t=>T(t,n)):e}function K(e,n,t){return new Proxy(n,{get(r,s){if(s in r)return r[s];let o=t?.[s];throw o?new Error(`${e}.${s} is not available. ${o}`):new Error(`${e}.${s} is not supported in AsyncJS. Check docs for available ${e} methods.`)}})}function X(e){if(e===null)return{type:"null"};if(e===void 0)return{};if(typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string")return e;if(typeof e=="object"&&e!==null&&"schema"in e&&typeof e.schema=="object")return e.schema;let n=typeof e;if(n==="string")return{type:"string"};if(n==="number")return Number.isInteger(e)?{type:"integer"}:{type:"number"};if(n==="boolean")return{type:"boolean"};if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:X(e[0])};if(n==="object"){let t={},r=[];for(let[s,o]of Object.entries(e))t[s]=X(o),r.push(s);return{type:"object",properties:t,required:r}}return{}}var z={Math:K("Math",{PI:Math.PI,E:Math.E,LN2:Math.LN2,LN10:Math.LN10,LOG2E:Math.LOG2E,LOG10E:Math.LOG10E,SQRT2:Math.SQRT2,SQRT1_2:Math.SQRT1_2,abs:Math.abs,ceil:Math.ceil,floor:Math.floor,round:Math.round,trunc:Math.trunc,sign:Math.sign,sqrt:Math.sqrt,cbrt:Math.cbrt,pow:Math.pow,exp:Math.exp,expm1:Math.expm1,log:Math.log,log2:Math.log2,log10:Math.log10,log1p:Math.log1p,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,hypot:Math.hypot,min:Math.min,max:Math.max,clz32:Math.clz32,imul:Math.imul,fround:Math.fround,random:()=>{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]/4294967296}return Math.random()}}),JSON:K("JSON",{parse:e=>JSON.parse(e),stringify:(e,n,t)=>JSON.stringify(e,n,t)}),console:K("console",{log:(...e)=>{},warn:(...e)=>{},error:(...e)=>{},info:(...e)=>{}},{table:"Use console.log with JSON.stringify for structured data.",dir:"Use console.log instead.",trace:"Stack traces are not available in AsyncJS."}),Array:K("Array",{isArray:e=>Array.isArray(e),from:(e,n,t)=>Array.from(e,n,t),of:(...e)=>Array.of(...e)},{prototype:"Prototype access is not allowed."}),Object:K("Object",{keys:e=>Object.keys(e),values:e=>Object.values(e),entries:e=>Object.entries(e),fromEntries:e=>Object.fromEntries(e),assign:(e,...n)=>Object.assign({},e,...n),hasOwn:(e,n)=>Object.hasOwn(e,n)},{prototype:"Prototype access is not allowed.",create:"Use object literals instead.",defineProperty:"Property descriptors are not supported.",getPrototypeOf:"Prototype access is not allowed.",setPrototypeOf:"Prototype modification is not allowed."}),String:K("String",{fromCharCode:(...e)=>String.fromCharCode(...e),fromCodePoint:(...e)=>String.fromCodePoint(...e)}),Number:K("Number",{isNaN:Number.isNaN,isFinite:Number.isFinite,isInteger:Number.isInteger,isSafeInteger:Number.isSafeInteger,parseFloat,parseInt,MAX_VALUE:Number.MAX_VALUE,MIN_VALUE:Number.MIN_VALUE,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,POSITIVE_INFINITY:Number.POSITIVE_INFINITY,NEGATIVE_INFINITY:Number.NEGATIVE_INFINITY,NaN:Number.NaN,EPSILON:Number.EPSILON}),parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,undefined:void 0,null:null,NaN:NaN,Infinity:1/0,filter:(e,n)=>{let t=X(n),r=De(e,t);if(r instanceof Error)throw r;return r},Schema:{...f,response:(e,n)=>{let t=n?.schema!=null?n.schema:X(n);return{type:"json_schema",json_schema:{name:e,strict:!0,schema:t}}},fromExample:e=>X(e),isValid:(e,n)=>n?.schema!=null?Ee(e,n):Ee(e,X(n))},Set:(e=[])=>{let n=[...new globalThis.Set(e)];return{add(t){return n.includes(t)||n.push(t),this},remove(t){let r=n.indexOf(t);return r!==-1&&n.splice(r,1),this},clear(){return n.length=0,this},has(t){return n.includes(t)},get size(){return n.length},toArray(){return[...n]},union(t){let r=t?.toArray?.()??t??[];return z.Set([...n,...r])},intersection(t){let r=t?.toArray?.()??t??[];return z.Set(n.filter(s=>r.includes(s)))},diff(t){let r=t?.toArray?.()??t??[];return z.Set(n.filter(s=>!r.includes(s)))},forEach(t){n.forEach(t)},map(t){return z.Set(n.map(t))},filter(t){return z.Set(n.filter(t))},toJSON(){return[...n]}}},Date:(()=>{let e=t=>({get value(){return t.toISOString()},get timestamp(){return t.getTime()},get year(){return t.getFullYear()},get month(){return t.getMonth()+1},get day(){return t.getDate()},get hours(){return t.getHours()},get minutes(){return t.getMinutes()},get seconds(){return t.getSeconds()},get dayOfWeek(){return t.getDay()},add({years:r=0,months:s=0,days:o=0,hours:i=0,minutes:a=0,seconds:l=0,ms:c=0}={}){let p=new globalThis.Date(t.getTime());return r&&p.setFullYear(p.getFullYear()+r),s&&p.setMonth(p.getMonth()+s),o&&p.setDate(p.getDate()+o),i&&p.setHours(p.getHours()+i),a&&p.setMinutes(p.getMinutes()+a),l&&p.setSeconds(p.getSeconds()+l),c&&p.setMilliseconds(p.getMilliseconds()+c),e(p)},diff(r,s="ms"){let o=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime(),i=t.getTime()-o;switch(s){case"seconds":return i/1e3;case"minutes":return i/6e4;case"hours":return i/36e5;case"days":return i/864e5;default:return i}},format(r="ISO"){return r==="ISO"?t.toISOString():r==="date"?t.toISOString().split("T")[0]:r==="time"?t.toISOString().split("T")[1].split(".")[0]:r.replace("YYYY",String(t.getFullYear())).replace("MM",String(t.getMonth()+1).padStart(2,"0")).replace("DD",String(t.getDate()).padStart(2,"0")).replace("HH",String(t.getHours()).padStart(2,"0")).replace("mm",String(t.getMinutes()).padStart(2,"0")).replace("ss",String(t.getSeconds()).padStart(2,"0"))},isBefore(r){let s=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime();return t.getTime()<s},isAfter(r){let s=typeof r=="object"&&r.timestamp?r.timestamp:new globalThis.Date(r).getTime();return t.getTime()>s},toString(){return t.toISOString()},toJSON(){return t.toISOString()}}),n=t=>{let r=t!==void 0?new globalThis.Date(t):new globalThis.Date;if(isNaN(r.getTime()))throw new Error(`Invalid date: ${t}`);return e(r)};return n.now=()=>globalThis.Date.now(),n.parse=t=>e(new globalThis.Date(t)),n})()},ue={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."},Wt=.01,Pe=1e-4,Be=.001,Vt=new Set(["concat","slice","map","filter","flatMap","flat","toReversed","toSorted","toSpliced","repeat","padStart","padEnd","split","join","replace","replaceAll","substring","substr","trim","trimStart","trimEnd","toLowerCase","toUpperCase","match","matchAll","parse","stringify"]);function B(e,n){if(e==null||typeof e!="object"||!("$expr"in e))return e;if(n.fuel&&(n.fuel.current-=Wt,n.fuel.current<=0))throw new Error("Out of Fuel");switch(e.$expr){case"literal":return e.value;case"ident":{if(e.name in n.state)return n.state[e.name];if(e.name in n.args)return n.args[e.name];if(e.name in z)return z[e.name];if(e.name in ue)throw new Error(ue[e.name]);return}case"member":{let t=B(e.object,n);if(e.optional&&t==null)return;let r=typeof e.property=="object"&&e.property!==null?B(e.property,n):e.property;return Re(String(r)),t?.[r]}case"binary":{let t=B(e.left,n),r=B(e.right,n);switch(e.op){case"+":{let s=t+r;if(typeof s=="string"&&n.fuel&&(n.fuel.current-=s.length*Pe,n.fuel.current<=0)){n.error=new D("Out of Fuel","expr.concat");return}return s}case"-":return t-r;case"*":return t*r;case"/":return t/r;case"%":return t%r;case"**":return t**r;case">":return t>r;case"<":return t<r;case">=":return t>=r;case"<=":return t<=r;case"==":return fe(t,r);case"!=":return!fe(t,r);case"===":return t===r;case"!==":return t!==r;default:throw new Error(`Unknown binary operator: ${e.op}`)}}case"unary":{let t=B(e.argument,n);switch(e.op){case"!":return!t;case"-":return-t;case"+":return+t;case"typeof":return typeof t;default:throw new Error(`Unknown unary operator: ${e.op}`)}}case"logical":{let t=B(e.left,n);return e.op==="&&"?t&&B(e.right,n):e.op==="??"?t??B(e.right,n):t||B(e.right,n)}case"conditional":{let t=B(e.test,n);return B(t?e.consequent:e.alternate,n)}case"array":return e.elements.map(t=>B(t,n));case"object":{let t={};for(let r of e.properties)t[r.key]=B(r.value,n);return t}case"call":{if(e.callee==="Error"){let r=e.arguments.map(o=>B(o,n)),s=typeof r[0]=="string"?r[0]:"Error";n.error=new D(s,"Error");return}if(e.callee in z){let r=z[e.callee];if(typeof r=="function"){let s=e.arguments.map(o=>B(o,n));return r(...s)}}throw n.resolver(e.callee)?new Error(`Atom calls in expressions not yet supported: ${e.callee}`):e.callee in ue?new Error(ue[e.callee]):new Error(`Unknown function: ${e.callee}`)}case"methodCall":{let t=B(e.object,n);if(e.optional&&t==null)return;let r=e.method;if(Re(r),t==null)throw new Error(`Cannot call method '${r}' on ${t}`);let s=t[r];if(typeof s!="function")throw new Error(`'${r}' is not a function`);let o=e.arguments.map(a=>B(a,n)),i=s.apply(t,o);if(n.fuel&&Vt.has(r)){let a=0;if(typeof i=="string"?a=i.length*Pe:Array.isArray(i)?a=i.length*Be:typeof i=="object"&&i!==null&&(a=Object.keys(i).length*Be),n.fuel.current-=a,n.fuel.current<=0){n.error=new D("Out of Fuel",`expr.${r}`);return}}return i}default:throw new Error(`Unknown expression type: ${e.$expr}`)}}function k(e,n,t,r,s={}){let{docs:o="",timeoutMs:i=1e3,cost:a=1}=typeof s=="string"?{docs:s}:s;return{op:e,inputSchema:n,outputSchema:t,exec:async(c,p)=>{let{op:m,result:u,...d}=c;if(p.error)return;let g=p.trace?{...p.state}:null,b=p.fuel.current,h,S;try{let $=p.costOverrides?.[e],y=$!==void 0?$:a,x=typeof y=="function"?y(d,p):y;if((p.fuel.current-=x)<=0){p.error=new D("Out of Fuel",e);return}let E,w=async()=>r(c,p);if(h=i>0?await Promise.race([w(),new Promise((j,v)=>{E=setTimeout(()=>v(new Error(`Atom '${e}' timed out`)),i)})]).finally(()=>clearTimeout(E)):await w(),c.result){if(p.consts.has(c.result))throw new Error(`Cannot reassign const variable '${c.result}'`);if(h!==void 0&&t&&!Ee(h,t)){p.error=new D(`Output validation failed for '${e}'`,e);return}p.state[c.result]=h,c.resultConst&&p.consts.add(c.result)}}catch($){S=$.message||String($),p.error=new D(S,e,$)}finally{if(p.trace&&g){let $=Lt(g,p.state);p.trace.push({op:e,input:d,stateDiff:$,result:h,error:S,fuelBefore:b,fuelAfter:p.fuel.current,timestamp:new Date().toISOString()})}}},docs:o,timeoutMs:i,cost:a,create:c=>({op:e,...c})}}var q=k("seq",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{for(let t of e){if(n.output!==void 0||n.error)return;let r=n.resolver(t.op);if(!r)throw new Error(`Unknown Atom: ${t.op}`);await r.exec(t,n)}},{docs:"Sequence",timeoutMs:0,cost:.1}),zt=k("if",f.object({condition:f.any,then:f.array(f.any),else:f.array(f.any).optional}),void 0,async(e,n)=>{B(e.condition,n)?await q.exec({op:"seq",steps:e.then},n):e.else&&await q.exec({op:"seq",steps:e.else},n)},{docs:"If/Else",timeoutMs:0,cost:.1}),Jt=k("while",f.object({condition:f.any,body:f.array(f.any)}),void 0,async(e,n)=>{for(;B(e.condition,n);){if(n.signal?.aborted)throw new Error("Execution aborted");if((n.fuel.current-=.1)<=0)throw new Error("Out of Fuel");if(await q.exec({op:"seq",steps:e.body},n),n.output!==void 0||n.error)return}},{docs:"While Loop",timeoutMs:0,cost:.1}),Zt=k("return",void 0,f.any,async(e,n)=>{if(n.error)return n.output=n.error,n.error;if("value"in e){let r=T(e.value,n);if(r!=null&&!It(r)&&(typeof r!="object"||Array.isArray(r))){let s=new D(`Agent must return an object, got ${Array.isArray(r)?"array":typeof r}`,"return");return n.error=s,n.output=s,s}return n.output=r,r}let t={};if(e.schema?.properties){for(let r of Object.keys(e.schema.properties))t[r]=n.state[r];if(e.filter!==!1){let r=De(t,e.schema);r instanceof Error||(t=r)}}return n.output=t,t},{docs:"Return",cost:.1}),Gt=k("try",f.object({try:f.array(f.any),catch:f.array(f.any).optional,catchParam:f.string.optional}),void 0,async(e,n)=>{if(await q.exec({op:"seq",steps:e.try},n),n.error&&e.catch){let t=e.catchParam||"error";n.state[t]=n.error.message,n.state.errorOp=n.error.op,n.error=void 0,await q.exec({op:"seq",steps:e.catch},n)}},{docs:"Try/Catch",timeoutMs:0,cost:.1}),Kt=k("Error",f.object({args:f.array(f.any).optional}),void 0,async(e,n)=>{let t=e.args?.[0]??"Error";n.error=new D(String(t),"Error")},{docs:"Trigger error flow",cost:.1}),Ht=k("varSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{if(t.consts.has(e))throw new Error(`Cannot reassign const variable '${e}'`);t.state[e]=T(n,t)},{docs:"Set Variable",cost:.1}),Yt=k("constSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{if(t.consts.has(e))throw new Error(`Cannot reassign const variable '${e}'`);if(e in t.state)throw new Error(`Cannot redeclare variable '${e}' as const`);t.state[e]=T(n,t),t.consts.add(e)},{docs:"Set Const Variable (immutable)",cost:.1}),Xt=k("varGet",f.object({key:f.string}),f.any,async({key:e},n)=>T(e,n),{docs:"Get Variable",cost:.1}),Qt=k("varsImport",f.object({keys:f.union([f.array(f.string),f.record(f.string)])}),void 0,async({keys:e},n)=>{if(Array.isArray(e))for(let t of e)n.state[t]=T({$kind:"arg",path:t},n);else for(let[t,r]of Object.entries(e))n.state[t]=T({$kind:"arg",path:r},n)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:.2}),en=k("varsLet",f.record(f.any),void 0,async(e,n)=>{for(let t of Object.keys(e))t==="op"||t==="result"||(n.state[t]=T(e[t],n))},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:.1}),tn=k("varsExport",f.object({keys:f.union([f.array(f.string),f.record(f.string)])}),f.record(f.any),async({keys:e},n)=>{let t={};if(Array.isArray(e))for(let r of e)t[r]=T(r,n);else for(let[r,s]of Object.entries(e))t[r]=T(s,n);return t},{docs:"Export variables from the current scope, with optional renaming.",cost:.2}),nn=k("scope",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{let t=G(n);await q.exec({op:"seq",steps:e},t),t.output!==void 0&&(n.output=t.output)},{docs:"Create new scope",timeoutMs:0,cost:.1}),rn=k("map",f.object({items:f.array(f.any),as:f.string,steps:f.array(f.any)}),f.array(f.any),async({items:e,as:n,steps:t},r)=>{let s=[],o=T(e,r);if(!Array.isArray(o))throw new Error("map: items is not an array");for(let i of o){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=i,await q.exec({op:"seq",steps:t},a),s.push(a.state.result??null)}return s},{docs:"Map Array",timeoutMs:0,cost:1}),sn=k("filter",f.object({items:f.array(f.any),as:f.string,condition:f.any}),f.array(f.any),async({items:e,as:n,condition:t},r)=>{let s=[],o=T(e,r);if(!Array.isArray(o))throw new Error("filter: items is not an array");for(let i of o){if(r.signal?.aborted)throw new Error("Execution aborted");let a=G(r);a.state[n]=i,B(t,a)&&s.push(i)}return s},{docs:"Filter Array",timeoutMs:0,cost:1}),on=k("reduce",f.object({items:f.array(f.any),as:f.string,accumulator:f.string,initial:f.any,steps:f.array(f.any)}),f.any,async({items:e,as:n,accumulator:t,initial:r,steps:s},o)=>{let i=T(e,o),a=T(r,o);if(!Array.isArray(i))throw new Error("reduce: items is not an array");let l=a;for(let c of i){if(o.signal?.aborted)throw new Error("Execution aborted");let p=G(o);p.state[n]=c,p.state[t]=l,await q.exec({op:"seq",steps:s},p),l=p.state.result??l}return l},{docs:"Reduce Array",timeoutMs:0,cost:1}),an=k("find",f.object({items:f.array(f.any),as:f.string,condition:f.any}),f.any,async({items:e,as:n,condition:t},r)=>{let s=T(e,r);if(!Array.isArray(s))throw new Error("find: items is not an array");for(let o of s){if(r.signal?.aborted)throw new Error("Execution aborted");let i=G(r);if(i.state[n]=o,B(t,i))return o}return null},{docs:"Find in Array",timeoutMs:0,cost:1}),ln=k("push",f.object({list:f.array(f.any),item:f.any}),f.array(f.any),async({list:e,item:n},t)=>{let r=T(e,t),s=T(n,t);return Array.isArray(r)&&r.push(s),r},{docs:"Push to Array",cost:1}),cn=k("len",f.object({list:f.any}),f.number,async({list:e},n)=>{let t=T(e,n);return Array.isArray(t)||typeof t=="string"?t.length:0},{docs:"Length",cost:1}),un=k("split",f.object({str:f.string,sep:f.string}),f.array(f.string),async({str:e,sep:n},t)=>T(e,t).split(T(n,t)),{docs:"Split String",cost:1}),fn=k("join",f.object({list:f.array(f.string),sep:f.string}),f.string,async({list:e,sep:n},t)=>T(e,t).join(T(n,t)),{docs:"Join String",cost:1}),pn=k("template",f.object({tmpl:f.string,vars:f.record(f.any)}),f.string,async({tmpl:e,vars:n},t)=>T(e,t).replace(/\{\{(\w+)\}\}/g,(s,o)=>String(T(n[o],t)??"")),{docs:"String Template",cost:1}),mn=k("regexMatch",f.object({pattern:f.string,value:f.any}),f.boolean,async({pattern:e,value:n},t)=>{if(qt(e))throw new Error(`Suspicious regex pattern rejected (potential ReDoS): ${e}`);let r=T(n,t);return new RegExp(e).test(r)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),dn=k("pick",f.object({obj:f.record(f.any),keys:f.array(f.string)}),f.record(f.any),async({obj:e,keys:n},t)=>{let r=T(e,t),s=T(n,t),o={};return r&&Array.isArray(s)&&s.forEach(i=>o[i]=r[i]),o},{docs:"Pick Keys",cost:1}),gn=k("omit",f.object({obj:f.record(f.any),keys:f.array(f.string)}),f.record(f.any),async({obj:e,keys:n},t)=>{let r=T(e,t),s=new Set(T(n,t)),o={};return r&&Object.keys(r).forEach(i=>{s.has(i)||(o[i]=r[i])}),o},{docs:"Omit Keys",cost:1}),yn=k("merge",f.object({a:f.record(f.any),b:f.record(f.any)}),f.record(f.any),async({a:e,b:n},t)=>({...T(e,t),...T(n,t)}),{docs:"Merge Objects",cost:1}),hn=k("keys",f.object({obj:f.record(f.any)}),f.array(f.string),async({obj:e},n)=>Object.keys(T(e,n)??{}),{docs:"Object Keys",cost:1}),Ie=10,_e="X-Agent-Depth";function bn(e,n){try{let r=new URL(e).hostname.toLowerCase();for(let s of n){let o=s.toLowerCase();if(o.startsWith("*.")){let i=o.slice(1);if(r.endsWith(i)||r===o.slice(2))return!0}else if(r===o)return!0}return!1}catch{return!1}}var wn=k("httpFetch",f.object({url:f.string,method:f.string.optional,headers:f.record(f.string).optional,body:f.any.optional,responseType:f.string.optional}),f.any,async(e,n)=>{let t=T(e.url,n),r=T(e.method,n),s=T(e.headers,n)||{},o=T(e.body,n),i=T(e.responseType,n),a=n.context?.requestDepth??0;if(a>=Ie)throw new Error(`Agent request depth exceeded (max ${Ie}). This prevents recursive agent loops.`);if(n.capabilities.fetch)return n.capabilities.fetch(t,{method:r,headers:{...s,[_e]:String(a+1)},body:o,signal:n.signal,responseType:i});let l=n.context?.allowedFetchDomains;if(l){if(!bn(t,l))throw new Error(`Fetch blocked: domain not in allowlist. Allowed: ${l.join(", ")}`)}else{if(Ut(t))throw new Error("Blocked URL: private/internal addresses not allowed in default fetch");try{let p=new URL(t).hostname.toLowerCase();if(p!=="localhost"&&p!=="127.0.0.1"&&p!=="[::1]")throw new Error("Fetch blocked: no allowedFetchDomains configured. Set ctx.context.allowedFetchDomains or provide a custom fetch capability.")}catch(c){throw c.message.includes("allowedFetchDomains")?c:new Error(`Invalid URL: ${t}`,{cause:c})}}if(typeof globalThis.fetch=="function"){let c=await globalThis.fetch(t,{method:r,headers:{...s,[_e]:String(a+1)},body:o?JSON.stringify(o):void 0,signal:n.signal});if(i==="dataUrl"){let m=await c.arrayBuffer(),u=new Uint8Array(m),d="";for(let h=0;h<u.length;h++)d+=String.fromCharCode(u[h]);let g=btoa(d);return`data:${c.headers.get("content-type")||"application/octet-stream"};base64,${g}`}let p=c.headers.get("content-type");return i==="json"||p&&p.includes("application/json")?c.json():c.text()}throw new Error("Capability 'fetch' missing and no global fetch available")},{docs:"HTTP Fetch",timeoutMs:3e4,cost:5}),Sn=k("storeGet",f.object({key:f.string}),f.any,async({key:e},n)=>{let t=T(e,n);return n.capabilities.store?.get(t)},{docs:"Store Get",cost:5}),$n=k("storeSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{let r=T(e,t),s=T(n,t);return t.capabilities.store?.set(r,s)},{docs:"Store Set",cost:5}),En=k("storeQuery",f.object({query:f.any}),f.array(f.any),async({query:e},n)=>n.capabilities.store?.query?.(T(e,n))??[],{docs:"Store Query",cost:5}),xn=k("storeVectorSearch",f.object({collection:f.string.optional,vector:f.array(f.number),k:f.number.optional}),f.array(f.any),async({collection:e,vector:n,k:t},r)=>r.capabilities.store?.vectorSearch?.(T(e,r),T(n,r),T(t,r))??[],{docs:"Vector Search",cost:(e,n)=>5+(T(e.k,n)??5)}),Tn=k("llmPredict",f.object({prompt:f.string,options:f.any.optional}),f.string,async({prompt:e,options:n},t)=>{if(!t.capabilities.llm?.predict)throw new Error("Capability 'llm.predict' missing");return t.capabilities.llm.predict(T(e,t),T(n,t))},{docs:"LLM Predict",timeoutMs:12e4,cost:100}),jn=k("agentRun",f.object({agentId:f.any,input:f.any}),f.any,async({agentId:e,input:n},t)=>{let r=T(e,t),s=T(n,t),o=s;if(s&&typeof s=="object"&&!Array.isArray(s)){o={};for(let a in s)o[a]=T(s[a],t)}if(Te(r)){let a=je(r),l={...t,args:o,state:{},consts:new Set,output:void 0,error:void 0},c=t.resolver("seq");if(!c)throw new Error("seq atom not found");if(await c.exec(a,l),l.error)throw new Error(l.error.message||"Sub-agent failed");return l.output}if(r&&typeof r=="object"&&"op"in r){let a={...t,args:o,state:{},consts:new Set,output:void 0,error:void 0},l=t.resolver("seq");if(!l)throw new Error("seq atom not found");if(await l.exec(r,a),a.error)throw new Error(a.error.message||"Sub-agent failed");return a.output}if(!t.capabilities.agent?.run)throw new Error("Capability 'agent.run' missing");let i=await t.capabilities.agent.run(r,o);if(i&&typeof i=="object"&&"fuelUsed"in i&&typeof i.fuelUsed=="number"){if(i.error)throw new Error(i.error.message||"Sub-agent failed");return i.result}return i},{docs:"Run Sub-Agent (accepts procedure token, AST, or agent ID)",cost:1}),An=k("transpileCode",f.object({code:f.string}),f.any,async({code:e},n)=>{if(!n.capabilities.code?.transpile)throw new Error("Capability 'code.transpile' missing. Enable code transpilation by providing the code capability.");let t=T(e,n);try{return n.capabilities.code.transpile(t)}catch(r){throw new Error(`Code transpilation failed: ${r.message}`,{cause:r})}},{docs:"Transpile AsyncJS code to AST",cost:1}),Oe=10,vn=k("runCode",f.object({code:f.string,args:f.record(f.any).optional}),f.any,async({code:e,args:n},t)=>{let r=t.runCodeDepth??0;if(r>=Oe)throw new Error(`runCode recursion limit exceeded (max ${Oe}). This prevents infinite loops from dynamically generated code calling runCode.`);if(!t.capabilities.code?.transpile)throw new Error("Capability 'code.transpile' missing. Enable dynamic code execution by providing the code capability.");let s=T(e,t),o=n?T(n,t):{},i;try{i=t.capabilities.code.transpile(s)}catch(l){throw new Error(`Code transpilation failed: ${l.message}`,{cause:l})}if(i.op!=="seq")throw new Error("Transpiled code must be a seq node");let a=G(t);if(a.args=o,a.output=void 0,a.runCodeDepth=r+1,await q.exec(i,a),a.error){t.error=a.error;return}return a.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),kn=k("jsonParse",f.object({str:f.string}),f.any,async({str:e},n)=>JSON.parse(T(e,n)),{docs:"Parse JSON",cost:1}),Mn=k("jsonStringify",f.object({value:f.any}),f.string,async({value:e},n)=>JSON.stringify(T(e,n)),{docs:"Stringify JSON",cost:1}),Cn=k("xmlParse",f.object({str:f.string}),f.any,async({str:e},n)=>{if(!n.capabilities.xml?.parse)throw new Error("Capability 'xml.parse' missing");return n.capabilities.xml.parse(T(e,n))},{docs:"Parse XML",cost:1}),Nn=k("memoize",f.object({key:f.string.optional,steps:f.array(f.any)}),f.any,async({key:e,steps:n},t)=>{t.memo||(t.memo=new Map);let r=T(e,t)??await Ae.exec({value:n,algorithm:"SHA-256"},t);if(t.memo.has(r))return t.memo.get(r);let s=G(t);await q.exec({op:"seq",steps:n},s);let o=s.output??s.state.result;return t.memo.set(r,o),o},{docs:"Memoize steps result in memory",cost:1}),Rn=k("cache",f.object({key:f.string.optional,steps:f.array(f.any),ttlMs:f.number.optional}),f.any,async({key:e,steps:n,ttlMs:t},r)=>{if(!r.capabilities.store)throw new Error("Capability 'store' missing for caching");let o=`cache:${T(e,r)??await Ae.exec({value:n,algorithm:"SHA-256"},r)}`,i=await r.capabilities.store.get(o);if(i)if(typeof i=="object"&&i._exp){if(Date.now()<i._exp)return i.val}else return i;let a=G(r);await q.exec({op:"seq",steps:n},a);let l=a.output??a.state.result,c=Date.now()+(t??24*3600*1e3);if((r.fuel.current-=5)<=0)throw new Error("Out of Fuel");return await r.capabilities.store.set(o,{val:l,_exp:c}),l},{docs:"Cache steps result in store with TTL",cost:5}),Pn=k("random",f.object({min:f.number.optional,max:f.number.optional,format:f.string.optional,length:f.number.optional}),f.any,async({min:e,max:n,format:t,length:r},s)=>{let o=T(t,s)??"float",i=T(r,s)??10,a=T(e,s)??0,l=T(n,s)??1;if(o==="base36"){let u="0123456789abcdefghijklmnopqrstuvwxyz",d="";if(typeof crypto<"u"&&crypto.getRandomValues){let g=new Uint8Array(i);crypto.getRandomValues(g);for(let b=0;b<i;b++)d+=u[g[b]%36]}else for(let g=0;g<i;g++)d+=u.charAt(Math.floor(Math.random()*36));return d}let c;if(typeof crypto<"u"&&crypto.getRandomValues){let u=new Uint32Array(1);crypto.getRandomValues(u),c=u[0]/4294967296}else c=Math.random();let p=l-a,m=c*p+a;return o==="integer"?Math.floor(m):m},{docs:"Generate Random",cost:1}),Bn=k("uuid",void 0,f.string,async()=>{if(typeof crypto<"u"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.random()*16|0;return(e==="x"?n:n&3|8).toString(16)})},{docs:"Generate UUID",cost:1}),Ae=k("hash",f.object({value:f.any,algorithm:f.string.optional}),f.string,async({value:e,algorithm:n},t)=>{let r=typeof e=="string"?e:JSON.stringify(T(e,t)),s=T(n,t)||"SHA-256";if(typeof crypto<"u"&&crypto.subtle){let a=new TextEncoder().encode(r),l=await crypto.subtle.digest(s,a);return Array.from(new Uint8Array(l)).map(p=>p.toString(16).padStart(2,"0")).join("")}let o=0;for(let i=0;i<r.length;i++){let a=r.charCodeAt(i);o=(o<<5)-o+a,o|=0}return String(o)},{docs:"Hash a value",cost:1}),In=k("consoleLog",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=T(e,n);n.trace&&n.trace.push({op:"console.log",input:{message:t},stateDiff:{},result:t,fuelBefore:n.fuel.current,fuelAfter:n.fuel.current,timestamp:new Date().toISOString()})},{docs:"Log to trace",cost:.1}),_n=k("consoleWarn",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=T(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.warnings||(n.warnings=[]),n.warnings.push(r),n.trace&&n.trace.push({op:"console.warn",input:{message:t},stateDiff:{},result:t,fuelBefore:n.fuel.current,fuelAfter:n.fuel.current,timestamp:new Date().toISOString()})},{docs:"Add warning",cost:.1}),On=k("consoleError",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=T(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.error=new D(r,"console.error")},{docs:"Emit error and stop",cost:.1}),Dn=k("storeProcedure",f.object({ast:f.any,ttl:f.number.optional,maxSize:f.number.optional}),f.string,async({ast:e,ttl:n,maxSize:t},r)=>{let s=T(e,r),o=n?T(n,r):_t,i=t?T(t,r):Ot;if(!s||typeof s!="object"||!s.op)throw new Error('Invalid AST: must be an object with an "op" property');let a=JSON.stringify(s);if(a.length>i)throw new Error(`AST too large: ${a.length} bytes exceeds limit of ${i} bytes. Consider reducing AST size or using a shorter TTL.`);let l=Dt(),c=Date.now();return Q.set(l,{ast:s,createdAt:c,expiresAt:c+o}),l},{docs:"Store an AST and return a token for later execution",cost:1}),Fn=k("releaseProcedure",f.object({token:f.string}),f.boolean,async({token:e},n)=>{let t=T(e,n);return Q.delete(t)},{docs:"Release a stored procedure by token",cost:.1}),Un=k("clearExpiredProcedures",void 0,f.number,async()=>{let e=Date.now(),n=0;for(let[t,r]of Q)e>r.expiresAt&&(Q.delete(t),n++);return n},{docs:"Clear all expired procedures and return count",cost:.5}),Ue={seq:q,if:zt,while:Jt,return:Zt,try:Gt,Error:Kt,varSet:Ht,constSet:Yt,varGet:Xt,varsImport:Qt,varsLet:en,varsExport:tn,scope:nn,map:rn,filter:sn,reduce:on,find:an,push:ln,len:cn,split:un,join:fn,template:pn,regexMatch:mn,pick:dn,omit:gn,merge:yn,keys:hn,httpFetch:wn,storeGet:Sn,storeSet:$n,storeQuery:En,storeVectorSearch:xn,llmPredict:Tn,agentRun:jn,transpileCode:An,runCode:vn,jsonParse:kn,jsonStringify:Mn,xmlParse:Cn,memoize:Nn,cache:Rn,random:Pn,uuid:Bn,hash:Ae,consoleLog:In,consoleWarn:_n,consoleError:On,storeProcedure:Dn,releaseProcedure:Fn,clearExpiredProcedures:Un};var qn=new Set(["true","false","null","undefined","and","or","not"]);function Ln(e,n){let t=e.replace(/"[^"]*"/g,'""').replace(/'[^']*'/g,"''"),r=[],s=/(?<![.])\b([a-zA-Z_][a-zA-Z0-9_]*)\b/g,o;for(;(o=s.exec(t))!==null;)r.push(o[1]);let a=[...new Set(r)].filter(l=>!qn.has(l)&&!(l in n)&&!new RegExp(`\\b${l}\\s*\\(`).test(t));a.length>0&&console.warn(`[Agent99 Builder] Condition "${e}" references variables not in vars mapping: ${a.join(", ")}. Add them to vars or use AsyncJS syntax (ajs\`...\`) which handles this automatically.`)}function pe(e,n){Ln(e,n);let t=Wn(e),r=ze(t,0,n);if(r.pos<t.length){let s=t.slice(r.pos).join(" ");throw new Error(`Unsupported condition syntax near '${s}' in: ${e}
2
+ Supported: comparisons, &&, ||, !, arithmetic, member access (a.b), literals`)}return r.node}function Wn(e){let n=[],t=0;for(;t<e.length;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)break;if(e[t]==='"'||e[t]==="'"){let r=e[t++],s="";for(;t<e.length&&e[t]!==r;)e[t]==="\\"&&t+1<e.length&&t++,s+=e[t++];t++,n.push(JSON.stringify(s));continue}if(e.slice(t,t+2).match(/^(&&|\|\||==|!=|>=|<=)$/)){n.push(e.slice(t,t+2)),t+=2;continue}if("+-*/%><!().?:[]".includes(e[t])){n.push(e[t]),t++;continue}if(/\d/.test(e[t])){let r="";for(;t<e.length&&/[\d.]/.test(e[t]);)r+=e[t++];n.push(r);continue}if(/[a-zA-Z_]/.test(e[t])){let r="";for(;t<e.length&&/[a-zA-Z0-9_]/.test(e[t]);)r+=e[t++];n.push(r);continue}t++}return n}function ze(e,n,t){return Vn(e,n,t)}function Vn(e,n,t){let{node:r,pos:s}=qe(e,n,t);for(;e[s]==="||";){s++;let{node:o,pos:i}=qe(e,s,t);r={$expr:"logical",op:"||",left:r,right:o},s=i}return{node:r,pos:s}}function qe(e,n,t){let{node:r,pos:s}=Le(e,n,t);for(;e[s]==="&&";){s++;let{node:o,pos:i}=Le(e,s,t);r={$expr:"logical",op:"&&",left:r,right:o},s=i}return{node:r,pos:s}}function Le(e,n,t){let{node:r,pos:s}=We(e,n,t),o=["==","!=",">","<",">=","<="];for(;o.includes(e[s]);){let i=e[s++],{node:a,pos:l}=We(e,s,t);r={$expr:"binary",op:i,left:r,right:a},s=l}return{node:r,pos:s}}function We(e,n,t){let{node:r,pos:s}=Ve(e,n,t);for(;e[s]==="+"||e[s]==="-";){let o=e[s++],{node:i,pos:a}=Ve(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function Ve(e,n,t){let{node:r,pos:s}=ve(e,n,t);for(;e[s]==="*"||e[s]==="/"||e[s]==="%";){let o=e[s++],{node:i,pos:a}=ve(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function ve(e,n,t){if(e[n]==="!"||e[n]==="-"){let r=e[n++],{node:s,pos:o}=ve(e,n,t);return{node:{$expr:"unary",op:r,argument:s},pos:o}}return zn(e,n,t)}function zn(e,n,t){let r=e[n];if(r==="("){let{node:s,pos:o}=ze(e,n+1,t);return{node:s,pos:o+1}}if(r&&r.startsWith('"'))return{node:{$expr:"literal",value:JSON.parse(r)},pos:n+1};if(r&&/^\d/.test(r))return{node:{$expr:"literal",value:parseFloat(r)},pos:n+1};if(r==="true")return{node:{$expr:"literal",value:!0},pos:n+1};if(r==="false")return{node:{$expr:"literal",value:!1},pos:n+1};if(r==="null")return{node:{$expr:"literal",value:null},pos:n+1};if(r&&/^[a-zA-Z_]/.test(r)){let s={$expr:"ident",name:r},o=n+1;for(;e[o]===".";){o++;let i=e[o++];s={$expr:"member",object:s,property:i}}return{node:s,pos:o}}return{node:{$expr:"literal",value:null},pos:n+1}}var re=class e{steps=[];atoms;proxy;constructor(n){return this.atoms=n,this.proxy=new Proxy(this,{get:(t,r,s)=>{if(r in t)return t[r];if(typeof r=="string"&&r in t.atoms)return o=>{let i=t.atoms[r];return t.add(i.create(o)),s}}}),this.proxy}add(n){return this.steps.push(n),this.proxy}as(n){if(this.steps.length===0)throw new Error("No step to capture");let t=this.steps[this.steps.length-1];return t.result=n,this.proxy}step(n){return this.add(n)}return(n){let t=this.atoms.return;if(!t)throw new Error("Atom 'return' not found");let r=n.schema??n;return this.add(t.create({schema:r}))}toJSON(){return{op:"seq",steps:[...this.steps]}}varsImport(n){return this.add(this.atoms.varsImport.create({keys:n}))}varsExport(n){return this.add(this.atoms.varsExport.create({keys:n}))}if(n,t,r,s){let o=new e(this.atoms);r(o);let i;if(s){let c=new e(this.atoms);s(c),i=c.steps}let a=pe(n,t),l=this.atoms.if;return this.add(l.create({condition:a,then:o.steps,else:i}))}while(n,t,r){let s=new e(this.atoms);r(s);let o=pe(n,t),i=this.atoms.while;return this.add(i.create({condition:o,body:s.steps}))}scope(n){let t=new e(this.atoms);n(t);let r=this.atoms.scope;return this.add(r.create({steps:t.steps}))}map(n,t,r){let s=new e(this.atoms);r(s);let o=this.atoms.map;return this.add(o.create({items:n,as:t,steps:s.steps}))}filter(n,t,r,s={}){let o=pe(r,s),i=this.atoms.filter;return this.add(i.create({items:n,as:t,condition:o}))}find(n,t,r,s={}){let o=pe(r,s),i=this.atoms.find;return this.add(i.create({items:n,as:t,condition:o}))}reduce(n,t,r,s,o){let i=new e(this.atoms);o(i);let a=this.atoms.reduce;return this.add(a.create({items:n,as:t,accumulator:r,initial:s,steps:i.steps}))}memoize(n,t){let r=new e(this.atoms);n(r);let s=this.atoms.memoize;return this.add(s.create({key:t,steps:r.steps}))}cache(n,t,r){let s=new e(this.atoms);n(s);let o=this.atoms.cache;return this.add(o.create({key:t,steps:s.steps,ttlMs:r}))}try(n){let t=new e(this.atoms);n.try(t);let r;if(n.catch){let o=new e(this.atoms);n.catch(o),r=o.steps}let s=this.atoms.try;return this.add(s.create({try:t.steps,catch:r}))}};import{validate as Ar}from"tosijs-schema";import*as jt from"acorn";var P=class extends Error{line;column;source;filename;constructor(n,t,r,s){let o=`${s||"<source>"}:${t.line}:${t.column}`;super(`${n} at ${o}`),this.name="TranspileError",this.line=t.line,this.column=t.column,this.source=r,this.filename=s}},_=class extends P{constructor(n,t,r,s){super(n,t,r,s),this.name="SyntaxError"}formatWithContext(n=2){if(!this.source)return this.message;let t=this.source.split(`
3
3
  `),r=this.line-1,s=Math.max(0,r-n),o=Math.min(t.length-1,r+n),i=[],a=String(o+1).length;for(let l=s;l<=o;l++){let c=String(l+1).padStart(a),p=l===r?">":" ";if(i.push(`${p} ${c} | ${t[l]}`),l===r){let m=" ".repeat(a+4+this.column);i.push(`${m}^ ${this.message.split(" at ")[0]}`)}}return i.join(`
4
- `)}};function L(e){return{depth:e.depth+1,locals:new Map,parent:e,parameters:e.parameters,atoms:e.atoms,warnings:e.warnings,source:e.source,filename:e.filename,options:e.options}}function B(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function Vn(e,n){let t=e.match(n);if(!t)return null;let r=t.index+t[0].length-1,s=1,o=r+1;for(;o<e.length&&s>0;)e[o]==="{"?s++:e[o]==="}"&&s--,o++;if(s!==0)return null;let i=e.slice(r,o),a=[t[0].slice(0,-1)+i,i];return a.index=t.index,a}function Ke(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\btry\s*\{/);if(r){let o=t+r[0].length-1+1,i=1,a=o;for(;a<e.length&&i>0;){let c=e[a];c==="{"?i++:c==="}"&&i--,a++}if(i!==0){n+=e[t],t++;continue}if(e.slice(a).match(/^\s*(catch|finally)\b/))n+=e.slice(t,a),t=a;else{let c=e.slice(o,a-1);n+=`try {${c}} catch (__try_err) { return new (__tjs?.MonadicError ?? Error)(__try_err?.message || String(__try_err), 'try', undefined, undefined, __tjs?.getStack?.()) }`,t=a}}else n+=e[t],t++}return n}function Ye(e){let n=[],t="",r=0,s=0;for(;r<e.length;){let o=e.slice(r).match(/^\bwasm\s*\{/);if(o){let i=r,a=r+o[0].length,l=1,c=a;for(;c<e.length&&l>0;){let E=e[c];E==="{"?l++:E==="}"&&l--,c++}if(l!==0){t+=e[r],r++;continue}let p=e.slice(a,c-1),m,u=c,d=e.slice(c).match(/^\s*fallback\s*\{/);if(d){let E=c+d[0].length;l=1;let S=E;for(;S<e.length&&l>0;){let j=e[S];j==="{"?l++:j==="}"&&l--,S++}l===0&&(m=e.slice(E,S-1),u=S)}let b=Jn(p).map(E=>{let S=Zn(e,i,E);return S?`${E}: ${S}`:E}),h={id:`__tjs_wasm_${s}`,body:p,fallback:m,captures:b,start:i,end:u};n.push(h);let w=m??p,x=b.map(E=>E.split(":")[0].trim()),y=x.length>0?x.join(", "):"",T=x.length>0?`globalThis.${h.id}(${y})`:`globalThis.${h.id}()`,A=`(globalThis.${h.id} ? ${T} : (() => {${w}})())`;t+=A,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function zn(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function Jn(e){let n=e.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),t=new Set,r=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,s;for(;(s=r.exec(n))!==null;)t.add(s[1]);let o=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,i=new Set;for(;(s=o.exec(n))!==null;)i.add(s[1]);for(let u of t){if(!i.has(u))continue;let d=new RegExp(`(?<!\\.)\\b${u}\\b`,"g"),g=new RegExp(`\\.${u}\\b`,"g"),b=n.match(d)?.length||0,h=n.match(g)?.length||0;b<=h&&i.delete(u)}let a=new Set,l=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=l.exec(n))!==null;)a.add(s[1]);let c=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=c.exec(n))!==null;)a.add(s[1]);let p=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","let","const","var","new","this","true","false","null","undefined","typeof","instanceof","in","of","try","catch","finally","throw","async","await","class","extends","super","import","export","default","from","as","static","get","set","yield","console","Math","Array","Object","String","Number","Boolean","Date","JSON","Promise","Map","Set","WeakMap","WeakSet","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","ArrayBuffer","DataView","Error","TypeError","RangeError","length","push","pop","shift","unshift","slice","splice","map","filter","reduce","forEach","find","findIndex","indexOf","includes","globalThis","window","document","Infinity","NaN","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","eval","wasmBuffer"]),m=[];for(let u of i)!a.has(u)&&!p.has(u)&&!zn(u)&&m.push(u);return m.sort()}function Zn(e,n,t){let r=e.slice(0,n),s=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,o=r.match(s);if(!o){let i=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,a=r.match(i);return a?Je(a[1],t):void 0}return Je(o[1],t)}function Je(e,n){let t=e.split(",").map(r=>r.trim());for(let r of t){let s=r.match(new RegExp(`^${n}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(s)return s[1];let o=r.match(new RegExp(`^${n}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(o)return o[1]}}function Xe(e){let n=`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,t=new RegExp(n+"\\s+IsNot\\s+"+n,"g");e=e.replace(t,"IsNot($1, $2)");let r=new RegExp(n+"\\s+Is\\s+"+n,"g");return e=e.replace(r,"Is($1, $2)"),e}function Qe(e){let n=/^[\s]*[([`]/,t=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,r=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,s=e.split(`
4
+ `)}};function L(e){return{depth:e.depth+1,locals:new Map,parent:e,parameters:e.parameters,atoms:e.atoms,warnings:e.warnings,source:e.source,filename:e.filename,options:e.options}}function I(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function Jn(e,n){let t=e.match(n);if(!t)return null;let r=t.index+t[0].length-1,s=1,o=r+1;for(;o<e.length&&s>0;)e[o]==="{"?s++:e[o]==="}"&&s--,o++;if(s!==0)return null;let i=e.slice(r,o),a=[t[0].slice(0,-1)+i,i];return a.index=t.index,a}function He(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\btry\s*\{/);if(r){let o=t+r[0].length-1+1,i=1,a=o;for(;a<e.length&&i>0;){let c=e[a];c==="{"?i++:c==="}"&&i--,a++}if(i!==0){n+=e[t],t++;continue}if(e.slice(a).match(/^\s*(catch|finally)\b/))n+=e.slice(t,a),t=a;else{let c=e.slice(o,a-1);n+=`try {${c}} catch (__try_err) { return new (__tjs?.MonadicError ?? Error)(__try_err?.message || String(__try_err), 'try', undefined, undefined, __tjs?.getStack?.()) }`,t=a}}else n+=e[t],t++}return n}function Ye(e){let n=[],t="",r=0,s=0;for(;r<e.length;){let o=e.slice(r).match(/^\bwasm\s*\{/);if(o){let i=r,a=r+o[0].length,l=1,c=a;for(;c<e.length&&l>0;){let w=e[c];w==="{"?l++:w==="}"&&l--,c++}if(l!==0){t+=e[r],r++;continue}let p=e.slice(a,c-1),m,u=c,d=e.slice(c).match(/^\s*fallback\s*\{/);if(d){let w=c+d[0].length;l=1;let j=w;for(;j<e.length&&l>0;){let v=e[j];v==="{"?l++:v==="}"&&l--,j++}l===0&&(m=e.slice(w,j-1),u=j)}let b=Kn(p).map(w=>{let j=Hn(e,i,w);return j?`${w}: ${j}`:w}),h={id:`__tjs_wasm_${s}`,body:p,fallback:m,captures:b,start:i,end:u};n.push(h);let S=m??p,$=b.map(w=>w.split(":")[0].trim()),y=$.length>0?$.join(", "):"",x=$.length>0?`globalThis.${h.id}(${y})`:`globalThis.${h.id}()`,E=`(globalThis.${h.id} ? ${x} : (() => {${S}})())`;t+=E,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function Xe(e){let n=[],t="",r=0;for(;r<e.length;){let s=/^\b(export\s+)?wasm\s+function\s+(\w+)\s*\(/,o=e.slice(r).match(s);if(!o){t+=e[r],r++;continue}let i=!!o[1],a=o[2],l=r,c=r+o[0].length,p=1,m=c;for(;m<e.length&&p>0;)e[m]==="("?p++:e[m]===")"&&p--,m++;if(p!==0){t+=e[r],r++;continue}let u=e.slice(c,m-1);if(u.match(/^\s*!/))throw new _(`Unsafe wasm functions (with \`!\` marker) are reserved for a future phase. Remove the bang from \`wasm function ${a}\` to declare it as a regular (pure) wasm function, or wait until the unsafe variant is implemented.`,J(e,l));let g,b=m,h=e.slice(m).match(/^\s*:\s*(\w+)/);h&&(g=h[1],b=m+h[0].length);let S=e.slice(b).match(/^\s*\{/);if(!S){t+=e[r],r++;continue}let $=b+S[0].length,y=1,x=$;for(;x<e.length&&y>0;)e[x]==="{"?y++:e[x]==="}"&&y--,x++;if(y!==0){t+=e[r],r++;continue}let E=e.slice($,x-1),w=Zn(u),j=`__tjs_wasm_${a}`,v={id:j,name:a,returnType:g,body:E,captures:w,start:l,end:x};n.push(v);let A=w.map(R=>R.split(":")[0].trim()),C=`${i?"export ":""}function ${a}(${A.join(", ")}) { return globalThis.${j}(${A.join(", ")}) }`;t+=C,r=x}return{source:t,blocks:n}}function Qe(e,n){let{loader:t,importerPath:r}=n;if(!t)return{source:e,blocks:[]};let s=[],o=new Set;function i(c,p){if(!o.has(c.id)){s.push(c),o.add(c.id);for(let[m,u]of p){if(m===c.name||o.has(u.id))continue;new RegExp(`\\b${m}\\s*\\(`).test(c.body)&&i(u,p)}}}let a=/^(\s*)import\s*\{([^}]*?)\}\s*from\s*(['"])([^'"]+)\3\s*;?\s*$/gm;return{source:e.replace(a,(c,p,m,u,d)=>{let g=t.load(d,r);if(!g)return c;let b=new Map;for(let E of g.parseResult.wasmBlocks)E.name&&b.set(E.name,E);if(b.size===0)return c;let h=m.split(",").map(E=>E.trim()).filter(E=>E.length>0),S=[],$=[];for(let E of h){let w=E.match(/^(\w+)(?:\s+as\s+(\w+))?$/);if(!w){$.push(E);continue}let j=w[1],v=w[2]??w[1],A=b.get(j);if(!A){$.push(E);continue}i(A,b);let M=A.captures.map(C=>C.split(":")[0].trim());S.push(`function ${v}(${M.join(", ")}) { return globalThis.${A.id}(${M.join(", ")}) }`)}let y=S.join(`
5
+ `);if($.length===0)return y?`${p}${y}`:`${p}`;let x=`${p}import { ${$.join(", ")} } from '${d}'`;return y?`${x}
6
+ ${p}${y}`:x}),blocks:s}}function Zn(e){let n=e.trim();return n?n.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function Gn(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function Kn(e){let n=e.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),t=new Set,r=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,s;for(;(s=r.exec(n))!==null;)t.add(s[1]);let o=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,i=new Set;for(;(s=o.exec(n))!==null;)i.add(s[1]);for(let u of t){if(!i.has(u))continue;let d=new RegExp(`(?<!\\.)\\b${u}\\b`,"g"),g=new RegExp(`\\.${u}\\b`,"g"),b=n.match(d)?.length||0,h=n.match(g)?.length||0;b<=h&&i.delete(u)}let a=new Set,l=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=l.exec(n))!==null;)a.add(s[1]);let c=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=c.exec(n))!==null;)a.add(s[1]);let p=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","let","const","var","new","this","true","false","null","undefined","typeof","instanceof","in","of","try","catch","finally","throw","async","await","class","extends","super","import","export","default","from","as","static","get","set","yield","console","Math","Array","Object","String","Number","Boolean","Date","JSON","Promise","Map","Set","WeakMap","WeakSet","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","ArrayBuffer","DataView","Error","TypeError","RangeError","length","push","pop","shift","unshift","slice","splice","map","filter","reduce","forEach","find","findIndex","indexOf","includes","globalThis","window","document","Infinity","NaN","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","eval","wasmBuffer"]),m=[];for(let u of i)!a.has(u)&&!p.has(u)&&!Gn(u)&&m.push(u);return m.sort()}function Hn(e,n,t){let r=e.slice(0,n),s=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,o=r.match(s);if(!o){let i=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,a=r.match(i);return a?Je(a[1],t):void 0}return Je(o[1],t)}function Je(e,n){let t=e.split(",").map(r=>r.trim());for(let r of t){let s=r.match(new RegExp(`^${n}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(s)return s[1];let o=r.match(new RegExp(`^${n}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(o)return o[1]}}function et(e){let n=`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,t=new RegExp(n+"\\s+IsNot\\s+"+n,"g");e=e.replace(t,"IsNot($1, $2)");let r=new RegExp(n+"\\s+Is\\s+"+n,"g");return e=e.replace(r,"Is($1, $2)"),e}function tt(e){let n=/^[\s]*[([`]/,t=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,r=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,s=e.split(`
5
7
  `),o=[],i=!1;for(let a=0;a<s.length;a++){let l=s[a],c=a>0?s[a-1]:"";if(i){o.push(l),l.includes("*/")&&(i=!1);continue}let p=l.indexOf("/*"),m=l.indexOf("*/");if(p!==-1&&(m===-1||m<p)){i=!0,o.push(l);continue}if(a>0&&n.test(l)){let u=c.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!t.test(u)&&!r.test(u)){let d=l.match(/^(\s*)/),g=d?d[1]:"",b=l.slice(g.length);o.push(g+";"+b);continue}}o.push(l)}return o.join(`
6
- `)}function Gn(e){let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
7
- `&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let l=t-1;for(;l>=0&&/\s/.test(e[l]);)l--;let c=l>=0?e[l]:"";if(!c||/[=(!,;:{[&|?+\-*%<>~^]/.test(c)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){t++,r="regex";continue}}if(i==="t"&&e.slice(t,t+6)==="typeof"&&(t===0||!/[\w$]/.test(e[t-1]))&&/\s/.test(e[t+6]??"")){let l=t+6;for(;l<e.length&&/\s/.test(e[l]);)l++;if(l<e.length&&/[a-zA-Z_$]/.test(e[l])){let c=l;for(;l<e.length&&/[\w$]/.test(e[l]);)l++;for(;l<e.length;)if(e[l]==="."&&/[a-zA-Z_$]/.test(e[l+1]??""))for(l++;l<e.length&&/[\w$]/.test(e[l]);)l++;else if(e[l]==="?"&&e[l+1]==="."&&/[a-zA-Z_$]/.test(e[l+2]??""))for(l+=2;l<e.length&&/[\w$]/.test(e[l]);)l++;else break;n.push({keywordStart:t,operandEnd:l,operand:e.slice(c,l)}),t=l;continue}}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let a=n[i];o=o.slice(0,a.keywordStart)+`TypeOf(${a.operand})`+o.slice(a.operandEnd)}return o}function et(e){e=Gn(e);let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
8
- `&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let l=t-1;for(;l>=0&&/\s/.test(e[l]);)l--;let c=l>=0?e[l]:"";if(!c||/[=(!,;:{[&|?+\-*%<>~^]/.test(c)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){t++,r="regex";continue}}if(i==="="&&a==="="&&e[t+2]!=="="&&e[t-1]!=="!"){n.push({pos:t,op:"=="}),t+=2;continue}if(i==="!"&&a==="="&&e[t+2]!=="="){n.push({pos:t,op:"!="}),t+=2;continue}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let{pos:a,op:l}=n[i],c=l==="=="?"Eq":"NotEq",p=Hn(o,a),m=Kn(o,a+2),u=o.slice(p,a).trim(),d=o.slice(a+2,m).trim();if(u&&d){let g=o.slice(0,p),b=o.slice(m),w=/[a-zA-Z0-9_$]$/.test(g)?" ":"";o=`${g}${w}${c}(${u}, ${d})${b}`}}return o}function Hn(e,n){let t=n-1;for(;t>=0&&/\s/.test(e[t]);)t--;if(t<0)return 0;let r=0,s=!1,o="";for(;t>=0;){let i=e[t],a=t>0?e[t-1]:"";if(s){i===o&&a!=="\\"&&(s=!1),t--;continue}if((i==='"'||i==="'"||i==="`")&&a!=="\\"){s=!0,o=i,t--;continue}if(i===")"||i==="]"||i==="}"){r++,t--;continue}if(i==="("||i==="["){if(r>0){r--,t--;continue}return t+1}if(i==="{"){if(r>0){r--,t--;continue}return t+1}if(r>0){t--;continue}if(i===";")return t+1;if(/[a-z]/.test(i)){let l=t+1,c=t;for(;c>0&&/[a-z]/i.test(e[c-1]);)c--;let p=e.slice(c,l),m=c>0?e[c-1]:"";if(!/[a-zA-Z0-9_$]/.test(m)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(p))return l;if(p==="new")return c}}if(i===">"&&a==="="||i==="="&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"||i==="&"&&a==="&"||i==="|"&&a==="|"||i==="?"||i===":"||i===",")return t+1;t--}return 0}function Kn(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return e.length;let r=0,s=!1,o="";for(;t<e.length;){let i=e[t],a=t+1<e.length?e[t+1]:"";if(s){i===o&&e[t-1]!=="\\"&&(s=!1),t++;continue}if((i==='"'||i==="'"||i==="`")&&e[t-1]!=="\\"){s=!0,o=i,t++;continue}if(i==="("||i==="["||i==="{"){r++,t++;continue}if(i===")"||i==="]"||i==="}"){if(r>0){r--,t++;continue}return t}if(r>0){t++;continue}if(i===";"||i==="&"&&a==="&"||i==="|"&&a==="|"||i==="?"||i===":"||i===","||(i==="="||i==="!")&&a==="="&&e[t+2]!=="=")return t;t++}return e.length}function tt(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(r){let s=r[1],o=t+r[0].length,i=s,a=!1,l=e.slice(o).match(/^(['"`])([^]*?)\1\s*/);if(l){let u=o+l[0].length,d=e[u],g=d===void 0||u>=e.length||d!=="="&&d!=="{";if(d==="="||d==="{")i=l[2],a=!0,o=u;else if(g){let b=l[0].trim(),h=l[0].slice(b.length);n+=`const ${s} = Type('${s}', ${b})${h}`,t=u;continue}}let c,p=o,m=e.slice(o).match(/^=\s*/);if(m){o+=m[0].length;let u=e.slice(o).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(u){c=u[0],o+=u[0].length,p=o;let d=e.slice(o).match(/^\s*/);d&&(o+=d[0].length)}}if(e[o]==="{"){let u=o+1,d=1,g=u;for(;g<e.length&&d>0;){let A=e[g];A==="{"?d++:A==="}"&&d--,g++}if(d!==0){n+=e[t],t++;continue}let b=e.slice(u,g-1).trim(),h=g,w=b.match(/description\s*:\s*(['"`])([^]*?)\1/);w&&!a&&(i=w[2]);let x,y=b.match(/example\s*:\s*/);if(y){let A=y.index+y[0].length,E=St(b,A);E&&(x=E.value.trim())}let T=b.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(T&&x){let A=T[1].trim(),E=T[2].trim(),S=c?`, ${c}`:"";n+=`const ${s} = Type('${i}', (${A}) => { if (!globalThis.__tjs?.validate(${A}, globalThis.__tjs?.infer(${x}))) return false; ${E} }, ${x}${S})`}else if(T){let A=T[1].trim(),E=T[2].trim(),S=c?`, undefined, ${c}`:"";n+=`const ${s} = Type('${i}', (${A}) => { ${E} }${S})`}else if(x){let A=c?`, ${c}`:"";n+=`const ${s} = Type('${i}', undefined, ${x}${A})`}else c?n+=`const ${s} = Type('${i}', ${c})`:n+=`const ${s} = Type('${i}')`;t=h;continue}else if(c){n+=`const ${s} = Type('${i}', ${c})`,t=p;continue}else if(!l){let u=e.slice(o).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(u){let d=u[0];n+=`const ${s} = Type('${s}', ${d})`,t=o+u[0].length;continue}}}n+=e[t],t++}return n}function nt(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bFunctionPredicate\s+([A-Z_][a-zA-Z0-9_]*)\s*(?:<([^>]+)>)?\s*/);if(r){let s=r[1],o=r[2],i=t+r[0].length;if(e[i]==="{"){let a=1,l=i+1;for(;l<e.length&&a>0;)e[l]==="{"?a++:e[l]==="}"&&a--,l++;if(a===0){let c=e.slice(i+1,l-1).trim(),p=Vn(c,/params\s*:\s*\{/),m=c.match(/returns\s*:\s*(.+?)(?:\n|$)/),u=c.match(/returnContract\s*:\s*['"](\w+)['"]/),d=c.match(/description\s*:\s*(['"])([^]*?)\1/),g=[];p&&g.push(`params: ${p[1]}`),m&&g.push(`returns: ${m[1].trim()}`),u&&g.push(`returnContract: '${u[1]}'`);let b=d?d[2]:s;if(o){let h=o.split(",").map(x=>{let y=x.trim().split("=").map(T=>T.trim());if(y.length===2){let T=y[1]==="any"||y[1]==="undefined"?"null":y[1];return`['${y[0]}', ${T}]`}return`'${y[0]}'`}),w=o.split(",").map(x=>x.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${b}', [${h.join(", ")}], (${w.join(", ")}) => ({ ${g.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${b}', { ${g.join(", ")} })`;t=l;continue}}if(e[i]==="("){let a=1,l=i+1;for(;l<e.length&&a>0;)e[l]==="("?a++:e[l]===")"&&a--,l++;if(a===0){let c=e.slice(i+1,l-1).trim(),p=c.indexOf(",");if(p!==-1){let m=c.slice(0,p).trim(),u=c.slice(p+1).trim();n+=`const ${s} = FunctionPredicate(${u}, ${m})`}else n+=`const ${s} = FunctionPredicate('${s}', ${c})`;t=l;continue}}}n+=e[t],t++}return n}function rt(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(r){let s=r[1],o=r[2],a=t+r[0].length-1+1,l=1,c=a;for(;c<e.length&&l>0;){let x=e[c];x==="{"?l++:x==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,u=o.split(",").map(x=>{let y=x.trim().split("=").map(T=>T.trim());if(y.length===2){let T=y[1]==="any"||y[1]==="undefined"?"null":y[1];return`['${y[0]}', ${T}]`}return`'${y[0]}'`}),d=p,g=d.search(/\bdeclaration\s*\{/);if(g!==-1){let x=d.indexOf("{",g),y=1,T=x+1;for(;T<d.length&&y>0;)d[T]==="{"?y++:d[T]==="}"&&y--,T++;d=d.slice(0,g)+d.slice(T)}let b=d.match(/description\s*:\s*(['"`])([^]*?)\1/),h=d.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),w=b?b[2]:s;if(h){let x=h[1].trim().split(",").map(S=>S.trim()),y=h[2].trim(),T=x[0]||"x",A=x.slice(1),E=A.map(S=>`check${S}`);A.forEach((S,j)=>{y=y.replace(new RegExp(`\\b${S}\\s*\\(`,"g"),`${E[j]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${T}, ${E.join(", ")}) => { ${y} }, '${w}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${w}')`;t=m;continue}n+=e[t],t++}return n}function st(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(r){let s=r[1],o=r[3],i=t+r[0].length;if(e[i]==="{"){let a=i+1,l=1,c=a;for(;c<e.length&&l>0;){let d=e[c];d==="{"?l++:d==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,u=Ze(p);n+=`const ${s} = Union('${o}', [${u.join(", ")}])`,t=m;continue}else{let a=e.indexOf(`
9
- `,i);a===-1&&(a=e.length);let l=e.slice(i,a).trim();if(l){let c=Ze(l);n+=`const ${s} = Union('${o}', [${c.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function Ze(e){let n=[],t=e.split("|").map(r=>r.trim());for(let r of t)r&&n.push(r);return n}function it(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(r){let s=r[1],o=r[3],a=t+r[0].length-1+1,l=1,c=a;for(;c<e.length&&l>0;){let g=e[c];g==="{"?l++:g==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,d=Yn(p).map(([g,b])=>`${g}: ${b}`).join(", ");n+=`const ${s} = Enum('${o}', { ${d} })`,t=m;continue}n+=e[t],t++}return n}function Yn(e){let n=[],t=0,r=e.split(/[\n,]/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("//"));for(let s of r){let o=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(o){let i=o[1],a=o[2]?.trim();if(a!==void 0){n.push([i,a]);let l=Number(a);isNaN(l)||(t=l+1)}else n.push([i,String(t)]),t++}}return n}function ot(e){let n=new Map,t="",r=0;for(;r<e.length;){let s=e.slice(r),o=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/);if(!o){if(r===0||e[r-1]===`
10
- `||e[r-1]===";"||e[r-1]==="}"){let y=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/)}t+=e[r],r++;continue}let i=o[1],a=o[2],l=r+o[0].length-1,c=se(e,l),p=e.slice(l+1,c-1).trim(),m=[],u=0,d=e.slice(l+1,c-1);for(;u<d.length;){let y=d.slice(u).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!y){u++;continue}let T=y[1],A=!!y[2],E=y[3],S=u+y[0].length-1,j=1,M=S+1;for(;M<d.length&&j>0;)d[M]==="("&&j++,d[M]===")"&&j--,M++;let C=d.slice(S+1,M-1),k=M;for(;k<d.length&&/\s/.test(d[k]);)k++;if(d[k]==="="&&d[k+1]===">"){let Z=H(e,l+1+u);throw new O(`Arrow functions are not allowed in extend blocks (method '${E}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,Z)}if(d[k]!=="{"){u++;continue}let R=se(d,k),_=d.slice(u,R).trim(),J=C.split(",").map(Z=>Z.trim()).filter(Z=>Z.length>0).map(Z=>{let Ee=Z.match(/^(\w+)\s*:\s*(.+)$/);return Ee?`${Ee[1]} = ${Ee[2]}`:Z}).join(", "),K=A?"async ":"",ne=d.slice(k+1,R-1);m.push({name:E,isAsync:A,fullText:`${E}: ${K}function(${J}) {${ne}}`}),u=R}let g=!n.has(a);g&&n.set(a,new Set);let b=n.get(a);for(let x of m)b.add(x.name);let h=m.map(x=>` ${x.fullText}`).join(`,
11
- `),w;g?w=`${i}const __ext_${a} = {
8
+ `)}function Yn(e){let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
9
+ `&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let l=t-1;for(;l>=0&&/\s/.test(e[l]);)l--;let c=l>=0?e[l]:"";if(!c||/[=(!,;:{[&|?+\-*%<>~^]/.test(c)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){t++,r="regex";continue}}if(i==="t"&&e.slice(t,t+6)==="typeof"&&(t===0||!/[\w$]/.test(e[t-1]))&&/\s/.test(e[t+6]??"")){let l=t+6;for(;l<e.length&&/\s/.test(e[l]);)l++;if(l<e.length&&/[a-zA-Z_$]/.test(e[l])){let c=l;for(;l<e.length&&/[\w$]/.test(e[l]);)l++;for(;l<e.length;)if(e[l]==="."&&/[a-zA-Z_$]/.test(e[l+1]??""))for(l++;l<e.length&&/[\w$]/.test(e[l]);)l++;else if(e[l]==="?"&&e[l+1]==="."&&/[a-zA-Z_$]/.test(e[l+2]??""))for(l+=2;l<e.length&&/[\w$]/.test(e[l]);)l++;else break;n.push({keywordStart:t,operandEnd:l,operand:e.slice(c,l)}),t=l;continue}}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let a=n[i];o=o.slice(0,a.keywordStart)+`TypeOf(${a.operand})`+o.slice(a.operandEnd)}return o}function nt(e){e=Yn(e);let n=[],t=0,r="normal",s=[];for(;t<e.length;){let i=e[t],a=e[t+1];switch(r){case"single-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==="'"&&(r="normal"),t++;continue;case"double-string":if(i==="\\"&&t+1<e.length){t+=2;continue}i==='"'&&(r="normal"),t++;continue;case"template-string":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="$"&&a==="{"){t+=2,s.push(1),r="normal";continue}i==="`"&&(r="normal"),t++;continue;case"line-comment":i===`
10
+ `&&(r="normal"),t++;continue;case"block-comment":if(i==="*"&&a==="/"){t+=2,r="normal";continue}t++;continue;case"regex":if(i==="\\"&&t+1<e.length){t+=2;continue}if(i==="["){for(t++;t<e.length&&e[t]!=="]";)e[t]==="\\"&&t+1<e.length?t+=2:t++;t<e.length&&t++;continue}if(i==="/"){for(t++;t<e.length&&/[gimsuy]/.test(e[t]);)t++;r="normal";continue}t++;continue;case"normal":if(s.length>0){if(i==="{")s[s.length-1]++;else if(i==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),t++,r="template-string";continue}}if(i==="'"){t++,r="single-string";continue}if(i==='"'){t++,r="double-string";continue}if(i==="`"){t++,r="template-string";continue}if(i==="/"&&a==="/"){t+=2,r="line-comment";continue}if(i==="/"&&a==="*"){t+=2,r="block-comment";continue}if(i==="/"){let l=t-1;for(;l>=0&&/\s/.test(e[l]);)l--;let c=l>=0?e[l]:"";if(!c||/[=(!,;:{[&|?+\-*%<>~^]/.test(c)||l>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,l-10),l+1))){t++,r="regex";continue}}if(i==="="&&a==="="&&e[t+2]!=="="&&e[t-1]!=="!"){n.push({pos:t,op:"=="}),t+=2;continue}if(i==="!"&&a==="="&&e[t+2]!=="="){n.push({pos:t,op:"!="}),t+=2;continue}break}t++}if(n.length===0)return e;let o=e;for(let i=n.length-1;i>=0;i--){let{pos:a,op:l}=n[i],c=l==="=="?"Eq":"NotEq",p=Xn(o,a),m=Qn(o,a+2),u=o.slice(p,a).trim(),d=o.slice(a+2,m).trim();if(u&&d){let g=o.slice(0,p),b=o.slice(m),S=/[a-zA-Z0-9_$]$/.test(g)?" ":"";o=`${g}${S}${c}(${u}, ${d})${b}`}}return o}function Xn(e,n){let t=n-1;for(;t>=0&&/\s/.test(e[t]);)t--;if(t<0)return 0;let r=0,s=!1,o="";for(;t>=0;){let i=e[t],a=t>0?e[t-1]:"";if(s){i===o&&a!=="\\"&&(s=!1),t--;continue}if((i==='"'||i==="'"||i==="`")&&a!=="\\"){s=!0,o=i,t--;continue}if(i===")"||i==="]"||i==="}"){r++,t--;continue}if(i==="("||i==="["){if(r>0){r--,t--;continue}return t+1}if(i==="{"){if(r>0){r--,t--;continue}return t+1}if(r>0){t--;continue}if(i===";")return t+1;if(/[a-z]/.test(i)){let l=t+1,c=t;for(;c>0&&/[a-z]/i.test(e[c-1]);)c--;let p=e.slice(c,l),m=c>0?e[c-1]:"";if(!/[a-zA-Z0-9_$]/.test(m)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(p))return l;if(p==="new")return c}}if(i===">"&&a==="="||i==="="&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"||i==="&"&&a==="&"||i==="|"&&a==="|"||i==="?"||i===":"||i===",")return t+1;t--}return 0}function Qn(e,n){let t=n;for(;t<e.length&&/\s/.test(e[t]);)t++;if(t>=e.length)return e.length;let r=0,s=!1,o="";for(;t<e.length;){let i=e[t],a=t+1<e.length?e[t+1]:"";if(s){i===o&&e[t-1]!=="\\"&&(s=!1),t++;continue}if((i==='"'||i==="'"||i==="`")&&e[t-1]!=="\\"){s=!0,o=i,t++;continue}if(i==="("||i==="["||i==="{"){r++,t++;continue}if(i===")"||i==="]"||i==="}"){if(r>0){r--,t++;continue}return t}if(r>0){t++;continue}if(i===";"||i==="&"&&a==="&"||i==="|"&&a==="|"||i==="?"||i===":"||i===","||(i==="="||i==="!")&&a==="="&&e[t+2]!=="=")return t;t++}return e.length}function rt(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(r){let s=r[1],o=t+r[0].length,i=s,a=!1,l=e.slice(o).match(/^(['"`])([^]*?)\1\s*/);if(l){let u=o+l[0].length,d=e[u],g=d===void 0||u>=e.length||d!=="="&&d!=="{";if(d==="="||d==="{")i=l[2],a=!0,o=u;else if(g){let b=l[0].trim(),h=l[0].slice(b.length);n+=`const ${s} = Type('${s}', ${b})${h}`,t=u;continue}}let c,p=o,m=e.slice(o).match(/^=\s*/);if(m){o+=m[0].length;let u=e.slice(o).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(u){c=u[0],o+=u[0].length,p=o;let d=e.slice(o).match(/^\s*/);d&&(o+=d[0].length)}}if(e[o]==="{"){let u=o+1,d=1,g=u;for(;g<e.length&&d>0;){let E=e[g];E==="{"?d++:E==="}"&&d--,g++}if(d!==0){n+=e[t],t++;continue}let b=e.slice(u,g-1).trim(),h=g,S=b.match(/description\s*:\s*(['"`])([^]*?)\1/);S&&!a&&(i=S[2]);let $,y=b.match(/example\s*:\s*/);if(y){let E=y.index+y[0].length,w=Et(b,E);w&&($=w.value.trim())}let x=b.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(x&&$){let E=x[1].trim(),w=x[2].trim(),j=c?`, ${c}`:"";n+=`const ${s} = Type('${i}', (${E}) => { if (!globalThis.__tjs?.validate(${E}, globalThis.__tjs?.infer(${$}))) return false; ${w} }, ${$}${j})`}else if(x){let E=x[1].trim(),w=x[2].trim(),j=c?`, undefined, ${c}`:"";n+=`const ${s} = Type('${i}', (${E}) => { ${w} }${j})`}else if($){let E=c?`, ${c}`:"";n+=`const ${s} = Type('${i}', undefined, ${$}${E})`}else c?n+=`const ${s} = Type('${i}', ${c})`:n+=`const ${s} = Type('${i}')`;t=h;continue}else if(c){n+=`const ${s} = Type('${i}', ${c})`,t=p;continue}else if(!l){let u=e.slice(o).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(u){let d=u[0];n+=`const ${s} = Type('${s}', ${d})`,t=o+u[0].length;continue}}}n+=e[t],t++}return n}function st(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bFunctionPredicate\s+([A-Z_][a-zA-Z0-9_]*)\s*(?:<([^>]+)>)?\s*/);if(r){let s=r[1],o=r[2],i=t+r[0].length;if(e[i]==="{"){let a=1,l=i+1;for(;l<e.length&&a>0;)e[l]==="{"?a++:e[l]==="}"&&a--,l++;if(a===0){let c=e.slice(i+1,l-1).trim(),p=Jn(c,/params\s*:\s*\{/),m=c.match(/returns\s*:\s*(.+?)(?:\n|$)/),u=c.match(/returnContract\s*:\s*['"](\w+)['"]/),d=c.match(/description\s*:\s*(['"])([^]*?)\1/),g=[];p&&g.push(`params: ${p[1]}`),m&&g.push(`returns: ${m[1].trim()}`),u&&g.push(`returnContract: '${u[1]}'`);let b=d?d[2]:s;if(o){let h=o.split(",").map($=>{let y=$.trim().split("=").map(x=>x.trim());if(y.length===2){let x=y[1]==="any"||y[1]==="undefined"?"null":y[1];return`['${y[0]}', ${x}]`}return`'${y[0]}'`}),S=o.split(",").map($=>$.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${b}', [${h.join(", ")}], (${S.join(", ")}) => ({ ${g.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${b}', { ${g.join(", ")} })`;t=l;continue}}if(e[i]==="("){let a=1,l=i+1;for(;l<e.length&&a>0;)e[l]==="("?a++:e[l]===")"&&a--,l++;if(a===0){let c=e.slice(i+1,l-1).trim(),p=c.indexOf(",");if(p!==-1){let m=c.slice(0,p).trim(),u=c.slice(p+1).trim();n+=`const ${s} = FunctionPredicate(${u}, ${m})`}else n+=`const ${s} = FunctionPredicate('${s}', ${c})`;t=l;continue}}}n+=e[t],t++}return n}function it(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(r){let s=r[1],o=r[2],a=t+r[0].length-1+1,l=1,c=a;for(;c<e.length&&l>0;){let $=e[c];$==="{"?l++:$==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,u=o.split(",").map($=>{let y=$.trim().split("=").map(x=>x.trim());if(y.length===2){let x=y[1]==="any"||y[1]==="undefined"?"null":y[1];return`['${y[0]}', ${x}]`}return`'${y[0]}'`}),d=p,g=d.search(/\bdeclaration\s*\{/);if(g!==-1){let $=d.indexOf("{",g),y=1,x=$+1;for(;x<d.length&&y>0;)d[x]==="{"?y++:d[x]==="}"&&y--,x++;d=d.slice(0,g)+d.slice(x)}let b=d.match(/description\s*:\s*(['"`])([^]*?)\1/),h=d.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),S=b?b[2]:s;if(h){let $=h[1].trim().split(",").map(j=>j.trim()),y=h[2].trim(),x=$[0]||"x",E=$.slice(1),w=E.map(j=>`check${j}`);E.forEach((j,v)=>{y=y.replace(new RegExp(`\\b${j}\\s*\\(`,"g"),`${w[v]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${x}, ${w.join(", ")}) => { ${y} }, '${S}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${S}')`;t=m;continue}n+=e[t],t++}return n}function ot(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(r){let s=r[1],o=r[3],i=t+r[0].length;if(e[i]==="{"){let a=i+1,l=1,c=a;for(;c<e.length&&l>0;){let d=e[c];d==="{"?l++:d==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,u=Ze(p);n+=`const ${s} = Union('${o}', [${u.join(", ")}])`,t=m;continue}else{let a=e.indexOf(`
11
+ `,i);a===-1&&(a=e.length);let l=e.slice(i,a).trim();if(l){let c=Ze(l);n+=`const ${s} = Union('${o}', [${c.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function Ze(e){let n=[],t=e.split("|").map(r=>r.trim());for(let r of t)r&&n.push(r);return n}function at(e){let n="",t=0;for(;t<e.length;){let r=e.slice(t).match(/^\bEnum\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*\{/);if(r){let s=r[1],o=r[3],a=t+r[0].length-1+1,l=1,c=a;for(;c<e.length&&l>0;){let g=e[c];g==="{"?l++:g==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,d=er(p).map(([g,b])=>`${g}: ${b}`).join(", ");n+=`const ${s} = Enum('${o}', { ${d} })`,t=m;continue}n+=e[t],t++}return n}function er(e){let n=[],t=0,r=e.split(/[\n,]/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("//"));for(let s of r){let o=s.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=\s*(.+))?$/);if(o){let i=o[1],a=o[2]?.trim();if(a!==void 0){n.push([i,a]);let l=Number(a);isNaN(l)||(t=l+1)}else n.push([i,String(t)]),t++}}return n}function lt(e){let n=new Map,t="",r=0;for(;r<e.length;){let s=e.slice(r),o=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/);if(!o){if(r===0||e[r-1]===`
12
+ `||e[r-1]===";"||e[r-1]==="}"){let y=s.match(/^(\s*)extend\s+([A-Z]\w*)\s*\{/)}t+=e[r],r++;continue}let i=o[1],a=o[2],l=r+o[0].length-1,c=se(e,l),p=e.slice(l+1,c-1).trim(),m=[],u=0,d=e.slice(l+1,c-1);for(;u<d.length;){let y=d.slice(u).match(/^(\s*)(async\s+)?(\w+)\s*\(/);if(!y){u++;continue}let x=y[1],E=!!y[2],w=y[3],j=u+y[0].length-1,v=1,A=j+1;for(;A<d.length&&v>0;)d[A]==="("&&v++,d[A]===")"&&v--,A++;let M=d.slice(j+1,A-1),C=A;for(;C<d.length&&/\s/.test(d[C]);)C++;if(d[C]==="="&&d[C+1]===">"){let Z=J(e,l+1+u);throw new _(`Arrow functions are not allowed in extend blocks (method '${w}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,Z)}if(d[C]!=="{"){u++;continue}let R=se(d,C),U=d.slice(u,R).trim(),ee=M.split(",").map(Z=>Z.trim()).filter(Z=>Z.length>0).map(Z=>{let $e=Z.match(/^(\w+)\s*:\s*(.+)$/);return $e?`${$e[1]} = ${$e[2]}`:Z}).join(", "),te=E?"async ":"",ne=d.slice(C+1,R-1);m.push({name:w,isAsync:E,fullText:`${w}: ${te}function(${ee}) {${ne}}`}),u=R}let g=!n.has(a);g&&n.set(a,new Set);let b=n.get(a);for(let $ of m)b.add($.name);let h=m.map($=>` ${$.fullText}`).join(`,
13
+ `),S;g?S=`${i}const __ext_${a} = {
12
14
  ${h}
13
15
  ${i}}
14
- `:w=`${i}Object.assign(__ext_${a}, {
16
+ `:S=`${i}Object.assign(__ext_${a}, {
15
17
  ${h}
16
18
  ${i}})
17
- `;for(let x of m)w+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${x.name}', __ext_${a}.${x.name}) }
18
- `;t+=w,r=c}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function at(e,n){if(n.size===0)return e;let t=new Map;for(let[s,o]of n)for(let i of o)t.has(i)||t.set(i,[]),t.get(i).push(s);let r=e;for(let[s,o]of t){if(!o.includes("String"))continue;let i=new RegExp(`('(?:[^'\\\\]|\\\\.)*')\\.(${s})\\((\\))?`,"g");r=r.replace(i,(c,p,m,u)=>u?`__ext_String.${m}.call(${p})`:`__ext_String.${m}.call(${p}, `);let a=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${s})\\((\\))?`,"g");r=r.replace(a,(c,p,m,u)=>u?`__ext_String.${m}.call(${p})`:`__ext_String.${m}.call(${p}, `);let l=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+s+"\\((\\))?","g");r=r.replace(l,(c,p,m)=>m?`__ext_String.${s}.call(${p})`:`__ext_String.${s}.call(${p}, `)}for(let[s,o]of t){if(!o.includes("Array"))continue;let i=`].${s}(`,a=0,l;for(;(l=r.indexOf(i,a))!==-1;){let c=1,p=l-1,m=!1;for(;p>=0&&c>0;){let u=r[p];m?u===m&&(p===0||r[p-1]!=="\\")&&(m=!1):(u==="]"&&c++,u==="["&&c--,(u==="'"||u==='"'||u==="`")&&(m=u)),p--}if(c===0){let u=r.slice(p+1,l+1),d=r.slice(0,p+1),g=r.slice(l+i.length);g[0]===")"?r=`${d}__ext_Array.${s}.call(${u})${g.slice(1)}`:r=`${d}__ext_Array.${s}.call(${u}, ${g}`}a=l+1}}for(let[s,o]of t){if(!o.includes("Number"))continue;let i=new RegExp(`(\\d+(?:\\.\\d+)?)\\.(${s})\\((\\))?`,"g");r=r.replace(i,(a,l,c,p)=>p?`__ext_Number.${c}.call(${l})`:`__ext_Number.${c}.call(${l}, `)}return r}function H(e,n){let t=1,r=0;for(let s=0;s<n&&s<e.length;s++)e[s]===`
19
- `?(t++,r=0):r++;return{line:t,column:r}}function lt(e,n){let t=n.trim();return/^['"`]/.test(t)?`typeof ${e} === 'string'`:t==="true"||t==="false"?`typeof ${e} === 'boolean'`:t==="null"?`${e} === null`:t==="undefined"?`${e} === undefined`:t.startsWith("[")?`Array.isArray(${e})`:t.startsWith("{")?`(typeof ${e} === 'object' && ${e} !== null && !Array.isArray(${e}))`:/^\+\d+/.test(t)?`(typeof ${e} === 'number' && Number.isInteger(${e}) && ${e} >= 0)`:/^-?\d+\.\d+/.test(t)?`typeof ${e} === 'number'`:/^-?\d+$/.test(t)?`(typeof ${e} === 'number' && Number.isInteger(${e}))`:"true"}function me(e){let n=e.trim();return/^['"`]/.test(n)?"string":n==="true"||n==="false"?"boolean":n==="null"?"null":n==="undefined"?"undefined":n.startsWith("[")?"array":n.startsWith("{")?"object":/^\+\d+/.test(n)?"non-negative-integer":/^-?\d+\.\d+/.test(n)?"number":/^-?\d+$/.test(n)?"integer":"any"}function Me(e,n){let t=[],r=0,s="",o=!1;for(let a=0;a<e.length;a++){let l=e[a];if(!o&&(l==="'"||l==='"'||l==="`")){o=l,s+=l;continue}if(o){if(s+=l,l==="\\"){a++,a<e.length&&(s+=e[a]);continue}l===o&&(o=!1);continue}if(l==="("||l==="["||l==="{"){r++,s+=l;continue}if(l===")"||l==="]"||l==="}"){r--,s+=l;continue}if(l===","&&r===0){let c=Ge(s.trim(),n);c&&t.push(c),s="";continue}s+=l}let i=s.trim();if(i){let a=Ge(i,n);a&&t.push(a)}return t}function Ge(e,n){let t=e.replace(/^\/\*\s*unsafe\s*\*\/\s*/,"");if(t.startsWith("..."))return null;let r=t.indexOf("=");if(r===-1)return{name:t.trim(),defaultValue:"",required:!0};let s=t.slice(0,r).trim(),o=t.slice(r+1).trim();return{name:s,defaultValue:o,required:n.has(s)}}function se(e,n){let t=1,r=n+1,s=!1,o=!1,i=!1;for(;r<e.length&&t>0;){let a=e[r],l=r+1<e.length?e[r+1]:"";if(o){a===`
20
- `&&(o=!1),r++;continue}if(i){if(a==="*"&&l==="/"){i=!1,r+=2;continue}r++;continue}if(s){if(a==="\\"){r+=2;continue}a===s&&(s=!1),r++;continue}if(a==="/"&&l==="/"){o=!0,r+=2;continue}if(a==="/"&&l==="*"){i=!0,r+=2;continue}if(a==="'"||a==='"'||a==="`"){s=a,r++;continue}a==="{"&&t++,a==="}"&&t--,r++}return r}function ct(e,n){let t=new Set,r=/(?:^|(?<=[\n;{}]))\s*(export\s+)?(async\s+)?function\s+(\w+)\s*\(/gm,s=new Map,o,i=[];for(;(o=r.exec(e))!==null;){let m=!!o[1],u=!!o[2],d=o[3],g=o.index,b=g,w=o[0].indexOf("function");w>=0&&(b=g+w),i.push({name:d,fullMatchStart:g,funcKeywordStart:b,exported:m,isAsync:u})}for(let m of i)s.has(m.name)||s.set(m.name,[]);let a=new Map;for(let m of i)a.set(m.name,(a.get(m.name)||0)+1);let l=new Set;for(let[m,u]of a)u>1&&l.add(m);if(l.size===0)return{source:e,polymorphicNames:t};for(let m of i){if(!l.has(m.name))continue;let u=e.indexOf("(",m.funcKeywordStart);if(u===-1)continue;let d=1,g=u+1;for(;g<e.length&&d>0;)e[g]==="("&&d++,e[g]===")"&&d--,g++;let b=g-1,h=e.slice(u+1,b),w=g;for(;w<e.length&&e[w]!=="{";)w++;if(w>=e.length)continue;let x=se(e,w),y=m.fullMatchStart;for(;y>0&&e[y-1]===" ";)y--;let T=s.get(m.name),A=Me(h,n);if(h.includes("...")){let S=H(e,m.funcKeywordStart);throw new O(`Rest parameters are not supported in polymorphic function '${m.name}'. Use separate function names instead.`,S)}T.push({index:T.length+1,start:y,end:x,text:e.slice(y,x),exported:m.exported,isAsync:m.isAsync,params:A})}for(let[m,u]of s){if(u.length<2)continue;let d=u.filter(g=>g.isAsync).length;if(d>0&&d<u.length){let g=H(e,u[0].start);throw new O(`Polymorphic function '${m}': all variants must be either sync or async, not mixed.`,g)}for(let g=0;g<u.length;g++)for(let b=g+1;b<u.length;b++){let h=u[g],w=u[b];if(h.params.length!==w.params.length)continue;let x=!0;for(let y=0;y<h.params.length;y++){let T=h.params[y].defaultValue?me(h.params[y].defaultValue):"any",A=w.params[y].defaultValue?me(w.params[y].defaultValue):"any";if(T!==A){x=!1;break}}if(x){let y=H(e,w.start);throw new O(`Polymorphic function '${m}': variants ${g+1} and ${b+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,y)}}}let c=[];for(let[m,u]of s)if(!(u.length<2))for(let d of u)c.push({name:m,variant:d});c.sort((m,u)=>u.variant.start-m.variant.start);let p=e;for(let{name:m,variant:u}of c){let d=u.isAsync?"async ":"",g=u.text.replace(new RegExp(`(?:export\\s+)?${d?d.replace(/\s+$/,"\\s+"):""}function\\s+${m}\\s*\\(`),`${d}function ${m}$$${u.index}(`);p=p.slice(0,u.start)+g+p.slice(u.end)}for(let[m,u]of s){if(u.length<2)continue;t.add(m);let d=u[0].isAsync,g=u.some(T=>T.exported),b=d?"async ":"",h=g?"export ":"",w=[...u].sort((T,A)=>{if(T.params.length!==A.params.length)return 0;let E=0,S=0;for(let j of T.params){let M=j.defaultValue?me(j.defaultValue):"any";M==="non-negative-integer"?E+=3:M==="integer"?E+=2:M!=="any"&&(E+=1)}for(let j of A.params){let M=j.defaultValue?me(j.defaultValue):"any";M==="non-negative-integer"?S+=3:M==="integer"?S+=2:M!=="any"&&(S+=1)}return S-E}),x=[];for(let T of w){let A=[`__args.length === ${T.params.length}`],E=[];for(let S=0;S<T.params.length;S++){let j=T.params[S];if(E.push(`__args[${S}]`),j.defaultValue){let M=lt(`__args[${S}]`,j.defaultValue);M!=="true"&&A.push(M)}}x.push(` if (${A.join(" && ")}) return ${m}$${T.index}(${E.join(", ")})`)}let y=`
19
+ `;for(let $ of m)S+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${$.name}', __ext_${a}.${$.name}) }
20
+ `;t+=S,r=c}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function ct(e,n){if(n.size===0)return e;let t=new Map;for(let[s,o]of n)for(let i of o)t.has(i)||t.set(i,[]),t.get(i).push(s);let r=e;for(let[s,o]of t){if(!o.includes("String"))continue;let i=new RegExp(`('(?:[^'\\\\]|\\\\.)*')\\.(${s})\\((\\))?`,"g");r=r.replace(i,(c,p,m,u)=>u?`__ext_String.${m}.call(${p})`:`__ext_String.${m}.call(${p}, `);let a=new RegExp(`("(?:[^"\\\\]|\\\\.)*")\\.(${s})\\((\\))?`,"g");r=r.replace(a,(c,p,m,u)=>u?`__ext_String.${m}.call(${p})`:`__ext_String.${m}.call(${p}, `);let l=new RegExp("(`(?:[^`\\\\]|\\\\.)*`)\\."+s+"\\((\\))?","g");r=r.replace(l,(c,p,m)=>m?`__ext_String.${s}.call(${p})`:`__ext_String.${s}.call(${p}, `)}for(let[s,o]of t){if(!o.includes("Array"))continue;let i=`].${s}(`,a=0,l;for(;(l=r.indexOf(i,a))!==-1;){let c=1,p=l-1,m=!1;for(;p>=0&&c>0;){let u=r[p];m?u===m&&(p===0||r[p-1]!=="\\")&&(m=!1):(u==="]"&&c++,u==="["&&c--,(u==="'"||u==='"'||u==="`")&&(m=u)),p--}if(c===0){let u=r.slice(p+1,l+1),d=r.slice(0,p+1),g=r.slice(l+i.length);g[0]===")"?r=`${d}__ext_Array.${s}.call(${u})${g.slice(1)}`:r=`${d}__ext_Array.${s}.call(${u}, ${g}`}a=l+1}}for(let[s,o]of t){if(!o.includes("Number"))continue;let i=new RegExp(`(\\d+(?:\\.\\d+)?)\\.(${s})\\((\\))?`,"g");r=r.replace(i,(a,l,c,p)=>p?`__ext_Number.${c}.call(${l})`:`__ext_Number.${c}.call(${l}, `)}return r}function J(e,n){let t=1,r=0;for(let s=0;s<n&&s<e.length;s++)e[s]===`
21
+ `?(t++,r=0):r++;return{line:t,column:r}}function ut(e,n){let t=n.trim();return/^['"`]/.test(t)?`typeof ${e} === 'string'`:t==="true"||t==="false"?`typeof ${e} === 'boolean'`:t==="null"?`${e} === null`:t==="undefined"?`${e} === undefined`:t.startsWith("[")?`Array.isArray(${e})`:t.startsWith("{")?`(typeof ${e} === 'object' && ${e} !== null && !Array.isArray(${e}))`:/^\+\d+/.test(t)?`(typeof ${e} === 'number' && Number.isInteger(${e}) && ${e} >= 0)`:/^-?\d+\.\d+/.test(t)?`typeof ${e} === 'number'`:/^-?\d+$/.test(t)?`(typeof ${e} === 'number' && Number.isInteger(${e}))`:"true"}function me(e){let n=e.trim();return/^['"`]/.test(n)?"string":n==="true"||n==="false"?"boolean":n==="null"?"null":n==="undefined"?"undefined":n.startsWith("[")?"array":n.startsWith("{")?"object":/^\+\d+/.test(n)?"non-negative-integer":/^-?\d+\.\d+/.test(n)?"number":/^-?\d+$/.test(n)?"integer":"any"}function ke(e,n){let t=[],r=0,s="",o=!1;for(let a=0;a<e.length;a++){let l=e[a];if(!o&&(l==="'"||l==='"'||l==="`")){o=l,s+=l;continue}if(o){if(s+=l,l==="\\"){a++,a<e.length&&(s+=e[a]);continue}l===o&&(o=!1);continue}if(l==="("||l==="["||l==="{"){r++,s+=l;continue}if(l===")"||l==="]"||l==="}"){r--,s+=l;continue}if(l===","&&r===0){let c=Ge(s.trim(),n);c&&t.push(c),s="";continue}s+=l}let i=s.trim();if(i){let a=Ge(i,n);a&&t.push(a)}return t}function Ge(e,n){let t=e.replace(/^\/\*\s*unsafe\s*\*\/\s*/,"");if(t.startsWith("..."))return null;let r=t.indexOf("=");if(r===-1)return{name:t.trim(),defaultValue:"",required:!0};let s=t.slice(0,r).trim(),o=t.slice(r+1).trim();return{name:s,defaultValue:o,required:n.has(s)}}function se(e,n){let t=1,r=n+1,s=!1,o=!1,i=!1;for(;r<e.length&&t>0;){let a=e[r],l=r+1<e.length?e[r+1]:"";if(o){a===`
22
+ `&&(o=!1),r++;continue}if(i){if(a==="*"&&l==="/"){i=!1,r+=2;continue}r++;continue}if(s){if(a==="\\"){r+=2;continue}a===s&&(s=!1),r++;continue}if(a==="/"&&l==="/"){o=!0,r+=2;continue}if(a==="/"&&l==="*"){i=!0,r+=2;continue}if(a==="'"||a==='"'||a==="`"){s=a,r++;continue}a==="{"&&t++,a==="}"&&t--,r++}return r}function ft(e,n){let t=new Set,r=/(?:^|(?<=[\n;{}]))\s*(export\s+)?(async\s+)?function\s+(\w+)\s*\(/gm,s=new Map,o,i=[];for(;(o=r.exec(e))!==null;){let m=!!o[1],u=!!o[2],d=o[3],g=o.index,b=g,S=o[0].indexOf("function");S>=0&&(b=g+S),i.push({name:d,fullMatchStart:g,funcKeywordStart:b,exported:m,isAsync:u})}for(let m of i)s.has(m.name)||s.set(m.name,[]);let a=new Map;for(let m of i)a.set(m.name,(a.get(m.name)||0)+1);let l=new Set;for(let[m,u]of a)u>1&&l.add(m);if(l.size===0)return{source:e,polymorphicNames:t};for(let m of i){if(!l.has(m.name))continue;let u=e.indexOf("(",m.funcKeywordStart);if(u===-1)continue;let d=1,g=u+1;for(;g<e.length&&d>0;)e[g]==="("&&d++,e[g]===")"&&d--,g++;let b=g-1,h=e.slice(u+1,b),S=g;for(;S<e.length&&e[S]!=="{";)S++;if(S>=e.length)continue;let $=se(e,S),y=m.fullMatchStart;for(;y>0&&e[y-1]===" ";)y--;let x=s.get(m.name),E=ke(h,n);if(h.includes("...")){let j=J(e,m.funcKeywordStart);throw new _(`Rest parameters are not supported in polymorphic function '${m.name}'. Use separate function names instead.`,j)}x.push({index:x.length+1,start:y,end:$,text:e.slice(y,$),exported:m.exported,isAsync:m.isAsync,params:E})}for(let[m,u]of s){if(u.length<2)continue;let d=u.filter(g=>g.isAsync).length;if(d>0&&d<u.length){let g=J(e,u[0].start);throw new _(`Polymorphic function '${m}': all variants must be either sync or async, not mixed.`,g)}for(let g=0;g<u.length;g++)for(let b=g+1;b<u.length;b++){let h=u[g],S=u[b];if(h.params.length!==S.params.length)continue;let $=!0;for(let y=0;y<h.params.length;y++){let x=h.params[y].defaultValue?me(h.params[y].defaultValue):"any",E=S.params[y].defaultValue?me(S.params[y].defaultValue):"any";if(x!==E){$=!1;break}}if($){let y=J(e,S.start);throw new _(`Polymorphic function '${m}': variants ${g+1} and ${b+1} have ambiguous signatures (same parameter types at every position). Overloads must differ by arity or parameter types.`,y)}}}let c=[];for(let[m,u]of s)if(!(u.length<2))for(let d of u)c.push({name:m,variant:d});c.sort((m,u)=>u.variant.start-m.variant.start);let p=e;for(let{name:m,variant:u}of c){let d=u.isAsync?"async ":"",g=u.text.replace(new RegExp(`(?:export\\s+)?${d?d.replace(/\s+$/,"\\s+"):""}function\\s+${m}\\s*\\(`),`${d}function ${m}$$${u.index}(`);p=p.slice(0,u.start)+g+p.slice(u.end)}for(let[m,u]of s){if(u.length<2)continue;t.add(m);let d=u[0].isAsync,g=u.some(x=>x.exported),b=d?"async ":"",h=g?"export ":"",S=[...u].sort((x,E)=>{if(x.params.length!==E.params.length)return 0;let w=0,j=0;for(let v of x.params){let A=v.defaultValue?me(v.defaultValue):"any";A==="non-negative-integer"?w+=3:A==="integer"?w+=2:A!=="any"&&(w+=1)}for(let v of E.params){let A=v.defaultValue?me(v.defaultValue):"any";A==="non-negative-integer"?j+=3:A==="integer"?j+=2:A!=="any"&&(j+=1)}return j-w}),$=[];for(let x of S){let E=[`__args.length === ${x.params.length}`],w=[];for(let j=0;j<x.params.length;j++){let v=x.params[j];if(w.push(`__args[${j}]`),v.defaultValue){let A=ut(`__args[${j}]`,v.defaultValue);A!=="true"&&E.push(A)}}$.push(` if (${E.join(" && ")}) return ${m}$${x.index}(${w.join(", ")})`)}let y=`
21
23
  ${h}${b}function ${m}(...__args) {
22
- ${x.join(`
24
+ ${$.join(`
23
25
  `)}
24
26
  return __tjs.typeError('${m}', 'no matching overload', __args)
25
27
  }
26
- `;p+=y}return{source:p,polymorphicNames:t}}function ut(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function ft(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,b=!1;for(;d<e.length&&u>0;){let h=e[d];if(b){b=!1,d++;continue}if(h==="\\"&&g){b=!0,d++;continue}if(g){h===g&&(g=null),d++;continue}if(h==="/"&&e[d+1]==="/"){let w=e.indexOf(`
27
- `,d);d=w===-1?e.length:w+1;continue}if(h==="/"&&e[d+1]==="*"){let w=e.indexOf("*/",d+2);d=w===-1?e.length:w+2;continue}if(h==="'"||h==='"'||h==="`"){g=h,d++;continue}h==="{"?u++:h==="}"&&u--,d++}if(u===0){let h=e.slice(m,d-1).trim(),w=d,x=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:c,body:h,start:a,end:w,line:x}),!n)try{new Function(h)()}catch(A){let E=c||`test at line ${x}`;r.push(`Test failed: ${E} (line ${x})
28
- ${A.message||A}`)}let T=(e.slice(a,w).match(/\n/g)||[]).length;s+=`
29
- `.repeat(T),o=w;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function pt(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,b=[];for(;(g=d.exec(u))!==null;)b.push(g.index);if(b.length<2)continue;t.add(l);let h=[];for(let S=0;S<b.length;S++){let j=b[S],M=u.indexOf("(",j),C=1,k=M+1;for(;k<u.length&&C>0;)u[k]==="("&&C++,u[k]===")"&&C--,k++;let R=u.slice(M+1,k-1),_=k;for(;_<u.length&&u[_]!=="{";)_++;let J=se(u,_),K=u.slice(_+1,J-1);h.push({index:S+1,paramStr:R,bodyText:K,fullStart:j,fullEnd:J})}let w=u.slice(0,h[0].fullEnd),x=h[h.length-1].fullEnd;w+=u.slice(x);let y=u;for(let S=h.length-1;S>=1;S--){let j=h[S],M=j.fullStart;for(;M>0&&y[M-1]===" ";)M--;M>0&&y[M-1]===`
30
- `&&M--,y=y.slice(0,M)+y.slice(j.fullEnd)}let T="";for(let S=1;S<h.length;S++){let j=h[S],M=Me(j.paramStr,n);if(j.paramStr.includes("...")){let k=H(e,p+j.fullStart);throw new O(`Rest parameters are not supported in polymorphic constructors for '${l}'.`,k)}T+=`
31
- function ${l}$ctor$${j.index}(${j.paramStr}) {`,T+=`
32
- const __obj = Object.create(${l}.prototype)`,T+=`
33
- ;(function() {${j.bodyText}}).call(__obj)`,T+=`
34
- return __obj`,T+=`
28
+ `;p+=y}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,b=!1;for(;d<e.length&&u>0;){let h=e[d];if(b){b=!1,d++;continue}if(h==="\\"&&g){b=!0,d++;continue}if(g){h===g&&(g=null),d++;continue}if(h==="/"&&e[d+1]==="/"){let S=e.indexOf(`
29
+ `,d);d=S===-1?e.length:S+1;continue}if(h==="/"&&e[d+1]==="*"){let S=e.indexOf("*/",d+2);d=S===-1?e.length:S+2;continue}if(h==="'"||h==='"'||h==="`"){g=h,d++;continue}h==="{"?u++:h==="}"&&u--,d++}if(u===0){let h=e.slice(m,d-1).trim(),S=d,$=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:c,body:h,start:a,end:S,line:$}),!n)try{new Function(h)()}catch(E){let w=c||`test at line ${$}`;r.push(`Test failed: ${w} (line ${$})
30
+ ${E.message||E}`)}let x=(e.slice(a,S).match(/\n/g)||[]).length;s+=`
31
+ `.repeat(x),o=S;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,b=[];for(;(g=d.exec(u))!==null;)b.push(g.index);if(b.length<2)continue;t.add(l);let h=[];for(let E=0;E<b.length;E++){let w=b[E],j=u.indexOf("(",w),v=1,A=j+1;for(;A<u.length&&v>0;)u[A]==="("&&v++,u[A]===")"&&v--,A++;let M=u.slice(j+1,A-1),C=A;for(;C<u.length&&u[C]!=="{";)C++;let R=se(u,C),U=u.slice(C+1,R-1);h.push({index:E+1,paramStr:M,bodyText:U,fullStart:w,fullEnd:R})}let S=u;for(let E=h.length-1;E>=1;E--){let w=h[E],j=w.fullStart;for(;j>0&&S[j-1]===" ";)j--;j>0&&S[j-1]===`
32
+ `&&j--,S=S.slice(0,j)+S.slice(w.fullEnd)}let $="";for(let E=1;E<h.length;E++){let w=h[E],j=ke(w.paramStr,n);if(w.paramStr.includes("...")){let A=J(e,p+w.fullStart);throw new _(`Rest parameters are not supported in polymorphic constructors for '${l}'.`,A)}$+=`
33
+ function ${l}$ctor$${w.index}(${w.paramStr}) {`,$+=`
34
+ const __obj = Object.create(${l}.prototype)`,$+=`
35
+ ;(function() {${w.bodyText}}).call(__obj)`,$+=`
36
+ return __obj`,$+=`
35
37
  }
36
- `}let A=[];for(let S=0;S<h.length;S++){let j=h[S],M=Me(j.paramStr,n),C=[`a.length === ${M.length}`];for(let k=0;k<M.length;k++){let R=M[k];if(R.defaultValue){let _=lt(`a[${k}]`,R.defaultValue);_!=="true"&&C.push(_)}}if(S===0)A.push(` if (${C.join(" && ")}) return Reflect.construct(t, a)`);else{let k=M.map((R,_)=>`a[${_}]`).join(", ");A.push(` if (${C.join(" && ")}) return ${l}$ctor$${j.index}(${k})`)}}T+=`
38
+ `}let y=[];for(let E=0;E<h.length;E++){let w=h[E],j=ke(w.paramStr,n),v=[`a.length === ${j.length}`];for(let A=0;A<j.length;A++){let M=j[A];if(M.defaultValue){let C=ut(`a[${A}]`,M.defaultValue);C!=="true"&&v.push(C)}}if(E===0)y.push(` if (${v.join(" && ")}) return Reflect.construct(t, a)`);else{let A=j.map((M,C)=>`a[${C}]`).join(", ");y.push(` if (${v.join(" && ")}) return ${l}$ctor$${w.index}(${A})`)}}$+=`
37
39
  function ${l}$dispatch(t, a) {
38
- `,T+=A.join(`
40
+ `,$+=y.join(`
39
41
  `)+`
40
- `,T+=` return __tjs.typeError('${l}', 'no matching constructor', a)
41
- `,T+=`}
42
- `,i=i.slice(0,p)+y+i.slice(m);let E=p+y.length;i=i.slice(0,E)+T+i.slice(E)}return{source:i,polyCtorClasses:t}}function mt(e,n=new Set){let t=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,r="",s=0,o;for(;(o=t.exec(e))!==null;){let i=o[1],a=o[2]||"",l=o.index,c=l+o[0].length-1,p=1,m=c+1;for(;m<e.length&&p>0;){let u=e[m];u==="{"?p++:u==="}"&&p--,m++}if(p===0){let u=m,d=e.slice(c,u);r+=e.slice(s,l),r+=`let ${i} = class ${i}${a} ${d}; `,n.has(i)?r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return ${i}$dispatch(t, a) }, construct(t, a) { return ${i}$dispatch(t, a) } });`:r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,s=u}}return r+=e.slice(s),r}function dt(e){let n=[{pattern:/\bnew\s+Date\b/,message:"new Date() is not allowed in TjsDate mode. Use Timestamp.now() or Timestamp.from()"},{pattern:/\bDate\.now\b/,message:"Date.now() is not allowed in TjsDate mode. Use Timestamp.now()"},{pattern:/\bDate\.parse\b/,message:"Date.parse() is not allowed in TjsDate mode. Use Timestamp.parse()"},{pattern:/\bDate\.UTC\b/,message:"Date.UTC() is not allowed in TjsDate mode. Use Timestamp.from()"}];for(let{pattern:t,message:r}of n)if(t.test(e))throw new Error(r);return e}function gt(e){let n=new Set,t=/\bconst!\s+(\w+)\b/g,r;for(;(r=t.exec(e))!==null;)n.add(r[1]);if(n.size===0)return e;e=e.replace(/\bconst!\s+/g,"const ");let s=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"");for(let o of n){if(new RegExp(`\\b${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])\\s*(?:=(?!=)|\\+\\+|--|\\+=|-=|\\*=|\\/=|%=|&&=|\\|\\|=|\\?\\?=|<<=|>>=|>>>=|\\^=|&=|\\|=)`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);if(new RegExp(`(?:\\+\\+|--)\\s*${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\bdelete\\s+${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);let c="push|pop|splice|shift|unshift|sort|reverse|fill|copyWithin|set";if(new RegExp(`\\b${o}\\s*\\.\\s*(?:${c})\\s*\\(`,"g").test(s))throw new Error(`Cannot call mutating method on immutable binding '${o}'. const! bindings are read-only at compile time.`)}return e}function yt(e){if(/(?<![a-zA-Z_$])\bvar\s+/.test(e))throw new Error("var is not allowed in TjsNoVar mode. Use const or let instead.");return e}function ht(e){if(/(?<![A-Za-z_$])\beval\s*\(/.test(e))throw new Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(e))throw new Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return e}function bt(e){if(!e.includes("!."))return e;let n="",t=0,r="normal",s=0;for(;t<e.length;){let o=e[t],i=e[t+1];if(r==="normal"){if(o==="/"&&i==="/"){r="line-comment",n+=o,t++;continue}if(o==="/"&&i==="*"){r="block-comment",n+=o,t++;continue}if(o==="'"){r="string-single",n+=o,t++;continue}if(o==='"'){r="string-double",n+=o,t++;continue}if(o==="`"){r="string-template",s++,n+=o,t++;continue}if(o==="!"&&i==="."&&t+2<e.length&&/[a-zA-Z_$]/.test(e[t+2])){let a=n.length,l=Xn(n);if(l<a){let c=n.slice(l);n=n.slice(0,l);let p=t+2;for(;p<e.length&&/[\w$]/.test(e[p]);)p++;let m=e.slice(t+2,p);n+=`__tjs.bang(${c},'${m}')`,t=p;continue}}n+=o,t++}else r==="line-comment"?(n+=o,o===`
43
- `&&(r="normal"),t++):r==="block-comment"?(n+=o,o==="*"&&i==="/"?(n+=i,r="normal",t+=2):t++):r==="string-single"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==="'"&&(r="normal"),t++)):r==="string-double"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==='"'&&(r="normal"),t++)):r==="string-template"?(n+=o,o==="\\"?(n+=i||"",t+=2):o==="`"?(s--,r=s>0?"string-template":"normal",t++):o==="$"&&i==="{"?(n+=i,t+=2,r="normal"):t++):(n+=o,t++)}return n}function Xn(e){let n=e.length-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return e.length;for(;n>=0;){let t=e[n];if(/[\w$]/.test(t)){for(;n>=0&&/[\w$]/.test(e[n]);)n--;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t===")"){if(n=He(e,n,"(",")"),n<0)return 0;if(n--,n>=0&&/[\w$]/.test(e[n]))continue;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t==="]"){if(n=He(e,n,"[","]"),n<0)return 0;if(n--,n>=0&&/[\w$]/.test(e[n]))continue;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else return n+1}return 0}function He(e,n,t,r){let s=1;for(n--;n>=0&&s>0;)e[n]===r?s++:e[n]===t&&s--,s>0&&n--;return n}function wt(e){let n=new Map;if(!e.includes("let "))return{source:e,annotations:n};let t=[],r=0,s="normal",o=[];for(;r<e.length;){let a=e[r],l=e[r+1];switch(s){case"single-string":if(a==="\\"&&r+1<e.length){r+=2;continue}a==="'"&&(s="normal"),r++;continue;case"double-string":if(a==="\\"&&r+1<e.length){r+=2;continue}a==='"'&&(s="normal"),r++;continue;case"template-string":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="$"&&l==="{"){r+=2,o.push(1),s="normal";continue}a==="`"&&(s="normal"),r++;continue;case"line-comment":a===`
44
- `&&(s="normal"),r++;continue;case"block-comment":if(a==="*"&&l==="/"){r+=2,s="normal";continue}r++;continue;case"regex":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="["){for(r++;r<e.length&&e[r]!=="]";)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}if(a==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)r++;s="normal";continue}r++;continue;case"normal":if(o.length>0){if(a==="{")o[o.length-1]++;else if(a==="}"&&(o[o.length-1]--,o[o.length-1]===0)){o.pop(),r++,s="template-string";continue}}if(a==="'"){r++,s="single-string";continue}if(a==='"'){r++,s="double-string";continue}if(a==="`"){r++,s="template-string";continue}if(a==="/"&&l==="/"){r+=2,s="line-comment";continue}if(a==="/"&&l==="*"){r+=2,s="block-comment";continue}if(a==="/"){let c=r-1;for(;c>=0&&/\s/.test(e[c]);)c--;let p=c>=0?e[c]:"";if(!p||/[=(!,;:{[&|?+\-*%<>~^]/.test(p)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){r++,s="regex";continue}}if(a==="l"&&e.slice(r,r+4)==="let "&&(r===0||!/[\w$]/.test(e[r-1]))){let c=r+4;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&/[a-zA-Z_$]/.test(e[c])){let p=c;for(;c<e.length&&/[\w$]/.test(e[c]);)c++;let m=c,u=e.slice(p,m),d=c;for(;d<e.length&&/\s/.test(e[d]);)d++;if(d<e.length&&e[d]===":"&&e[d+1]!==":"){let b=d+1;for(;b<e.length&&/[ \t]/.test(e[b]);)b++;let h=Qn(e,b);if(h>b){let w=e.slice(b,h).trim();n.set(u,w),t.push({start:m,end:h,replacement:""}),r=h;continue}}}}break}r++}if(t.length===0)return{source:e,annotations:n};let i=e;for(let a=t.length-1;a>=0;a--){let l=t[a];i=i.slice(0,l.start)+l.replacement+i.slice(l.end)}return{source:i,annotations:n}}function Qn(e,n){let t=n,r=0,s=0,o=0,i="normal",a=[];for(;t<e.length;){let l=e[t];if(i==="sq"){if(l==="\\"){t+=2;continue}l==="'"&&(i="normal"),t++;continue}if(i==="dq"){if(l==="\\"){t+=2;continue}l==='"'&&(i="normal"),t++;continue}if(i==="tpl"){if(l==="\\"){t+=2;continue}if(l==="$"&&e[t+1]==="{"){a.push(1),i="normal",t+=2;continue}l==="`"&&(i="normal"),t++;continue}if(a.length>0){if(l==="{")a[a.length-1]++;else if(l==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),i="tpl",t++;continue}}if(l==="'"){i="sq",t++;continue}if(l==='"'){i="dq",t++;continue}if(l==="`"){i="tpl",t++;continue}if(l==="("?r++:l===")"?r--:l==="{"?s++:l==="}"?s--:l==="["?o++:l==="]"&&o--,r===0&&s===0&&o===0&&(l==="="||l===","||l===";"||l===`
42
+ `,$+=` return __tjs.typeError('${l}', 'no matching constructor', a)
43
+ `,$+=`}
44
+ `,i=i.slice(0,p)+S+i.slice(m);let x=p+S.length;i=i.slice(0,x)+$+i.slice(x)}return{source:i,polyCtorClasses:t}}function gt(e,n=new Set){let t=/\bclass\s+(\w+)(\s+extends\s+\w+)?\s*\{/g,r="",s=0,o;for(;(o=t.exec(e))!==null;){let i=o[1],a=o[2]||"",l=o.index,c=l+o[0].length-1,p=1,m=c+1;for(;m<e.length&&p>0;){let u=e[m];u==="{"?p++:u==="}"&&p--,m++}if(p===0){let u=m,d=e.slice(c,u);r+=e.slice(s,l),r+=`let ${i} = class ${i}${a} ${d}; `,n.has(i)?r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return ${i}$dispatch(t, a) }, construct(t, a) { return ${i}$dispatch(t, a) } });`:r+=`${i} = new Proxy(${i}, { apply(t, _, a) { return Reflect.construct(t, a) } });`,s=u}}return r+=e.slice(s),r}function yt(e){let n=[{pattern:/\bnew\s+Date\b/,message:"new Date() is not allowed in TjsDate mode. Use Timestamp.now() or Timestamp.from()"},{pattern:/\bDate\.now\b/,message:"Date.now() is not allowed in TjsDate mode. Use Timestamp.now()"},{pattern:/\bDate\.parse\b/,message:"Date.parse() is not allowed in TjsDate mode. Use Timestamp.parse()"},{pattern:/\bDate\.UTC\b/,message:"Date.UTC() is not allowed in TjsDate mode. Use Timestamp.from()"}];for(let{pattern:t,message:r}of n)if(t.test(e))throw new Error(r);return e}function ht(e){let n=new Set,t=/\bconst!\s+(\w+)\b/g,r;for(;(r=t.exec(e))!==null;)n.add(r[1]);if(n.size===0)return e;e=e.replace(/\bconst!\s+/g,"const ");let s=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"");for(let o of n){if(new RegExp(`\\b${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])\\s*(?:=(?!=)|\\+\\+|--|\\+=|-=|\\*=|\\/=|%=|&&=|\\|\\|=|\\?\\?=|<<=|>>=|>>>=|\\^=|&=|\\|=)`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);if(new RegExp(`(?:\\+\\+|--)\\s*${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);if(new RegExp(`\\bdelete\\s+${o}\\s*(?:\\.[\\w]+|\\[[^\\]]+\\])`,"g").test(s))throw new Error(`Cannot mutate immutable binding '${o}'. const! bindings are read-only at compile time.`);let c="push|pop|splice|shift|unshift|sort|reverse|fill|copyWithin|set";if(new RegExp(`\\b${o}\\s*\\.\\s*(?:${c})\\s*\\(`,"g").test(s))throw new Error(`Cannot call mutating method on immutable binding '${o}'. const! bindings are read-only at compile time.`)}return e}function bt(e){if(/(?<![a-zA-Z_$])\bvar\s+/.test(e))throw new Error("var is not allowed in TjsNoVar mode. Use const or let instead.");return e}function wt(e){if(/(?<![A-Za-z_$])\beval\s*\(/.test(e))throw new Error("eval() is not allowed in TjsNoeval mode. Use Eval() from TJS runtime for safe evaluation.");if(/\bnew\s+Function\s*\(/.test(e))throw new Error("new Function() is not allowed in TjsNoeval mode. Use SafeFunction() from TJS runtime.");return e}function St(e){if(!e.includes("!."))return e;let n="",t=0,r="normal",s=0;for(;t<e.length;){let o=e[t],i=e[t+1];if(r==="normal"){if(o==="/"&&i==="/"){r="line-comment",n+=o,t++;continue}if(o==="/"&&i==="*"){r="block-comment",n+=o,t++;continue}if(o==="'"){r="string-single",n+=o,t++;continue}if(o==='"'){r="string-double",n+=o,t++;continue}if(o==="`"){r="string-template",s++,n+=o,t++;continue}if(o==="!"&&i==="."&&t+2<e.length&&/[a-zA-Z_$]/.test(e[t+2])){let a=n.length,l=tr(n);if(l<a){let c=n.slice(l);n=n.slice(0,l);let p=t+2;for(;p<e.length&&/[\w$]/.test(e[p]);)p++;let m=e.slice(t+2,p);n+=`__tjs.bang(${c},'${m}')`,t=p;continue}}n+=o,t++}else r==="line-comment"?(n+=o,o===`
45
+ `&&(r="normal"),t++):r==="block-comment"?(n+=o,o==="*"&&i==="/"?(n+=i,r="normal",t+=2):t++):r==="string-single"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==="'"&&(r="normal"),t++)):r==="string-double"?(n+=o,o==="\\"?(n+=i||"",t+=2):(o==='"'&&(r="normal"),t++)):r==="string-template"?(n+=o,o==="\\"?(n+=i||"",t+=2):o==="`"?(s--,r=s>0?"string-template":"normal",t++):o==="$"&&i==="{"?(n+=i,t+=2,r="normal"):t++):(n+=o,t++)}return n}function tr(e){let n=e.length-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return e.length;for(;n>=0;){let t=e[n];if(/[\w$]/.test(t)){for(;n>=0&&/[\w$]/.test(e[n]);)n--;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t===")"){if(n=Ke(e,n,"(",")"),n<0)return 0;if(n--,n>=0&&/[\w$]/.test(e[n]))continue;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else if(t==="]"){if(n=Ke(e,n,"[","]"),n<0)return 0;if(n--,n>=0&&/[\w$]/.test(e[n]))continue;if(n>=0&&e[n]==="."){n>=1&&e[n-1]==="?"?n-=2:n--;continue}return n+1}else return n+1}return 0}function Ke(e,n,t,r){let s=1;for(n--;n>=0&&s>0;)e[n]===r?s++:e[n]===t&&s--,s>0&&n--;return n}function $t(e){let n=new Map;if(!e.includes("let "))return{source:e,annotations:n};let t=[],r=0,s="normal",o=[];for(;r<e.length;){let a=e[r],l=e[r+1];switch(s){case"single-string":if(a==="\\"&&r+1<e.length){r+=2;continue}a==="'"&&(s="normal"),r++;continue;case"double-string":if(a==="\\"&&r+1<e.length){r+=2;continue}a==='"'&&(s="normal"),r++;continue;case"template-string":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="$"&&l==="{"){r+=2,o.push(1),s="normal";continue}a==="`"&&(s="normal"),r++;continue;case"line-comment":a===`
46
+ `&&(s="normal"),r++;continue;case"block-comment":if(a==="*"&&l==="/"){r+=2,s="normal";continue}r++;continue;case"regex":if(a==="\\"&&r+1<e.length){r+=2;continue}if(a==="["){for(r++;r<e.length&&e[r]!=="]";)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}if(a==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)r++;s="normal";continue}r++;continue;case"normal":if(o.length>0){if(a==="{")o[o.length-1]++;else if(a==="}"&&(o[o.length-1]--,o[o.length-1]===0)){o.pop(),r++,s="template-string";continue}}if(a==="'"){r++,s="single-string";continue}if(a==='"'){r++,s="double-string";continue}if(a==="`"){r++,s="template-string";continue}if(a==="/"&&l==="/"){r+=2,s="line-comment";continue}if(a==="/"&&l==="*"){r+=2,s="block-comment";continue}if(a==="/"){let c=r-1;for(;c>=0&&/\s/.test(e[c]);)c--;let p=c>=0?e[c]:"";if(!p||/[=(!,;:{[&|?+\-*%<>~^]/.test(p)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){r++,s="regex";continue}}if(a==="l"&&e.slice(r,r+4)==="let "&&(r===0||!/[\w$]/.test(e[r-1]))){let c=r+4;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&/[a-zA-Z_$]/.test(e[c])){let p=c;for(;c<e.length&&/[\w$]/.test(e[c]);)c++;let m=c,u=e.slice(p,m),d=c;for(;d<e.length&&/\s/.test(e[d]);)d++;if(d<e.length&&e[d]===":"&&e[d+1]!==":"){let b=d+1;for(;b<e.length&&/[ \t]/.test(e[b]);)b++;let h=nr(e,b);if(h>b){let S=e.slice(b,h).trim();n.set(u,S),t.push({start:m,end:h,replacement:""}),r=h;continue}}}}break}r++}if(t.length===0)return{source:e,annotations:n};let i=e;for(let a=t.length-1;a>=0;a--){let l=t[a];i=i.slice(0,l.start)+l.replacement+i.slice(l.end)}return{source:i,annotations:n}}function nr(e,n){let t=n,r=0,s=0,o=0,i="normal",a=[];for(;t<e.length;){let l=e[t];if(i==="sq"){if(l==="\\"){t+=2;continue}l==="'"&&(i="normal"),t++;continue}if(i==="dq"){if(l==="\\"){t+=2;continue}l==='"'&&(i="normal"),t++;continue}if(i==="tpl"){if(l==="\\"){t+=2;continue}if(l==="$"&&e[t+1]==="{"){a.push(1),i="normal",t+=2;continue}l==="`"&&(i="normal"),t++;continue}if(a.length>0){if(l==="{")a[a.length-1]++;else if(l==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),i="tpl",t++;continue}}if(l==="'"){i="sq",t++;continue}if(l==='"'){i="dq",t++;continue}if(l==="`"){i="tpl",t++;continue}if(l==="("?r++:l===")"?r--:l==="{"?s++:l==="}"?s--:l==="["?o++:l==="]"&&o--,r===0&&s===0&&o===0&&(l==="="||l===","||l===";"||l===`
45
47
  `))return t;t++}return t}function he(e,n){let t="",r=0,s,o,i="normal",a=[],l=[{type:"top-level",braceDepth:0}],c=0,p=()=>l[l.length-1]?.type||"top-level",m=()=>{let u=l[l.length-1];return u?.type==="class-body"&&c===u.braceDepth+1};for(;r<e.length;){let u=e[r],d=e[r+1];switch(i){case"single-string":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}u==="'"&&(i="normal"),r++;continue;case"double-string":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}u==='"'&&(i="normal"),r++;continue;case"template-string":if(t+=u,u==="\\"&&r+1<e.length){t+=d,r+=2;continue}if(u==="$"&&d==="{"){t+=d,r+=2,a.push(1),i="normal";continue}u==="`"&&(i="normal"),r++;continue;case"line-comment":t+=u,u===`
46
- `&&(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 y=t.trimEnd();if(!y[y.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(y)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(y)){t+=u,r++,i="regex";continue}}break}if(u==="{"){c++,t+=u,r++;continue}if(u==="}"){c--;let y=l[l.length-1];y&&c===y.braceDepth&&l.pop(),t+=u,r++;continue}let g=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(g){let y=g[0].slice(0,-1);t+=y,r+=y.length,l.push({type:"class-body",braceDepth:c});continue}let b=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(b){let y=b[1],T=b[0].length,A=e[r+T],E=null,S=r+T;(A==="?"||A==="!")&&(E=A,S++,E==="!"?n.unsafeFunctions.add(y):n.safeFunctions.add(y)),t+=`function ${y}(`,r=S;let j=de(e,r,"(",")");if(!j){t+=e[r],r++;continue}let{content:M,endPos:C}=j;r=C;let k=Ce(M,n,!0);t+=k+")";let R=r;for(;R<e.length&&/\s/.test(e[R]);)R++;if(e[R]===":"){let J=e.slice(R,R+2),K;for(J===":?"||J===":!"?(R+=2,K=J===":?"?"safe":"unsafe"):R+=1;R<e.length&&/\s/.test(e[R]);)R++;let ne=ke(e,R);ne&&(s===void 0&&(s=ne.type,K&&(o=K)),r=ne.endPos)}let _=r;for(;_<e.length&&/\s/.test(e[_]);)_++;if(e[_]==="="&&e[_+1]===">")throw new O("Unexpected '=>' after function declaration. Function declarations use `function name(params) { body }`, not arrow syntax. Remove the `=>`.",H(n.originalSource,_),n.originalSource);continue}let h=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),w=(()=>{for(let y=t.length-1;y>=0;y--)if(!/\s/.test(t[y]))return t[y];return`
47
- `})(),x=w!=="="&&w!==","&&w!=="("&&w!=="["&&w!==">";if(h&&m()&&!x){let y=h[1].length;t+=e.slice(r,r+y),r+=y;continue}if(h&&m()&&x){let y=h[1],T=h[0].length,A=r+T;t+=y+"(",r=A;let E=de(e,r,"(",")");if(!E){t+=e[r],r++;continue}let{content:S,endPos:j}=E;r=j;let M=Ce(S,n,!0);t+=M+")";let C=r;for(;C<e.length&&/\s/.test(e[C]);)C++;if(e[C]===":"){let R=e.slice(C,C+2);for(R===":?"||R===":!"?C+=2:C++;C<e.length&&/\s/.test(e[C]);)C++;let _=ke(e,C);_&&(r=_.endPos)}let k=r;for(;k<e.length&&/\s/.test(e[k]);)k++;if(e[k]==="="&&e[k+1]===">")throw new O("Unexpected '=>' after method declaration. Methods use `name(params) { body }`, not arrow syntax. Remove the `=>`.",H(n.originalSource,k),n.originalSource);continue}if(e[r]==="("){let y=de(e,r+1,"(",")");if(!y){t+=e[r],r++;continue}let T=y.content,A=y.endPos,E=A;for(;E<e.length&&/\s/.test(e[E]);)E++;let S;if(e[E]===":"){let j=e.slice(E,E+2);for(j===":?"||j===":!"?E+=2:E++;E<e.length&&/\s/.test(e[E]);)E++;let M=ke(e,E);if(M)for(S=M.type,E=M.endPos;E<e.length&&/\s/.test(e[E]);)E++}if(e.slice(E,E+2)==="=>"){let j=null,M=T,C=T.trimStart();C.startsWith("?")&&(C.length===1||/\s/.test(C[1]))?(j="?",M=C.slice(1)):C.startsWith("!")&&(C.length===1||/\s/.test(C[1]))&&(j="!",M=C.slice(1));let k=Ce(M,n,!1);for(t+=`(${j==="?"?"/* safe */ ":j==="!"?"/* unsafe */ ":""}${k})`,r=A;r<E&&/\s/.test(e[r]);)t+=e[r],r++;S&&(r=E)}else{let j=he(T,n);t+=`(${j.source})`,r=A}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:o}}function de(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 St(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=de(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 ke(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 be(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===`
48
- `){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 Ce(e,n,t){let r=he(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=be(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`{ ${Et(d,n)} }`}if(t&&p.startsWith("[")&&p.endsWith("]")){let d=p.slice(1,-1);return`[ ${Et(d,n)} ]`}if(p.startsWith("...")){let d=$t(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(!er(p)){let d=p.match(/^(\w+)\s*=/);return d&&a(d[1]),o=!0,c}let u=$t(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 Et(e,n){return be(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=ge(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=ye(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 ge(e){let n=e.slice(1,-1).trim();return`{ ${be(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}: ${ge(u)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,m,u]=a;return`${m}: ${ge(u)}`}let l=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(l){let[,m,u]=l;return`${m}: ${ye(u)}`}let c=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(c){let[,m,u]=c;return`${m}: ${ye(u)}`}let p=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(p){let[,m,u]=p;return`${m}: ${u}`}return s}).join(", ")} }`}function ye(e){let n=e.slice(1,-1).trim();return`[ ${be(n).map(s=>{let o=s.trim();return o?o.startsWith("{")&&o.endsWith("}")?ge(o):o.startsWith("[")&&o.endsWith("]")?ye(o):s:s}).join(", ")} ]`}function er(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 $t(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 tr(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(`
49
- `,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function nr(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,l=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e)||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 S=u[2];S==="TjsStrict"?(c.tjsEquals=!0,c.tjsClass=!0,c.tjsDate=!0,c.tjsNoeval=!0,c.tjsNoVar=!0,c.tjsStandard=!0,c.tjsSafeAssign=!0):S==="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):S==="TjsEquals"?c.tjsEquals=!0:S==="TjsClass"?c.tjsClass=!0:S==="TjsDate"?c.tjsDate=!0:S==="TjsNoeval"?c.tjsNoeval=!0:S==="TjsNoVar"?c.tjsNoVar=!0:S==="TjsStandard"?c.tjsStandard=!0:S==="TjsSafeEval"?c.tjsSafeEval=!0:S==="TjsSafeAssign"&&(c.tjsSafeAssign=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${S}\\s*`),"$1")}e=tr(e),c.tjsStandard&&(e=Qe(e)),e=gt(e),e=bt(e);let d=wt(e);e=d.source;let g=d.annotations;e=Xe(e),c.tjsEquals&&!n.vmTarget&&(e=et(e)),e=tt(e),e=rt(e),e=nt(e),e=st(e),e=it(e),e=ut(e);let{source:b,returnType:h,returnSafety:w}=he(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=b;let x=ot(e);e=x.source,e=Ke(e);let y=ct(e,s);e=y.source;let T=Ye(e);e=T.source;let A=ft(e,n.dangerouslySkipTests);e=A.source;let E=pt(e,s);e=E.source;for(let S of E.polyCtorClasses)o.add(`${S}$dispatch`);return c.tjsClass&&(e=mt(e,E.polyCtorClasses)),c.tjsDate&&(e=dt(e)),c.tjsNoeval&&(e=ht(e)),c.tjsNoVar&&(e=yt(e)),e=at(e,x.extensions),{source:e,returnType:h,returnSafety:w,moduleSafety:r,tjsModes:c,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:T.blocks,tests:A.tests,testErrors:A.errors,polymorphicNames:y.polymorphicNames,extensions:x.extensions,letAnnotations:g}}function Tt(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1}=n,{source:o,returnType:i,returnSafety:a,moduleSafety:l,originalSource:c,requiredParams:p,unsafeFunctions:m,safeFunctions:u,wasmBlocks:d,tests:g,testErrors:b,letAnnotations:h,tjsModes:w}=r?nr(e,{vmTarget:s}):{source:e,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:e,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[],letAnnotations:new Map,tjsModes:{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}};try{return{ast:xt.parse(o,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:i,returnSafety:a,moduleSafety:l,originalSource:c,requiredParams:p,unsafeFunctions:m,safeFunctions:u,wasmBlocks:d,tests:g,testErrors:b,letAnnotations:h,tjsModes:w}}catch(x){let y=x.loc||{line:1,column:0};throw new O(x.message.replace(/\s*\(\d+:\d+\)$/,""),y,c,t)}}function At(e,n){for(let r of e.body){if(r.type==="ImportDeclaration")throw new O("Imports are not supported. All atoms must be registered with the VM.",r.loc?.start||{line:1,column:0},void 0,n);if(r.type==="ExportNamedDeclaration"||r.type==="ExportDefaultDeclaration")throw new O("Exports are not supported. The function is automatically exported.",r.loc?.start||{line:1,column:0},void 0,n);if(r.type==="ClassDeclaration")throw new O("Classes are not supported. Agent99 uses functional composition.",r.loc?.start||{line:1,column:0},void 0,n)}let t=e.body.filter(r=>r.type==="FunctionDeclaration");if(t.length===0)throw new O("Source must contain a function declaration",{line:1,column:0},void 0,n);if(t.length>1){let r=t[1];throw new O("Only a single function per agent is allowed",r.loc?.start||{line:1,column:0},void 0,n)}return t[0]}function jt(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(`
50
- `),g=d.filter(b=>b.trim().length>0).reduce((b,h)=>{let w=h.match(/^(\s*)/)?.[1].length||0;return Math.min(b,w)},1/0);return g>0&&g<1/0&&(u=d.map(b=>b.slice(g)).join(`
51
- `)),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 rr}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=>sr(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 sr(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 Ne(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",B(e));let s=t.name,o=n?.has(s)??!1,i=U(r),a=W(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=Ne(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}`,B(e))}function W(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?W(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=W(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=W(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=W(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?W(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?W(t)??W(r):void 0}default:return}}function vt(e){try{let n=rr(e,0,{ecmaVersion:2022});return U(n)}catch{return{kind:"any"}}}function we(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?we(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=we(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(we)}:{};default:return{}}}function ir(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=we(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function kt(e,n,t,r={},s){let o=jt(n,e),i=new Map;for(let h of e.params){let w=Ne(h,s);if(w.name==="__destructured__"&&w.type.kind==="object"&&w.type.destructuredParams)for(let[x,y]of Object.entries(w.type.destructuredParams))i.set(x,{...y,description:o.params[x]});else w.description=o.params[w.name],i.set(w.name,w)}let a;t&&(a=vt(t));let l={depth:0,locals:new Map,parameters:i,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r},c=V(e.body,l),p=[],m=[],u=[];for(let[h,w]of i.entries())w.required?m.push(h):w.default!==void 0?u.push({name:h,defaultValue:w.default}):m.push(h);m.length>0&&p.push({op:"varsImport",keys:m});for(let{name:h,defaultValue:w}of u)p.push({op:"varsImport",keys:[h]}),p.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:h},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:h,value:w}]});p.push(...c);let d=Object.fromEntries(i),g={name:e.id?.name||"anonymous",description:o.description,parameters:d,returns:a},b=ir(d);return{ast:{op:"seq",steps:p,inputSchema:b},signature:g,warnings:l.warnings}}function V(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 or(e,n);case"ExpressionStatement":return ar(e,n);case"IfStatement":return cr(e,n);case"WhileStatement":return ur(e,n);case"ForOfStatement":return fr(e,n);case"TryStatement":return pr(e,n);case"ReturnStatement":return mr(e,n);case"ThrowStatement":throw new P("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",B(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:V(e,L(n))};case"EmptyStatement":return null;default:throw new P(`Unsupported statement type: ${e.type}`,B(e),n.source,n.filename)}}function or(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",B(o),n.source,n.filename);let i=o.id.name;if(o.init){let{step:a,resultVar:l}=X(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",B(o),n.source,n.filename);t.push({op:"varSet",key:i,value:null}),n.locals.set(i,{kind:"any",nullable:!0})}}return t}function ar(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return lr(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=X(t,n);return r||(s?{op:"varSet",key:"_",value:s}:null)}return n.warnings.push({message:"Expression statement has no effect",line:B(e).line,column:B(e).column}),null}function lr(e,n){if(e.left.type!=="Identifier")throw new P("Only simple variable assignment is supported",B(e),n.source,n.filename);let t=e.left.name,{step:r,resultVar:s}=X(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function cr(e,n){let t=N(e.test,n),r=e.consequent.type==="BlockStatement"?V(e.consequent,L(n)):[oe(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?V(e.alternate,L(n)):[oe(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function ur(e,n){let t=N(e.test,n),r=e.body.type==="BlockStatement"?V(e.body,L(n)):[oe(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function fr(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",B(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",B(e.left),n.source,n.filename);let r=D(e.right,n),s=L(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?V(e.body,s):[oe(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function pr(e,n){let t=V(e.block,L(n)),r,s;if(e.handler){let o=L(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=V(e.handler.body,o)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function mr(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=X(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:D(e.argument,n)}}var Ct=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),dr=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"]),gr=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 yr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return dr.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(Ct.has(t)||ae.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(gr.has(t))return!0}}return!1}function hr(e){if(e.object.type==="Identifier"){let n=e.object.name;return Ct.has(n)||ae.has(n)}return!1}var Mt={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 br(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(ae.has(n))return Mt[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 Mt[t]||`${t} is not available in AsyncJS.`}}return null}function Nt(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 X(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return X(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let l=Nt(a);throw new P(`The 'new' keyword is not supported in AsyncJS.${l}`,B(e),n.source,n.filename)}if(e.type==="CallExpression"){let i=br(e);if(i)throw new P(i,B(e),n.source,n.filename)}if(e.type==="CallExpression"&&yr(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"&&hr(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 wr(e,n,t,r);if(e.type==="TemplateLiteral")return Er(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 wr(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",B(e),n.source,n.filename)}else throw new P("Only named function calls are supported",B(e),n.source,n.filename);if(o)return Sr(s,i,e.arguments,n,t,r);s==="console"&&e.callee.type;let a=$r(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function Sr(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=L(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")p=V(i.body,c);else{let{step:m,resultVar:u}=X(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=L(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",B(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=L(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",B(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=L(r);m.locals.set(c,{kind:"any"}),m.locals.set(p,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=V(i.body,m);else{let{step:g,resultVar:b}=X(i.body,m,"result");u=g?[g]:[{op:"varSet",key:"result",value:b}]}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 Er(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")return{$expr:"call",callee:t.callee.name,arguments:t.arguments.map(s=>N(s,n))};throw new P("Complex function calls in expressions should be lifted to statements",B(e),n.source,n.filename)}case"NewExpression":{let t=e,r="constructor";t.callee.type==="Identifier"&&(r=t.callee.name);let s=Nt(r);throw new P(`The 'new' keyword is not supported in AsyncJS.${s}`,B(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",B(e),n.source,n.filename);default:throw new P(`Unsupported expression type in condition: ${e.type}`,B(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 $r(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}=Tt(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),i=At(t,n.filename),{ast:a,signature:l,warnings:c}=kt(i,s,r,n,o);return{ast:a,signature:l,warnings:c}}var Tr=10,Se=class{atoms;constructor(n={}){this.atoms={...Ue,...n}}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(Te(n))s=Ae(n);else try{s=le(n).ast}catch(g){throw new Error(`AJS transpilation failed: ${g.message}`)}else s=n;let o=r.fuel??1e3,i=r.timeoutMs??o*Tr,a=r.capabilities??{},l=[];if(!a.store){let g=new Map,b=!1;a.store={get:async h=>(b||(b=!0,l.push("Using default in-memory store (not suitable for production)")),g.get(h)),set:async(h,w)=>{b||(b=!0,l.push("Using default in-memory store (not suitable for production)")),g.set(h,w)}}}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,context:r.context,warnings:l};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&&!xr(t,u)){let g=new F("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,b)=>{c.signal.addEventListener("abort",()=>{b(new Error(`Execution timeout after ${i}ms (fuel: ${o}). Consider increasing fuel or optimizing your agent.`))}),c.signal.aborted&&b(new Error(`Execution timeout after ${i}ms (fuel: ${o}). Consider increasing fuel or optimizing your agent.`))})])}catch(g){if(g.message?.includes("timeout")||g.message?.includes("aborted")||c.signal.aborted)m.error=new F(`Execution timeout after ${i}ms (fuel: ${o}). Consider increasing fuel or optimizing your agent.`,"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 Ar=null,Rt=()=>Ar??=new Se;function Q(e){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let n of e)Q(n);return}e.op==="return"&&"value"in e&&(e.value={__result:e.value}),e.steps&&Q(e.steps),e.then&&Q(e.then),e.else&&Q(e.else),e.body&&Q(e.body)}}async function ss(e){let{code:n,context:t={},fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=Rt(),l=/\breturn\b/.test(n)?`function __eval() { ${n} }`:`function __eval() { return (${n}) }`;try{let{ast:c}=le(l);Q(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 is(e){let{body:n,params:t=[],fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=Rt(),l=`function __safeFn(${t.join(", ")}) { ${n} }`,{ast:c}=le(l);return Q(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{ss as Eval,is as SafeFunction};
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 y=t.trimEnd();if(!y[y.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(y)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(y)){t+=u,r++,i="regex";continue}}break}if(u==="{"){c++,t+=u,r++;continue}if(u==="}"){c--;let y=l[l.length-1];y&&c===y.braceDepth&&l.pop(),t+=u,r++;continue}let g=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(g){let y=g[0].slice(0,-1);t+=y,r+=y.length,l.push({type:"class-body",braceDepth:c});continue}let b=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(b){let y=b[1],x=b[0].length,E=e[r+x],w,j=r+x;(E==="?"||E==="!")&&(w=E,j++,w==="!"?n.unsafeFunctions.add(y):n.safeFunctions.add(y)),t+=`function ${y}(`,r=j;let v=de(e,r,"(",")");if(!v){t+=e[r],r++;continue}let{content:A,endPos:M}=v;r=M;let C=Ce(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 U=r;for(;U<e.length&&/\s/.test(e[U]);)U++;if(e[U]==="="&&e[U+1]===">")throw new _("Unexpected '=>' after function declaration. Function declarations use `function name(params) { body }`, not arrow syntax. Remove the `=>`.",J(n.originalSource,U),n.originalSource);continue}let h=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),S=(()=>{for(let y=t.length-1;y>=0;y--)if(!/\s/.test(t[y]))return t[y];return`
49
+ `})(),$=S!=="="&&S!==","&&S!=="("&&S!=="["&&S!==">";if(h&&m()&&!$){let y=h[1].length;t+=e.slice(r,r+y),r+=y;continue}if(h&&m()&&$){let y=h[1],x=h[0].length,E=r+x;t+=y+"(",r=E;let w=de(e,r,"(",")");if(!w){t+=e[r],r++;continue}let{content:j,endPos:v}=w;r=v;let A=Ce(j,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 U=Me(e,M);U&&(r=U.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 y=de(e,r+1,"(",")");if(!y){t+=e[r],r++;continue}let x=y.content,E=y.endPos,w=E;for(;w<e.length&&/\s/.test(e[w]);)w++;let j;if(e[w]===":"){let v=e.slice(w,w+2);for(v===":?"||v===":!"?w+=2:w++;w<e.length&&/\s/.test(e[w]);)w++;let A=Me(e,w);if(A)for(j=A.type,w=A.endPos;w<e.length&&/\s/.test(e[w]);)w++}if(e.slice(w,w+2)==="=>"){let v=null,A=x,M=x.trimStart();M.startsWith("?")&&(M.length===1||/\s/.test(M[1]))?(v="?",A=M.slice(1)):M.startsWith("!")&&(M.length===1||/\s/.test(M[1]))&&(v="!",A=M.slice(1));let C=Ce(A,n,!1);for(t+=`(${v==="?"?"/* safe */ ":v==="!"?"/* unsafe */ ":""}${C})`,r=E;r<w&&/\s/.test(e[r]);)t+=e[r],r++;j&&(r=w)}else{let v=he(x,n);t+=`(${v.source})`,r=E}continue}t+=e[r],r++}return{source:t,returnType:s,returnSafety:o}}function de(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=de(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 be(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
+ `){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 Ce(e,n,t){let r=he(e,{originalSource:e,requiredParams:n.requiredParams,unsafeFunctions:n.unsafeFunctions,safeFunctions:n.safeFunctions}).source,s=be(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`{ ${xt(d,n)} }`}if(t&&p.startsWith("[")&&p.endsWith("]")){let d=p.slice(1,-1);return`[ ${xt(d,n)} ]`}if(p.startsWith("...")){let d=Tt(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(!rr(p)){let d=p.match(/^(\w+)\s*=/);return d&&a(d[1]),o=!0,c}let u=Tt(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 xt(e,n){return be(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=ge(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=ye(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 ge(e){let n=e.slice(1,-1).trim();return`{ ${be(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}: ${ge(u)}`}let a=o.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,m,u]=a;return`${m}: ${ge(u)}`}let l=o.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(l){let[,m,u]=l;return`${m}: ${ye(u)}`}let c=o.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(c){let[,m,u]=c;return`${m}: ${ye(u)}`}let p=o.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(p){let[,m,u]=p;return`${m}: ${u}`}return s}).join(", ")} }`}function ye(e){let n=e.slice(1,-1).trim();return`[ ${be(n).map(s=>{let o=s.trim();return o?o.startsWith("{")&&o.endsWith("}")?ge(o):o.startsWith("[")&&o.endsWith("]")?ye(o):s:s}).join(", ")} ]`}function rr(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 Tt(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 sr(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 ir(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,l=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e)||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=sr(e),c.tjsStandard&&(e=tt(e)),e=ht(e),e=St(e);let d=$t(e);e=d.source;let g=d.annotations,b=Xe(e);e=b.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 h=Qe(e,{loader:n.moduleLoader,importerPath:n.filename});e=h.source;let{source:S,returnType:$,returnSafety:y}=he(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=S;let x=lt(e);e=x.source,e=He(e);let E=ft(e,s);e=E.source;let w=Ye(e);e=w.source;let j=[...b.blocks,...h.blocks,...w.blocks],v=mt(e,n.dangerouslySkipTests);e=v.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=yt(e)),c.tjsNoeval&&(e=wt(e)),c.tjsNoVar&&(e=bt(e)),e=ct(e,x.extensions),{source:e,returnType:$,returnSafety:y,moduleSafety:r,tjsModes:c,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:j,tests:v.tests,testErrors:v.errors,polymorphicNames:E.polymorphicNames,extensions:x.extensions,letAnnotations:g}}function At(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1}=n,{source:o,returnType:i,returnSafety:a,moduleSafety:l,originalSource:c,requiredParams:p,unsafeFunctions:m,safeFunctions:u,wasmBlocks:d,tests:g,testErrors:b,letAnnotations:h,tjsModes:S}=r?ir(e,{vmTarget:s,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:jt.parse(o,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:i,returnSafety:a,moduleSafety:l,originalSource:c,requiredParams:p,unsafeFunctions:m,safeFunctions:u,wasmBlocks:d,tests:g,testErrors:b,letAnnotations:h,tjsModes:S}}catch($){let y=$.loc||{line:1,column:0};throw new _($.message.replace(/\s*\(\d+:\d+\)$/,""),y,c,t)}}function vt(e,n){for(let r of e.body){if(r.type==="ImportDeclaration")throw new _("Imports are not supported. All atoms must be registered with the VM.",r.loc?.start||{line:1,column:0},void 0,n);if(r.type==="ExportNamedDeclaration"||r.type==="ExportDefaultDeclaration")throw new _("Exports are not supported. The function is automatically exported.",r.loc?.start||{line:1,column:0},void 0,n);if(r.type==="ClassDeclaration")throw new _("Classes are not supported. Agent99 uses functional composition.",r.loc?.start||{line:1,column:0},void 0,n)}let t=e.body.filter(r=>r.type==="FunctionDeclaration");if(t.length===0)throw new _("Source must contain a function declaration",{line:1,column:0},void 0,n);if(t.length>1){let r=t[1];throw new _("Only a single function per agent is allowed",r.loc?.start||{line:1,column:0},void 0,n)}return t[0]}function kt(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(`
52
+ `),g=d.filter(b=>b.trim().length>0).reduce((b,h)=>{let S=h.match(/^(\s*)/)?.[1].length||0;return Math.min(b,S)},1/0);return g>0&&g<1/0&&(u=d.map(b=>b.slice(g)).join(`
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 or}from"acorn";function F(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=>F(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]=F(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?F(t):n==="&&"||n==="??"?F(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=F(t),o=F(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=>ar(s)),r={kind:"any"};return n.type==="ArrowFunctionExpression"&&n.body&&n.body.type!=="BlockStatement"&&(r=F(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 ar(e){return e.type==="Identifier"?{name:e.name,type:{kind:"any"}}:e.type==="AssignmentPattern"&&e.left?.type==="Identifier"?{name:e.left.name,type:F(e.right)}:e.type==="RestElement"&&e.argument?.type==="Identifier"?{name:`...${e.argument.name}`,type:{kind:"array",items:{kind:"any"}}}:{name:"?",type:{kind:"any"}}}function Ne(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=F(r),a=W(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=Ne(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 W(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?W(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=W(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=W(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=W(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?W(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?W(t)??W(r):void 0}default:return}}function Mt(e){try{let n=or(e,0,{ecmaVersion:2022});return F(n)}catch{return{kind:"any"}}}function we(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?we(e.items):{}};case"object":if(e.shape){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=we(r);return{type:"object",properties:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{oneOf:e.members.map(we)}:{};default:return{}}}function lr(e){let n={},t=[];for(let[r,s]of Object.entries(e))n[r]=we(s.type),s.required&&t.push(r);return{type:"object",properties:n,required:t.length>0?t:void 0,additionalProperties:!1}}function Nt(e,n,t,r={},s){let o=kt(n,e),i=new Map;for(let h of e.params){let S=Ne(h,s);if(S.name==="__destructured__"&&S.type.kind==="object"&&S.type.destructuredParams)for(let[$,y]of Object.entries(S.type.destructuredParams))i.set($,{...y,description:o.params[$]});else S.description=o.params[S.name],i.set(S.name,S)}let a;t&&(a=Mt(t));let l={depth:0,locals:new Map,parameters:i,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r},c=V(e.body,l),p=[],m=[],u=[];for(let[h,S]of i.entries())S.required?m.push(h):S.default!==void 0?u.push({name:h,defaultValue:S.default}):m.push(h);m.length>0&&p.push({op:"varsImport",keys:m});for(let{name:h,defaultValue:S}of u)p.push({op:"varsImport",keys:[h]}),p.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:h},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:h,value:S}]});p.push(...c);let d=Object.fromEntries(i),g={name:e.id?.name||"anonymous",description:o.description,parameters:d,returns:a},b=lr(d);return{ast:{op:"seq",steps:p,inputSchema:b},signature:g,warnings:l.warnings}}function V(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 cr(e,n);case"ExpressionStatement":return ur(e,n);case"IfStatement":return pr(e,n);case"WhileStatement":return mr(e,n);case"ForOfStatement":return dr(e,n);case"TryStatement":return gr(e,n);case"ReturnStatement":return yr(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:V(e,L(n))};case"EmptyStatement":return null;default:throw new P(`Unsupported statement type: ${e.type}`,I(e),n.source,n.filename)}}function cr(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}=H(o.init,n,i,r);a?t.push(a):l!==i&&t.push({op:s,key:i,value:l});let c=F(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 ur(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return fr(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=H(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 fr(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}=H(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function pr(e,n){let t=N(e.test,n),r=e.consequent.type==="BlockStatement"?V(e.consequent,L(n)):[oe(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?V(e.alternate,L(n)):[oe(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function mr(e,n){let t=N(e.test,n),r=e.body.type==="BlockStatement"?V(e.body,L(n)):[oe(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function dr(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=O(e.right,n),s=L(n);s.locals.set(t,{kind:"any"});let o=e.body.type==="BlockStatement"?V(e.body,s):[oe(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function gr(e,n){let t=V(e.block,L(n)),r,s;if(e.handler){let o=L(n);e.handler.param?.type==="Identifier"&&(s=e.handler.param.name,o.locals.set(s,{kind:"any"})),r=V(e.handler.body,o)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function yr(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=H(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:O(e.argument,n)}}var Rt=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),hr=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"]),br=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 wr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return hr.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(br.has(t))return!0}}return!1}function Sr(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 $r(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 H(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return H(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=$r(e);if(i)throw new P(i,I(e),n.source,n.filename)}if(e.type==="CallExpression"&&wr(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"&&Sr(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 Er(e,n,t,r);if(e.type==="TemplateLiteral")return Tr(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:O(e,n)}}function Er(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=O(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 xr(s,i,e.arguments,n,t,r);s==="console"&&e.callee.type;let a=jr(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function xr(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=L(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")p=V(i.body,c);else{let{step:m,resultVar:u}=H(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=L(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=L(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=L(r);m.locals.set(c,{kind:"any"}),m.locals.set(p,{kind:"any"});let u;if(i.body.type==="BlockStatement")u=V(i.body,m);else{let{step:g,resultVar:b}=H(i.body,m,"result");u=g?[g]:[{op:"varSet",key:"result",value:b}]}let d=O(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:O(t[0],r),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"join":return{step:{op:"join",list:n,sep:t.length>0?O(t[0],r):"",...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s};case"split":return{step:{op:"split",str:n,sep:t.length>0?O(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=>O(i,r)),...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}function Tr(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]=O(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")return{$expr:"call",callee:t.callee.name,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 O(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=O(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 O(e.expression,n);case"ArrayExpression":return e.elements.map(t=>t?O(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]=O(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 jr(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]=O(s.value,n)}return r}return{args:e.arguments.map(t=>O(t,n))}}function le(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=At(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),i=vt(t,n.filename),{ast:a,signature:l,warnings:c}=Nt(i,s,r,n,o);return{ast:a,signature:l,warnings:c}}var vr=10,Se=class{atoms;constructor(n={}){this.atoms={...Ue,...n}}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(Te(n))s=je(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??o*vr,a=r.capabilities??{},l=[];if(!a.store){let g=new Map,b=!1;a.store={get:async h=>(b||(b=!0,l.push("Using default in-memory store (not suitable for production)")),g.get(h)),set:async(h,S)=>{b||(b=!0,l.push("Using default in-memory store (not suitable for production)")),g.set(h,S)}}}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,context:r.context,warnings:l};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&&!Ar(t,u)){let g=new D("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,b)=>{c.signal.addEventListener("abort",()=>{b(new Error(`Execution timeout after ${i}ms (fuel: ${o}). Consider increasing fuel or optimizing your agent.`))}),c.signal.aborted&&b(new Error(`Execution timeout after ${i}ms (fuel: ${o}). Consider increasing fuel or optimizing your agent.`))})])}catch(g){if(g.message?.includes("timeout")||g.message?.includes("aborted")||c.signal.aborted)m.error=new D(`Execution timeout after ${i}ms (fuel: ${o}). Consider increasing fuel or optimizing your agent.`,"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 kr=null,Bt=()=>kr??=new Se;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 as(e){let{code:n,context:t={},fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=Bt(),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 ls(e){let{body:n,params:t=[],fuel:r=1e3,timeoutMs:s,capabilities:o={}}=e,i=Bt(),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{as as Eval,ls as SafeFunction};
52
54
  //# sourceMappingURL=tjs-eval.js.map