tjs-lang 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +15 -5
- package/CONTEXT.md +4 -0
- package/demo/docs.json +12 -690
- package/demo/examples.test.ts +6 -2
- package/demo/src/playground-shared.ts +48 -16
- package/demo/src/playground-test-results.test.ts +112 -0
- package/demo/src/tjs-playground.ts +11 -5
- package/dist/eslint.config.d.ts +2 -0
- package/dist/index.js +146 -141
- package/dist/index.js.map +4 -4
- package/dist/src/lang/core.d.ts +1 -1
- package/dist/src/lang/dialect.d.ts +35 -0
- package/dist/src/lang/emitters/ast.d.ts +1 -1
- package/dist/src/lang/emitters/js-tests.d.ts +7 -0
- package/dist/src/lang/emitters/js-wasm.d.ts +5 -1
- package/dist/src/lang/emitters/js.d.ts +21 -0
- package/dist/src/lang/index.d.ts +3 -1
- package/dist/src/lang/module-loader.d.ts +125 -0
- package/dist/src/lang/parser-transforms.d.ts +79 -0
- package/dist/src/lang/parser-types.d.ts +50 -0
- package/dist/src/lang/parser.d.ts +18 -0
- package/dist/src/lang/transpiler.d.ts +1 -0
- package/dist/src/lang/types.d.ts +18 -0
- package/dist/src/lang/wasm.d.ts +67 -1
- package/dist/src/vm/runtime.d.ts +18 -0
- package/dist/src/vm/vm.d.ts +15 -1
- package/dist/tjs-batteries.js +2 -2
- package/dist/tjs-batteries.js.map +2 -2
- package/dist/tjs-eval.js +43 -41
- package/dist/tjs-eval.js.map +3 -3
- package/dist/tjs-from-ts.js +2 -2
- package/dist/tjs-from-ts.js.map +2 -2
- package/dist/tjs-lang.js +107 -104
- package/dist/tjs-lang.js.map +4 -4
- package/dist/tjs-vm.js +53 -51
- package/dist/tjs-vm.js.map +3 -3
- package/docs/README.md +2 -0
- package/docs/lm-studio-setup.md +143 -0
- package/docs/universal-endpoint.md +122 -0
- package/llms.txt +9 -2
- package/package.json +24 -4
- package/src/batteries/audit.ts +6 -5
- package/src/batteries/llm.ts +8 -3
- package/src/builder.ts +0 -3
- package/src/cli/commands/check.ts +3 -2
- package/src/cli/commands/emit.ts +4 -2
- package/src/cli/commands/run.ts +6 -2
- package/src/cli/commands/test.ts +1 -1
- package/src/cli/commands/types.ts +2 -2
- package/src/lang/codegen.test.ts +4 -1
- package/src/lang/core.ts +6 -4
- package/src/lang/dialect.test.ts +63 -0
- package/src/lang/dialect.ts +50 -0
- package/src/lang/docs.test.ts +0 -1
- package/src/lang/emitters/ast.ts +145 -2
- package/src/lang/emitters/from-ts.ts +1 -1
- package/src/lang/emitters/js-tests.ts +46 -37
- package/src/lang/emitters/js.ts +19 -3
- package/src/lang/features.test.ts +6 -5
- package/src/lang/index.ts +18 -5
- package/src/lang/linter.ts +1 -1
- package/src/lang/module-loader.test.ts +9 -5
- package/src/lang/module-loader.ts +4 -5
- package/src/lang/parser-params.ts +1 -1
- package/src/lang/parser-transforms.ts +12 -18
- package/src/lang/parser-types.ts +17 -0
- package/src/lang/parser.test.ts +12 -6
- package/src/lang/parser.ts +113 -3
- package/src/lang/perf.test.ts +10 -4
- package/src/lang/runtime.ts +0 -1
- package/src/lang/subset-invariant.test.ts +90 -0
- package/src/lang/transpiler.ts +8 -0
- package/src/lang/types.ts +18 -0
- package/src/lang/wasm.test.ts +22 -16
- package/src/linalg/linalg.test.ts +16 -4
- package/src/linalg/vector-search.bench.test.ts +31 -10
- package/src/types/Type.ts +6 -6
- package/src/use-cases/asymmetric-client-server.test.ts +0 -2
- package/src/use-cases/batteries.test.ts +4 -0
- package/src/use-cases/client-server.test.ts +1 -1
- package/src/use-cases/local-helpers.test.ts +219 -0
- package/src/use-cases/timeout-overrides.test.ts +169 -0
- package/src/use-cases/unbundled-imports.test.ts +0 -1
- package/src/vm/atoms/batteries.ts +17 -3
- package/src/vm/runtime.ts +92 -7
- package/src/vm/vm.ts +50 -10
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
|
|
1
|
+
import{s as f,validate as Ee,filter as Fe}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 O=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 _t(e){return e instanceof O||e&&e.$error===!0}var Q=new Map,Ot=3600*1e3,Dt=100*1024,Te="proc_";function xe(e){return typeof e=="string"&&e.startsWith(Te)}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 Ft(){return typeof crypto<"u"&&crypto.randomUUID?Te+crypto.randomUUID():Te+Math.random().toString(36).slice(2)+Date.now().toString(36)}var Ue=new Set(["__proto__","constructor","prototype"]);function Ne(e){if(Ue.has(e))throw new Error(`Security Error: Access to '${e}' is forbidden`)}var Ut=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","metadata.google.internal"]);function qt(e){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;let t=n.hostname.toLowerCase();return!!(Ut.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 Lt(e){return!!(/\([^)]*[+*][^)]*\)[+*]/.test(e)||/\(([^|)]+)\|\1\)[+*]/.test(e)||/\(\.\*\)\+/.test(e)||/\(\.\+\)\+/.test(e)||/\(\[.*\]\+\)\+/.test(e))}function G(e){return{...e,state:Object.create(e.state)}}function Wt(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 x(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(Ue.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]=x(e[r],n);return t}return Array.isArray(e)?e.map(t=>x(t,n)):e}function H(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:H("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:H("JSON",{parse:e=>JSON.parse(e),stringify:(e,n,t)=>JSON.stringify(e,n,t)}),console:H("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:H("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:H("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:H("String",{fromCharCode:(...e)=>String.fromCharCode(...e),fromCodePoint:(...e)=>String.fromCodePoint(...e)}),Number:H("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=Fe(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."},Vt=.01,Pe=1e-4,Ie=.001,zt=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-=Vt,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 Ne(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 O("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 O(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(Ne(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&&zt.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 O("Out of Fuel",`expr.${r}`);return}}return i}default:throw new Error(`Unknown expression type: ${e.$expr}`)}}function M(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,h=p.fuel.current,w,E;try{let S=p.costOverrides?.[e],y=S!==void 0?S:a,T=typeof y=="function"?y(d,p):y;if((p.fuel.current-=T)<=0){p.error=new O("Out of Fuel",e);return}let $=p.timeoutOverrides?.[e],b=$!==void 0?$:i,j=typeof b=="function"?b(d,p):b,v,A=async()=>r(c,p);if(w=j>0?await Promise.race([A(),new Promise((k,C)=>{v=setTimeout(()=>C(new Error(`Atom '${e}' timed out`)),j)})]).finally(()=>clearTimeout(v)):await A(),c.result){if(p.consts.has(c.result))throw new Error(`Cannot reassign const variable '${c.result}'`);if(w!==void 0&&t&&!Ee(w,t)){p.error=new O(`Output validation failed for '${e}'`,e);return}p.state[c.result]=w,c.resultConst&&p.consts.add(c.result)}}catch(S){E=S.message||String(S),p.error=new O(E,e,S)}finally{if(p.trace&&g){let S=Wt(g,p.state);p.trace.push({op:e,input:d,stateDiff:S,result:w,error:E,fuelBefore:h,fuelAfter:p.fuel.current,timestamp:new Date().toISOString()})}}},docs:o,timeoutMs:i,cost:a,create:c=>({op:e,...c})}}var F=M("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}),Jt=M("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 F.exec({op:"seq",steps:e.then},n):e.else&&await F.exec({op:"seq",steps:e.else},n)},{docs:"If/Else",timeoutMs:0,cost:.1}),Zt=M("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 F.exec({op:"seq",steps:e.body},n),n.output!==void 0||n.error)return}},{docs:"While Loop",timeoutMs:0,cost:.1}),Gt=M("return",void 0,f.any,async(e,n)=>{if(n.error)return n.output=n.error,n.error;if("value"in e){let r=x(e.value,n);if(!n.localCall&&r!==void 0&&r!==null&&!_t(r)&&(typeof r!="object"||Array.isArray(r))){let s=new O(`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=Fe(t,e.schema);r instanceof Error||(t=r)}}return n.output=t,t},{docs:"Return",cost:.1}),Ht=M("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 F.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 F.exec({op:"seq",steps:e.catch},n)}},{docs:"Try/Catch",timeoutMs:0,cost:.1}),Kt=M("Error",f.object({args:f.array(f.any).optional}),void 0,async(e,n)=>{let t=e.args?.[0]??"Error";n.error=new O(String(t),"Error")},{docs:"Trigger error flow",cost:.1}),Yt=M("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]=x(n,t)},{docs:"Set Variable",cost:.1}),Xt=M("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]=x(n,t),t.consts.add(e)},{docs:"Set Const Variable (immutable)",cost:.1}),Qt=M("varGet",f.object({key:f.string}),f.any,async({key:e},n)=>x(e,n),{docs:"Get Variable",cost:.1}),en=M("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]=x({$kind:"arg",path:t},n);else for(let[t,r]of Object.entries(e))n.state[t]=x({$kind:"arg",path:r},n)},{docs:"Import variables from args into the current scope, with optional renaming.",cost:.2}),tn=M("varsLet",f.record(f.any),void 0,async(e,n)=>{for(let t of Object.keys(e))t==="op"||t==="result"||(n.state[t]=x(e[t],n))},{docs:"Initialize a set of variables in the current scope from the step object properties.",cost:.1}),nn=M("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]=x(r,n);else for(let[r,s]of Object.entries(e))t[r]=x(s,n);return t},{docs:"Export variables from the current scope, with optional renaming.",cost:.2}),rn=M("scope",f.object({steps:f.array(f.any)}),void 0,async({steps:e},n)=>{let t=G(n);await F.exec({op:"seq",steps:e},t),t.output!==void 0&&(n.output=t.output)},{docs:"Create new scope",timeoutMs:0,cost:.1}),Be=256,sn=M("callLocal",f.object({name:f.string,args:f.array(f.any)}),void 0,async({name:e,args:n},t)=>{let r=t.helpers?.[e];if(!r)return t.error=new O(`Unknown helper: ${e}`,"callLocal"),t.error;let s=(t.callDepth??0)+1;if(s>Be)return t.error=new O(`Maximum helper call depth (${Be}) exceeded \u2014 likely infinite recursion in '${e}'`,"callLocal"),t.error;let o=n.map(a=>x(a,t)),i={...t,state:{},consts:new Set,output:void 0,error:void 0,localCall:!0,callDepth:s};for(let a=0;a<r.paramNames.length;a++)i.state[r.paramNames[a]]=o[a];return await F.exec({op:"seq",steps:r.steps},i),i.error&&(t.error=i.error),i.output},{docs:"Invoke a local helper function by name",timeoutMs:0,cost:.1}),on=M("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=x(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 F.exec({op:"seq",steps:t},a),s.push(a.state.result??null)}return s},{docs:"Map Array",timeoutMs:0,cost:1}),an=M("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=x(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}),ln=M("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=x(e,o),a=x(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 F.exec({op:"seq",steps:s},p),l=p.state.result??l}return l},{docs:"Reduce Array",timeoutMs:0,cost:1}),cn=M("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=x(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}),un=M("push",f.object({list:f.array(f.any),item:f.any}),f.array(f.any),async({list:e,item:n},t)=>{let r=x(e,t),s=x(n,t);return Array.isArray(r)&&r.push(s),r},{docs:"Push to Array",cost:1}),fn=M("len",f.object({list:f.any}),f.number,async({list:e},n)=>{let t=x(e,n);return Array.isArray(t)||typeof t=="string"?t.length:0},{docs:"Length",cost:1}),pn=M("split",f.object({str:f.string,sep:f.string}),f.array(f.string),async({str:e,sep:n},t)=>x(e,t).split(x(n,t)),{docs:"Split String",cost:1}),mn=M("join",f.object({list:f.array(f.string),sep:f.string}),f.string,async({list:e,sep:n},t)=>x(e,t).join(x(n,t)),{docs:"Join String",cost:1}),dn=M("template",f.object({tmpl:f.string,vars:f.record(f.any)}),f.string,async({tmpl:e,vars:n},t)=>x(e,t).replace(/\{\{(\w+)\}\}/g,(s,o)=>String(x(n[o],t)??"")),{docs:"String Template",cost:1}),gn=M("regexMatch",f.object({pattern:f.string,value:f.any}),f.boolean,async({pattern:e,value:n},t)=>{if(Lt(e))throw new Error(`Suspicious regex pattern rejected (potential ReDoS): ${e}`);let r=x(n,t);return new RegExp(e).test(r)},{docs:"Returns true if the value matches the regex pattern.",cost:2}),yn=M("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=x(e,t),s=x(n,t),o={};return r&&Array.isArray(s)&&s.forEach(i=>o[i]=r[i]),o},{docs:"Pick Keys",cost:1}),hn=M("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=x(e,t),s=new Set(x(n,t)),o={};return r&&Object.keys(r).forEach(i=>{s.has(i)||(o[i]=r[i])}),o},{docs:"Omit Keys",cost:1}),bn=M("merge",f.object({a:f.record(f.any),b:f.record(f.any)}),f.record(f.any),async({a:e,b:n},t)=>({...x(e,t),...x(n,t)}),{docs:"Merge Objects",cost:1}),wn=M("keys",f.object({obj:f.record(f.any)}),f.array(f.string),async({obj:e},n)=>Object.keys(x(e,n)??{}),{docs:"Object Keys",cost:1}),_e=10,Oe="X-Agent-Depth";function Sn(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 $n=M("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=x(e.url,n),r=x(e.method,n),s=x(e.headers,n)||{},o=x(e.body,n),i=x(e.responseType,n),a=n.context?.requestDepth??0;if(a>=_e)throw new Error(`Agent request depth exceeded (max ${_e}). This prevents recursive agent loops.`);if(n.capabilities.fetch)return n.capabilities.fetch(t,{method:r,headers:{...s,[Oe]:String(a+1)},body:o,signal:n.signal,responseType:i});let l=n.context?.allowedFetchDomains;if(l){if(!Sn(t,l))throw new Error(`Fetch blocked: domain not in allowlist. Allowed: ${l.join(", ")}`)}else{if(qt(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,[Oe]: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 w=0;w<u.length;w++)d+=String.fromCharCode(u[w]);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}),En=M("storeGet",f.object({key:f.string}),f.any,async({key:e},n)=>{let t=x(e,n);return n.capabilities.store?.get(t)},{docs:"Store Get",cost:5}),Tn=M("storeSet",f.object({key:f.string,value:f.any}),void 0,async({key:e,value:n},t)=>{let r=x(e,t),s=x(n,t);return t.capabilities.store?.set(r,s)},{docs:"Store Set",cost:5}),xn=M("storeQuery",f.object({query:f.any}),f.array(f.any),async({query:e},n)=>n.capabilities.store?.query?.(x(e,n))??[],{docs:"Store Query",cost:5}),jn=M("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?.(x(e,r),x(n,r),x(t,r))??[],{docs:"Vector Search",cost:(e,n)=>5+(x(e.k,n)??5)}),An=M("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(x(e,t),x(n,t))},{docs:"LLM Predict",timeoutMs:12e4,cost:100}),vn=M("agentRun",f.object({agentId:f.any,input:f.any}),f.any,async({agentId:e,input:n},t)=>{let r=x(e,t),s=x(n,t),o=s;if(s&&typeof s=="object"&&!Array.isArray(s)){o={};for(let a in s)o[a]=x(s[a],t)}if(xe(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}),Mn=M("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=x(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}),De=10,kn=M("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>=De)throw new Error(`runCode recursion limit exceeded (max ${De}). 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=x(e,t),o=n?x(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 F.exec(i,a),a.error){t.error=a.error;return}return a.output},{docs:"Run dynamically generated AsyncJS code",cost:1}),Cn=M("jsonParse",f.object({str:f.string}),f.any,async({str:e},n)=>JSON.parse(x(e,n)),{docs:"Parse JSON",cost:1}),Rn=M("jsonStringify",f.object({value:f.any}),f.string,async({value:e},n)=>JSON.stringify(x(e,n)),{docs:"Stringify JSON",cost:1}),Nn=M("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(x(e,n))},{docs:"Parse XML",cost:1}),Pn=M("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=x(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 F.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}),In=M("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:${x(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 F.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}),Bn=M("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=x(t,s)??"float",i=x(r,s)??10,a=x(e,s)??0,l=x(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 h=0;h<i;h++)d+=u[g[h]%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}),_n=M("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=M("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(x(e,t)),s=x(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}),On=M("consoleLog",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(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}),Dn=M("consoleWarn",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(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}),Fn=M("consoleError",f.object({message:f.any}),void 0,async({message:e},n)=>{let t=x(e,n),r=typeof t=="string"?t:JSON.stringify(t);n.error=new O(r,"console.error")},{docs:"Emit error and stop",cost:.1}),Un=M("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=x(e,r),o=n?x(n,r):Ot,i=t?x(t,r):Dt;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=Ft(),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}),qn=M("releaseProcedure",f.object({token:f.string}),f.boolean,async({token:e},n)=>{let t=x(e,n);return Q.delete(t)},{docs:"Release a stored procedure by token",cost:.1}),Ln=M("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}),qe={seq:F,if:Jt,while:Zt,return:Gt,try:Ht,Error:Kt,varSet:Yt,constSet:Xt,varGet:Qt,varsImport:en,varsLet:tn,varsExport:nn,scope:rn,callLocal:sn,map:on,filter:an,reduce:ln,find:cn,push:un,len:fn,split:pn,join:mn,template:dn,regexMatch:gn,pick:yn,omit:hn,merge:bn,keys:wn,httpFetch:$n,storeGet:En,storeSet:Tn,storeQuery:xn,storeVectorSearch:jn,llmPredict:An,agentRun:vn,transpileCode:Mn,runCode:kn,jsonParse:Cn,jsonStringify:Rn,xmlParse:Nn,memoize:Pn,cache:In,random:Bn,uuid:_n,hash:Ae,consoleLog:On,consoleWarn:Dn,consoleError:Fn,storeProcedure:Un,releaseProcedure:qn,clearExpiredProcedures:Ln};var Wn=new Set(["true","false","null","undefined","and","or","not"]);function Vn(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=>!Wn.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){Vn(e,n);let t=zn(e),r=Je(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 zn(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 Je(e,n,t){return Jn(e,n,t)}function Jn(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);for(;e[s]==="&&";){s++;let{node:o,pos:i}=We(e,s,t);r={$expr:"logical",op:"&&",left:r,right:o},s=i}return{node:r,pos:s}}function We(e,n,t){let{node:r,pos:s}=Ve(e,n,t),o=["==","!=",">","<",">=","<="];for(;o.includes(e[s]);){let i=e[s++],{node:a,pos:l}=Ve(e,s,t);r={$expr:"binary",op:i,left:r,right:a},s=l}return{node:r,pos:s}}function Ve(e,n,t){let{node:r,pos:s}=ze(e,n,t);for(;e[s]==="+"||e[s]==="-";){let o=e[s++],{node:i,pos:a}=ze(e,s,t);r={$expr:"binary",op:o,left:r,right:i},s=a}return{node:r,pos:s}}function ze(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}=Je(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 kr}from"tosijs-schema";import*as At from"acorn";var N=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 N{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
|
|
5
|
-
`)
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`),
|
|
12
|
-
${h}
|
|
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,helpers:e.helpers,helperSteps:e.helperSteps,helperTransforming:e.helperTransforming}}function P(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function Gn(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 Ye(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 Xe(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 b=e[c];b==="{"?l++:b==="}"&&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 b=c+d[0].length;l=1;let j=b;for(;j<e.length&&l>0;){let v=e[j];v==="{"?l++:v==="}"&&l--,j++}l===0&&(m=e.slice(b,j-1),u=j)}let h=Yn(p).map(b=>{let j=Xn(e,i,b);return j?`${b}: ${j}`:b}),w={id:`__tjs_wasm_${s}`,body:p,fallback:m,captures:h,start:i,end:u};n.push(w);let E=m??p,S=h.map(b=>b.split(":")[0].trim()),y=S.length>0?S.join(", "):"",T=S.length>0?`globalThis.${w.id}(${y})`:`globalThis.${w.id}()`,$=`(globalThis.${w.id} ? ${T} : (() => {${E}})())`;t+=$,r=u,s++}else t+=e[r],r++}return{source:t,blocks:n}}function Qe(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,h=m,w=e.slice(m).match(/^\s*:\s*(\w+)/);w&&(g=w[1],h=m+w[0].length);let E=e.slice(h).match(/^\s*\{/);if(!E){t+=e[r],r++;continue}let S=h+E[0].length,y=1,T=S;for(;T<e.length&&y>0;)e[T]==="{"?y++:e[T]==="}"&&y--,T++;if(y!==0){t+=e[r],r++;continue}let $=e.slice(S,T-1),b=Hn(u),j=`__tjs_wasm_${a}`,v={id:j,name:a,returnType:g,body:$,captures:b,start:l,end:T};n.push(v);let A=b.map(I=>I.split(":")[0].trim()),C=`${i?"export ":""}function ${a}(${A.join(", ")}) { return globalThis.${j}(${A.join(", ")}) }`;t+=C,r=T}return{source:t,blocks:n}}function et(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 h=new Map;for(let $ of g.parseResult.wasmBlocks)$.name&&h.set($.name,$);if(h.size===0)return c;let w=m.split(",").map($=>$.trim()).filter($=>$.length>0),E=[],S=[];for(let $ of w){let b=$.match(/^(\w+)(?:\s+as\s+(\w+))?$/);if(!b){S.push($);continue}let j=b[1],v=b[2]??b[1],A=h.get(j);if(!A){S.push($);continue}i(A,h);let k=A.captures.map(C=>C.split(":")[0].trim());E.push(`function ${v}(${k.join(", ")}) { return globalThis.${A.id}(${k.join(", ")}) }`)}let y=E.join(`
|
|
5
|
+
`);if(S.length===0)return y?`${p}${y}`:`${p}`;let T=`${p}import { ${S.join(", ")} } from '${d}'`;return y?`${T}
|
|
6
|
+
${p}${y}`:T}),blocks:s}}function Hn(e){let n=e.trim();return n?n.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function Kn(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function Yn(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"),h=n.match(d)?.length||0,w=n.match(g)?.length||0;h<=w&&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)&&!Kn(u)&&m.push(u);return m.sort()}function Xn(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?Ze(a[1],t):void 0}return Ze(o[1],t)}function Ze(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 tt(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 nt(e){let n=/^[\s]*[([`]/,t=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,r=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,s=e.split(`
|
|
7
|
+
`),o=[],i=!1;for(let a=0;a<s.length;a++){let 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]:"",h=l.slice(g.length);o.push(g+";"+h);continue}}o.push(l)}return o.join(`
|
|
8
|
+
`)}function Qn(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 rt(e){e=Qn(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=er(o,a),m=tr(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),h=o.slice(m),E=/[a-zA-Z0-9_$]$/.test(g)?" ":"";o=`${g}${E}${c}(${u}, ${d})${h}`}}return o}function er(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 tr(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 st(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 h=l[0].trim(),w=l[0].slice(h.length);n+=`const ${s} = Type('${s}', ${h})${w}`,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[g];$==="{"?d++:$==="}"&&d--,g++}if(d!==0){n+=e[t],t++;continue}let h=e.slice(u,g-1).trim(),w=g,E=h.match(/description\s*:\s*(['"`])([^]*?)\1/);E&&!a&&(i=E[2]);let S,y=h.match(/example\s*:\s*/);if(y){let $=y.index+y[0].length,b=Tt(h,$);b&&(S=b.value.trim())}let T=h.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(T&&S){let $=T[1].trim(),b=T[2].trim(),j=c?`, ${c}`:"";n+=`const ${s} = Type('${i}', (${$}) => { if (!globalThis.__tjs?.validate(${$}, globalThis.__tjs?.infer(${S}))) return false; ${b} }, ${S}${j})`}else if(T){let $=T[1].trim(),b=T[2].trim(),j=c?`, undefined, ${c}`:"";n+=`const ${s} = Type('${i}', (${$}) => { ${b} }${j})`}else if(S){let $=c?`, ${c}`:"";n+=`const ${s} = Type('${i}', undefined, ${S}${$})`}else c?n+=`const ${s} = Type('${i}', ${c})`:n+=`const ${s} = Type('${i}')`;t=w;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 it(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=Gn(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 h=d?d[2]:s;if(o){let w=o.split(",").map(S=>{let y=S.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]}'`}),E=o.split(",").map(S=>S.trim().split("=")[0].trim());n+=`const ${s} = FunctionPredicate('${h}', [${w.join(", ")}], (${E.join(", ")}) => ({ ${g.join(", ")} }))`}else n+=`const ${s} = FunctionPredicate('${h}', { ${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 ot(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 S=e[c];S==="{"?l++:S==="}"&&l--,c++}if(l!==0){n+=e[t],t++;continue}let p=e.slice(a,c-1).trim(),m=c,u=o.split(",").map(S=>{let y=S.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 S=d.indexOf("{",g),y=1,T=S+1;for(;T<d.length&&y>0;)d[T]==="{"?y++:d[T]==="}"&&y--,T++;d=d.slice(0,g)+d.slice(T)}let h=d.match(/description\s*:\s*(['"`])([^]*?)\1/),w=d.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),E=h?h[2]:s;if(w){let S=w[1].trim().split(",").map(j=>j.trim()),y=w[2].trim(),T=S[0]||"x",$=S.slice(1),b=$.map(j=>`check${j}`);$.forEach((j,v)=>{y=y.replace(new RegExp(`\\b${j}\\s*\\(`,"g"),`${b[v]}(`)}),n+=`const ${s} = Generic([${u.join(", ")}], (${T}, ${b.join(", ")}) => { ${y} }, '${E}')`}else n+=`const ${s} = Generic([${u.join(", ")}], () => true, '${E}')`;t=m;continue}n+=e[t],t++}return n}function at(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=Ge(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=Ge(l);n+=`const ${s} = Union('${o}', [${c.join(", ")}])`,t=a;continue}}}n+=e[t],t++}return n}function Ge(e){let n=[],t=e.split("|").map(r=>r.trim());for(let r of t)r&&n.push(r);return n}function lt(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=nr(p).map(([g,h])=>`${g}: ${h}`).join(", ");n+=`const ${s} = Enum('${o}', { ${d} })`,t=m;continue}n+=e[t],t++}return n}function nr(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 ct(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 T=y[1],$=!!y[2],b=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 k=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 '${b}' in extend ${a}). Use regular function syntax instead, as extension methods need 'this' binding.`,Z)}if(d[C]!=="{"){u++;continue}let I=se(d,C),q=d.slice(u,I).trim(),ee=k.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=$?"async ":"",ne=d.slice(C+1,I-1);m.push({name:b,isAsync:$,fullText:`${b}: ${te}function(${ee}) {${ne}}`}),u=I}let g=!n.has(a);g&&n.set(a,new Set);let h=n.get(a);for(let S of m)h.add(S.name);let w=m.map(S=>` ${S.fullText}`).join(`,
|
|
13
|
+
`),E;g?E=`${i}const __ext_${a} = {
|
|
14
|
+
${w}
|
|
13
15
|
${i}}
|
|
14
|
-
`:
|
|
15
|
-
${
|
|
16
|
+
`:E=`${i}Object.assign(__ext_${a}, {
|
|
17
|
+
${w}
|
|
16
18
|
${i}})
|
|
17
|
-
`;for(let
|
|
18
|
-
`;t+=
|
|
19
|
-
`?(t++,r=0):r++;return{line:t,column:r}}function
|
|
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
|
|
21
|
-
${
|
|
22
|
-
${
|
|
19
|
+
`;for(let S of m)E+=`${i}if (__tjs?.registerExtension) { __tjs.registerExtension('${a}', '${S.name}', __ext_${a}.${S.name}) }
|
|
20
|
+
`;t+=E,r=c}return r<=e.length&&t.length<e.length,{source:t,extensions:n}}function ut(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 ft(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=He(s.trim(),n);c&&t.push(c),s="";continue}s+=l}let i=s.trim();if(i){let a=He(i,n);a&&t.push(a)}return t}function He(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 pt(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,h=g,E=o[0].indexOf("function");E>=0&&(h=g+E),i.push({name:d,fullMatchStart:g,funcKeywordStart:h,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 h=g-1,w=e.slice(u+1,h),E=g;for(;E<e.length&&e[E]!=="{";)E++;if(E>=e.length)continue;let S=se(e,E),y=m.fullMatchStart;for(;y>0&&e[y-1]===" ";)y--;let T=s.get(m.name),$=Me(w,n);if(w.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)}T.push({index:T.length+1,start:y,end:S,text:e.slice(y,S),exported:m.exported,isAsync:m.isAsync,params:$})}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 h=g+1;h<u.length;h++){let w=u[g],E=u[h];if(w.params.length!==E.params.length)continue;let S=!0;for(let y=0;y<w.params.length;y++){let T=w.params[y].defaultValue?me(w.params[y].defaultValue):"any",$=E.params[y].defaultValue?me(E.params[y].defaultValue):"any";if(T!==$){S=!1;break}}if(S){let y=J(e,E.start);throw new _(`Polymorphic function '${m}': variants ${g+1} and ${h+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),h=d?"async ":"",w=g?"export ":"",E=[...u].sort((T,$)=>{if(T.params.length!==$.params.length)return 0;let b=0,j=0;for(let v of T.params){let A=v.defaultValue?me(v.defaultValue):"any";A==="non-negative-integer"?b+=3:A==="integer"?b+=2:A!=="any"&&(b+=1)}for(let v of $.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-b}),S=[];for(let T of E){let $=[`__args.length === ${T.params.length}`],b=[];for(let j=0;j<T.params.length;j++){let v=T.params[j];if(b.push(`__args[${j}]`),v.defaultValue){let A=ft(`__args[${j}]`,v.defaultValue);A!=="true"&&$.push(A)}}S.push(` if (${$.join(" && ")}) return ${m}$${T.index}(${b.join(", ")})`)}let y=`
|
|
23
|
+
${w}${h}function ${m}(...__args) {
|
|
24
|
+
${S.join(`
|
|
23
25
|
`)}
|
|
24
26
|
return __tjs.typeError('${m}', 'no matching overload', __args)
|
|
25
27
|
}
|
|
26
|
-
`;p+=y}return{source:p,polymorphicNames:t}}function
|
|
27
|
-
`,d);d=
|
|
28
|
-
${
|
|
29
|
-
`.repeat(T),o=
|
|
30
|
-
`&&
|
|
31
|
-
function ${l}$ctor$${
|
|
32
|
-
const __obj = Object.create(${l}.prototype)`,
|
|
33
|
-
;(function() {${
|
|
34
|
-
return __obj`,
|
|
28
|
+
`;p+=y}return{source:p,polymorphicNames:t}}function mt(e){return e.replace(/(?<=^|[;\n{])\s*([A-Z][a-zA-Z0-9_]*)\s*=(?!=)/gm,(n,t)=>n.replace(t,`const ${t}`))}function dt(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,h=!1;for(;d<e.length&&u>0;){let w=e[d];if(h){h=!1,d++;continue}if(w==="\\"&&g){h=!0,d++;continue}if(g){w===g&&(g=null),d++;continue}if(w==="/"&&e[d+1]==="/"){let E=e.indexOf(`
|
|
29
|
+
`,d);d=E===-1?e.length:E+1;continue}if(w==="/"&&e[d+1]==="*"){let E=e.indexOf("*/",d+2);d=E===-1?e.length:E+2;continue}if(w==="'"||w==='"'||w==="`"){g=w,d++;continue}w==="{"?u++:w==="}"&&u--,d++}if(u===0){let w=e.slice(m,d-1).trim(),E=d,S=(e.slice(0,a).match(/\n/g)||[]).length+1;if(t.push({description:c,body:w,start:a,end:E,line:S}),!n)try{new Function(w)()}catch($){let b=c||`test at line ${S}`;r.push(`Test failed: ${b} (line ${S})
|
|
30
|
+
${$.message||$}`)}let T=(e.slice(a,E).match(/\n/g)||[]).length;s+=`
|
|
31
|
+
`.repeat(T),o=E;continue}}}s+=e[o],o++}return{source:s,tests:t,errors:r}}function gt(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,h=[];for(;(g=d.exec(u))!==null;)h.push(g.index);if(h.length<2)continue;t.add(l);let w=[];for(let $=0;$<h.length;$++){let b=h[$],j=u.indexOf("(",b),v=1,A=j+1;for(;A<u.length&&v>0;)u[A]==="("&&v++,u[A]===")"&&v--,A++;let k=u.slice(j+1,A-1),C=A;for(;C<u.length&&u[C]!=="{";)C++;let I=se(u,C),q=u.slice(C+1,I-1);w.push({index:$+1,paramStr:k,bodyText:q,fullStart:b,fullEnd:I})}let E=u;for(let $=w.length-1;$>=1;$--){let b=w[$],j=b.fullStart;for(;j>0&&E[j-1]===" ";)j--;j>0&&E[j-1]===`
|
|
32
|
+
`&&j--,E=E.slice(0,j)+E.slice(b.fullEnd)}let S="";for(let $=1;$<w.length;$++){let b=w[$],j=Me(b.paramStr,n);if(b.paramStr.includes("...")){let A=J(e,p+b.fullStart);throw new _(`Rest parameters are not supported in polymorphic constructors for '${l}'.`,A)}S+=`
|
|
33
|
+
function ${l}$ctor$${b.index}(${b.paramStr}) {`,S+=`
|
|
34
|
+
const __obj = Object.create(${l}.prototype)`,S+=`
|
|
35
|
+
;(function() {${b.bodyText}}).call(__obj)`,S+=`
|
|
36
|
+
return __obj`,S+=`
|
|
35
37
|
}
|
|
36
|
-
`}let
|
|
38
|
+
`}let y=[];for(let $=0;$<w.length;$++){let b=w[$],j=Me(b.paramStr,n),v=[`a.length === ${j.length}`];for(let A=0;A<j.length;A++){let k=j[A];if(k.defaultValue){let C=ft(`a[${A}]`,k.defaultValue);C!=="true"&&v.push(C)}}if($===0)y.push(` if (${v.join(" && ")}) return Reflect.construct(t, a)`);else{let A=j.map((k,C)=>`a[${C}]`).join(", ");y.push(` if (${v.join(" && ")}) return ${l}$ctor$${b.index}(${A})`)}}S+=`
|
|
37
39
|
function ${l}$dispatch(t, a) {
|
|
38
|
-
`,
|
|
40
|
+
`,S+=y.join(`
|
|
39
41
|
`)+`
|
|
40
|
-
`,
|
|
41
|
-
`,
|
|
42
|
-
`,i=i.slice(0,p)+
|
|
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
|
|
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
|
|
42
|
+
`,S+=` return __tjs.typeError('${l}', 'no matching constructor', a)
|
|
43
|
+
`,S+=`}
|
|
44
|
+
`,i=i.slice(0,p)+E+i.slice(m);let T=p+E.length;i=i.slice(0,T)+S+i.slice(T)}return{source:i,polyCtorClasses:t}}function yt(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 ht(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 bt(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 wt(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 St(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 $t(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=rr(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 rr(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 Et(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 h=d+1;for(;h<e.length&&/[ \t]/.test(e[h]);)h++;let w=sr(e,h);if(w>h){let E=e.slice(h,w).trim();n.set(u,E),t.push({start:m,end:w,replacement:""}),r=w;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 sr(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
|
|
47
|
-
`})(),
|
|
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`{ ${
|
|
49
|
-
`,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function
|
|
50
|
-
`),g=d.filter(
|
|
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 h=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(h){let y=h[1],T=h[0].length,$=e[r+T],b,j=r+T;($==="?"||$==="!")&&(b=$,j++,b==="!"?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:k}=v;r=k;let C=Ce(A,n,!0);t+=C+")";let I=r;for(;I<e.length&&/\s/.test(e[I]);)I++;if(e[I]===":"){let ee=e.slice(I,I+2),te;for(ee===":?"||ee===":!"?(I+=2,te=ee===":?"?"safe":"unsafe"):I+=1;I<e.length&&/\s/.test(e[I]);)I++;let ne=ke(e,I);ne&&(s===void 0&&(s=ne.type,te&&(o=te)),r=ne.endPos)}let q=r;for(;q<e.length&&/\s/.test(e[q]);)q++;if(e[q]==="="&&e[q+1]===">")throw new _("Unexpected '=>' after function declaration. Function declarations use `function name(params) { body }`, not arrow syntax. Remove the `=>`.",J(n.originalSource,q),n.originalSource);continue}let w=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),E=(()=>{for(let y=t.length-1;y>=0;y--)if(!/\s/.test(t[y]))return t[y];return`
|
|
49
|
+
`})(),S=E!=="="&&E!==","&&E!=="("&&E!=="["&&E!==">";if(w&&m()&&!S){let y=w[1].length;t+=e.slice(r,r+y),r+=y;continue}if(w&&m()&&S){let y=w[1],T=w[0].length,$=r+T;t+=y+"(",r=$;let b=de(e,r,"(",")");if(!b){t+=e[r],r++;continue}let{content:j,endPos:v}=b;r=v;let A=Ce(j,n,!0);t+=A+")";let k=r;for(;k<e.length&&/\s/.test(e[k]);)k++;if(e[k]===":"){let I=e.slice(k,k+2);for(I===":?"||I===":!"?k+=2:k++;k<e.length&&/\s/.test(e[k]);)k++;let q=ke(e,k);q&&(r=q.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 T=y.content,$=y.endPos,b=$;for(;b<e.length&&/\s/.test(e[b]);)b++;let j;if(e[b]===":"){let v=e.slice(b,b+2);for(v===":?"||v===":!"?b+=2:b++;b<e.length&&/\s/.test(e[b]);)b++;let A=ke(e,b);if(A)for(j=A.type,b=A.endPos;b<e.length&&/\s/.test(e[b]);)b++}if(e.slice(b,b+2)==="=>"){let v=null,A=T,k=T.trimStart();k.startsWith("?")&&(k.length===1||/\s/.test(k[1]))?(v="?",A=k.slice(1)):k.startsWith("!")&&(k.length===1||/\s/.test(k[1]))&&(v="!",A=k.slice(1));let C=Ce(A,n,!1);for(t+=`(${v==="?"?"/* safe */ ":v==="!"?"/* unsafe */ ":""}${C})`,r=$;r<b&&/\s/.test(e[r]);)t+=e[r],r++;j&&(r=b)}else{let v=he(T,n);t+=`(${v.source})`,r=$}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 Tt(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===`
|
|
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=jt(p);return d!==-1?p.slice(0,d).trim():c}let m=p.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(m){let[,d,g]=m;return a(d),o=!0,`${d} = ${g}`}if(!ir(p)){let d=p.match(/^(\w+)\s*=/);return d&&a(d[1]),o=!0,c}let u=jt(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 ir(e){let n=0,t=!1,r=!1,s=!1,o="";for(let i=0;i<e.length;i++){let a=e[i];if(!s&&(a==="'"||a==='"'||a==="`")){s=!0,o=a;continue}if(s){a===o&&e[i-1]!=="\\"&&(s=!1);continue}a==="("||a==="{"||a==="["?n++:a===")"||a==="}"||a==="]"?n--:n===0&&(a===":"&&(t=!0),a==="="&&e[i+1]!==">"&&(r=!0))}return t&&!r}function jt(e){let n=0,t=!1,r="";for(let s=0;s<e.length;s++){let o=e[s];if(!t&&(o==="'"||o==='"'||o==="`")){t=!0,r=o;continue}if(t){o===r&&e[s-1]!=="\\"&&(t=!1);continue}if(o==="("||o==="{"||o==="[")n++;else if(o===")"||o==="}"||o==="]")n--;else if(n===0&&o===":")return s}return-1}function or(e){let n="",t=0;for(;t<e.length;){let r=e[t];if(r==="'"||r==='"'||r==="`"){let s=r;for(n+=r,t++;t<e.length&&e[t]!==s;)e[t]==="\\"&&(n+=e[t++]),t<e.length&&(n+=e[t++]);t<e.length&&(n+=e[t++]);continue}if(r==="/"&&e[t+1]==="*"){let s=e.indexOf("*/",t+2),o=s===-1?e.slice(t):e.slice(t,s+2);n+=o,t+=o.length;continue}if(r==="/"&&e[t+1]==="/"){let s=e.indexOf(`
|
|
51
|
+
`,t),o=s===-1?e.length:s;n+=" ".repeat(o-t),t=o;continue}n+=r,t++}return n}function ar(e,n={}){let t=e,r,s=new Set,o=new Set,i=new Set,a=/\/\*\s*tjs\s*<-\s*\S+\s*\*\//.test(e),l=n.dialect==="js"?!0:n.dialect==="tjs"?!1:a||n.vmTarget,c=l?{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}:{tjsEquals:!0,tjsClass:!0,tjsDate:!0,tjsNoeval:!0,tjsStandard:!0,tjsSafeEval:!1,tjsNoVar:!0,tjsSafeAssign:!0};l&&(r="none");let p=e.match(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\b/);p&&(r=p[2],e=e.replace(/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*safety\s+(none|inputs|all)\s*/,"$1"));let m=/^(\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)\s*(TjsStrict|TjsCompat|TjsEquals|TjsClass|TjsDate|TjsNoeval|TjsNoVar|TjsStandard|TjsSafeEval|TjsSafeAssign)\b/,u;for(;u=e.match(m);){let k=u[2];k==="TjsStrict"?(c.tjsEquals=!0,c.tjsClass=!0,c.tjsDate=!0,c.tjsNoeval=!0,c.tjsNoVar=!0,c.tjsStandard=!0,c.tjsSafeAssign=!0):k==="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):k==="TjsEquals"?c.tjsEquals=!0:k==="TjsClass"?c.tjsClass=!0:k==="TjsDate"?c.tjsDate=!0:k==="TjsNoeval"?c.tjsNoeval=!0:k==="TjsNoVar"?c.tjsNoVar=!0:k==="TjsStandard"?c.tjsStandard=!0:k==="TjsSafeEval"?c.tjsSafeEval=!0:k==="TjsSafeAssign"&&(c.tjsSafeAssign=!0),e=e.replace(new RegExp(`^(\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)\\s*${k}\\s*`),"$1")}e=or(e),c.tjsStandard&&(e=nt(e)),e=bt(e),e=$t(e);let d=Et(e);e=d.source;let g=d.annotations,h=Qe(e);e=h.source,e=tt(e),c.tjsEquals&&!n.vmTarget&&(e=rt(e)),e=st(e),e=ot(e),e=it(e),e=at(e),e=lt(e),e=mt(e);let w=et(e,{loader:n.moduleLoader,importerPath:n.filename});e=w.source;let{source:E,returnType:S,returnSafety:y}=he(e,{originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i});e=E;let T=ct(e);e=T.source,e=Ye(e);let $=pt(e,s);e=$.source;let b=Xe(e);e=b.source;let j=[...h.blocks,...w.blocks,...b.blocks],v=dt(e,n.dangerouslySkipTests);e=v.source;let A=gt(e,s);e=A.source;for(let k of A.polyCtorClasses)o.add(`${k}$dispatch`);return c.tjsClass&&(e=yt(e,A.polyCtorClasses)),c.tjsDate&&(e=ht(e)),c.tjsNoeval&&(e=St(e)),c.tjsNoVar&&(e=wt(e)),e=ut(e,T.extensions),{source:e,returnType:S,returnSafety:y,moduleSafety:r,tjsModes:c,originalSource:t,requiredParams:s,unsafeFunctions:o,safeFunctions:i,wasmBlocks:j,tests:v.tests,testErrors:v.errors,polymorphicNames:$.polymorphicNames,extensions:T.extensions,letAnnotations:g}}function vt(e,n={}){let{filename:t="<source>",colonShorthand:r=!0,vmTarget:s=!1,dialect:o}=n,{source:i,returnType:a,returnSafety:l,moduleSafety:c,originalSource:p,requiredParams:m,unsafeFunctions:u,safeFunctions:d,wasmBlocks:g,tests:h,testErrors:w,letAnnotations:E,tjsModes:S}=r?ar(e,{vmTarget:s,dialect:o,moduleLoader:n.moduleLoader,filename:n.filename}):{source:e,returnType:void 0,returnSafety:void 0,moduleSafety:void 0,originalSource:e,requiredParams:new Set,unsafeFunctions:new Set,safeFunctions:new Set,wasmBlocks:[],tests:[],testErrors:[],letAnnotations:new Map,tjsModes:{tjsEquals:!1,tjsClass:!1,tjsDate:!1,tjsNoeval:!1,tjsStandard:!1,tjsSafeEval:!1,tjsNoVar:!1,tjsSafeAssign:!1}};try{return{ast:At.parse(i,{ecmaVersion:2022,sourceType:"module",locations:!0,allowReturnOutsideFunction:!1}),returnType:a,returnSafety:l,moduleSafety:c,originalSource:p,requiredParams:m,unsafeFunctions:u,safeFunctions:d,wasmBlocks:g,tests:h,testErrors:w,letAnnotations:E,tjsModes:S}}catch(y){let T=y.loc||{line:1,column:0};throw new _(y.message.replace(/\s*\(\d+:\d+\)$/,""),T,p,t)}}function Mt(e,n){for(let o of e.body){if(o.type==="ImportDeclaration")throw new _("Imports are not supported. All atoms must be registered with the VM.",o.loc?.start||{line:1,column:0},void 0,n);if(o.type==="ExportNamedDeclaration"||o.type==="ExportDefaultDeclaration")throw new _("Exports are not supported. The function is automatically exported.",o.loc?.start||{line:1,column:0},void 0,n);if(o.type==="ClassDeclaration")throw new _("Classes are not supported. Agent99 uses functional composition.",o.loc?.start||{line:1,column:0},void 0,n)}let t=e.body.filter(o=>o.type==="FunctionDeclaration");if(t.length===0)throw new _("Source must contain a function declaration",{line:1,column:0},void 0,n);let r=t[t.length-1],s=new Map;for(let o=0;o<t.length-1;o++){let i=t[o],a=i.id?.name;if(!a)throw new _("Helper function must have a name",i.loc?.start||{line:1,column:0},void 0,n);if(s.has(a))throw new _(`Duplicate helper function name: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);if(a===r.id?.name)throw new _(`Helper function cannot share a name with the entry function: ${a}`,i.loc?.start||{line:1,column:0},void 0,n);s.set(a,i)}return{entry:r,helpers:s}}function 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(h=>h.trim().length>0).reduce((h,w)=>{let E=w.match(/^(\s*)/)?.[1].length||0;return Math.min(h,E)},1/0);return g>0&&g<1/0&&(u=d.map(h=>h.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 lr}from"acorn";function U(e){switch(e.type){case"Literal":{let n=e.value;if(n===null)return{kind:"null"};if(typeof n=="string")return{kind:"string"};if(typeof n=="number"){let t=e.raw;return t&&t.includes(".")?{kind:"number"}:{kind:"integer"}}return typeof n=="boolean"?{kind:"boolean"}:{kind:"any"}}case"ArrayExpression":{let n=e.elements;if(n.length===0)return{kind:"array",items:{kind:"any"}};let t=n.filter(i=>i!=null).map(i=>U(i));if(t.length===0)return{kind:"array",items:{kind:"any"}};let r=new Map;for(let i of t){let a=JSON.stringify(i);r.has(a)||r.set(a,i)}let s=[...r.values()];return{kind:"array",items:s.length===1?s[0]:{kind:"union",members:s}}}case"ObjectExpression":{let n=e.properties,t={};for(let r of n)if(r.type==="Property"&&r.key.type==="Identifier"){let s=r.key.name;t[s]=U(r.value)}return{kind:"object",shape:t}}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="||"?U(t):n==="&&"||n==="??"?U(r):{kind:"any"}}case"BinaryExpression":{let{operator:n,left:t,right:r}=e;if(n==="|"){let s=U(t),o=U(r);return o.kind==="null"?{...s,nullable:!0}:s.kind==="null"?{...o,nullable:!0}:{kind:"union",members:[s,o]}}return{kind:"any"}}case"Identifier":return e.name==="undefined"?{kind:"undefined"}:{kind:"any"};case"ArrowFunctionExpression":case"FunctionExpression":{let n=e,t=n.params.map(s=>cr(s)),r={kind:"any"};return n.type==="ArrowFunctionExpression"&&n.body&&n.body.type!=="BlockStatement"&&(r=U(n.body)),{kind:"function",params:t,returns:r}}case"UnaryExpression":{let n=e.operator,t=e.argument;if(n==="+"&&t.type==="Literal"&&typeof t.value=="number")return{kind:"non-negative-integer"};if(n==="-"&&t.type==="Literal"&&typeof t.value=="number"){let s=t.raw;return s&&s.includes(".")?{kind:"number"}:{kind:"integer"}}return{kind:"any"}}default:return{kind:"any"}}}function cr(e){return e.type==="Identifier"?{name:e.name,type:{kind:"any"}}:e.type==="AssignmentPattern"&&e.left?.type==="Identifier"?{name:e.left.name,type:U(e.right)}:e.type==="RestElement"&&e.argument?.type==="Identifier"?{name:`...${e.argument.name}`,type:{kind:"array",items:{kind:"any"}}}:{name:"?",type:{kind:"any"}}}function Re(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 N("Only simple parameter names are supported",P(e));let s=t.name,o=n?.has(s)??!1,i=U(r),a=V(r);return{name:s,type:i,required:o,default:o?null:a,example:a,loc:{start:e.start,end:e.end}}}if(e.type==="ObjectPattern"){let t=e.properties,r={},s={};for(let o of t)if(o.type==="Property"){let i=o.key.type==="Identifier"?o.key.name:String(o.key.value);if(o.value.type==="Identifier")r[i]={kind:"any"},s[i]={name:i,type:{kind:"any"},required:!0};else if(o.value.type==="AssignmentPattern"){let a=Re(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 N(`Unsupported parameter pattern: ${e.type}`,P(e))}function V(e){switch(e.type){case"Literal":return e.value;case"ArrayExpression":return e.elements.map(n=>n?V(n):null);case"ObjectExpression":{let n={};for(let t of e.properties)t.type==="Property"&&t.key.type==="Identifier"&&(n[t.key.name]=V(t.value));return n}case"UnaryExpression":if(e.operator==="-"){let n=V(e.argument);return typeof n=="number"?-n:void 0}if(e.operator==="+"){let n=V(e.argument);return typeof n=="number"?+n:void 0}return;case"BinaryExpression":{let{operator:n,left:t}=e;return n==="|"?V(t):void 0}case"LogicalExpression":{let{operator:n,left:t,right:r}=e;return n==="&&"&&t.type==="Literal"&&t.value===null?null:n==="||"||n==="??"?V(t)??V(r):void 0}default:return}}function Ct(e){try{let n=lr(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 ur(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,o){let i=kt(n,e),a=new Map;for(let S of e.params){let y=Re(S,s);if(y.name==="__destructured__"&&y.type.kind==="object"&&y.type.destructuredParams)for(let[T,$]of Object.entries(y.type.destructuredParams))a.set(T,{...$,description:i.params[T]});else y.description=i.params[y.name],a.set(y.name,y)}let l;t&&(l=Ct(t));let c={depth:0,locals:new Map,parameters:a,atoms:new Set(Object.keys(r.atoms||{})),warnings:[],source:n,filename:r.filename||"<source>",options:r,helpers:o,helperSteps:o?new Map:void 0,helperTransforming:o?new Set:void 0},p=W(e.body,c),m=[],u=[],d=[];for(let[S,y]of a.entries())y.required?u.push(S):y.default!==void 0?d.push({name:S,defaultValue:y.default}):u.push(S);u.length>0&&m.push({op:"varsImport",keys:u});for(let{name:S,defaultValue:y}of d)m.push({op:"varsImport",keys:[S]}),m.push({op:"if",condition:{$expr:"binary",op:"==",left:{$expr:"ident",name:S},right:{$expr:"literal",value:null}},then:[{op:"varSet",key:S,value:y}]});m.push(...p);let g=Object.fromEntries(a),h={name:e.id?.name||"anonymous",description:i.description,parameters:g,returns:l},w=ur(g),E=c.helperSteps&&c.helperSteps.size>0?Object.fromEntries(c.helperSteps):void 0;return{ast:{op:"seq",steps:m,inputSchema:w,...E&&{helpers:E}},signature:h,warnings:c.warnings}}function W(e,n){let t=[];for(let r of e.body){let s=oe(r,n);s&&(Array.isArray(s)?t.push(...s):t.push(s))}return t}function oe(e,n){switch(e.type){case"VariableDeclaration":return fr(e,n);case"ExpressionStatement":return pr(e,n);case"IfStatement":return dr(e,n);case"WhileStatement":return gr(e,n);case"ForOfStatement":return yr(e,n);case"TryStatement":return hr(e,n);case"ReturnStatement":return br(e,n);case"ThrowStatement":throw new N("'throw' is not supported in AsyncJS. Use Error('message') to trigger error flow",P(e),n.source,n.filename);case"BlockStatement":return{op:"scope",steps:W(e,L(n))};case"EmptyStatement":return null;default:throw new N(`Unsupported statement type: ${e.type}`,P(e),n.source,n.filename)}}function fr(e,n){let t=[],r=e.kind==="const",s=r?"constSet":"varSet";for(let o of e.declarations){if(o.id.type!=="Identifier")throw new N("Only simple variable names are supported",P(o),n.source,n.filename);let i=o.id.name;if(o.init){let{step:a,resultVar:l}=K(o.init,n,i,r);a?t.push(a):l!==i&&t.push({op:s,key:i,value:l});let c=U(o.init);n.locals.set(i,c)}else{if(r)throw new N("const declarations must be initialized",P(o),n.source,n.filename);t.push({op:"varSet",key:i,value:null}),n.locals.set(i,{kind:"any",nullable:!0})}}return t}function pr(e,n){let t=e.expression;if(t.type==="AssignmentExpression")return mr(t,n);if(t.type==="CallExpression"){let{step:r,resultVar:s}=K(t,n);return r||(s?{op:"varSet",key:"_",value:s}:null)}return n.warnings.push({message:"Expression statement has no effect",line:P(e).line,column:P(e).column}),null}function mr(e,n){if(e.left.type!=="Identifier")throw new N("Only simple variable assignment is supported",P(e),n.source,n.filename);let t=e.left.name,{step:r,resultVar:s}=K(e.right,n,t);return r||{op:"varSet",key:t,value:s}}function dr(e,n){let t=R(e.test,n),r=e.consequent.type==="BlockStatement"?W(e.consequent,L(n)):[oe(e.consequent,n)].filter(Boolean),s;return e.alternate&&(s=e.alternate.type==="BlockStatement"?W(e.alternate,L(n)):[oe(e.alternate,n)].filter(Boolean)),{op:"if",condition:t,then:r,...s&&{else:s}}}function gr(e,n){let t=R(e.test,n),r=e.body.type==="BlockStatement"?W(e.body,L(n)):[oe(e.body,n)].filter(Boolean);return{op:"while",condition:t,body:r}}function yr(e,n){let t;if(e.left.type==="VariableDeclaration"){let i=e.left.declarations[0];if(i.id.type!=="Identifier")throw new N("Only simple variable names are supported in for...of",P(e.left),n.source,n.filename);t=i.id.name}else if(e.left.type==="Identifier")t=e.left.name;else throw new N("Unsupported for...of left-hand side",P(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"?W(e.body,s):[oe(e.body,s)].filter(Boolean);return{op:"map",items:r,as:t,steps:o}}function hr(e,n){let t=W(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=W(e.handler.body,o)}return{op:"try",try:t,...r&&{catch:r},...s&&{catchParam:s}}}function br(e,n){if(!e.argument)return{op:"return",value:{}};let{step:t,resultVar:r}=K(e.argument,n,"__returnVal__");return t?[t,{op:"return",value:r}]:{op:"return",value:D(e.argument,n)}}var Pt=new Set(["Math","JSON","Array","Object","String","Number","console","Date","Schema"]),wr=new Set(["parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent","Set","Date","filter"]),ae=new Set(["RegExp","Promise","Map","WeakSet","WeakMap","Symbol","Proxy","Reflect","Function","eval","setTimeout","setInterval","fetch","require","import","process","window","document","global","globalThis"]),Sr=new Set(["toUpperCase","toLowerCase","trim","trimStart","trimEnd","charAt","charCodeAt","codePointAt","concat","includes","indexOf","lastIndexOf","startsWith","endsWith","slice","substring","substr","replace","replaceAll","match","search","padStart","padEnd","repeat","normalize","localeCompare","toString","valueOf","at","reverse","sort","fill","copyWithin","flat","flatMap","every","some","forEach","add","remove","has","clear","toArray","union","intersection","diff","format","isBefore","isAfter"]);function $r(e){if(e.callee.type==="Identifier"){let n=e.callee.name;return wr.has(n)||ae.has(n)}if(e.callee.type==="MemberExpression"){let n=e.callee;if(n.object.type==="Identifier"){let t=n.object.name;if(Pt.has(t)||ae.has(t))return!0}if(n.property.type==="Identifier"){let t=n.property.name;if(Sr.has(t))return!0}}return!1}function Er(e){if(e.object.type==="Identifier"){let n=e.object.name;return Pt.has(n)||ae.has(n)}return!1}var Rt={RegExp:"RegExp is not available. Use string methods or the regexMatch atom.",Promise:"Promise is not needed. All operations are implicitly async.",Map:"Map is not available. Use plain objects instead.",WeakSet:"WeakSet is not available.",WeakMap:"WeakMap is not available.",Symbol:"Symbol is not available.",Proxy:"Proxy is not available.",Reflect:"Reflect is not available.",Function:"Function constructor is not available. Define functions normally.",eval:"eval is not available. Code is compiled, not evaluated.",setTimeout:"setTimeout is not available. Use the delay atom.",setInterval:"setInterval is not available. Use while loops with delay.",fetch:"fetch is not available. Use the httpFetch atom.",require:"require is not available. Atoms must be registered with the VM.",import:"import is not available. Atoms must be registered with the VM.",process:"process is not available. AsyncJS runs in a sandboxed environment.",window:"window is not available. AsyncJS runs in a sandboxed environment.",document:"document is not available. AsyncJS runs in a sandboxed environment.",global:"global is not available. AsyncJS runs in a sandboxed environment.",globalThis:"globalThis is not available. Use builtins directly."};function Tr(e){if(e.callee.type==="Identifier"){let n=e.callee.name;if(ae.has(n))return Rt[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 Rt[t]||`${t} is not available in AsyncJS.`}}return null}function It(e){return{Date:" Use Date() or Date('2024-01-15') instead - no 'new' needed.",Set:" Use Set([items]) instead - no 'new' needed.",Map:" Use plain objects instead of Map.",Array:" Use array literals like [1, 2, 3] instead.",Object:" Use object literals like { key: value } instead.",Error:" Return an error object like { error: 'message' } instead.",RegExp:" Use string methods or the regexMatch atom.",Promise:" Not needed - all operations are implicitly async.",WeakSet:" WeakSet is not available.",WeakMap:" WeakMap is not available."}[e]||" Use factory functions or object literals instead."}function K(e,n,t,r){let s=r?"constSet":"varSet";if(e.type==="ChainExpression")return K(e.expression,n,t,r);if(e.type==="NewExpression"){let i=e,a="constructor";i.callee.type==="Identifier"&&(a=i.callee.name);let l=It(a);throw new N(`The 'new' keyword is not supported in AsyncJS.${l}`,P(e),n.source,n.filename)}if(e.type==="CallExpression"){let i=Tr(e);if(i)throw new N(i,P(e),n.source,n.filename)}if(e.type==="CallExpression"&&$r(e)){let i=R(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="MemberExpression"&&Er(e)){let i=R(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}if(e.type==="CallExpression")return xr(e,n,t,r);if(e.type==="TemplateLiteral")return vr(e,n,t,r);if(e.type==="BinaryExpression"||e.type==="LogicalExpression"||e.type==="UnaryExpression"){let i=R(e,n);return t?{step:{op:s,key:t,value:i},resultVar:t}:{step:null,resultVar:i}}return{step:null,resultVar:D(e,n)}}function xr(e,n,t,r){let s,o=!1,i;if(e.callee.type==="Identifier")s=e.callee.name;else if(e.callee.type==="MemberExpression"){let l=e.callee;if(l.property.type==="Identifier")s=l.property.name,o=!0,i=D(l.object,n);else throw new N("Computed method names are not supported",P(e),n.source,n.filename)}else throw new N("Only named function calls are supported",P(e),n.source,n.filename);if(o)return Ar(s,i,e.arguments,n,t,r);if(s==="console"&&e.callee.type,n.helpers?.has(s)){let l=jr(s,n,e),c=e.arguments.map(p=>D(p,n));if(c.length!==l.length)throw new N(`Helper '${s}' expects ${l.length} argument(s), got ${c.length}`,P(e),n.source,n.filename);return{step:{op:"callLocal",name:s,args:c,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}let a=Mr(e,n);return{step:{op:s,...a,...t&&{result:t},...t&&r&&{resultConst:!0}},resultVar:t}}function jr(e,n,t){let r=n.helpers.get(e),s=[];for(let o of r.params){let i;if(o.type==="Identifier"?i=o:o.type==="AssignmentPattern"&&o.left?.type==="Identifier"&&(i=o.left),!i)throw new N(`Helper '${e}' parameters must be plain identifiers (optionally with an example value); destructuring is not supported`,o.loc?.start??P(t),n.source,n.filename);s.push(i.name)}if(n.helperSteps.has(e)||n.helperTransforming.has(e))return s;n.helperTransforming.add(e);try{let o={depth:0,locals:new Map,parameters:new Map(s.map(a=>[a,{name:a,type:{kind:"any"},required:!0}])),atoms:n.atoms,warnings:n.warnings,source:n.source,filename:n.filename,options:n.options,helpers:n.helpers,helperSteps:n.helperSteps,helperTransforming:n.helperTransforming},i=W(r.body,o);n.helperSteps.set(e,{steps:i,paramNames:s})}finally{n.helperTransforming.delete(e)}return s}function Ar(e,n,t,r,s,o){switch(e){case"map":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=L(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")p=W(i.body,c);else{let{step:m,resultVar:u}=K(i.body,c,"result");p=m?[m]:[{op:"varSet",key:"result",value:u}]}return{step:{op:"map",items:n,as:l,steps:p,...s&&{result:s},...s&&o&&{resultConst:!0}},resultVar:s}}break;case"filter":if(t.length>0&&(t[0].type==="ArrowFunctionExpression"||t[0].type==="FunctionExpression")){let i=t[0],a=i.params[0],l=a?.type==="Identifier"?a.name:"item",c=L(r);c.locals.set(l,{kind:"any"});let p;if(i.body.type==="BlockStatement")throw new N("filter callback must be an expression, not a block",P(t[0]),r.source,r.filename);return p=R(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 N("find callback must be an expression, not a block",P(t[0]),r.source,r.filename);return p=R(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=W(i.body,m);else{let{step:g,resultVar:h}=K(i.body,m,"result");u=g?[g]:[{op:"varSet",key:"result",value:h}]}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 vr(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 R(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=R(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:R(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 R(e.expression,n);case"BinaryExpression":{let t=e;return{$expr:"binary",op:t.operator,left:R(t.left,n),right:R(t.right,n)}}case"LogicalExpression":{let t=e;return{$expr:"logical",op:t.operator,left:R(t.left,n),right:R(t.right,n)}}case"UnaryExpression":{let t=e;return{$expr:"unary",op:t.operator,argument:R(t.argument,n)}}case"ConditionalExpression":{let t=e;return{$expr:"conditional",test:R(t.test,n),consequent:R(t.consequent,n),alternate:R(t.alternate,n)}}case"ArrayExpression":return{$expr:"array",elements:e.elements.filter(r=>r!==null).map(r=>R(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:R(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:R(r.object,n),method:s,arguments:t.arguments.map(i=>R(i,n)),...o&&{optional:!0}}}if(t.callee.type==="Identifier"){let r=t.callee.name;if(n.helpers?.has(r))throw new N(`Helper '${r}' cannot be called inside an expression. Assign its result to a variable first: const result = ${r}(...); then use result.`,P(e),n.source,n.filename);return{$expr:"call",callee:r,arguments:t.arguments.map(s=>R(s,n))}}throw new N("Complex function calls in expressions should be lifted to statements",P(e),n.source,n.filename)}case"NewExpression":{let t=e,r="constructor";t.callee.type==="Identifier"&&(r=t.callee.name);let s=It(r);throw new N(`The 'new' keyword is not supported in AsyncJS.${s}`,P(e),n.source,n.filename)}case"TemplateLiteral":throw new N("Template literals inside expressions are not supported. Assign to a variable first: const msg = `hello ${name}`; then use msg",P(e),n.source,n.filename);default:throw new N(`Unsupported expression type in condition: ${e.type}`,P(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 R(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 R(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 R(e,n);case"CallExpression":return R(e,n);case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"ConditionalExpression":return R(e,n);default:return null}}function Mr(e,n){if(e.arguments.length===1&&e.arguments[0].type==="ObjectExpression"){let t=e.arguments[0],r={};for(let s of t.properties)if(s.type==="Property"){let o=s.key.type==="Identifier"?s.key.name:String(s.key.value);r[o]=D(s.value,n)}return r}return{args:e.arguments.map(t=>D(t,n))}}function le(e,n={}){let{ast:t,returnType:r,originalSource:s,requiredParams:o}=vt(e,{filename:n.filename,colonShorthand:!0,vmTarget:!0}),{entry:i,helpers:a}=Mt(t,n.filename),{ast:l,signature:c,warnings:p}=Nt(i,s,r,n,o,a.size>0?a:void 0);return{ast:l,signature:c,warnings:p}}var Cr=6e4,Se=class{atoms;_defaultRunTimeout;constructor(n={}){this.atoms={...qe,...n}}get defaultRunTimeout(){if(this._defaultRunTimeout===void 0){let n=0;for(let t of Object.values(this.atoms)){let r=t.timeoutMs??1e3;r>0&&r>n&&(n=r)}this._defaultRunTimeout=Math.max(Cr,n*2)}return this._defaultRunTimeout}get builder(){return new re(this.atoms)}get Agent(){return new re(this.atoms)}get A99(){return this.Agent}resolve(n){return this.atoms[n]}getTools(n="all"){let t=Object.values(this.atoms);if(Array.isArray(n))t=t.filter(r=>n.includes(r.op));else if(n==="flow"){let r=["seq","if","while","return","try","varSet","varGet","scope"];t=t.filter(s=>r.includes(s.op))}return t.map(r=>({type:"function",function:{name:r.op,description:r.docs,parameters:r.inputSchema?.schema??{}}}))}async run(n,t={},r={}){let s;if(typeof n=="string")if(xe(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??this.defaultRunTimeout,a=r.capabilities??{},l=[];if(!a.store){let g=new Map,h=!1;a.store={get:async w=>(h||(h=!0,l.push("Using default in-memory store (not suitable for production)")),g.get(w)),set:async(w,E)=>{h||(h=!0,l.push("Using default in-memory store (not suitable for production)")),g.set(w,E)}}}let c=new AbortController,p=setTimeout(()=>c.abort(),i);r.signal&&r.signal.addEventListener("abort",()=>c.abort());let m={fuel:{current:o},args:t,state:{},consts:new Set,capabilities:a,resolver:g=>this.resolve(g),output:void 0,signal:c.signal,costOverrides:r.costOverrides,timeoutOverrides:r.timeoutOverrides,context:r.context,warnings:l,helpers:s.helpers};if(r.trace&&(m.trace=[]),s.op!=="seq")throw new Error("Root AST must be 'seq'. Ensure you're passing a transpiled agent (use ajs`...` or transpile()).");let u=s.inputSchema;if(u&&!kr(t,u)){let g=new O("Input validation failed: args do not match expected schema","vm.run");return{result:g,error:g,fuelUsed:0,trace:m.trace,warnings:l.length>0?l:void 0}}try{await Promise.race([this.resolve("seq")?.exec(s,m),new Promise((g,h)=>{c.signal.addEventListener("abort",()=>{h(new Error(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`))}),c.signal.aborted&&h(new Error(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`))})])}catch(g){if(g.message?.includes("timeout")||g.message?.includes("aborted")||c.signal.aborted)m.error=new O(`Execution timeout after ${i}ms. Pass a higher \`timeoutMs\` to vm.run() or set per-atom \`timeoutOverrides\` for slow IO atoms.`,"vm.run");else throw g}finally{clearTimeout(p)}m.error&&m.output===void 0&&(m.output=m.error);let d=[...l,...m.warnings??[]];return{result:m.output,error:m.error,fuelUsed:o-m.fuel.current,trace:m.trace,warnings:d.length>0?d:void 0}}};var Rr=null,Bt=()=>Rr??=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 us(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 fs(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{us as Eval,fs as SafeFunction};
|
|
52
54
|
//# sourceMappingURL=tjs-eval.js.map
|