@mcpcloud/runtime 0.12.4 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.js CHANGED
@@ -1,12 +1,12 @@
1
- /*! @mcpcloud/runtime v0.12.4 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
- var L9=Object.create;var{getPrototypeOf:F9,defineProperty:$8,getOwnPropertyNames:O9}=Object;var R9=Object.prototype.hasOwnProperty;function M9(Z){return this[Z]}var V9,_9,w9=(Z,$,W)=>{var Y=Z!=null&&typeof Z==="object";if(Y){var B=$?V9??=new WeakMap:_9??=new WeakMap,C=B.get(Z);if(C)return C}W=Z!=null?L9(F9(Z)):{};let H=$||!Z||!Z.__esModule?$8(W,"default",{value:Z,enumerable:!0}):W;for(let K of O9(Z))if(!R9.call(H,K))$8(H,K,{get:M9.bind(Z,K),enumerable:!0});if(Y)B.set(Z,H);return H};var P9=(Z,$)=>()=>($||Z(($={exports:{}}).exports,$),$.exports);var N9=(Z)=>Z;function E9(Z,$){this[Z]=N9.bind(null,$)}var S9=(Z,$)=>{for(var W in $)$8(Z,W,{get:$[W],enumerable:!0,configurable:!0,set:E9.bind($,W)})};var X8=(Z,$)=>()=>(Z&&($=Z(Z=0)),$);var k,W8,l,h,c;var i=X8(()=>{k={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},W8={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},l={Pending:0,Fulfilled:1,Rejected:2},h={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},c={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function m(...Z){B8&&console.log("quickjs-emscripten:",...Z)}function*W9(Z){return yield Z}function y9(Z){return W9(q8(Z))}function p8(Z,$){return(...W)=>{let Y=$.call(Z,J8,...W);return q8(Y)}}function k9(Z,$){let W=$.call(Z,J8);return q8(W)}function q8(Z){function $(W){return W.done?W.value:W.value instanceof Promise?W.value.then((Y)=>$(Z.next(Y)),(Y)=>$(Z.throw(Y))):$(Z.next(W.value))}return $(Z.next())}function z8(Z,$){let W;try{Z.dispose()}catch(Y){W=Y}if($&&W)throw Object.assign($,{message:`${$.message}
3
- Then, failed to dispose scope: ${W.message}`,disposeError:W}),$;if($||W)throw $||W}function h9(Z){let $=Z?Array.from(Z):[];function W(){return $.forEach((B)=>B.alive?B.dispose():void 0)}function Y(){return $.some((B)=>B.alive)}return Object.defineProperty($,G8,{configurable:!0,enumerable:!1,value:W}),Object.defineProperty($,"dispose",{configurable:!0,enumerable:!1,value:W}),Object.defineProperty($,"alive",{configurable:!0,enumerable:!1,get:Y}),$}function n(Z){return!!(Z&&(typeof Z=="object"||typeof Z=="function")&&("alive"in Z)&&typeof Z.alive=="boolean"&&("dispose"in Z)&&typeof Z.dispose=="function")}function m9(Z){if(!Z)return 0;let $=0;for(let[W,Y]of Object.entries(Z)){if(!(W in W8))throw new e8(W);Y&&($|=W8[W])}return $}function d9(Z){if(typeof Z=="number")return Z;if(Z===void 0)return 0;let{type:$,strict:W,strip:Y,compileOnly:B,backtraceBarrier:C}=Z,H=0;return $==="global"&&(H|=k.JS_EVAL_TYPE_GLOBAL),$==="module"&&(H|=k.JS_EVAL_TYPE_MODULE),W&&(H|=k.JS_EVAL_FLAG_STRICT),Y&&(H|=k.JS_EVAL_FLAG_STRIP),B&&(H|=k.JS_EVAL_FLAG_COMPILE_ONLY),C&&(H|=k.JS_EVAL_FLAG_BACKTRACE_BARRIER),H}function p9(Z){if(typeof Z=="number")return Z;if(Z===void 0)return 0;let{strings:$,symbols:W,quickjsPrivate:Y,onlyEnumerable:B,numbers:C,numbersAsStrings:H}=Z,K=0;return $&&(K|=h.JS_GPN_STRING_MASK),W&&(K|=h.JS_GPN_SYMBOL_MASK),Y&&(K|=h.JS_GPN_PRIVATE_MASK),B&&(K|=h.JS_GPN_ENUM_ONLY),C&&(K|=h.QTS_GPN_NUMBER_MASK),H&&(K|=h.QTS_STANDARD_COMPLIANT_NUMBER),K}function u9(...Z){let $=[];for(let W of Z)W!==void 0&&($=$.concat(W));return $}function K8(Z){return Z>>8}function H8(Z,$){$.interruptHandler&&Z.setInterruptHandler($.interruptHandler),$.maxStackSizeBytes!==void 0&&Z.setMaxStackSize($.maxStackSizeBytes),$.memoryLimitBytes!==void 0&&Z.setMemoryLimit($.memoryLimitBytes)}function j8(Z,$){$.moduleLoader&&Z.setModuleLoader($.moduleLoader),$.shouldInterrupt&&Z.setInterruptHandler($.shouldInterrupt),$.memoryLimitBytes!==void 0&&Z.setMemoryLimit($.memoryLimitBytes),$.maxStackSizeBytes!==void 0&&Z.setMaxStackSize($.maxStackSizeBytes)}var x9,b9=(Z,$)=>{for(var W in $)x9(Z,W,{get:$[W],enumerable:!0})},B8=!1,A9,Q8,a8,Y8,s8,t8,r8,T9,f9,e8,Z9,$9,X9,f,J8,b,G8,u8,w,v,l8,I,C8,v9,g9,g,c9,z9=class{constructor(Z){this.module=Z}toPointerArray(Z){let $=new Int32Array(Z.map((B)=>B.value)),W=$.length*$.BYTES_PER_ELEMENT,Y=this.module._malloc(W);return new Uint8Array(this.module.HEAPU8.buffer,Y,W).set(new Uint8Array($.buffer)),new w(Y,void 0,(B)=>this.module._free(B))}newTypedArray(Z,$){let W=new Z(Array($).fill(0)),Y=W.length*W.BYTES_PER_ELEMENT,B=this.module._malloc(Y),C=new Z(this.module.HEAPU8.buffer,B,$);return C.set(W),new w({typedArray:C,ptr:B},void 0,(H)=>this.module._free(H.ptr))}newMutablePointerArray(Z){return this.newTypedArray(Int32Array,Z)}newHeapCharPointer(Z){let $=this.module.lengthBytesUTF8(Z),W=$+1,Y=this.module._malloc(W);return this.module.stringToUTF8(Z,Y,W),new w({ptr:Y,strlen:$},void 0,(B)=>this.module._free(B.ptr))}newHeapBufferPointer(Z){let $=Z.byteLength,W=this.module._malloc($);return this.module.HEAPU8.set(Z,W),new w({pointer:W,numBytes:$},void 0,(Y)=>this.module._free(Y.pointer))}consumeHeapCharPointer(Z){let $=this.module.UTF8ToString(Z);return this.module._free(Z),$}},RZ,MZ,l9,i8=-2147483648,o8=2147483647,o=0,i9=class{constructor(){this.nextId=i8,this.freelist=[],this.groups=new Map}put(Z){let $=this.allocateId(),W=K8($),Y=this.groups.get(W);return Y||(Y=new Map,this.groups.set(W,Y)),Y.set($,Z),$}get(Z){if(Z===o)throw new f("no host reference id defined");let $=K8(Z),W=this.groups.get($);if(!W)throw new f(`host reference id ${Z} is not defined`);let Y=W.get(Z);if(!Y)throw new f(`host reference id ${Z} is not defined`);return Y}delete(Z){if(Z===o)throw new f("no host reference id defined");let $=K8(Z),W=this.groups.get($);if(!W)throw new f(`host reference id ${Z} is not defined`);W.delete(Z),W.size===0&&this.groups.delete($),this.freelist.push(Z)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===o&&this.nextId++,this.nextId>o8)throw new X9(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${o8-i8}`);return this.nextId++}},n8,o9,n9,a9,s9=class{constructor(Z){this.freeHostRef=Z.freeHostRef,this.callFunction=Z.callFunction,this.shouldInterrupt=Z.shouldInterrupt,this.loadModuleSource=Z.loadModuleSource,this.normalizeModule=Z.normalizeModule}},U8=class{constructor(Z){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new s9({freeHostRef:($,W,Y)=>{let B=this.runtimeCallbacks.get(W);if(!B)throw Error(`QuickJSRuntime(rt = ${W}) not found when trying to free HostRef(id = ${Y})`);B.freeHostRef(W,Y)},callFunction:($,W,Y,B,C,H)=>this.handleAsyncify($,()=>{try{let K=this.contextCallbacks.get(W);if(!K)throw Error(`QuickJSContext(ctx = ${W}) not found for C function call "${H}"`);return K.callFunction(W,Y,B,C,H)}catch(K){return console.error("[C to host error: returning null]",K),0}}),shouldInterrupt:($,W)=>this.handleAsyncify($,()=>{try{let Y=this.runtimeCallbacks.get(W);if(!Y)throw Error(`QuickJSRuntime(rt = ${W}) not found for C interrupt`);return Y.shouldInterrupt(W)}catch(Y){return console.error("[C to host interrupt: returning error]",Y),1}}),loadModuleSource:($,W,Y,B)=>this.handleAsyncify($,()=>{try{let C=this.runtimeCallbacks.get(W);if(!C)throw Error(`QuickJSRuntime(rt = ${W}) not found for C module loader`);let H=C.loadModuleSource;if(!H)throw Error(`QuickJSRuntime(rt = ${W}) does not support module loading`);return H(W,Y,B)}catch(C){return console.error("[C to host module loader error: returning null]",C),0}}),normalizeModule:($,W,Y,B,C)=>this.handleAsyncify($,()=>{try{let H=this.runtimeCallbacks.get(W);if(!H)throw Error(`QuickJSRuntime(rt = ${W}) not found for C module loader`);let K=H.normalizeModule;if(!K)throw Error(`QuickJSRuntime(rt = ${W}) does not support module loading`);return K(W,Y,B,C)}catch(H){return console.error("[C to host module loader error: returning null]",H),0}})}),this.module=Z,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(Z,$){this.runtimeCallbacks.set(Z,$)}deleteRuntime(Z){this.runtimeCallbacks.delete(Z)}setContextCallbacks(Z,$){this.contextCallbacks.set(Z,$)}deleteContext(Z){this.contextCallbacks.delete(Z)}handleAsyncify(Z,$){if(Z)return Z.handleSleep((Y)=>{try{let B=$();if(!(B instanceof Promise)){m("asyncify.handleSleep: not suspending:",B),Y(B);return}if(this.suspended)throw new t8(`Already suspended at: ${this.suspended.stack}
4
- Attempted to suspend at:`);this.suspended=new r8(`(${this.suspendedCount++})`),m("asyncify.handleSleep: suspending:",this.suspended),B.then((C)=>{this.suspended=void 0,m("asyncify.handleSleep: resolved:",C),Y(C)},(C)=>{m("asyncify.handleSleep: rejected:",C),console.error("QuickJS: cannot handle error in suspended function",C),this.suspended=void 0})}catch(B){throw m("asyncify.handleSleep: error:",B),this.suspended=void 0,B}});let W=$();if(W instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return W}},K9=class{constructor(Z,$){this.module=Z,this.ffi=$,this.callbacks=new U8(Z)}newRuntime(Z={}){let $=new w(this.ffi.QTS_NewRuntime(),void 0,(Y)=>{this.ffi.QTS_FreeRuntime(Y),this.callbacks.deleteRuntime(Y)}),W=new a9({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:$});return H8(W,Z),Z.moduleLoader&&W.setModuleLoader(Z.moduleLoader),W}newContext(Z={}){let $=this.newRuntime(),W=$.newContext({...Z,ownedLifetimes:u9($,Z.ownedLifetimes)});return $.context=W,W}evalCode(Z,$={}){return I.withScope((W)=>{let Y=W.manage(this.newContext());j8(Y.runtime,$);let B=Y.evalCode(Z,"eval.js");if($.memoryLimitBytes!==void 0&&Y.runtime.setMemoryLimit(-1),B.error)throw Y.dump(W.manage(B.error));return Y.dump(W.manage(B.value))})}getWasmMemory(){let Z=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!Z)throw Error("Variant does not support getting WebAssembly.Memory");return Z}getFFI(){return this.ffi}};var Q9=X8(()=>{i();i();x9=Object.defineProperty;A9={};b9(A9,{QuickJSAsyncifyError:()=>t8,QuickJSAsyncifySuspended:()=>r8,QuickJSEmptyGetOwnPropertyNames:()=>$9,QuickJSEmscriptenModuleError:()=>f9,QuickJSHostRefInvalid:()=>f,QuickJSHostRefRangeExceeded:()=>X9,QuickJSMemoryLeakDetected:()=>T9,QuickJSNotImplemented:()=>s8,QuickJSPromisePending:()=>Z9,QuickJSUnknownIntrinsic:()=>e8,QuickJSUnwrapError:()=>Q8,QuickJSUseAfterFree:()=>Y8,QuickJSWrongOwner:()=>a8});Q8=class extends Error{constructor(Z,$){let W=typeof Z=="object"&&Z&&"message"in Z?String(Z.message):String(Z);super(W);this.cause=Z,this.context=$,this.name="QuickJSUnwrapError"}},a8=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},Y8=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},s8=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},t8=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},r8=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},T9=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},f9=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},e8=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},Z9=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},$9=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},X9=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},f=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};J8=W9;J8.of=y9;b=class{[Symbol.dispose](){return this.dispose()}},G8=Symbol.dispose??Symbol.for("Symbol.dispose"),u8=b.prototype;u8[G8]||(u8[G8]=function(){return this.dispose()});w=class Z extends b{constructor($,W,Y,B){super();this._value=$,this.copier=W,this.disposer=Y,this._owner=B,this._alive=!0,this._constructorStack=B8?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new Z(this.copier(this._value),this.copier,this.disposer,this._owner)}consume($){this.assertAlive();let W=$(this);return this.dispose(),W}map($){return this.assertAlive(),$(this)}tap($){return $(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new Y8(`Lifetime not alive
1
+ /*! @mcpcloud/runtime v0.15.0 — (c) MCPCloud.sh. All rights reserved. SEE LICENSE: https://www.npmjs.com/package/@mcpcloud/runtime */
2
+ var Tt=Object.create;var{getPrototypeOf:Et,defineProperty:re,getOwnPropertyNames:yt}=Object;var St=Object.prototype.hasOwnProperty;function Rt(e){return this[e]}var wt,At,Pt=(e,t,n)=>{var a=e!=null&&typeof e==="object";if(a){var l=t?wt??=new WeakMap:At??=new WeakMap,d=l.get(e);if(d)return d}n=e!=null?Tt(Et(e)):{};let m=t||!e||!e.__esModule?re(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let s of yt(e))if(!St.call(m,s))re(m,s,{get:Rt.bind(e,s),enumerable:!0})}if(a)l.set(e,m);return m};var bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ot=(e)=>e;function Mt(e,t){this[e]=Ot.bind(null,t)}var vt=(e,t)=>{for(var n in t)re(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Mt.bind(t,n)})};var ne=(e,t)=>()=>(e&&(t=e(e=0)),t);var U,ie,j,K,J;var V=ne(()=>{U={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},ie={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},j={Pending:0,Fulfilled:1,Rejected:2},K={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},J={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function H(...e){ce&&console.log("quickjs-emscripten:",...e)}function*it(e){return yield e}function Ut(e){return it(de(e))}function De(e,t){return(...n)=>{let a=t.call(e,he,...n);return de(a)}}function Kt(e,t){let n=t.call(e,he);return de(n)}function de(e){function t(n){return n.done?n.value:n.value instanceof Promise?n.value.then((a)=>t(e.next(a)),(a)=>t(e.throw(a))):t(e.next(n.value))}return t(e.next())}function se(e,t){let n;try{e.dispose()}catch(a){n=a}if(t&&n)throw Object.assign(t,{message:`${t.message}
3
+ Then, failed to dispose scope: ${n.message}`,disposeError:n}),t;if(t||n)throw t||n}function Yt(e){let t=e?Array.from(e):[];function n(){return t.forEach((l)=>l.alive?l.dispose():void 0)}function a(){return t.some((l)=>l.alive)}return Object.defineProperty(t,le,{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:n}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:a}),t}function W(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&("alive"in e)&&typeof e.alive=="boolean"&&("dispose"in e)&&typeof e.dispose=="function")}function Ft(e){if(!e)return 0;let t=0;for(let[n,a]of Object.entries(e)){if(!(n in ie))throw new et(n);a&&(t|=ie[n])}return t}function Qt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:n,strip:a,compileOnly:l,backtraceBarrier:d}=e,m=0;return t==="global"&&(m|=U.JS_EVAL_TYPE_GLOBAL),t==="module"&&(m|=U.JS_EVAL_TYPE_MODULE),n&&(m|=U.JS_EVAL_FLAG_STRICT),a&&(m|=U.JS_EVAL_FLAG_STRIP),l&&(m|=U.JS_EVAL_FLAG_COMPILE_ONLY),d&&(m|=U.JS_EVAL_FLAG_BACKTRACE_BARRIER),m}function Dt(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:n,quickjsPrivate:a,onlyEnumerable:l,numbers:d,numbersAsStrings:m}=e,s=0;return t&&(s|=K.JS_GPN_STRING_MASK),n&&(s|=K.JS_GPN_SYMBOL_MASK),a&&(s|=K.JS_GPN_PRIVATE_MASK),l&&(s|=K.JS_GPN_ENUM_ONLY),d&&(s|=K.QTS_GPN_NUMBER_MASK),m&&(s|=K.QTS_STANDARD_COMPLIANT_NUMBER),s}function jt(...e){let t=[];for(let n of e)n!==void 0&&(t=t.concat(n));return t}function oe(e){return e>>8}function pe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}function _e(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}var Nt,kt=(e,t)=>{for(var n in t)Nt(e,n,{get:t[n],enumerable:!0})},ce=!1,It,ae,qe,ue,ze,Xe,Ze,Ct,Lt,et,tt,rt,nt,C,he,N,le,je,A,Y,$e,v,fe,Bt,Jt,B,Ht,st=class{constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map((l)=>l.value)),n=t.length*t.BYTES_PER_ELEMENT,a=this.module._malloc(n);return new Uint8Array(this.module.HEAPU8.buffer,a,n).set(new Uint8Array(t.buffer)),new A(a,void 0,(l)=>this.module._free(l))}newTypedArray(e,t){let n=new e(Array(t).fill(0)),a=n.length*n.BYTES_PER_ELEMENT,l=this.module._malloc(a),d=new e(this.module.HEAPU8.buffer,l,t);return d.set(n),new A({typedArray:d,ptr:l},void 0,(m)=>this.module._free(m.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),n=t+1,a=this.module._malloc(n);return this.module.stringToUTF8(e,a,n),new A({ptr:a,strlen:t},void 0,(l)=>this.module._free(l.ptr))}newHeapBufferPointer(e){let t=e.byteLength,n=this.module._malloc(t);return this.module.HEAPU8.set(e,n),new A({pointer:n,numBytes:t},void 0,(a)=>this.module._free(a.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}},Sr,Rr,$t,Ve=-2147483648,Ge=2147483647,G=0,Vt=class{constructor(){this.nextId=Ve,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),n=oe(t),a=this.groups.get(n);return a||(a=new Map,this.groups.set(n,a)),a.set(t,e),t}get(e){if(e===G)throw new C("no host reference id defined");let t=oe(e),n=this.groups.get(t);if(!n)throw new C(`host reference id ${e} is not defined`);let a=n.get(e);if(!a)throw new C(`host reference id ${e} is not defined`);return a}delete(e){if(e===G)throw new C("no host reference id defined");let t=oe(e),n=this.groups.get(t);if(!n)throw new C(`host reference id ${e} is not defined`);n.delete(e),n.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===G&&this.nextId++,this.nextId>Ge)throw new nt(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${Ge-Ve}`);return this.nextId++}},We,Gt,Wt,qt,zt=class{constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},me=class{constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new zt({freeHostRef:(t,n,a)=>{let l=this.runtimeCallbacks.get(n);if(!l)throw Error(`QuickJSRuntime(rt = ${n}) not found when trying to free HostRef(id = ${a})`);l.freeHostRef(n,a)},callFunction:(t,n,a,l,d,m)=>this.handleAsyncify(t,()=>{try{let s=this.contextCallbacks.get(n);if(!s)throw Error(`QuickJSContext(ctx = ${n}) not found for C function call "${m}"`);return s.callFunction(n,a,l,d,m)}catch(s){return console.error("[C to host error: returning null]",s),0}}),shouldInterrupt:(t,n)=>this.handleAsyncify(t,()=>{try{let a=this.runtimeCallbacks.get(n);if(!a)throw Error(`QuickJSRuntime(rt = ${n}) not found for C interrupt`);return a.shouldInterrupt(n)}catch(a){return console.error("[C to host interrupt: returning error]",a),1}}),loadModuleSource:(t,n,a,l)=>this.handleAsyncify(t,()=>{try{let d=this.runtimeCallbacks.get(n);if(!d)throw Error(`QuickJSRuntime(rt = ${n}) not found for C module loader`);let m=d.loadModuleSource;if(!m)throw Error(`QuickJSRuntime(rt = ${n}) does not support module loading`);return m(n,a,l)}catch(d){return console.error("[C to host module loader error: returning null]",d),0}}),normalizeModule:(t,n,a,l,d)=>this.handleAsyncify(t,()=>{try{let m=this.runtimeCallbacks.get(n);if(!m)throw Error(`QuickJSRuntime(rt = ${n}) not found for C module loader`);let s=m.normalizeModule;if(!s)throw Error(`QuickJSRuntime(rt = ${n}) does not support module loading`);return s(n,a,l,d)}catch(m){return console.error("[C to host module loader error: returning null]",m),0}})}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep((a)=>{try{let l=t();if(!(l instanceof Promise)){H("asyncify.handleSleep: not suspending:",l),a(l);return}if(this.suspended)throw new Xe(`Already suspended at: ${this.suspended.stack}
4
+ Attempted to suspend at:`);this.suspended=new Ze(`(${this.suspendedCount++})`),H("asyncify.handleSleep: suspending:",this.suspended),l.then((d)=>{this.suspended=void 0,H("asyncify.handleSleep: resolved:",d),a(d)},(d)=>{H("asyncify.handleSleep: rejected:",d),console.error("QuickJS: cannot handle error in suspended function",d),this.suspended=void 0})}catch(l){throw H("asyncify.handleSleep: error:",l),this.suspended=void 0,l}});let n=t();if(n instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return n}},ot=class{constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new me(e)}newRuntime(e={}){let t=new A(this.ffi.QTS_NewRuntime(),void 0,(a)=>{this.ffi.QTS_FreeRuntime(a),this.callbacks.deleteRuntime(a)}),n=new qt({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return pe(n,e),e.moduleLoader&&n.setModuleLoader(e.moduleLoader),n}newContext(e={}){let t=this.newRuntime(),n=t.newContext({...e,ownedLifetimes:jt(t,e.ownedLifetimes)});return t.context=n,n}evalCode(e,t={}){return v.withScope((n)=>{let a=n.manage(this.newContext());_e(a.runtime,t);let l=a.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&a.runtime.setMemoryLimit(-1),l.error)throw a.dump(n.manage(l.error));return a.dump(n.manage(l.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};var at=ne(()=>{V();V();Nt=Object.defineProperty;It={};kt(It,{QuickJSAsyncifyError:()=>Xe,QuickJSAsyncifySuspended:()=>Ze,QuickJSEmptyGetOwnPropertyNames:()=>rt,QuickJSEmscriptenModuleError:()=>Lt,QuickJSHostRefInvalid:()=>C,QuickJSHostRefRangeExceeded:()=>nt,QuickJSMemoryLeakDetected:()=>Ct,QuickJSNotImplemented:()=>ze,QuickJSPromisePending:()=>tt,QuickJSUnknownIntrinsic:()=>et,QuickJSUnwrapError:()=>ae,QuickJSUseAfterFree:()=>ue,QuickJSWrongOwner:()=>qe});ae=class extends Error{constructor(e,t){let n=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(n);this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},qe=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},ue=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},Xe=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},Ze=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},Ct=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},Lt=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},et=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},tt=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},rt=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}},nt=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefRangeExceeded"}},C=class extends Error{constructor(){super(...arguments);this.name="QuickJSHostRefInvalid"}};he=it;he.of=Ut;N=class{[Symbol.dispose](){return this.dispose()}},le=Symbol.dispose??Symbol.for("Symbol.dispose"),je=N.prototype;je[le]||(je[le]=function(){return this.dispose()});A=class e extends N{constructor(t,n,a,l){super();this._value=t,this.copier=n,this.disposer=a,this._owner=l,this._alive=!0,this._constructorStack=ce?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new e(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let n=t(this);return this.dispose(),n}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new ue(`Lifetime not alive
5
5
  ${this._constructorStack}
6
- Lifetime used`):new Y8("Lifetime not alive")}},v=class extends w{constructor(Z,$){super(Z,void 0,void 0,$)}get dupable(){return!0}dup(){return this}dispose(){}},l8=class extends w{constructor(Z,$,W,Y){super(Z,$,W,Y)}dispose(){this._alive=!1}};I=class Z extends b{constructor(){super(...arguments);this._disposables=new w(new Set),this.manage=($)=>(this._disposables.value.add($),$)}static withScope($){let W=new Z,Y;try{return $(W)}catch(B){throw Y=B,B}finally{z8(W,Y)}}static withScopeMaybeAsync($,W){return k9(void 0,function*(Y){let B=new Z,C;try{return yield*Y.of(W.call($,Y,B))}catch(H){throw C=H,H}finally{z8(B,C)}})}static async withScopeAsync($){let W=new Z,Y;try{return await $(W)}catch(B){throw Y=B,B}finally{z8(W,Y)}}get alive(){return this._disposables.alive}dispose(){let $=Array.from(this._disposables.value.values()).reverse();for(let W of $)W.alive&&W.dispose();this._disposables.dispose()}};C8=class Z extends b{static success($){return new v9($)}static fail($,W){return new g9($,W)}static is($){return $ instanceof Z}},v9=class extends C8{constructor(Z){super();this.value=Z}get alive(){return n(this.value)?this.value.alive:!0}dispose(){n(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(Z){return this.value}},g9=class extends C8{constructor(Z,$){super();this.error=Z,this.onUnwrap=$}get alive(){return n(this.error)?this.error.alive:!0}dispose(){n(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(Z){return Z}},g=C8,c9=class extends b{constructor(Z){super();this.resolve=($)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,$||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=($)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,$||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=Z.context,this.owner=Z.context.runtime,this.handle=Z.promiseHandle,this.settled=new Promise(($)=>{this.onSettled=$}),this.resolveHandle=Z.resolveHandle,this.rejectHandle=Z.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},RZ=Symbol("Unstable"),MZ=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});l9=class extends b{constructor(Z,$){super();this.handle=Z,this.context=$,this._isDone=!1,this.owner=$.runtime}[Symbol.iterator](){return this}next(Z){if(!this.alive||this._isDone)return{done:!0,value:void 0};let $=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod($,Z)}return(Z){if(!this.alive)return{done:!0,value:void 0};let $=this.context.getProp(this.handle,"return");if($===this.context.undefined&&Z===void 0)return this.dispose(),{done:!0,value:void 0};let W=this.callIteratorMethod($,Z);return $.dispose(),this.dispose(),W}throw(Z){if(!this.alive)return{done:!0,value:void 0};let $=Z instanceof w?Z:this.context.newError(Z),W=this.context.getProp(this.handle,"throw"),Y=this.callIteratorMethod(W,Z);return $.alive&&$.dispose(),W.dispose(),this.dispose(),Y}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(Z,$){let W=$?this.context.callFunction(Z,this.handle,$):this.context.callFunction(Z,this.handle);if(W.error)return this.dispose(),{value:W};let Y=this.context.getProp(W.value,"done").consume((C)=>this.context.dump(C)),B=this.context.getProp(W.value,"value");return W.value.dispose(),Y&&this.dispose(),{value:g.success(B),done:Y}}};n8=class extends b{constructor(Z,$,W){if(W===o)throw new f("cannot create HostRef with undefined id");super();this.runtime=Z,this.handle=$,this.id=W}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},o9=class extends z9{constructor(Z){super(Z.module);this.scope=new I,this.copyJSValue=($)=>this.ffi.QTS_DupValuePointer(this.ctx.value,$),this.freeJSValue=($)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,$)},Z.ownedLifetimes?.forEach(($)=>this.scope.manage($)),this.owner=Z.owner,this.module=Z.module,this.ffi=Z.ffi,this.rt=Z.rt,this.ctx=this.scope.manage(Z.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(Z){return this.scope.manage(Z)}consumeJSCharPointer(Z){let $=this.module.UTF8ToString(Z);return this.ffi.QTS_FreeCString(this.ctx.value,Z),$}heapValueHandle(Z,$){let W=$?(Y)=>{$(),this.freeJSValue(Y)}:this.freeJSValue;return new w(Z,this.copyJSValue,W,this.owner)}staticHeapValueHandle(Z){return this.manage(this.heapValueHandle(Z)),new v(Z,this.owner)}},n9=class extends b{constructor(Z){super();this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.cToHostCallbacks={callFunction:($,W,Y,B,C)=>{if($!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let H=this.getFunction(C);return I.withScopeMaybeAsync(this,function*(K,D){let P=D.manage(new l8(W,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),x=Array(Y);for(let M=0;M<Y;M++){let A=this.ffi.QTS_ArgvGetJSValueConstPointer(B,M);x[M]=D.manage(new l8(A,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let M=yield*K(H.apply(P,x));if(M){if("error"in M&&M.error)throw this.runtime.debugLog("throw error",M.error),M.error;let A=D.manage(M instanceof w?M:M.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,A.value)}return 0}catch(M){return this.errorToHandle(M).consume((A)=>this.ffi.QTS_Throw(this.ctx.value,A.value))}})}},this.runtime=Z.runtime,this.module=Z.module,this.ffi=Z.ffi,this.rt=Z.rt,this.ctx=Z.ctx,this.memory=new o9({...Z,owner:this.runtime}),Z.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let Z=this.ffi.QTS_GetUndefined();return this._undefined=new v(Z)}get null(){if(this._null)return this._null;let Z=this.ffi.QTS_GetNull();return this._null=new v(Z)}get true(){if(this._true)return this._true;let Z=this.ffi.QTS_GetTrue();return this._true=new v(Z)}get false(){if(this._false)return this._false;let Z=this.ffi.QTS_GetFalse();return this._false=new v(Z)}get global(){if(this._global)return this._global;let Z=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(Z),this._global}newNumber(Z){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,Z))}newString(Z){let $=this.memory.newHeapCharPointer(Z).consume((W)=>this.ffi.QTS_NewString(this.ctx.value,W.value.ptr));return this.memory.heapValueHandle($)}newUniqueSymbol(Z){let $=(typeof Z=="symbol"?Z.description:Z)??"",W=this.memory.newHeapCharPointer($).consume((Y)=>this.ffi.QTS_NewSymbol(this.ctx.value,Y.value.ptr,0));return this.memory.heapValueHandle(W)}newSymbolFor(Z){let $=(typeof Z=="symbol"?Z.description:Z)??"",W=this.memory.newHeapCharPointer($).consume((Y)=>this.ffi.QTS_NewSymbol(this.ctx.value,Y.value.ptr,1));return this.memory.heapValueHandle(W)}getWellKnownSymbol(Z){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,Z)}newBigInt(Z){if(!this._BigInt){let Y=this.getProp(this.global,"BigInt");this.memory.manage(Y),this._BigInt=new v(Y.value,this.runtime)}let $=this._BigInt,W=String(Z);return this.newString(W).consume((Y)=>this.unwrapResult(this.callFunction($,this.undefined,Y)))}newObject(Z){Z&&this.runtime.assertOwned(Z);let $=Z?this.ffi.QTS_NewObjectProto(this.ctx.value,Z.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle($)}newArray(){let Z=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(Z)}newArrayBuffer(Z){let $=new Uint8Array(Z),W=this.memory.newHeapBufferPointer($),Y=this.ffi.QTS_NewArrayBuffer(this.ctx.value,W.value.pointer,$.length);return this.memory.heapValueHandle(Y)}newPromise(Z){let $=I.withScope((W)=>{let Y=W.manage(this.memory.newMutablePointerArray(2)),B=this.ffi.QTS_NewPromiseCapability(this.ctx.value,Y.value.ptr),C=this.memory.heapValueHandle(B),[H,K]=Array.from(Y.value.typedArray).map((D)=>this.memory.heapValueHandle(D));return new c9({context:this,promiseHandle:C,resolveHandle:H,rejectHandle:K})});return Z&&typeof Z=="function"&&(Z=new Promise(Z)),Z&&Promise.resolve(Z).then($.resolve,(W)=>W instanceof w?$.reject(W):this.newError(W).consume($.reject)),$}newFunction(Z,$){let W=typeof Z=="function"?Z:$;if(!W)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof Z=="string"?Z:void 0,length:W.length,isConstructor:!1,fn:W})}newConstructorFunction(Z,$){let W=typeof Z=="function"?Z:$;if(!W)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof Z=="string"?Z:void 0,length:W.length,isConstructor:!0,fn:W})}newFunctionWithOptions(Z){let{name:$,length:W,isConstructor:Y,fn:B}=Z,C=this.runtime.hostRefs.put(B);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,$??"",W,Y,C))}catch(H){throw this.runtime.hostRefs.delete(C),H}}newError(Z){let $=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return Z&&typeof Z=="object"?(Z.name!==void 0&&this.newString(Z.name).consume((W)=>this.setProp($,"name",W)),Z.message!==void 0&&this.newString(Z.message).consume((W)=>this.setProp($,"message",W))):typeof Z=="string"?this.newString(Z).consume((W)=>this.setProp($,"message",W)):Z!==void 0&&this.newString(String(Z)).consume((W)=>this.setProp($,"message",W)),$}newHostRef(Z){let $=this.runtime.hostRefs.put(Z);try{let W=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,$));return new n8(this.runtime,W,$)}catch(W){throw this.runtime.hostRefs.delete($),W}}toHostRef(Z){let $=this.ffi.QTS_GetHostRefId(Z.value);if($!==0)return this.runtime.hostRefs.get($),new n8(this.runtime,Z.dup(),$)}unwrapHostRef(Z){let $=this.ffi.QTS_GetHostRefId(Z.value);if($===0)throw new f("handle is not a HostRef");return this.runtime.hostRefs.get($)}typeof(Z){return this.runtime.assertOwned(Z),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,Z.value))}getNumber(Z){return this.runtime.assertOwned(Z),this.ffi.QTS_GetFloat64(this.ctx.value,Z.value)}getString(Z){return this.runtime.assertOwned(Z),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,Z.value))}getSymbol(Z){this.runtime.assertOwned(Z);let $=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,Z.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,Z.value)?Symbol.for($):Symbol($)}getBigInt(Z){this.runtime.assertOwned(Z);let $=this.getString(Z);return BigInt($)}getArrayBuffer(Z){this.runtime.assertOwned(Z);let $=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,Z.value),W=this.ffi.QTS_GetArrayBuffer(this.ctx.value,Z.value);if(!W)throw Error("Couldn't allocate memory to get ArrayBuffer");return new w(this.module.HEAPU8.subarray(W,W+$),void 0,()=>this.module._free(W))}getPromiseState(Z){this.runtime.assertOwned(Z);let $=this.ffi.QTS_PromiseState(this.ctx.value,Z.value);if($<0)return{type:"fulfilled",value:Z,notAPromise:!0};if($===l.Pending)return{type:"pending",get error(){return new Z9("Cannot unwrap a pending promise")}};let W=this.ffi.QTS_PromiseResult(this.ctx.value,Z.value),Y=this.memory.heapValueHandle(W);if($===l.Fulfilled)return{type:"fulfilled",value:Y};if($===l.Rejected)return{type:"rejected",error:Y};throw Y.dispose(),Error(`Unknown JSPromiseStateEnum: ${$}`)}resolvePromise(Z){this.runtime.assertOwned(Z);let $=I.withScope((W)=>{let Y=W.manage(this.getProp(this.global,"Promise")),B=W.manage(this.getProp(Y,"resolve"));return this.callFunction(B,Y,Z)});return $.error?Promise.resolve($):new Promise((W)=>{I.withScope((Y)=>{let B=Y.manage(this.newFunction("resolve",(D)=>{W(this.success(D&&D.dup()))})),C=Y.manage(this.newFunction("reject",(D)=>{W(this.fail(D&&D.dup()))})),H=Y.manage($.value),K=Y.manage(this.getProp(H,"then"));this.callFunction(K,H,B,C).unwrap().dispose()})})}isEqual(Z,$,W=c.IsStrictlyEqual){if(Z===$)return!0;this.runtime.assertOwned(Z),this.runtime.assertOwned($);let Y=this.ffi.QTS_IsEqual(this.ctx.value,Z.value,$.value,W);if(Y===-1)throw new s8("WASM variant does not expose equality");return!!Y}eq(Z,$){return this.isEqual(Z,$,c.IsStrictlyEqual)}sameValue(Z,$){return this.isEqual(Z,$,c.IsSameValue)}sameValueZero(Z,$){return this.isEqual(Z,$,c.IsSameValueZero)}getProp(Z,$){this.runtime.assertOwned(Z);let W;return typeof $=="number"&&$>=0?W=this.ffi.QTS_GetPropNumber(this.ctx.value,Z.value,$):W=this.borrowPropertyKey($).consume((Y)=>this.ffi.QTS_GetProp(this.ctx.value,Z.value,Y.value)),this.memory.heapValueHandle(W)}getLength(Z){if(this.runtime.assertOwned(Z),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,Z.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(Z,$={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(Z),Z.value;let W=p9($);if(W===0)throw new $9("No options set, will return an empty array");return I.withScope((Y)=>{let B=Y.manage(this.memory.newMutablePointerArray(1)),C=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,B.value.ptr,this.uint32Out.value.ptr,Z.value,W);if(C)return this.fail(this.memory.heapValueHandle(C));let H=this.uint32Out.value.typedArray[0],K=B.value.typedArray[0],D=new Uint32Array(this.module.HEAP8.buffer,K,H),P=Array.from(D).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,K),this.success(h9(P))})}getIterator(Z){let $=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return I.withScope((W)=>{let Y=W.manage(this.getProp(Z,$)),B=this.callFunction(Y,Z);return B.error?B:this.success(new l9(B.value,this))})}setProp(Z,$,W){this.runtime.assertOwned(Z),this.borrowPropertyKey($).consume((Y)=>this.ffi.QTS_SetProp(this.ctx.value,Z.value,Y.value,W.value))}defineProp(Z,$,W){this.runtime.assertOwned(Z),I.withScope((Y)=>{let B=Y.manage(this.borrowPropertyKey($)),C=W.value||this.undefined,H=!!W.configurable,K=!!W.enumerable,D=!!W.value,P=W.get?Y.manage(this.newFunction(W.get.name,W.get)):this.undefined,x=W.set?Y.manage(this.newFunction(W.set.name,W.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,Z.value,B.value,C.value,P.value,x.value,H,K,D)})}callFunction(Z,$,...W){this.runtime.assertOwned(Z);let Y,B=W[0];B===void 0||Array.isArray(B)?Y=B??[]:Y=W;let C=this.memory.toPointerArray(Y).consume((K)=>this.ffi.QTS_Call(this.ctx.value,Z.value,$.value,Y.length,K.value)),H=this.ffi.QTS_ResolveException(this.ctx.value,C);return H?(this.ffi.QTS_FreeValuePointer(this.ctx.value,C),this.fail(this.memory.heapValueHandle(H))):this.success(this.memory.heapValueHandle(C))}callMethod(Z,$,W=[]){return this.getProp(Z,$).consume((Y)=>this.callFunction(Y,Z,W))}evalCode(Z,$="eval.js",W){let Y=W===void 0?1:0,B=d9(W),C=this.memory.newHeapCharPointer(Z).consume((K)=>this.ffi.QTS_Eval(this.ctx.value,K.value.ptr,K.value.strlen,$,Y,B)),H=this.ffi.QTS_ResolveException(this.ctx.value,C);return H?(this.ffi.QTS_FreeValuePointer(this.ctx.value,C),this.fail(this.memory.heapValueHandle(H))):this.success(this.memory.heapValueHandle(C))}throw(Z){return this.errorToHandle(Z).consume(($)=>this.ffi.QTS_Throw(this.ctx.value,$.value))}borrowPropertyKey(Z){return typeof Z=="number"?this.newNumber(Z):typeof Z=="string"?this.newString(Z):new v(Z.value,this.runtime)}getMemory(Z){if(Z===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(Z){this.runtime.assertOwned(Z);let $=this.typeof(Z);if($==="string")return this.getString(Z);if($==="number")return this.getNumber(Z);if($==="bigint")return this.getBigInt(Z);if($==="undefined")return;if($==="symbol")return this.getSymbol(Z);let W=this.getPromiseState(Z);if(W.type==="fulfilled"&&!W.notAPromise)return Z.dispose(),{type:W.type,value:W.value.consume(this.dump)};if(W.type==="pending")return Z.dispose(),{type:W.type};if(W.type==="rejected")return Z.dispose(),{type:W.type,error:W.error.consume(this.dump)};let Y=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,Z.value));try{return JSON.parse(Y)}catch{return Y}}unwrapResult(Z){if(Z.error){let $="context"in Z.error?Z.error.context:this,W=Z.error.consume((Y)=>this.dump(Y));if(W&&typeof W=="object"&&typeof W.message=="string"){let{message:Y,name:B,stack:C,...H}=W,K=new Q8(W,$);typeof B=="string"&&(K.name=W.name),K.message=Y;let D=K.stack;throw typeof C=="string"&&(K.stack=`${B}: ${Y}
7
- ${W.stack}Host: ${D}`),Object.assign(K,H),K}throw new Q8(W)}return Z.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(Z){let $=this.runtime.hostRefs.get(Z);if(typeof $!="function")throw Error(`Host reference ${Z} is not a function`);return $}errorToHandle(Z){return Z instanceof w?Z:this.newError(Z)}encodeBinaryJSON(Z){let $=this.ffi.QTS_bjson_encode(this.ctx.value,Z.value);return this.memory.heapValueHandle($)}decodeBinaryJSON(Z){let $=this.ffi.QTS_bjson_decode(this.ctx.value,Z.value);return this.memory.heapValueHandle($)}success(Z){return g.success(Z)}fail(Z){return g.fail(Z,($)=>this.unwrapResult($))}},a9=class extends b{constructor(Z){super();this.scope=new I,this.contextMap=new Map,this.hostRefs=new i9,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:($,W)=>{if($!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(W)},shouldInterrupt:($)=>{if($!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let W=this.interruptHandler;if(!W)throw Error("QuickJSContext had no interrupt handler");return W(this)?1:0},loadModuleSource:p8(this,function*($,W,Y,B){let C=this.moduleLoader;if(!C)throw Error("Runtime has no module loader");if(W!==this.rt.value)throw Error("Runtime pointer mismatch");let H=this.contextMap.get(Y)??this.newContext({contextPointer:Y});try{let K=yield*$(C(B,H));if(typeof K=="object"&&"error"in K&&K.error)throw this.debugLog("cToHostLoadModule: loader returned error",K.error),K.error;let D=typeof K=="string"?K:("value"in K)?K.value:K;return this.memory.newHeapCharPointer(D).value.ptr}catch(K){return this.debugLog("cToHostLoadModule: caught error",K),H.throw(K),0}}),normalizeModule:p8(this,function*($,W,Y,B,C){let H=this.moduleNormalizer;if(!H)throw Error("Runtime has no module normalizer");if(W!==this.rt.value)throw Error("Runtime pointer mismatch");let K=this.contextMap.get(Y)??this.newContext({contextPointer:Y});try{let D=yield*$(H(B,C,K));if(typeof D=="object"&&"error"in D&&D.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",D.error),D.error;let P=typeof D=="string"?D:D.value;return K.getMemory(this.rt.value).newHeapCharPointer(P).value.ptr}catch(D){return this.debugLog("normalizeModule: caught error",D),K.throw(D),0}})},Z.ownedLifetimes?.forEach(($)=>this.scope.manage($)),this.module=Z.module,this.memory=new z9(this.module),this.ffi=Z.ffi,this.rt=Z.rt,this.callbacks=Z.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),B8&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(Z={}){let $=m9(Z.intrinsics),W=new w(Z.contextPointer||this.ffi.QTS_NewContext(this.rt.value,$),void 0,(B)=>{this.contextMap.delete(B),this.callbacks.deleteContext(B),this.ffi.QTS_FreeContext(B)}),Y=new n9({module:this.module,ctx:W,ffi:this.ffi,rt:this.rt,ownedLifetimes:Z.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(W.value,Y),Y}setModuleLoader(Z,$){this.moduleLoader=Z,this.moduleNormalizer=$,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(Z){let $=this.interruptHandler;this.interruptHandler=Z,$||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(Z=-1){let $=this.memory.newMutablePointerArray(1),W=this.ffi.QTS_ExecutePendingJob(this.rt.value,Z??-1,$.value.ptr),Y=$.value.typedArray[0];if($.dispose(),Y===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,W),g.success(0);let B=this.contextMap.get(Y)??this.newContext({contextPointer:Y}),C=B.getMemory(this.rt.value).heapValueHandle(W);if(B.typeof(C)==="number"){let H=B.getNumber(C);return C.dispose(),g.success(H)}else{let H=Object.assign(C,{context:B});return g.fail(H,(K)=>B.unwrapResult(K))}}setMemoryLimit(Z){if(Z<0&&Z!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,Z)}computeMemoryUsage(){let Z=this.getSystemContext().getMemory(this.rt.value);return Z.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,Z.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(Z){if(Z<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,Z)}assertOwned(Z){if(Z.owner&&Z.owner.rt!==this.rt)throw new a8(`Handle is not owned by this runtime: ${Z.owner.rt.value} != ${this.rt.value}`)}setDebugMode(Z){this._debugMode=Z,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,Z?1:0)}isDebugMode(){return this._debugMode}debugLog(...Z){this._debugMode&&console.log("quickjs-emscripten:",...Z)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}}});var Y9={};S9(Y9,{applyModuleEvalRuntimeOptions:()=>j8,applyBaseRuntimeOptions:()=>H8,QuickJSWASMModule:()=>K9,QuickJSModuleCallbacks:()=>U8});var G9=X8(()=>{Q9()});var H9=P9((a,U9)=>{(function(Z,$){typeof a==="object"&&typeof U9<"u"?$(a):typeof define==="function"&&define.amd?define(["exports"],$):(Z=typeof globalThis<"u"?globalThis:Z||self,$(Z.jmespath={}))})(a,function(Z){let $=(X)=>{return X!==null&&Object.prototype.toString.call(X)==="[object Object]"},W=(X,z)=>{if(X===z)return!0;if(typeof X!==typeof z)return!1;if(Array.isArray(X)&&Array.isArray(z)){if(X.length!==z.length)return!1;for(let Q=0;Q<X.length;Q+=1)if(!W(X[Q],z[Q]))return!1;return!0}if($(X)&&$(z)){let Q=Object.entries(X),G=new Set(Object.keys(z));if(Q.length!==G.size)return!1;for(let[q,U]of Q){if(!W(U,z[q]))return!1;G.delete(q)}return G.size===0}return!1},Y=(X)=>{if(X===""||X===!1||X===null||X===void 0)return!0;if(Array.isArray(X)&&X.length===0)return!0;if($(X)){for(let z in X)if(X.hasOwnProperty(z))return!1;return!0}return!1},B=(X)=>{return X>="a"&&X<="z"||X>="A"&&X<="Z"||X==="_"},C=(X)=>{return X>="0"&&X<="9"||X==="-"},H=(X)=>{return X>="a"&&X<="z"||X>="A"&&X<="Z"||X>="0"&&X<="9"||X==="_"};var K;(function(X){X.TOK_EOF="EOF",X.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",X.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",X.TOK_RBRACKET="Rbracket",X.TOK_RPAREN="Rparen",X.TOK_COMMA="Comma",X.TOK_COLON="Colon",X.TOK_RBRACE="Rbrace",X.TOK_NUMBER="Number",X.TOK_CURRENT="Current",X.TOK_ROOT="Root",X.TOK_EXPREF="Expref",X.TOK_PIPE="Pipe",X.TOK_OR="Or",X.TOK_AND="And",X.TOK_EQ="EQ",X.TOK_GT="GT",X.TOK_LT="LT",X.TOK_GTE="GTE",X.TOK_LTE="LTE",X.TOK_NE="NE",X.TOK_FLATTEN="Flatten",X.TOK_STAR="Star",X.TOK_FILTER="Filter",X.TOK_DOT="Dot",X.TOK_NOT="Not",X.TOK_LBRACE="Lbrace",X.TOK_LBRACKET="Lbracket",X.TOK_LPAREN="Lparen",X.TOK_LITERAL="Literal"})(K||(K={}));let D={"(":K.TOK_LPAREN,")":K.TOK_RPAREN,"*":K.TOK_STAR,",":K.TOK_COMMA,".":K.TOK_DOT,":":K.TOK_COLON,"@":K.TOK_CURRENT,["$"]:K.TOK_ROOT,"]":K.TOK_RBRACKET,"{":K.TOK_LBRACE,"}":K.TOK_RBRACE},P={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class M{constructor(){this._current=0}tokenize(X){let z=[];this._current=0;let Q,G,q;while(this._current<X.length)if(B(X[this._current]))Q=this._current,G=this.consumeUnquotedIdentifier(X),z.push({start:Q,type:K.TOK_UNQUOTEDIDENTIFIER,value:G});else if(D[X[this._current]]!==void 0)z.push({start:this._current,type:D[X[this._current]],value:X[this._current]}),this._current+=1;else if(C(X[this._current]))q=this.consumeNumber(X),z.push(q);else if(X[this._current]==="[")q=this.consumeLBracket(X),z.push(q);else if(X[this._current]==='"')Q=this._current,G=this.consumeQuotedIdentifier(X),z.push({start:Q,type:K.TOK_QUOTEDIDENTIFIER,value:G});else if(X[this._current]==="'")Q=this._current,G=this.consumeRawStringLiteral(X),z.push({start:Q,type:K.TOK_LITERAL,value:G});else if(X[this._current]==="`"){Q=this._current;let U=this.consumeLiteral(X);z.push({start:Q,type:K.TOK_LITERAL,value:U})}else if(P[X[this._current]]!==void 0)q=this.consumeOperator(X),q&&z.push(q);else if(x[X[this._current]]!==void 0)this._current+=1;else if(X[this._current]==="&")if(Q=this._current,this._current+=1,X[this._current]==="&")this._current+=1,z.push({start:Q,type:K.TOK_AND,value:"&&"});else z.push({start:Q,type:K.TOK_EXPREF,value:"&"});else if(X[this._current]==="|")if(Q=this._current,this._current+=1,X[this._current]==="|")this._current+=1,z.push({start:Q,type:K.TOK_OR,value:"||"});else z.push({start:Q,type:K.TOK_PIPE,value:"|"});else{let U=Error(`Unknown character: ${X[this._current]}`);throw U.name="LexerError",U}return z}consumeUnquotedIdentifier(X){let z=this._current;this._current+=1;while(this._current<X.length&&H(X[this._current]))this._current+=1;return X.slice(z,this._current)}consumeQuotedIdentifier(X){let z=this._current;this._current+=1;let Q=X.length;while(X[this._current]!=='"'&&this._current<Q){let G=this._current;if(X[G]==="\\"&&(X[G+1]==="\\"||X[G+1]==='"'))G+=2;else G+=1;this._current=G}return this._current+=1,JSON.parse(X.slice(z,this._current))}consumeRawStringLiteral(X){let z=this._current;this._current+=1;let Q=X.length;while(X[this._current]!=="'"&&this._current<Q){let q=this._current;if(X[q]==="\\"&&(X[q+1]==="\\"||X[q+1]==="'"))q+=2;else q+=1;this._current=q}return this._current+=1,X.slice(z+1,this._current-1).replace("\\'","'")}consumeNumber(X){let z=this._current;this._current+=1;let Q=X.length;while(C(X[this._current])&&this._current<Q)this._current+=1;let G=parseInt(X.slice(z,this._current),10);return{start:z,value:G,type:K.TOK_NUMBER}}consumeLBracket(X){let z=this._current;if(this._current+=1,X[this._current]==="?")return this._current+=1,{start:z,type:K.TOK_FILTER,value:"[?"};if(X[this._current]==="]")return this._current+=1,{start:z,type:K.TOK_FLATTEN,value:"[]"};return{start:z,type:K.TOK_LBRACKET,value:"["}}consumeOperator(X){let z=this._current,Q=X[z];if(this._current+=1,Q==="!"){if(X[this._current]==="=")return this._current+=1,{start:z,type:K.TOK_NE,value:"!="};return{start:z,type:K.TOK_NOT,value:"!"}}if(Q==="<"){if(X[this._current]==="=")return this._current+=1,{start:z,type:K.TOK_LTE,value:"<="};return{start:z,type:K.TOK_LT,value:"<"}}if(Q===">"){if(X[this._current]==="=")return this._current+=1,{start:z,type:K.TOK_GTE,value:">="};return{start:z,type:K.TOK_GT,value:">"}}if(Q==="="&&X[this._current]==="=")return this._current+=1,{start:z,type:K.TOK_EQ,value:"=="}}consumeLiteral(X){this._current+=1;let z=this._current,Q=X.length;while(X[this._current]!=="`"&&this._current<Q){let U=this._current;if(X[U]==="\\"&&(X[U+1]==="\\"||X[U+1]==="`"))U+=2;else U+=1;this._current=U}let G=X.slice(z,this._current).trimLeft();G=G.replace("\\`","`");let q=this.looksLikeJSON(G)?JSON.parse(G):JSON.parse(`"${G}"`);return this._current+=1,q}looksLikeJSON(X){let Q=["true","false","null"],G="-0123456789";if(X==="")return!1;if('[{"'.includes(X[0]))return!0;if(Q.includes(X))return!0;if("-0123456789".includes(X[0]))try{return JSON.parse(X),!0}catch(q){return!1}return!1}}let A=new M,_={[K.TOK_EOF]:0,[K.TOK_UNQUOTEDIDENTIFIER]:0,[K.TOK_QUOTEDIDENTIFIER]:0,[K.TOK_RBRACKET]:0,[K.TOK_RPAREN]:0,[K.TOK_COMMA]:0,[K.TOK_RBRACE]:0,[K.TOK_NUMBER]:0,[K.TOK_CURRENT]:0,[K.TOK_EXPREF]:0,[K.TOK_ROOT]:0,[K.TOK_PIPE]:1,[K.TOK_OR]:2,[K.TOK_AND]:3,[K.TOK_EQ]:5,[K.TOK_GT]:5,[K.TOK_LT]:5,[K.TOK_GTE]:5,[K.TOK_LTE]:5,[K.TOK_NE]:5,[K.TOK_FLATTEN]:9,[K.TOK_STAR]:20,[K.TOK_FILTER]:21,[K.TOK_DOT]:40,[K.TOK_NOT]:45,[K.TOK_LBRACE]:50,[K.TOK_LBRACKET]:55,[K.TOK_LPAREN]:60};class F8{constructor(){this.index=0,this.tokens=[]}parse(X){this.loadTokens(X),this.index=0;let z=this.expression(0);if(this.lookahead(0)!==K.TOK_EOF){let Q=this.lookaheadToken(0);this.errorToken(Q,`Unexpected token type: ${Q.type}, value: ${Q.value}`)}return z}loadTokens(X){this.tokens=[...A.tokenize(X),{type:K.TOK_EOF,value:"",start:X.length}]}expression(X){let z=this.lookaheadToken(0);this.advance();let Q=this.nud(z),G=this.lookahead(0);while(X<_[G])this.advance(),Q=this.led(G,Q),G=this.lookahead(0);return Q}lookahead(X){return this.tokens[this.index+X].type}lookaheadToken(X){return this.tokens[this.index+X]}advance(){this.index+=1}nud(X){let z,Q,G;switch(X.type){case K.TOK_LITERAL:return{type:"Literal",value:X.value};case K.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:X.value};case K.TOK_QUOTEDIDENTIFIER:let q={type:"Field",name:X.value};if(this.lookahead(0)===K.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return q;case K.TOK_NOT:return Q=this.expression(_.Not),{type:"NotExpression",children:[Q]};case K.TOK_STAR:return z={type:"Identity"},Q=this.lookahead(0)===K.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(_.Star),{type:"ValueProjection",children:[z,Q]};case K.TOK_FILTER:return this.led(X.type,{type:"Identity"});case K.TOK_LBRACE:return this.parseMultiselectHash();case K.TOK_FLATTEN:return z={type:K.TOK_FLATTEN,children:[{type:"Identity"}]},Q=this.parseProjectionRHS(_.Flatten),{type:"Projection",children:[z,Q]};case K.TOK_LBRACKET:if(this.lookahead(0)===K.TOK_NUMBER||this.lookahead(0)===K.TOK_COLON)return Q=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},Q);if(this.lookahead(0)===K.TOK_STAR&&this.lookahead(1)===K.TOK_RBRACKET)return this.advance(),this.advance(),Q=this.parseProjectionRHS(_.Star),{children:[{type:"Identity"},Q],type:"Projection"};return this.parseMultiselectList();case K.TOK_CURRENT:return{type:K.TOK_CURRENT};case K.TOK_ROOT:return{type:K.TOK_ROOT};case K.TOK_EXPREF:return G=this.expression(_.Expref),{type:"ExpressionReference",children:[G]};case K.TOK_LPAREN:let U=[];while(this.lookahead(0)!==K.TOK_RPAREN){if(this.lookahead(0)===K.TOK_CURRENT)G={type:K.TOK_CURRENT},this.advance();else G=this.expression(0);U.push(G)}return this.match(K.TOK_RPAREN),U[0];default:this.errorToken(X)}}led(X,z){let Q;switch(X){case K.TOK_DOT:let G=_.Dot;if(this.lookahead(0)!==K.TOK_STAR)return Q=this.parseDotRHS(G),{type:"Subexpression",children:[z,Q]};return this.advance(),Q=this.parseProjectionRHS(G),{type:"ValueProjection",children:[z,Q]};case K.TOK_PIPE:return Q=this.expression(_.Pipe),{type:K.TOK_PIPE,children:[z,Q]};case K.TOK_OR:return Q=this.expression(_.Or),{type:"OrExpression",children:[z,Q]};case K.TOK_AND:return Q=this.expression(_.And),{type:"AndExpression",children:[z,Q]};case K.TOK_LPAREN:let q=z.name,U=[],L;while(this.lookahead(0)!==K.TOK_RPAREN){if(this.lookahead(0)===K.TOK_CURRENT)L={type:K.TOK_CURRENT},this.advance();else L=this.expression(0);if(this.lookahead(0)===K.TOK_COMMA)this.match(K.TOK_COMMA);U.push(L)}return this.match(K.TOK_RPAREN),{name:q,type:"Function",children:U};case K.TOK_FILTER:let O=this.expression(0);return this.match(K.TOK_RBRACKET),Q=this.lookahead(0)===K.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(_.Filter),{type:"FilterProjection",children:[z,Q,O]};case K.TOK_FLATTEN:let N={type:K.TOK_FLATTEN,children:[z]},R=this.parseProjectionRHS(_.Flatten);return{type:"Projection",children:[N,R]};case K.TOK_EQ:case K.TOK_NE:case K.TOK_GT:case K.TOK_GTE:case K.TOK_LT:case K.TOK_LTE:return this.parseComparator(z,X);case K.TOK_LBRACKET:let j=this.lookaheadToken(0);if(j.type===K.TOK_NUMBER||j.type===K.TOK_COLON)return Q=this.parseIndexExpression(),this.projectIfSlice(z,Q);return this.match(K.TOK_STAR),this.match(K.TOK_RBRACKET),Q=this.parseProjectionRHS(_.Star),{type:"Projection",children:[z,Q]};default:return this.errorToken(this.lookaheadToken(0))}}match(X){if(this.lookahead(0)===X){this.advance();return}else{let z=this.lookaheadToken(0);this.errorToken(z,`Expected ${X}, got: ${z.type}`)}}errorToken(X,z=""){let Q=Error(z||`Invalid token (${X.type}): "${X.value}"`);throw Q.name="ParserError",Q}parseIndexExpression(){if(this.lookahead(0)===K.TOK_COLON||this.lookahead(1)===K.TOK_COLON)return this.parseSliceExpression();let X={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(K.TOK_RBRACKET),X}projectIfSlice(X,z){let Q={type:"IndexExpression",children:[X,z]};if(z.type==="Slice")return{children:[Q,this.parseProjectionRHS(_.Star)],type:"Projection"};return Q}parseSliceExpression(){let X=[null,null,null],z=0,Q=this.lookahead(0);while(Q!==K.TOK_RBRACKET&&z<3){if(Q===K.TOK_COLON)z+=1,this.advance();else if(Q===K.TOK_NUMBER)X[z]=this.lookaheadToken(0).value,this.advance();else{let G=this.lookaheadToken(0);this.errorToken(G,`Syntax error, unexpected token: ${G.value}(${G.type})`)}Q=this.lookahead(0)}return this.match(K.TOK_RBRACKET),{children:X,type:"Slice"}}parseComparator(X,z){let Q=this.expression(_[z]);return{type:"Comparator",name:z,children:[X,Q]}}parseDotRHS(X){let z=this.lookahead(0);if([K.TOK_UNQUOTEDIDENTIFIER,K.TOK_QUOTEDIDENTIFIER,K.TOK_STAR].includes(z))return this.expression(X);if(z===K.TOK_LBRACKET)return this.match(K.TOK_LBRACKET),this.parseMultiselectList();if(z===K.TOK_LBRACE)return this.match(K.TOK_LBRACE),this.parseMultiselectHash();let G=this.lookaheadToken(0);this.errorToken(G,`Syntax error, unexpected token: ${G.value}(${G.type})`)}parseProjectionRHS(X){if(_[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===K.TOK_LBRACKET)return this.expression(X);if(this.lookahead(0)===K.TOK_FILTER)return this.expression(X);if(this.lookahead(0)===K.TOK_DOT)return this.match(K.TOK_DOT),this.parseDotRHS(X);let z=this.lookaheadToken(0);this.errorToken(z,`Syntax error, unexpected token: ${z.value}(${z.type})`)}parseMultiselectList(){let X=[];while(this.lookahead(0)!==K.TOK_RBRACKET){let z=this.expression(0);if(X.push(z),this.lookahead(0)===K.TOK_COMMA){if(this.match(K.TOK_COMMA),this.lookahead(0)===K.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(K.TOK_RBRACKET),{type:"MultiSelectList",children:X}}parseMultiselectHash(){let X=[],z=[K.TOK_UNQUOTEDIDENTIFIER,K.TOK_QUOTEDIDENTIFIER],Q,G,q;for(;;){if(Q=this.lookaheadToken(0),!z.includes(Q.type))throw Error(`Expecting an identifier token, got: ${Q.type}`);if(G=Q.value,this.advance(),this.match(K.TOK_COLON),q=this.expression(0),X.push({value:q,type:"KeyValuePair",name:G}),this.lookahead(0)===K.TOK_COMMA)this.match(K.TOK_COMMA);else if(this.lookahead(0)===K.TOK_RBRACE){this.match(K.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:X}}}let O8=new F8;var J;(function(X){X[X.TYPE_NUMBER=0]="TYPE_NUMBER",X[X.TYPE_ANY=1]="TYPE_ANY",X[X.TYPE_STRING=2]="TYPE_STRING",X[X.TYPE_ARRAY=3]="TYPE_ARRAY",X[X.TYPE_OBJECT=4]="TYPE_OBJECT",X[X.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",X[X.TYPE_EXPREF=6]="TYPE_EXPREF",X[X.TYPE_NULL=7]="TYPE_NULL",X[X.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",X[X.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(J||(J={}));class R8{constructor(X){this.TYPE_NAME_TABLE={[J.TYPE_NUMBER]:"number",[J.TYPE_ANY]:"any",[J.TYPE_STRING]:"string",[J.TYPE_ARRAY]:"array",[J.TYPE_OBJECT]:"object",[J.TYPE_BOOLEAN]:"boolean",[J.TYPE_EXPREF]:"expression",[J.TYPE_NULL]:"null",[J.TYPE_ARRAY_NUMBER]:"Array<number>",[J.TYPE_ARRAY_STRING]:"Array<string>"},this.functionAbs=([z])=>{return Math.abs(z)},this.functionAvg=([z])=>{let Q=0;for(let G=0;G<z.length;G+=1)Q+=z[G];return Q/z.length},this.functionCeil=([z])=>{return Math.ceil(z)},this.functionContains=(z)=>{let[Q,G]=z;return Q.includes(G)},this.functionEndsWith=(z)=>{let[Q,G]=z;return Q.includes(G,Q.length-G.length)},this.functionFloor=([z])=>{return Math.floor(z)},this.functionJoin=(z)=>{let[Q,G]=z;return G.join(Q)},this.functionKeys=([z])=>{return Object.keys(z)},this.functionLength=([z])=>{if(!$(z))return z.length;return Object.keys(z).length},this.functionMap=(z)=>{if(!this._interpreter)return[];let Q=[],G=this._interpreter,q=z[0],U=z[1];for(let L=0;L<U.length;L+=1)Q.push(G.visit(q,U[L]));return Q},this.functionMax=([z])=>{if(!z.length)return null;if(this.getTypeName(z[0])===J.TYPE_NUMBER)return Math.max(...z);let G=z,q=G[0];for(let U=1;U<G.length;U+=1)if(q.localeCompare(G[U])<0)q=G[U];return q},this.functionMaxBy=(z)=>{let Q=z[1],G=z[0],q=this.createKeyFunction(Q,[J.TYPE_NUMBER,J.TYPE_STRING]),U=-1/0,L,F;for(let O=0;O<G.length;O+=1)if(F=q&&q(G[O]),F!==void 0&&F>U)U=F,L=G[O];return L},this.functionMerge=(z)=>{let Q={};for(let G=0;G<z.length;G+=1){let q=z[G];Q=Object.assign(Q,q)}return Q},this.functionMin=([z])=>{if(!z.length)return null;if(this.getTypeName(z[0])===J.TYPE_NUMBER)return Math.min(...z);let G=z,q=G[0];for(let U=1;U<G.length;U+=1)if(G[U].localeCompare(q)<0)q=G[U];return q},this.functionMinBy=(z)=>{let Q=z[1],G=z[0],q=this.createKeyFunction(Q,[J.TYPE_NUMBER,J.TYPE_STRING]),U=1/0,L,F;for(let O=0;O<G.length;O+=1)if(F=q&&q(G[O]),F!==void 0&&F<U)U=F,L=G[O];return L},this.functionNotNull=(z)=>{for(let Q=0;Q<z.length;Q+=1)if(this.getTypeName(z[Q])!==J.TYPE_NULL)return z[Q];return null},this.functionReverse=([z])=>{if(this.getTypeName(z)===J.TYPE_STRING){let q=z,U="";for(let L=q.length-1;L>=0;L-=1)U+=q[L];return U}let G=z.slice(0);return G.reverse(),G},this.functionSort=([z])=>{return[...z].sort()},this.functionSortBy=(z)=>{if(!this._interpreter)return[];let Q=z[0].slice(0);if(Q.length===0)return Q;let G=this._interpreter,q=z[1],U=this.getTypeName(G.visit(q,Q[0]));if(U!==void 0&&![J.TYPE_NUMBER,J.TYPE_STRING].includes(U))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[U]})`);let L=[];for(let F=0;F<Q.length;F+=1)L.push([F,Q[F]]);L.sort((F,O)=>{let N=G.visit(q,F[1]),R=G.visit(q,O[1]);if(this.getTypeName(N)!==U)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[U]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(N)]}`);else if(this.getTypeName(R)!==U)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[U]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(R)]}`);if(N>R)return 1;return N<R?-1:F[0]-O[0]});for(let F=0;F<L.length;F+=1)Q[F]=L[F][1];return Q},this.functionStartsWith=([z,Q])=>{return z.startsWith(Q)},this.functionSum=([z])=>{return z.reduce((Q,G)=>Q+G,0)},this.functionToArray=([z])=>{if(this.getTypeName(z)===J.TYPE_ARRAY)return z;return[z]},this.functionToNumber=([z])=>{let Q=this.getTypeName(z),G;if(Q===J.TYPE_NUMBER)return z;if(Q===J.TYPE_STRING){if(G=+z,!isNaN(G))return G}return null},this.functionToString=([z])=>{if(this.getTypeName(z)===J.TYPE_STRING)return z;return JSON.stringify(z)},this.functionType=([z])=>{switch(this.getTypeName(z)){case J.TYPE_NUMBER:return"number";case J.TYPE_STRING:return"string";case J.TYPE_ARRAY:return"array";case J.TYPE_OBJECT:return"object";case J.TYPE_BOOLEAN:return"boolean";case J.TYPE_EXPREF:return"expref";case J.TYPE_NULL:return"null";default:return}},this.functionValues=([z])=>{return Object.values(z)},this.functionTable={abs:{_func:this.functionAbs,_signature:[{types:[J.TYPE_NUMBER]}]},avg:{_func:this.functionAvg,_signature:[{types:[J.TYPE_ARRAY_NUMBER]}]},ceil:{_func:this.functionCeil,_signature:[{types:[J.TYPE_NUMBER]}]},contains:{_func:this.functionContains,_signature:[{types:[J.TYPE_STRING,J.TYPE_ARRAY]},{types:[J.TYPE_ANY]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[J.TYPE_STRING]},{types:[J.TYPE_STRING]}]},floor:{_func:this.functionFloor,_signature:[{types:[J.TYPE_NUMBER]}]},join:{_func:this.functionJoin,_signature:[{types:[J.TYPE_STRING]},{types:[J.TYPE_ARRAY_STRING]}]},keys:{_func:this.functionKeys,_signature:[{types:[J.TYPE_OBJECT]}]},length:{_func:this.functionLength,_signature:[{types:[J.TYPE_STRING,J.TYPE_ARRAY,J.TYPE_OBJECT]}]},map:{_func:this.functionMap,_signature:[{types:[J.TYPE_EXPREF]},{types:[J.TYPE_ARRAY]}]},max:{_func:this.functionMax,_signature:[{types:[J.TYPE_ARRAY_NUMBER,J.TYPE_ARRAY_STRING]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[J.TYPE_ARRAY]},{types:[J.TYPE_EXPREF]}]},merge:{_func:this.functionMerge,_signature:[{types:[J.TYPE_OBJECT],variadic:!0}]},min:{_func:this.functionMin,_signature:[{types:[J.TYPE_ARRAY_NUMBER,J.TYPE_ARRAY_STRING]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[J.TYPE_ARRAY]},{types:[J.TYPE_EXPREF]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[J.TYPE_ANY],variadic:!0}]},reverse:{_func:this.functionReverse,_signature:[{types:[J.TYPE_STRING,J.TYPE_ARRAY]}]},sort:{_func:this.functionSort,_signature:[{types:[J.TYPE_ARRAY_STRING,J.TYPE_ARRAY_NUMBER]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[J.TYPE_ARRAY]},{types:[J.TYPE_EXPREF]}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[J.TYPE_STRING]},{types:[J.TYPE_STRING]}]},sum:{_func:this.functionSum,_signature:[{types:[J.TYPE_ARRAY_NUMBER]}]},to_array:{_func:this.functionToArray,_signature:[{types:[J.TYPE_ANY]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[J.TYPE_ANY]}]},to_string:{_func:this.functionToString,_signature:[{types:[J.TYPE_ANY]}]},type:{_func:this.functionType,_signature:[{types:[J.TYPE_ANY]}]},values:{_func:this.functionValues,_signature:[{types:[J.TYPE_OBJECT]}]}},this._interpreter=X}registerFunction(X,z,Q){if(X in this.functionTable)throw Error(`Function already defined: ${X}()`);this.functionTable[X]={_func:z.bind(this),_signature:Q}}callFunction(X,z){let Q=this.functionTable[X];if(Q===void 0)throw Error(`Unknown function: ${X}()`);return this.validateArgs(X,z,Q._signature),Q._func.call(this,z)}validateInputSignatures(X,z){for(let Q=0;Q<z.length;Q+=1)if("variadic"in z[Q]&&Q!==z.length-1)throw Error(`ArgumentError: ${X}() 'variadic' argument ${Q+1} must occur last`)}validateArgs(X,z,Q){var G,q;let U;this.validateInputSignatures(X,Q);let L=Q.filter((E)=>{var S;return(S=!E.optional)!==null&&S!==void 0?S:!1}).length,F=(q=(G=Q[Q.length-1])===null||G===void 0?void 0:G.variadic)!==null&&q!==void 0?q:!1,O=z.length<L,N=z.length>Q.length,R=O&&(!F&&L>1||F)?"at least ":"";if(F&&O||!F&&(O||N))throw U=Q.length>1,Error(`ArgumentError: ${X}() takes ${R}${L} argument${U&&"s"||""} but received ${z.length}`);let j,V,T;for(let E=0;E<Q.length;E+=1){T=!1,j=Q[E].types,V=this.getTypeName(z[E]);let S;for(S=0;S<j.length;S+=1)if(V!==void 0&&this.typeMatches(V,j[S],z[E])){T=!0;break}if(!T&&V!==void 0){let d=j.map((p)=>{return this.TYPE_NAME_TABLE[p]}).join(" | ");throw Error(`TypeError: ${X}() expected argument ${E+1} to be type (${d}) but received type ${this.TYPE_NAME_TABLE[V]} instead.`)}}}typeMatches(X,z,Q){if(z===J.TYPE_ANY)return!0;if(z===J.TYPE_ARRAY_STRING||z===J.TYPE_ARRAY_NUMBER||z===J.TYPE_ARRAY){if(z===J.TYPE_ARRAY)return X===J.TYPE_ARRAY;if(X===J.TYPE_ARRAY){let G;if(z===J.TYPE_ARRAY_NUMBER)G=J.TYPE_NUMBER;else if(z===J.TYPE_ARRAY_STRING)G=J.TYPE_STRING;for(let q=0;q<Q.length;q+=1){let U=this.getTypeName(Q[q]);if(U!==void 0&&G!==void 0&&!this.typeMatches(U,G,Q[q]))return!1}return!0}}else return X===z;return!1}getTypeName(X){switch(Object.prototype.toString.call(X)){case"[object String]":return J.TYPE_STRING;case"[object Number]":return J.TYPE_NUMBER;case"[object Array]":return J.TYPE_ARRAY;case"[object Boolean]":return J.TYPE_BOOLEAN;case"[object Null]":return J.TYPE_NULL;case"[object Object]":if(X.jmespathType===K.TOK_EXPREF)return J.TYPE_EXPREF;return J.TYPE_OBJECT;default:return}}createKeyFunction(X,z){if(!this._interpreter)return;let Q=this._interpreter;return(q)=>{let U=Q.visit(X,q);if(!z.includes(this.getTypeName(U))){let L=`TypeError: expected one of (${z.map((F)=>this.TYPE_NAME_TABLE[F]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(U)]}`;throw Error(L)}return U}}}class M8{constructor(){this._rootValue=null,this.runtime=new R8(this)}search(X,z){return this._rootValue=z,this.visit(X,z)}visit(X,z){let Q,G,q,U,L,F,O,N,R,j,V;switch(X.type){case"Field":if(z===null)return null;if($(z)){if(F=z[X.name],F===void 0)return null;return F}return null;case"Subexpression":q=this.visit(X.children[0],z);for(j=1;j<X.children.length;j+=1)if(q=this.visit(X.children[1],q),q===null)return null;return q;case"IndexExpression":return O=this.visit(X.children[0],z),N=this.visit(X.children[1],O),N;case"Index":if(!Array.isArray(z))return null;let T=X.value;if(T<0)T=z.length+T;if(q=z[T],q===void 0)q=null;return q;case"Slice":if(!Array.isArray(z))return null;let E=[...X.children],S=this.computeSliceParams(z.length,E),[d,p,t]=S;if(q=[],t>0)for(j=d;j<p;j+=t)q.push(z[j]);else for(j=d;j>p;j+=t)q.push(z[j]);return q;case"Projection":if(V=this.visit(X.children[0],z),!Array.isArray(V))return null;R=[];for(j=0;j<V.length;j+=1)if(G=this.visit(X.children[1],V[j]),G!==null)R.push(G);return R;case"ValueProjection":if(V=this.visit(X.children[0],z),!$(V))return null;R=[];let v8=Object.values(V);for(j=0;j<v8.length;j+=1)if(G=this.visit(X.children[1],v8[j]),G!==null)R.push(G);return R;case"FilterProjection":if(V=this.visit(X.children[0],z),!Array.isArray(V))return null;let r=[],g8=[];for(j=0;j<V.length;j+=1)if(Q=this.visit(X.children[2],V[j]),!Y(Q))r.push(V[j]);for(let y=0;y<r.length;y+=1)if(G=this.visit(X.children[1],r[y]),G!==null)g8.push(G);return g8;case"Comparator":switch(U=this.visit(X.children[0],z),L=this.visit(X.children[1],z),X.name){case K.TOK_EQ:q=W(U,L);break;case K.TOK_NE:q=!W(U,L);break;case K.TOK_GT:q=U>L;break;case K.TOK_GTE:q=U>=L;break;case K.TOK_LT:q=U<L;break;case K.TOK_LTE:q=U<=L;break;default:throw Error(`Unknown comparator: ${X.name}`)}return q;case K.TOK_FLATTEN:let e=this.visit(X.children[0],z);if(!Array.isArray(e))return null;let u=[];for(j=0;j<e.length;j+=1)if(G=e[j],Array.isArray(G))u=[...u,...G];else u.push(G);return u;case"Identity":return z;case"MultiSelectList":if(z===null)return null;R=[];for(j=0;j<X.children.length;j+=1)R.push(this.visit(X.children[j],z));return R;case"MultiSelectHash":if(z===null)return null;R={};let Z8;for(j=0;j<X.children.length;j+=1)Z8=X.children[j],R[Z8.name]=this.visit(Z8.value,z);return R;case"OrExpression":if(Q=this.visit(X.children[0],z),Y(Q))Q=this.visit(X.children[1],z);return Q;case"AndExpression":if(U=this.visit(X.children[0],z),Y(U))return U;return this.visit(X.children[1],z);case"NotExpression":return U=this.visit(X.children[0],z),Y(U);case"Literal":return X.value;case K.TOK_PIPE:return O=this.visit(X.children[0],z),this.visit(X.children[1],O);case K.TOK_CURRENT:return z;case K.TOK_ROOT:return this._rootValue;case"Function":let c8=[];for(let y=0;y<X.children.length;y+=1)c8.push(this.visit(X.children[y],z));return this.runtime.callFunction(X.name,c8);case"ExpressionReference":let m8=X.children[0];return m8.jmespathType=K.TOK_EXPREF,m8;default:throw Error(`Unknown node type: ${X.type}`)}}computeSliceParams(X,z){let[Q,G,q]=z;if(q===null)q=1;else if(q===0){let L=Error("Invalid slice, step cannot be 0");throw L.name="RuntimeError",L}let U=q<0?!0:!1;return Q=Q===null?U?X-1:0:this.capSliceRange(X,Q,q),G=G===null?U?-1:X:this.capSliceRange(X,G,q),[Q,G,q]}capSliceRange(X,z,Q){let G=z;if(G<0){if(G+=X,G<0)G=Q<0?-1:0}else if(G>=X)G=Q<0?X-1:X;return G}}let s=new M8,V8=J.TYPE_ANY,_8=J.TYPE_ARRAY,w8=J.TYPE_ARRAY_NUMBER,P8=J.TYPE_ARRAY_STRING,N8=J.TYPE_BOOLEAN,E8=J.TYPE_EXPREF,S8=J.TYPE_NULL,I8=J.TYPE_NUMBER,x8=J.TYPE_OBJECT,b8=J.TYPE_STRING;function A8(X){return O8.parse(X)}function T8(X){return A.tokenize(X)}let f8=(X,z,Q)=>{s.runtime.registerFunction(X,z,Q)};function y8(X,z){let Q=O8.parse(z);return s.search(Q,X)}let k8=s,h8={compile:A8,registerFunction:f8,search:y8,tokenize:T8,TreeInterpreter:k8,TYPE_ANY:V8,TYPE_ARRAY_NUMBER:w8,TYPE_ARRAY_STRING:P8,TYPE_ARRAY:_8,TYPE_BOOLEAN:N8,TYPE_EXPREF:E8,TYPE_NULL:S8,TYPE_NUMBER:I8,TYPE_OBJECT:x8,TYPE_STRING:b8};Z.TYPE_ANY=V8,Z.TYPE_ARRAY=_8,Z.TYPE_ARRAY_NUMBER=w8,Z.TYPE_ARRAY_STRING=P8,Z.TYPE_BOOLEAN=N8,Z.TYPE_EXPREF=E8,Z.TYPE_NULL=S8,Z.TYPE_NUMBER=I8,Z.TYPE_OBJECT=x8,Z.TYPE_STRING=b8,Z.TreeInterpreter=k8,Z.compile=A8,Z.default=h8,Z.jmespath=h8,Z.registerFunction=f8,Z.search=y8,Z.tokenize=T8,Object.defineProperty(Z,"__esModule",{value:!0})})});import{timingSafeEqual as YZ}from"node:crypto";import{createServer as GZ}from"node:http";import{Readable as BZ}from"node:stream";function I9(){return typeof process>"u"?{}:process.env}function d8(Z=I9()){return Z.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as KZ}from"node:fs";i();async function B9(Z){let $=D8(await Z),[W,Y,{QuickJSWASMModule:B}]=await Promise.all([$.importModuleLoader().then(D8),$.importFFI(),Promise.resolve().then(() => (G9(),Y9)).then(D8)]),C=await W();C.type="sync";let H=new Y(C);return new B(C,H)}function D8(Z){return Z&&"default"in Z&&Z.default?Z.default&&"default"in Z.default&&Z.default.default?Z.default.default:Z.default:Z}var q9="engine";function t9(Z){let $=(W)=>new URL(W,Z).href;return{type:"sync",importFFI:()=>import($("ffi.mjs")).then((W)=>W.QuickJSFFI),importModuleLoader:()=>import($("emscripten-module.mjs")).then((W)=>W.default)}}var J9=null;function C9(Z){return()=>{return J9??=B9(t9(Z)),J9}}var r9=w9(H9(),1);var ZZ="__mcpcloud_call_tool",B1=`globalThis.tool = (name, args) =>
8
- globalThis.${ZZ}(String(name), JSON.stringify(args ?? {}))
9
- .then((json) => JSON.parse(json));`;var $Z=6,XZ=["log","warn","error","info","debug"],WZ="__mcpcloud_console",C1=`globalThis.console = {
10
- ${XZ.map((Z)=>` ${Z}: (...args) => globalThis.${WZ}(${JSON.stringify(Z)}, JSON.stringify(args.slice(0, ${$Z}).map((value) => (value instanceof Error ? { __mcpcloudError: value.name + ': ' + value.message } : value)))),`).join(`
6
+ Lifetime used`):new ue("Lifetime not alive")}},Y=class extends A{constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},$e=class extends A{constructor(e,t,n,a){super(e,t,n,a)}dispose(){this._alive=!1}};v=class e extends N{constructor(){super(...arguments);this._disposables=new A(new Set),this.manage=(t)=>(this._disposables.value.add(t),t)}static withScope(t){let n=new e,a;try{return t(n)}catch(l){throw a=l,l}finally{se(n,a)}}static withScopeMaybeAsync(t,n){return Kt(void 0,function*(a){let l=new e,d;try{return yield*a.of(n.call(t,a,l))}catch(m){throw d=m,m}finally{se(l,d)}})}static async withScopeAsync(t){let n=new e,a;try{return await t(n)}catch(l){throw a=l,l}finally{se(n,a)}}get alive(){return this._disposables.alive}dispose(){let t=Array.from(this._disposables.value.values()).reverse();for(let n of t)n.alive&&n.dispose();this._disposables.dispose()}};fe=class e extends N{static success(t){return new Bt(t)}static fail(t,n){return new Jt(t,n)}static is(t){return t instanceof e}},Bt=class extends fe{constructor(e){super();this.value=e}get alive(){return W(this.value)?this.value.alive:!0}dispose(){W(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(e){return this.value}},Jt=class extends fe{constructor(e,t){super();this.error=e,this.onUnwrap=t}get alive(){return W(this.error)?this.error.alive:!0}dispose(){W(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(e){return e}},B=fe,Ht=class extends N{constructor(e){super();this.resolve=(t)=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=(t)=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=e.context,this.owner=e.context.runtime,this.handle=e.promiseHandle,this.settled=new Promise((t)=>{this.onSettled=t}),this.resolveHandle=e.resolveHandle,this.rejectHandle=e.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},Sr=Symbol("Unstable"),Rr=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});$t=class extends N{constructor(e,t){super();this.handle=e,this.context=t,this._isDone=!1,this.owner=t.runtime}[Symbol.iterator](){return this}next(e){if(!this.alive||this._isDone)return{done:!0,value:void 0};let t=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(t,e)}return(e){if(!this.alive)return{done:!0,value:void 0};let t=this.context.getProp(this.handle,"return");if(t===this.context.undefined&&e===void 0)return this.dispose(),{done:!0,value:void 0};let n=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),n}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof A?e:this.context.newError(e),n=this.context.getProp(this.handle,"throw"),a=this.callIteratorMethod(n,e);return t.alive&&t.dispose(),n.dispose(),this.dispose(),a}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let n=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(n.error)return this.dispose(),{value:n};let a=this.context.getProp(n.value,"done").consume((d)=>this.context.dump(d)),l=this.context.getProp(n.value,"value");return n.value.dispose(),a&&this.dispose(),{value:B.success(l),done:a}}};We=class extends N{constructor(e,t,n){if(n===G)throw new C("cannot create HostRef with undefined id");super();this.runtime=e,this.handle=t,this.id=n}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},Gt=class extends st{constructor(e){super(e.module);this.scope=new v,this.copyJSValue=(t)=>this.ffi.QTS_DupValuePointer(this.ctx.value,t),this.freeJSValue=(t)=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,t)},e.ownedLifetimes?.forEach((t)=>this.scope.manage(t)),this.owner=e.owner,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=this.scope.manage(e.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(e){return this.scope.manage(e)}consumeJSCharPointer(e){let t=this.module.UTF8ToString(e);return this.ffi.QTS_FreeCString(this.ctx.value,e),t}heapValueHandle(e,t){let n=t?(a)=>{t(),this.freeJSValue(a)}:this.freeJSValue;return new A(e,this.copyJSValue,n,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new Y(e,this.owner)}},Wt=class extends N{constructor(e){super();this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.cToHostCallbacks={callFunction:(t,n,a,l,d)=>{if(t!==this.ctx.value)throw Error("QuickJSContext instance received C -> JS call with mismatched ctx");let m=this.getFunction(d);return v.withScopeMaybeAsync(this,function*(s,_){let P=_.manage(new $e(n,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),x=Array(a);for(let S=0;S<a;S++){let k=this.ffi.QTS_ArgvGetJSValueConstPointer(l,S);x[S]=_.manage(new $e(k,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let S=yield*s(m.apply(P,x));if(S){if("error"in S&&S.error)throw this.runtime.debugLog("throw error",S.error),S.error;let k=_.manage(S instanceof A?S:S.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,k.value)}return 0}catch(S){return this.errorToHandle(S).consume((k)=>this.ffi.QTS_Throw(this.ctx.value,k.value))}})}},this.runtime=e.runtime,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=e.ctx,this.memory=new Gt({...e,owner:this.runtime}),e.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let e=this.ffi.QTS_GetUndefined();return this._undefined=new Y(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new Y(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new Y(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new Y(e)}get global(){if(this._global)return this._global;let e=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(e),this._global}newNumber(e){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,e))}newString(e){let t=this.memory.newHeapCharPointer(e).consume((n)=>this.ffi.QTS_NewString(this.ctx.value,n.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e=="symbol"?e.description:e)??"",n=this.memory.newHeapCharPointer(t).consume((a)=>this.ffi.QTS_NewSymbol(this.ctx.value,a.value.ptr,0));return this.memory.heapValueHandle(n)}newSymbolFor(e){let t=(typeof e=="symbol"?e.description:e)??"",n=this.memory.newHeapCharPointer(t).consume((a)=>this.ffi.QTS_NewSymbol(this.ctx.value,a.value.ptr,1));return this.memory.heapValueHandle(n)}getWellKnownSymbol(e){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,e)}newBigInt(e){if(!this._BigInt){let a=this.getProp(this.global,"BigInt");this.memory.manage(a),this._BigInt=new Y(a.value,this.runtime)}let t=this._BigInt,n=String(e);return this.newString(n).consume((a)=>this.unwrapResult(this.callFunction(t,this.undefined,a)))}newObject(e){e&&this.runtime.assertOwned(e);let t=e?this.ffi.QTS_NewObjectProto(this.ctx.value,e.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(t)}newArray(){let e=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(e)}newArrayBuffer(e){let t=new Uint8Array(e),n=this.memory.newHeapBufferPointer(t),a=this.ffi.QTS_NewArrayBuffer(this.ctx.value,n.value.pointer,t.length);return this.memory.heapValueHandle(a)}newPromise(e){let t=v.withScope((n)=>{let a=n.manage(this.memory.newMutablePointerArray(2)),l=this.ffi.QTS_NewPromiseCapability(this.ctx.value,a.value.ptr),d=this.memory.heapValueHandle(l),[m,s]=Array.from(a.value.typedArray).map((_)=>this.memory.heapValueHandle(_));return new Ht({context:this,promiseHandle:d,resolveHandle:m,rejectHandle:s})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,(n)=>n instanceof A?t.reject(n):this.newError(n).consume(t.reject)),t}newFunction(e,t){let n=typeof e=="function"?e:t;if(!n)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:n.length,isConstructor:!1,fn:n})}newConstructorFunction(e,t){let n=typeof e=="function"?e:t;if(!n)throw TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:n.length,isConstructor:!0,fn:n})}newFunctionWithOptions(e){let{name:t,length:n,isConstructor:a,fn:l}=e,d=this.runtime.hostRefs.put(l);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,t??"",n,a,d))}catch(m){throw this.runtime.hostRefs.delete(d),m}}newError(e){let t=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return e&&typeof e=="object"?(e.name!==void 0&&this.newString(e.name).consume((n)=>this.setProp(t,"name",n)),e.message!==void 0&&this.newString(e.message).consume((n)=>this.setProp(t,"message",n))):typeof e=="string"?this.newString(e).consume((n)=>this.setProp(t,"message",n)):e!==void 0&&this.newString(String(e)).consume((n)=>this.setProp(t,"message",n)),t}newHostRef(e){let t=this.runtime.hostRefs.put(e);try{let n=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,t));return new We(this.runtime,n,t)}catch(n){throw this.runtime.hostRefs.delete(t),n}}toHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t!==0)return this.runtime.hostRefs.get(t),new We(this.runtime,e.dup(),t)}unwrapHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t===0)throw new C("handle is not a HostRef");return this.runtime.hostRefs.get(t)}typeof(e){return this.runtime.assertOwned(e),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,e.value))}getNumber(e){return this.runtime.assertOwned(e),this.ffi.QTS_GetFloat64(this.ctx.value,e.value)}getString(e){return this.runtime.assertOwned(e),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,e.value))}getSymbol(e){this.runtime.assertOwned(e);let t=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,e.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,e.value)?Symbol.for(t):Symbol(t)}getBigInt(e){this.runtime.assertOwned(e);let t=this.getString(e);return BigInt(t)}getArrayBuffer(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,e.value),n=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!n)throw Error("Couldn't allocate memory to get ArrayBuffer");return new A(this.module.HEAPU8.subarray(n,n+t),void 0,()=>this.module._free(n))}getPromiseState(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_PromiseState(this.ctx.value,e.value);if(t<0)return{type:"fulfilled",value:e,notAPromise:!0};if(t===j.Pending)return{type:"pending",get error(){return new tt("Cannot unwrap a pending promise")}};let n=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),a=this.memory.heapValueHandle(n);if(t===j.Fulfilled)return{type:"fulfilled",value:a};if(t===j.Rejected)return{type:"rejected",error:a};throw a.dispose(),Error(`Unknown JSPromiseStateEnum: ${t}`)}resolvePromise(e){this.runtime.assertOwned(e);let t=v.withScope((n)=>{let a=n.manage(this.getProp(this.global,"Promise")),l=n.manage(this.getProp(a,"resolve"));return this.callFunction(l,a,e)});return t.error?Promise.resolve(t):new Promise((n)=>{v.withScope((a)=>{let l=a.manage(this.newFunction("resolve",(_)=>{n(this.success(_&&_.dup()))})),d=a.manage(this.newFunction("reject",(_)=>{n(this.fail(_&&_.dup()))})),m=a.manage(t.value),s=a.manage(this.getProp(m,"then"));this.callFunction(s,m,l,d).unwrap().dispose()})})}isEqual(e,t,n=J.IsStrictlyEqual){if(e===t)return!0;this.runtime.assertOwned(e),this.runtime.assertOwned(t);let a=this.ffi.QTS_IsEqual(this.ctx.value,e.value,t.value,n);if(a===-1)throw new ze("WASM variant does not expose equality");return!!a}eq(e,t){return this.isEqual(e,t,J.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,J.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,J.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let n;return typeof t=="number"&&t>=0?n=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):n=this.borrowPropertyKey(t).consume((a)=>this.ffi.QTS_GetProp(this.ctx.value,e.value,a.value)),this.memory.heapValueHandle(n)}getLength(e){if(this.runtime.assertOwned(e),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,e.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(e,t={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(e),e.value;let n=Dt(t);if(n===0)throw new rt("No options set, will return an empty array");return v.withScope((a)=>{let l=a.manage(this.memory.newMutablePointerArray(1)),d=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,l.value.ptr,this.uint32Out.value.ptr,e.value,n);if(d)return this.fail(this.memory.heapValueHandle(d));let m=this.uint32Out.value.typedArray[0],s=l.value.typedArray[0],_=new Uint32Array(this.module.HEAP8.buffer,s,m),P=Array.from(_).map((x)=>this.memory.heapValueHandle(x));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,s),this.success(Yt(P))})}getIterator(e){let t=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return v.withScope((n)=>{let a=n.manage(this.getProp(e,t)),l=this.callFunction(a,e);return l.error?l:this.success(new $t(l.value,this))})}setProp(e,t,n){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume((a)=>this.ffi.QTS_SetProp(this.ctx.value,e.value,a.value,n.value))}defineProp(e,t,n){this.runtime.assertOwned(e),v.withScope((a)=>{let l=a.manage(this.borrowPropertyKey(t)),d=n.value||this.undefined,m=!!n.configurable,s=!!n.enumerable,_=!!n.value,P=n.get?a.manage(this.newFunction(n.get.name,n.get)):this.undefined,x=n.set?a.manage(this.newFunction(n.set.name,n.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,l.value,d.value,P.value,x.value,m,s,_)})}callFunction(e,t,...n){this.runtime.assertOwned(e);let a,l=n[0];l===void 0||Array.isArray(l)?a=l??[]:a=n;let d=this.memory.toPointerArray(a).consume((s)=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,a.length,s.value)),m=this.ffi.QTS_ResolveException(this.ctx.value,d);return m?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(m))):this.success(this.memory.heapValueHandle(d))}callMethod(e,t,n=[]){return this.getProp(e,t).consume((a)=>this.callFunction(a,e,n))}evalCode(e,t="eval.js",n){let a=n===void 0?1:0,l=Qt(n),d=this.memory.newHeapCharPointer(e).consume((s)=>this.ffi.QTS_Eval(this.ctx.value,s.value.ptr,s.value.strlen,t,a,l)),m=this.ffi.QTS_ResolveException(this.ctx.value,d);return m?(this.ffi.QTS_FreeValuePointer(this.ctx.value,d),this.fail(this.memory.heapValueHandle(m))):this.success(this.memory.heapValueHandle(d))}throw(e){return this.errorToHandle(e).consume((t)=>this.ffi.QTS_Throw(this.ctx.value,t.value))}borrowPropertyKey(e){return typeof e=="number"?this.newNumber(e):typeof e=="string"?this.newString(e):new Y(e.value,this.runtime)}getMemory(e){if(e===this.rt.value)return this.memory;throw Error("Private API. Cannot get memory from a different runtime")}dump(e){this.runtime.assertOwned(e);let t=this.typeof(e);if(t==="string")return this.getString(e);if(t==="number")return this.getNumber(e);if(t==="bigint")return this.getBigInt(e);if(t==="undefined")return;if(t==="symbol")return this.getSymbol(e);let n=this.getPromiseState(e);if(n.type==="fulfilled"&&!n.notAPromise)return e.dispose(),{type:n.type,value:n.value.consume(this.dump)};if(n.type==="pending")return e.dispose(),{type:n.type};if(n.type==="rejected")return e.dispose(),{type:n.type,error:n.error.consume(this.dump)};let a=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,e.value));try{return JSON.parse(a)}catch{return a}}unwrapResult(e){if(e.error){let t="context"in e.error?e.error.context:this,n=e.error.consume((a)=>this.dump(a));if(n&&typeof n=="object"&&typeof n.message=="string"){let{message:a,name:l,stack:d,...m}=n,s=new ae(n,t);typeof l=="string"&&(s.name=n.name),s.message=a;let _=s.stack;throw typeof d=="string"&&(s.stack=`${l}: ${a}
7
+ ${n.stack}Host: ${_}`),Object.assign(s,m),s}throw new ae(n)}return e.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(e){let t=this.runtime.hostRefs.get(e);if(typeof t!="function")throw Error(`Host reference ${e} is not a function`);return t}errorToHandle(e){return e instanceof A?e:this.newError(e)}encodeBinaryJSON(e){let t=this.ffi.QTS_bjson_encode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}decodeBinaryJSON(e){let t=this.ffi.QTS_bjson_decode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}success(e){return B.success(e)}fail(e){return B.fail(e,(t)=>this.unwrapResult(t))}},qt=class extends N{constructor(e){super();this.scope=new v,this.contextMap=new Map,this.hostRefs=new Vt,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:(t,n)=>{if(t!==this.rt.value)throw Error("Runtime pointer mismatch");this.hostRefs.delete(n)},shouldInterrupt:(t)=>{if(t!==this.rt.value)throw Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let n=this.interruptHandler;if(!n)throw Error("QuickJSContext had no interrupt handler");return n(this)?1:0},loadModuleSource:De(this,function*(t,n,a,l){let d=this.moduleLoader;if(!d)throw Error("Runtime has no module loader");if(n!==this.rt.value)throw Error("Runtime pointer mismatch");let m=this.contextMap.get(a)??this.newContext({contextPointer:a});try{let s=yield*t(d(l,m));if(typeof s=="object"&&"error"in s&&s.error)throw this.debugLog("cToHostLoadModule: loader returned error",s.error),s.error;let _=typeof s=="string"?s:("value"in s)?s.value:s;return this.memory.newHeapCharPointer(_).value.ptr}catch(s){return this.debugLog("cToHostLoadModule: caught error",s),m.throw(s),0}}),normalizeModule:De(this,function*(t,n,a,l,d){let m=this.moduleNormalizer;if(!m)throw Error("Runtime has no module normalizer");if(n!==this.rt.value)throw Error("Runtime pointer mismatch");let s=this.contextMap.get(a)??this.newContext({contextPointer:a});try{let _=yield*t(m(l,d,s));if(typeof _=="object"&&"error"in _&&_.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",_.error),_.error;let P=typeof _=="string"?_:_.value;return s.getMemory(this.rt.value).newHeapCharPointer(P).value.ptr}catch(_){return this.debugLog("normalizeModule: caught error",_),s.throw(_),0}})},e.ownedLifetimes?.forEach((t)=>this.scope.manage(t)),this.module=e.module,this.memory=new st(this.module),this.ffi=e.ffi,this.rt=e.rt,this.callbacks=e.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),ce&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(e={}){let t=Ft(e.intrinsics),n=new A(e.contextPointer||this.ffi.QTS_NewContext(this.rt.value,t),void 0,(l)=>{this.contextMap.delete(l),this.callbacks.deleteContext(l),this.ffi.QTS_FreeContext(l)}),a=new Wt({module:this.module,ctx:n,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(n.value,a),a}setModuleLoader(e,t){this.moduleLoader=e,this.moduleNormalizer=t,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(e){let t=this.interruptHandler;this.interruptHandler=e,t||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(e=-1){let t=this.memory.newMutablePointerArray(1),n=this.ffi.QTS_ExecutePendingJob(this.rt.value,e??-1,t.value.ptr),a=t.value.typedArray[0];if(t.dispose(),a===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,n),B.success(0);let l=this.contextMap.get(a)??this.newContext({contextPointer:a}),d=l.getMemory(this.rt.value).heapValueHandle(n);if(l.typeof(d)==="number"){let m=l.getNumber(d);return d.dispose(),B.success(m)}else{let m=Object.assign(d,{context:l});return B.fail(m,(s)=>l.unwrapResult(s))}}setMemoryLimit(e){if(e<0&&e!==-1)throw Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,e)}computeMemoryUsage(){let e=this.getSystemContext().getMemory(this.rt.value);return e.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,e.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(e){if(e<0)throw Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,e)}assertOwned(e){if(e.owner&&e.owner.rt!==this.rt)throw new qe(`Handle is not owned by this runtime: ${e.owner.rt.value} != ${this.rt.value}`)}setDebugMode(e){this._debugMode=e,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,e?1:0)}isDebugMode(){return this._debugMode}debugLog(...e){this._debugMode&&console.log("quickjs-emscripten:",...e)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}}});var ut={};vt(ut,{QuickJSModuleCallbacks:()=>me,QuickJSWASMModule:()=>ot,applyBaseRuntimeOptions:()=>pe,applyModuleEvalRuntimeOptions:()=>_e});var lt=ne(()=>{at()});var pt=bt(function(q,mt){(function(e,t){typeof q==="object"&&typeof mt<"u"?t(q):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.jmespath={}))})(q,function(e){let t=(r)=>r!==null&&Object.prototype.toString.call(r)==="[object Object]",n=(r,i)=>{if(r===i)return!0;if(typeof r!==typeof i)return!1;if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let o=0;o<r.length;o+=1)if(!n(r[o],i[o]))return!1;return!0}if(t(r)&&t(i)){let o=Object.entries(r),u=new Set(Object.keys(i));if(o.length!==u.size)return!1;for(let[h,f]of o){if(!n(f,i[h]))return!1;u.delete(h)}return u.size===0}return!1},a=(r)=>{if(r===""||r===!1||r===null||r===void 0)return!0;if(Array.isArray(r)&&r.length===0)return!0;if(t(r)){for(let i in r)if(r.hasOwnProperty(i))return!1;return!0}return!1},l=(r)=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_",d=(r)=>r>="0"&&r<="9"||r==="-",m=(r)=>r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="_";var s;(function(r){r.TOK_EOF="EOF",r.TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier",r.TOK_QUOTEDIDENTIFIER="QuotedIdentifier",r.TOK_RBRACKET="Rbracket",r.TOK_RPAREN="Rparen",r.TOK_COMMA="Comma",r.TOK_COLON="Colon",r.TOK_RBRACE="Rbrace",r.TOK_NUMBER="Number",r.TOK_CURRENT="Current",r.TOK_ROOT="Root",r.TOK_EXPREF="Expref",r.TOK_PIPE="Pipe",r.TOK_OR="Or",r.TOK_AND="And",r.TOK_EQ="EQ",r.TOK_GT="GT",r.TOK_LT="LT",r.TOK_GTE="GTE",r.TOK_LTE="LTE",r.TOK_NE="NE",r.TOK_FLATTEN="Flatten",r.TOK_STAR="Star",r.TOK_FILTER="Filter",r.TOK_DOT="Dot",r.TOK_NOT="Not",r.TOK_LBRACE="Lbrace",r.TOK_LBRACKET="Lbracket",r.TOK_LPAREN="Lparen",r.TOK_LITERAL="Literal"})(s||(s={}));let _={"(":s.TOK_LPAREN,")":s.TOK_RPAREN,"*":s.TOK_STAR,",":s.TOK_COMMA,".":s.TOK_DOT,":":s.TOK_COLON,"@":s.TOK_CURRENT,["$"]:s.TOK_ROOT,"]":s.TOK_RBRACKET,"{":s.TOK_LBRACE,"}":s.TOK_RBRACE},P={"!":!0,"<":!0,"=":!0,">":!0},x={"\t":!0,"\n":!0,"\r":!0," ":!0};class S{constructor(){this._current=0}tokenize(r){let i=[];this._current=0;let o,u,h;while(this._current<r.length)if(l(r[this._current]))o=this._current,u=this.consumeUnquotedIdentifier(r),i.push({start:o,type:s.TOK_UNQUOTEDIDENTIFIER,value:u});else if(_[r[this._current]]!==void 0)i.push({start:this._current,type:_[r[this._current]],value:r[this._current]}),this._current+=1;else if(d(r[this._current]))h=this.consumeNumber(r),i.push(h);else if(r[this._current]==="[")h=this.consumeLBracket(r),i.push(h);else if(r[this._current]==='"')o=this._current,u=this.consumeQuotedIdentifier(r),i.push({start:o,type:s.TOK_QUOTEDIDENTIFIER,value:u});else if(r[this._current]==="'")o=this._current,u=this.consumeRawStringLiteral(r),i.push({start:o,type:s.TOK_LITERAL,value:u});else if(r[this._current]==="`"){o=this._current;let f=this.consumeLiteral(r);i.push({start:o,type:s.TOK_LITERAL,value:f})}else if(P[r[this._current]]!==void 0)h=this.consumeOperator(r),h&&i.push(h);else if(x[r[this._current]]!==void 0)this._current+=1;else if(r[this._current]==="&")if(o=this._current,this._current+=1,r[this._current]==="&")this._current+=1,i.push({start:o,type:s.TOK_AND,value:"&&"});else i.push({start:o,type:s.TOK_EXPREF,value:"&"});else if(r[this._current]==="|")if(o=this._current,this._current+=1,r[this._current]==="|")this._current+=1,i.push({start:o,type:s.TOK_OR,value:"||"});else i.push({start:o,type:s.TOK_PIPE,value:"|"});else{let f=Error(`Unknown character: ${r[this._current]}`);throw f.name="LexerError",f}return i}consumeUnquotedIdentifier(r){let i=this._current;this._current+=1;while(this._current<r.length&&m(r[this._current]))this._current+=1;return r.slice(i,this._current)}consumeQuotedIdentifier(r){let i=this._current;this._current+=1;let o=r.length;while(r[this._current]!=='"'&&this._current<o){let u=this._current;if(r[u]==="\\"&&(r[u+1]==="\\"||r[u+1]==='"'))u+=2;else u+=1;this._current=u}return this._current+=1,JSON.parse(r.slice(i,this._current))}consumeRawStringLiteral(r){let i=this._current;this._current+=1;let o=r.length;while(r[this._current]!=="'"&&this._current<o){let h=this._current;if(r[h]==="\\"&&(r[h+1]==="\\"||r[h+1]==="'"))h+=2;else h+=1;this._current=h}return this._current+=1,r.slice(i+1,this._current-1).replace("\\'","'")}consumeNumber(r){let i=this._current;this._current+=1;let o=r.length;while(d(r[this._current])&&this._current<o)this._current+=1;let u=parseInt(r.slice(i,this._current),10);return{start:i,value:u,type:s.TOK_NUMBER}}consumeLBracket(r){let i=this._current;if(this._current+=1,r[this._current]==="?")return this._current+=1,{start:i,type:s.TOK_FILTER,value:"[?"};if(r[this._current]==="]")return this._current+=1,{start:i,type:s.TOK_FLATTEN,value:"[]"};return{start:i,type:s.TOK_LBRACKET,value:"["}}consumeOperator(r){let i=this._current,o=r[i];if(this._current+=1,o==="!"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_NE,value:"!="};return{start:i,type:s.TOK_NOT,value:"!"}}if(o==="<"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_LTE,value:"<="};return{start:i,type:s.TOK_LT,value:"<"}}if(o===">"){if(r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_GTE,value:">="};return{start:i,type:s.TOK_GT,value:">"}}if(o==="="&&r[this._current]==="=")return this._current+=1,{start:i,type:s.TOK_EQ,value:"=="}}consumeLiteral(r){this._current+=1;let i=this._current,o=r.length;while(r[this._current]!=="`"&&this._current<o){let f=this._current;if(r[f]==="\\"&&(r[f+1]==="\\"||r[f+1]==="`"))f+=2;else f+=1;this._current=f}let u=r.slice(i,this._current).trimLeft();u=u.replace("\\`","`");let h=this.looksLikeJSON(u)?JSON.parse(u):JSON.parse(`"${u}"`);return this._current+=1,h}looksLikeJSON(r){let o=["true","false","null"],u="-0123456789";if(r==="")return!1;if('[{"'.includes(r[0]))return!0;if(o.includes(r))return!0;if("-0123456789".includes(r[0]))try{return JSON.parse(r),!0}catch(h){return!1}return!1}}let k=new S,w={[s.TOK_EOF]:0,[s.TOK_UNQUOTEDIDENTIFIER]:0,[s.TOK_QUOTEDIDENTIFIER]:0,[s.TOK_RBRACKET]:0,[s.TOK_RPAREN]:0,[s.TOK_COMMA]:0,[s.TOK_RBRACE]:0,[s.TOK_NUMBER]:0,[s.TOK_CURRENT]:0,[s.TOK_EXPREF]:0,[s.TOK_ROOT]:0,[s.TOK_PIPE]:1,[s.TOK_OR]:2,[s.TOK_AND]:3,[s.TOK_EQ]:5,[s.TOK_GT]:5,[s.TOK_LT]:5,[s.TOK_GTE]:5,[s.TOK_LTE]:5,[s.TOK_NE]:5,[s.TOK_FLATTEN]:9,[s.TOK_STAR]:20,[s.TOK_FILTER]:21,[s.TOK_DOT]:40,[s.TOK_NOT]:45,[s.TOK_LBRACE]:50,[s.TOK_LBRACKET]:55,[s.TOK_LPAREN]:60};class Ee{constructor(){this.index=0,this.tokens=[]}parse(r){this.loadTokens(r),this.index=0;let i=this.expression(0);if(this.lookahead(0)!==s.TOK_EOF){let o=this.lookaheadToken(0);this.errorToken(o,`Unexpected token type: ${o.type}, value: ${o.value}`)}return i}loadTokens(r){this.tokens=[...k.tokenize(r),{type:s.TOK_EOF,value:"",start:r.length}]}expression(r){let i=this.lookaheadToken(0);this.advance();let o=this.nud(i),u=this.lookahead(0);while(r<w[u])this.advance(),o=this.led(u,o),u=this.lookahead(0);return o}lookahead(r){return this.tokens[this.index+r].type}lookaheadToken(r){return this.tokens[this.index+r]}advance(){this.index+=1}nud(r){let i,o,u;switch(r.type){case s.TOK_LITERAL:return{type:"Literal",value:r.value};case s.TOK_UNQUOTEDIDENTIFIER:return{type:"Field",name:r.value};case s.TOK_QUOTEDIDENTIFIER:let h={type:"Field",name:r.value};if(this.lookahead(0)===s.TOK_LPAREN)throw Error("Quoted identifier not allowed for function names.");else return h;case s.TOK_NOT:return o=this.expression(w.Not),{type:"NotExpression",children:[o]};case s.TOK_STAR:return i={type:"Identity"},o=this.lookahead(0)===s.TOK_RBRACKET&&{type:"Identity"}||this.parseProjectionRHS(w.Star),{type:"ValueProjection",children:[i,o]};case s.TOK_FILTER:return this.led(r.type,{type:"Identity"});case s.TOK_LBRACE:return this.parseMultiselectHash();case s.TOK_FLATTEN:return i={type:s.TOK_FLATTEN,children:[{type:"Identity"}]},o=this.parseProjectionRHS(w.Flatten),{type:"Projection",children:[i,o]};case s.TOK_LBRACKET:if(this.lookahead(0)===s.TOK_NUMBER||this.lookahead(0)===s.TOK_COLON)return o=this.parseIndexExpression(),this.projectIfSlice({type:"Identity"},o);if(this.lookahead(0)===s.TOK_STAR&&this.lookahead(1)===s.TOK_RBRACKET)return this.advance(),this.advance(),o=this.parseProjectionRHS(w.Star),{children:[{type:"Identity"},o],type:"Projection"};return this.parseMultiselectList();case s.TOK_CURRENT:return{type:s.TOK_CURRENT};case s.TOK_ROOT:return{type:s.TOK_ROOT};case s.TOK_EXPREF:return u=this.expression(w.Expref),{type:"ExpressionReference",children:[u]};case s.TOK_LPAREN:let f=[];while(this.lookahead(0)!==s.TOK_RPAREN){if(this.lookahead(0)===s.TOK_CURRENT)u={type:s.TOK_CURRENT},this.advance();else u=this.expression(0);f.push(u)}return this.match(s.TOK_RPAREN),f[0];default:this.errorToken(r)}}led(r,i){let o;switch(r){case s.TOK_DOT:let u=w.Dot;if(this.lookahead(0)!==s.TOK_STAR)return o=this.parseDotRHS(u),{type:"Subexpression",children:[i,o]};return this.advance(),o=this.parseProjectionRHS(u),{type:"ValueProjection",children:[i,o]};case s.TOK_PIPE:return o=this.expression(w.Pipe),{type:s.TOK_PIPE,children:[i,o]};case s.TOK_OR:return o=this.expression(w.Or),{type:"OrExpression",children:[i,o]};case s.TOK_AND:return o=this.expression(w.And),{type:"AndExpression",children:[i,o]};case s.TOK_LPAREN:let h=i.name,f=[],g;while(this.lookahead(0)!==s.TOK_RPAREN){if(this.lookahead(0)===s.TOK_CURRENT)g={type:s.TOK_CURRENT},this.advance();else g=this.expression(0);if(this.lookahead(0)===s.TOK_COMMA)this.match(s.TOK_COMMA);f.push(g)}return this.match(s.TOK_RPAREN),{name:h,type:"Function",children:f};case s.TOK_FILTER:let E=this.expression(0);return this.match(s.TOK_RBRACKET),o=this.lookahead(0)===s.TOK_FLATTEN&&{type:"Identity"}||this.parseProjectionRHS(w.Filter),{type:"FilterProjection",children:[i,o,E]};case s.TOK_FLATTEN:let b={type:s.TOK_FLATTEN,children:[i]},y=this.parseProjectionRHS(w.Flatten);return{type:"Projection",children:[b,y]};case s.TOK_EQ:case s.TOK_NE:case s.TOK_GT:case s.TOK_GTE:case s.TOK_LT:case s.TOK_LTE:return this.parseComparator(i,r);case s.TOK_LBRACKET:let p=this.lookaheadToken(0);if(p.type===s.TOK_NUMBER||p.type===s.TOK_COLON)return o=this.parseIndexExpression(),this.projectIfSlice(i,o);return this.match(s.TOK_STAR),this.match(s.TOK_RBRACKET),o=this.parseProjectionRHS(w.Star),{type:"Projection",children:[i,o]};default:return this.errorToken(this.lookaheadToken(0))}}match(r){if(this.lookahead(0)===r){this.advance();return}else{let i=this.lookaheadToken(0);this.errorToken(i,`Expected ${r}, got: ${i.type}`)}}errorToken(r,i=""){let o=Error(i||`Invalid token (${r.type}): "${r.value}"`);throw o.name="ParserError",o}parseIndexExpression(){if(this.lookahead(0)===s.TOK_COLON||this.lookahead(1)===s.TOK_COLON)return this.parseSliceExpression();let r={type:"Index",value:this.lookaheadToken(0).value};return this.advance(),this.match(s.TOK_RBRACKET),r}projectIfSlice(r,i){let o={type:"IndexExpression",children:[r,i]};if(i.type==="Slice")return{children:[o,this.parseProjectionRHS(w.Star)],type:"Projection"};return o}parseSliceExpression(){let r=[null,null,null],i=0,o=this.lookahead(0);while(o!==s.TOK_RBRACKET&&i<3){if(o===s.TOK_COLON)i+=1,this.advance();else if(o===s.TOK_NUMBER)r[i]=this.lookaheadToken(0).value,this.advance();else{let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`)}o=this.lookahead(0)}return this.match(s.TOK_RBRACKET),{children:r,type:"Slice"}}parseComparator(r,i){let o=this.expression(w[i]);return{type:"Comparator",name:i,children:[r,o]}}parseDotRHS(r){let i=this.lookahead(0);if([s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER,s.TOK_STAR].includes(i))return this.expression(r);if(i===s.TOK_LBRACKET)return this.match(s.TOK_LBRACKET),this.parseMultiselectList();if(i===s.TOK_LBRACE)return this.match(s.TOK_LBRACE),this.parseMultiselectHash();let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`)}parseProjectionRHS(r){if(w[this.lookahead(0)]<10)return{type:"Identity"};if(this.lookahead(0)===s.TOK_LBRACKET)return this.expression(r);if(this.lookahead(0)===s.TOK_FILTER)return this.expression(r);if(this.lookahead(0)===s.TOK_DOT)return this.match(s.TOK_DOT),this.parseDotRHS(r);let i=this.lookaheadToken(0);this.errorToken(i,`Syntax error, unexpected token: ${i.value}(${i.type})`)}parseMultiselectList(){let r=[];while(this.lookahead(0)!==s.TOK_RBRACKET){let i=this.expression(0);if(r.push(i),this.lookahead(0)===s.TOK_COMMA){if(this.match(s.TOK_COMMA),this.lookahead(0)===s.TOK_RBRACKET)throw Error("Unexpected token Rbracket")}}return this.match(s.TOK_RBRACKET),{type:"MultiSelectList",children:r}}parseMultiselectHash(){let r=[],i=[s.TOK_UNQUOTEDIDENTIFIER,s.TOK_QUOTEDIDENTIFIER],o,u,h;for(;;){if(o=this.lookaheadToken(0),!i.includes(o.type))throw Error(`Expecting an identifier token, got: ${o.type}`);if(u=o.value,this.advance(),this.match(s.TOK_COLON),h=this.expression(0),r.push({value:h,type:"KeyValuePair",name:u}),this.lookahead(0)===s.TOK_COMMA)this.match(s.TOK_COMMA);else if(this.lookahead(0)===s.TOK_RBRACE){this.match(s.TOK_RBRACE);break}}return{type:"MultiSelectHash",children:r}}}let ye=new Ee;var c;(function(r){r[r.TYPE_NUMBER=0]="TYPE_NUMBER",r[r.TYPE_ANY=1]="TYPE_ANY",r[r.TYPE_STRING=2]="TYPE_STRING",r[r.TYPE_ARRAY=3]="TYPE_ARRAY",r[r.TYPE_OBJECT=4]="TYPE_OBJECT",r[r.TYPE_BOOLEAN=5]="TYPE_BOOLEAN",r[r.TYPE_EXPREF=6]="TYPE_EXPREF",r[r.TYPE_NULL=7]="TYPE_NULL",r[r.TYPE_ARRAY_NUMBER=8]="TYPE_ARRAY_NUMBER",r[r.TYPE_ARRAY_STRING=9]="TYPE_ARRAY_STRING"})(c||(c={}));class Se{constructor(r){this.TYPE_NAME_TABLE={[c.TYPE_NUMBER]:"number",[c.TYPE_ANY]:"any",[c.TYPE_STRING]:"string",[c.TYPE_ARRAY]:"array",[c.TYPE_OBJECT]:"object",[c.TYPE_BOOLEAN]:"boolean",[c.TYPE_EXPREF]:"expression",[c.TYPE_NULL]:"null",[c.TYPE_ARRAY_NUMBER]:"Array<number>",[c.TYPE_ARRAY_STRING]:"Array<string>"},this.functionAbs=([i])=>Math.abs(i),this.functionAvg=([i])=>{let o=0;for(let u=0;u<i.length;u+=1)o+=i[u];return o/i.length},this.functionCeil=([i])=>Math.ceil(i),this.functionContains=(i)=>{let[o,u]=i;return o.includes(u)},this.functionEndsWith=(i)=>{let[o,u]=i;return o.includes(u,o.length-u.length)},this.functionFloor=([i])=>Math.floor(i),this.functionJoin=(i)=>{let[o,u]=i;return u.join(o)},this.functionKeys=([i])=>Object.keys(i),this.functionLength=([i])=>{if(!t(i))return i.length;return Object.keys(i).length},this.functionMap=(i)=>{if(!this._interpreter)return[];let o=[],u=this._interpreter,h=i[0],f=i[1];for(let g=0;g<f.length;g+=1)o.push(u.visit(h,f[g]));return o},this.functionMax=([i])=>{if(!i.length)return null;if(this.getTypeName(i[0])===c.TYPE_NUMBER)return Math.max(...i);let u=i,h=u[0];for(let f=1;f<u.length;f+=1)if(h.localeCompare(u[f])<0)h=u[f];return h},this.functionMaxBy=(i)=>{let o=i[1],u=i[0],h=this.createKeyFunction(o,[c.TYPE_NUMBER,c.TYPE_STRING]),f=-1/0,g,T;for(let E=0;E<u.length;E+=1)if(T=h&&h(u[E]),T!==void 0&&T>f)f=T,g=u[E];return g},this.functionMerge=(i)=>{let o={};for(let u=0;u<i.length;u+=1){let h=i[u];o=Object.assign(o,h)}return o},this.functionMin=([i])=>{if(!i.length)return null;if(this.getTypeName(i[0])===c.TYPE_NUMBER)return Math.min(...i);let u=i,h=u[0];for(let f=1;f<u.length;f+=1)if(u[f].localeCompare(h)<0)h=u[f];return h},this.functionMinBy=(i)=>{let o=i[1],u=i[0],h=this.createKeyFunction(o,[c.TYPE_NUMBER,c.TYPE_STRING]),f=1/0,g,T;for(let E=0;E<u.length;E+=1)if(T=h&&h(u[E]),T!==void 0&&T<f)f=T,g=u[E];return g},this.functionNotNull=(i)=>{for(let o=0;o<i.length;o+=1)if(this.getTypeName(i[o])!==c.TYPE_NULL)return i[o];return null},this.functionReverse=([i])=>{if(this.getTypeName(i)===c.TYPE_STRING){let h=i,f="";for(let g=h.length-1;g>=0;g-=1)f+=h[g];return f}let u=i.slice(0);return u.reverse(),u},this.functionSort=([i])=>[...i].sort(),this.functionSortBy=(i)=>{if(!this._interpreter)return[];let o=i[0].slice(0);if(o.length===0)return o;let u=this._interpreter,h=i[1],f=this.getTypeName(u.visit(h,o[0]));if(f!==void 0&&![c.TYPE_NUMBER,c.TYPE_STRING].includes(f))throw Error(`TypeError: unexpected type (${this.TYPE_NAME_TABLE[f]})`);let g=[];for(let T=0;T<o.length;T+=1)g.push([T,o[T]]);g.sort((T,E)=>{let b=u.visit(h,T[1]),y=u.visit(h,E[1]);if(this.getTypeName(b)!==f)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[f]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(b)]}`);else if(this.getTypeName(y)!==f)throw Error(`TypeError: expected (${this.TYPE_NAME_TABLE[f]}), received ${this.TYPE_NAME_TABLE[this.getTypeName(y)]}`);if(b>y)return 1;return b<y?-1:T[0]-E[0]});for(let T=0;T<g.length;T+=1)o[T]=g[T][1];return o},this.functionStartsWith=([i,o])=>i.startsWith(o),this.functionSum=([i])=>i.reduce((o,u)=>o+u,0),this.functionToArray=([i])=>{if(this.getTypeName(i)===c.TYPE_ARRAY)return i;return[i]},this.functionToNumber=([i])=>{let o=this.getTypeName(i),u;if(o===c.TYPE_NUMBER)return i;if(o===c.TYPE_STRING){if(u=+i,!isNaN(u))return u}return null},this.functionToString=([i])=>{if(this.getTypeName(i)===c.TYPE_STRING)return i;return JSON.stringify(i)},this.functionType=([i])=>{switch(this.getTypeName(i)){case c.TYPE_NUMBER:return"number";case c.TYPE_STRING:return"string";case c.TYPE_ARRAY:return"array";case c.TYPE_OBJECT:return"object";case c.TYPE_BOOLEAN:return"boolean";case c.TYPE_EXPREF:return"expref";case c.TYPE_NULL:return"null";default:return}},this.functionValues=([i])=>Object.values(i),this.functionTable={abs:{_func:this.functionAbs,_signature:[{types:[c.TYPE_NUMBER]}]},avg:{_func:this.functionAvg,_signature:[{types:[c.TYPE_ARRAY_NUMBER]}]},ceil:{_func:this.functionCeil,_signature:[{types:[c.TYPE_NUMBER]}]},contains:{_func:this.functionContains,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY]},{types:[c.TYPE_ANY]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_STRING]}]},floor:{_func:this.functionFloor,_signature:[{types:[c.TYPE_NUMBER]}]},join:{_func:this.functionJoin,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_ARRAY_STRING]}]},keys:{_func:this.functionKeys,_signature:[{types:[c.TYPE_OBJECT]}]},length:{_func:this.functionLength,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY,c.TYPE_OBJECT]}]},map:{_func:this.functionMap,_signature:[{types:[c.TYPE_EXPREF]},{types:[c.TYPE_ARRAY]}]},max:{_func:this.functionMax,_signature:[{types:[c.TYPE_ARRAY_NUMBER,c.TYPE_ARRAY_STRING]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},merge:{_func:this.functionMerge,_signature:[{types:[c.TYPE_OBJECT],variadic:!0}]},min:{_func:this.functionMin,_signature:[{types:[c.TYPE_ARRAY_NUMBER,c.TYPE_ARRAY_STRING]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[c.TYPE_ANY],variadic:!0}]},reverse:{_func:this.functionReverse,_signature:[{types:[c.TYPE_STRING,c.TYPE_ARRAY]}]},sort:{_func:this.functionSort,_signature:[{types:[c.TYPE_ARRAY_STRING,c.TYPE_ARRAY_NUMBER]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[c.TYPE_ARRAY]},{types:[c.TYPE_EXPREF]}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[c.TYPE_STRING]},{types:[c.TYPE_STRING]}]},sum:{_func:this.functionSum,_signature:[{types:[c.TYPE_ARRAY_NUMBER]}]},to_array:{_func:this.functionToArray,_signature:[{types:[c.TYPE_ANY]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[c.TYPE_ANY]}]},to_string:{_func:this.functionToString,_signature:[{types:[c.TYPE_ANY]}]},type:{_func:this.functionType,_signature:[{types:[c.TYPE_ANY]}]},values:{_func:this.functionValues,_signature:[{types:[c.TYPE_OBJECT]}]}},this._interpreter=r}registerFunction(r,i,o){if(r in this.functionTable)throw Error(`Function already defined: ${r}()`);this.functionTable[r]={_func:i.bind(this),_signature:o}}callFunction(r,i){let o=this.functionTable[r];if(o===void 0)throw Error(`Unknown function: ${r}()`);return this.validateArgs(r,i,o._signature),o._func.call(this,i)}validateInputSignatures(r,i){for(let o=0;o<i.length;o+=1)if("variadic"in i[o]&&o!==i.length-1)throw Error(`ArgumentError: ${r}() 'variadic' argument ${o+1} must occur last`)}validateArgs(r,i,o){var u,h;let f;this.validateInputSignatures(r,o);let g=o.filter((O)=>{var M;return(M=!O.optional)!==null&&M!==void 0?M:!1}).length,T=(h=(u=o[o.length-1])===null||u===void 0?void 0:u.variadic)!==null&&h!==void 0?h:!1,E=i.length<g,b=i.length>o.length,y=E&&(!T&&g>1||T)?"at least ":"";if(T&&E||!T&&(E||b))throw f=o.length>1,Error(`ArgumentError: ${r}() takes ${y}${g} argument${f&&"s"||""} but received ${i.length}`);let p,R,I;for(let O=0;O<o.length;O+=1){I=!1,p=o[O].types,R=this.getTypeName(i[O]);let M;for(M=0;M<p.length;M+=1)if(R!==void 0&&this.typeMatches(R,p[M],i[O])){I=!0;break}if(!I&&R!==void 0){let F=p.map((Q)=>this.TYPE_NAME_TABLE[Q]).join(" | ");throw Error(`TypeError: ${r}() expected argument ${O+1} to be type (${F}) but received type ${this.TYPE_NAME_TABLE[R]} instead.`)}}}typeMatches(r,i,o){if(i===c.TYPE_ANY)return!0;if(i===c.TYPE_ARRAY_STRING||i===c.TYPE_ARRAY_NUMBER||i===c.TYPE_ARRAY){if(i===c.TYPE_ARRAY)return r===c.TYPE_ARRAY;if(r===c.TYPE_ARRAY){let u;if(i===c.TYPE_ARRAY_NUMBER)u=c.TYPE_NUMBER;else if(i===c.TYPE_ARRAY_STRING)u=c.TYPE_STRING;for(let h=0;h<o.length;h+=1){let f=this.getTypeName(o[h]);if(f!==void 0&&u!==void 0&&!this.typeMatches(f,u,o[h]))return!1}return!0}}else return r===i;return!1}getTypeName(r){switch(Object.prototype.toString.call(r)){case"[object String]":return c.TYPE_STRING;case"[object Number]":return c.TYPE_NUMBER;case"[object Array]":return c.TYPE_ARRAY;case"[object Boolean]":return c.TYPE_BOOLEAN;case"[object Null]":return c.TYPE_NULL;case"[object Object]":if(r.jmespathType===s.TOK_EXPREF)return c.TYPE_EXPREF;return c.TYPE_OBJECT;default:return}}createKeyFunction(r,i){if(!this._interpreter)return;let o=this._interpreter;return(h)=>{let f=o.visit(r,h);if(!i.includes(this.getTypeName(f))){let g=`TypeError: expected one of (${i.map((T)=>this.TYPE_NAME_TABLE[T]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(f)]}`;throw Error(g)}return f}}}class Re{constructor(){this._rootValue=null,this.runtime=new Se(this)}search(r,i){return this._rootValue=i,this.visit(r,i)}visit(r,i){let o,u,h,f,g,T,E,b,y,p,R;switch(r.type){case"Field":if(i===null)return null;if(t(i)){if(T=i[r.name],T===void 0)return null;return T}return null;case"Subexpression":h=this.visit(r.children[0],i);for(p=1;p<r.children.length;p+=1)if(h=this.visit(r.children[1],h),h===null)return null;return h;case"IndexExpression":return E=this.visit(r.children[0],i),b=this.visit(r.children[1],E),b;case"Index":if(!Array.isArray(i))return null;let I=r.value;if(I<0)I=i.length+I;if(h=i[I],h===void 0)h=null;return h;case"Slice":if(!Array.isArray(i))return null;let O=[...r.children],M=this.computeSliceParams(i.length,O),[F,Q,X]=M;if(h=[],X>0)for(p=F;p<Q;p+=X)h.push(i[p]);else for(p=F;p>Q;p+=X)h.push(i[p]);return h;case"Projection":if(R=this.visit(r.children[0],i),!Array.isArray(R))return null;y=[];for(p=0;p<R.length;p+=1)if(u=this.visit(r.children[1],R[p]),u!==null)y.push(u);return y;case"ValueProjection":if(R=this.visit(r.children[0],i),!t(R))return null;y=[];let Be=Object.values(R);for(p=0;p<Be.length;p+=1)if(u=this.visit(r.children[1],Be[p]),u!==null)y.push(u);return y;case"FilterProjection":if(R=this.visit(r.children[0],i),!Array.isArray(R))return null;let Z=[],Je=[];for(p=0;p<R.length;p+=1)if(o=this.visit(r.children[2],R[p]),!a(o))Z.push(R[p]);for(let L=0;L<Z.length;L+=1)if(u=this.visit(r.children[1],Z[L]),u!==null)Je.push(u);return Je;case"Comparator":switch(f=this.visit(r.children[0],i),g=this.visit(r.children[1],i),r.name){case s.TOK_EQ:h=n(f,g);break;case s.TOK_NE:h=!n(f,g);break;case s.TOK_GT:h=f>g;break;case s.TOK_GTE:h=f>=g;break;case s.TOK_LT:h=f<g;break;case s.TOK_LTE:h=f<=g;break;default:throw Error(`Unknown comparator: ${r.name}`)}return h;case s.TOK_FLATTEN:let ee=this.visit(r.children[0],i);if(!Array.isArray(ee))return null;let D=[];for(p=0;p<ee.length;p+=1)if(u=ee[p],Array.isArray(u))D=[...D,...u];else D.push(u);return D;case"Identity":return i;case"MultiSelectList":if(i===null)return null;y=[];for(p=0;p<r.children.length;p+=1)y.push(this.visit(r.children[p],i));return y;case"MultiSelectHash":if(i===null)return null;y={};let te;for(p=0;p<r.children.length;p+=1)te=r.children[p],y[te.name]=this.visit(te.value,i);return y;case"OrExpression":if(o=this.visit(r.children[0],i),a(o))o=this.visit(r.children[1],i);return o;case"AndExpression":if(f=this.visit(r.children[0],i),a(f))return f;return this.visit(r.children[1],i);case"NotExpression":return f=this.visit(r.children[0],i),a(f);case"Literal":return r.value;case s.TOK_PIPE:return E=this.visit(r.children[0],i),this.visit(r.children[1],E);case s.TOK_CURRENT:return i;case s.TOK_ROOT:return this._rootValue;case"Function":let He=[];for(let L=0;L<r.children.length;L+=1)He.push(this.visit(r.children[L],i));return this.runtime.callFunction(r.name,He);case"ExpressionReference":let Fe=r.children[0];return Fe.jmespathType=s.TOK_EXPREF,Fe;default:throw Error(`Unknown node type: ${r.type}`)}}computeSliceParams(r,i){let[o,u,h]=i;if(h===null)h=1;else if(h===0){let g=Error("Invalid slice, step cannot be 0");throw g.name="RuntimeError",g}let f=h<0?!0:!1;return o=o===null?f?r-1:0:this.capSliceRange(r,o,h),u=u===null?f?-1:r:this.capSliceRange(r,u,h),[o,u,h]}capSliceRange(r,i,o){let u=i;if(u<0){if(u+=r,u<0)u=o<0?-1:0}else if(u>=r)u=o<0?r-1:r;return u}}let z=new Re,we=c.TYPE_ANY,Ae=c.TYPE_ARRAY,Pe=c.TYPE_ARRAY_NUMBER,be=c.TYPE_ARRAY_STRING,Oe=c.TYPE_BOOLEAN,Me=c.TYPE_EXPREF,ve=c.TYPE_NULL,xe=c.TYPE_NUMBER,Ne=c.TYPE_OBJECT,ke=c.TYPE_STRING;function Ie(r){return ye.parse(r)}function Ce(r){return k.tokenize(r)}let Le=(r,i,o)=>{z.runtime.registerFunction(r,i,o)};function Ue(r,i){let o=ye.parse(i);return z.search(o,r)}let Ke=z,Ye={compile:Ie,registerFunction:Le,search:Ue,tokenize:Ce,TreeInterpreter:Ke,TYPE_ANY:we,TYPE_ARRAY_NUMBER:Pe,TYPE_ARRAY_STRING:be,TYPE_ARRAY:Ae,TYPE_BOOLEAN:Oe,TYPE_EXPREF:Me,TYPE_NULL:ve,TYPE_NUMBER:xe,TYPE_OBJECT:Ne,TYPE_STRING:ke};e.TYPE_ANY=we,e.TYPE_ARRAY=Ae,e.TYPE_ARRAY_NUMBER=Pe,e.TYPE_ARRAY_STRING=be,e.TYPE_BOOLEAN=Oe,e.TYPE_EXPREF=Me,e.TYPE_NULL=ve,e.TYPE_NUMBER=xe,e.TYPE_OBJECT=Ne,e.TYPE_STRING=ke,e.TreeInterpreter=Ke,e.compile=Ie,e.default=Ye,e.jmespath=Ye,e.registerFunction=Le,e.search=Ue,e.tokenize=Ce,Object.defineProperty(e,"__esModule",{value:!0})})});import{timingSafeEqual as ur}from"node:crypto";import{createServer as lr}from"node:http";import{Readable as cr}from"node:stream";function xt(){return typeof process>"u"?{}:process.env}function Qe(e=xt()){return e.MCP_BEARER_TOKEN?.trim()||null}import{existsSync as or}from"node:fs";V();async function ct(e){let t=ge(await e),[n,a,{QuickJSWASMModule:l}]=await Promise.all([t.importModuleLoader().then(ge),t.importFFI(),Promise.resolve().then(() => (lt(),ut)).then(ge)]),d=await n();d.type="sync";let m=new a(d);return new l(d,m)}function ge(e){return e&&"default"in e&&e.default?e.default&&"default"in e.default&&e.default.default?e.default.default:e.default:e}var dt="engine";function Xt(e){let t=(n)=>new URL(n,e).href;return{type:"sync",importFFI:()=>import(t("ffi.mjs")).then((n)=>n.QuickJSFFI),importModuleLoader:()=>import(t("emscripten-module.mjs")).then((n)=>n.default)}}var ht=null;function ft(e){return()=>(ht??=ct(Xt(e)),ht)}var Zt=Pt(pt(),1);var tr="__mcpcloud_call_tool",hn=`globalThis.tool = (name, args) =>
8
+ globalThis.${tr}(String(name), JSON.stringify(args ?? {}))
9
+ .then((json) => JSON.parse(json));`;var rr=6,nr=["log","warn","error","info","debug"],ir="__mcpcloud_console",mn=`globalThis.console = {
10
+ ${nr.map((e)=>` ${e}: (...args) => globalThis.${ir}(${JSON.stringify(e)}, JSON.stringify(args.slice(0, ${rr}).map((value) => (value instanceof Error ? { __mcpcloudError: value.name + ': ' + value.message } : value)))),`).join(`
11
11
  `)}
12
- };`;var zZ=Symbol.for("@mcpcloud/runtime.codeModeEngineProvider");function j9(Z){globalThis[zZ]=Z}var D9=[`./${q9}/`,"../engine/vendor/","../../engine/vendor/"];function QZ(Z=new URL(import.meta.url)){for(let $ of D9){let W=new URL($,Z);if(KZ(new URL("emscripten-module.wasm",W)))return W}throw Error(`Code Mode engine not found. Looked for emscripten-module.wasm in: ${D9.join(", ")} (relative to ${Z.href}).`)}function L8(){j9(()=>C9(QZ())())}function JZ(Z,$){let W=Buffer.from(Z),Y=Buffer.from($);return W.length===Y.length&&YZ(W,Y)}function qZ(Z,$){let W=d8($);if(!W)return null;if(new URL(Z.url).pathname==="/health")return null;let Y=Z.headers.get("authorization")??"",B=/^Bearer\s+(.+)$/i.exec(Y.trim());if(B&&JZ(B[1].trim(),W))return null;return Response.json({error:"unauthorized",message:"This MCP endpoint requires a bearer token (set in Authorization: Bearer <token>)."},{status:401,headers:{"www-authenticate":"Bearer"}})}function CZ(Z,$){let W=new URL(Z.url??"/",$),Y=new Headers;for(let[H,K]of Object.entries(Z.headers))if(Array.isArray(K))for(let D of K)Y.append(H,D);else if(typeof K==="string")Y.set(H,K);let B=Z.method??"GET",C=B==="GET"||B==="HEAD"?void 0:BZ.toWeb(Z);return new Request(W,{method:B,headers:Y,body:C,...C?{duplex:"half"}:{}})}async function UZ(Z,$){if($.statusCode=Z.status,Z.headers.forEach((Y,B)=>{$.setHeader(B,Y)}),!Z.body){$.end();return}let W=Z.body.getReader();for(;;){let{done:Y,value:B}=await W.read();if(Y)break;$.write(B)}$.end()}function HZ(Z,$={}){L8();let W=$.port??Number(process.env.PORT??8080),Y=$.hostname??"0.0.0.0",B=GZ((C,H)=>{let K=`http://${C.headers.host??`${Y}:${W}`}`,D=CZ(C,K),P=qZ(D,$.env);(P?Promise.resolve(P):Z.handleRequest(D,$.env)).then((M)=>UZ(M,H)).catch(()=>{H.statusCode=500,H.end(JSON.stringify({error:"internal_error"}))})});return B.listen(W,Y),B}export{HZ as serve,L8 as registerNodeCodeModeEngine};
12
+ };`;var sr=Symbol.for("@mcpcloud/runtime.codeModeEngineProvider");function _t(e){globalThis[sr]=e}var gt=[`./${dt}/`,"../engine/vendor/","../../engine/vendor/"];function ar(e=new URL(import.meta.url)){for(let t of gt){let n=new URL(t,e);if(or(new URL("emscripten-module.wasm",n)))return n}throw Error(`Code Mode engine not found. Looked for emscripten-module.wasm in: ${gt.join(", ")} (relative to ${e.href}).`)}function Te(){_t(()=>ft(ar())())}function hr(e,t){let n=Buffer.from(e),a=Buffer.from(t);return n.length===a.length&&ur(n,a)}function dr(e,t){let n=Qe(t);if(!n)return null;if(new URL(e.url).pathname==="/health")return null;let a=e.headers.get("authorization")??"",l=/^Bearer\s+(.+)$/i.exec(a.trim());if(l&&hr(l[1].trim(),n))return null;return Response.json({error:"unauthorized",message:"This MCP endpoint requires a bearer token (set in Authorization: Bearer <token>)."},{status:401,headers:{"www-authenticate":"Bearer"}})}function fr(e,t){let n=new URL(e.url??"/",t),a=new Headers;for(let[m,s]of Object.entries(e.headers))if(Array.isArray(s))for(let _ of s)a.append(m,_);else if(typeof s==="string")a.set(m,s);let l=e.method??"GET",d=l==="GET"||l==="HEAD"?void 0:cr.toWeb(e);return new Request(n,{method:l,headers:a,body:d,...d?{duplex:"half"}:{}})}async function mr(e,t){if(t.statusCode=e.status,e.headers.forEach((a,l)=>{t.setHeader(l,a)}),!e.body){t.end();return}let n=e.body.getReader();for(;;){let{done:a,value:l}=await n.read();if(a)break;t.write(l)}t.end()}function pr(e,t={}){Te();let n=t.port??Number(process.env.PORT??8080),a=t.hostname??"0.0.0.0",l=lr((d,m)=>{let s=`http://${d.headers.host??`${a}:${n}`}`,_=fr(d,s),P=dr(_,t.env);(P?Promise.resolve(P):e.handleRequest(_,t.env)).then((S)=>mr(S,m)).catch(()=>{m.statusCode=500,m.end(JSON.stringify({error:"internal_error"}))})});return l.listen(n,a),l}export{Te as registerNodeCodeModeEngine,pr as serve};
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The version of `@mcpcloud/runtime` COMPILED INTO this bundle.
3
+ *
4
+ * This exists because the platform previously had no way to ask a deployed
5
+ * server what it was actually running. `x-mcpcloud-runtime-version` and the
6
+ * dashboard's runtime badge are both read from `policy.runtimeVersion`, which
7
+ * Convex stamps at deploy time — a control-plane CLAIM about what should have
8
+ * shipped, never an observation of what did. When a deploy silently failed to
9
+ * replace a worker's script, every surface still reported the new version, and
10
+ * the obvious way to verify ("check the runtime version header") returned a
11
+ * false pass. That is not hypothetical: a staging server reported 0.14.0 while
12
+ * serving bytes older than 0.12.5, and had been drifting for several releases
13
+ * before anyone noticed.
14
+ *
15
+ * Because this constant travels INSIDE the bundle, it answers the different
16
+ * question: not "what did we intend to deploy?" but "what is running?".
17
+ * Comparing the two makes a failed-but-successful-looking deploy detectable.
18
+ */
19
+ export declare const RUNTIME_VERSION = "0.15.0";
@@ -11,7 +11,7 @@
11
11
  * inside the same policy layer everything else does." A second path that merely
12
12
  * resembled the first would be a lie with extra steps.
13
13
  */
14
- import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
14
+ import type { CallToolResult } from '@modelcontextprotocol/server';
15
15
  import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
16
16
  import type { CallerContext, RuntimeConfig } from '../config';
17
17
  import type { RegisteredTool } from '../server';
package/dist/server.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import type { CallToolResult } from '@modelcontextprotocol/server';
3
3
  import type { CallerContext, RuntimeConfig, RuntimeEnv, ServerIdentity } from './config';
4
4
  import type { CodeModeOptions } from './sandbox/codeModeTool';
5
5
  import type { PromptDefinition, ResourceDefinition, ToolDefinition } from './types';
@@ -37,6 +37,32 @@ export interface GeneratedServer {
37
37
  handleRequest: (request: Request, env?: RuntimeEnv) => Promise<Response>;
38
38
  options: DefineServerOptions;
39
39
  }
40
+ export declare function buildCacheHints(accessMode: RuntimeConfig['accessMode']): {
41
+ 'tools/list': {
42
+ ttlMs: number;
43
+ cacheScope: "public" | "private";
44
+ };
45
+ 'prompts/list': {
46
+ ttlMs: number;
47
+ cacheScope: "public" | "private";
48
+ };
49
+ 'resources/list': {
50
+ ttlMs: number;
51
+ cacheScope: "public" | "private";
52
+ };
53
+ 'resources/templates/list': {
54
+ ttlMs: number;
55
+ cacheScope: "public" | "private";
56
+ };
57
+ 'resources/read': {
58
+ ttlMs: number;
59
+ cacheScope: "public" | "private";
60
+ };
61
+ 'server/discover': {
62
+ ttlMs: number;
63
+ cacheScope: "public" | "private";
64
+ };
65
+ };
40
66
  /**
41
67
  * Assemble a generated MCP server from data: the per-server identity plus the
42
68
  * tool definitions/handlers the codegen emits. The package provides all
package/dist/stdio.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  /** stdio subpath entry (`@mcpcloud/runtime/stdio`) — imports node builtins. */
2
2
  export { startStdioServer } from './adapters/stdio';
3
- export { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ export { StdioServerTransport } from '@modelcontextprotocol/server/stdio';