@enfyra/kernel 1.1.15 → 1.1.17

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.
@@ -1 +1 @@
1
- "use strict";var P=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var g=P((L,b)=>{"use strict";function A({handles:e,createHandleId:t,callIsolateCallback:a}){function i(f,r){if(r==null)return r;let d=typeof r;if(d==="string"||d==="number"||d==="boolean")return r;if(r instanceof Date)return{__date:r.toISOString()};if(r instanceof Set)return{__set:Array.from(r.values()).map(n=>i(f,n))};if(r instanceof Map)return{__map:Array.from(r.entries()).map(([n,p])=>[i(f,n),i(f,p)])};if(r instanceof RegExp)return{__regexp:{source:r.source,flags:r.flags}};if(r instanceof Error)return{__error:{name:r.name,message:r.message,stack:r.stack}};if(typeof URL<"u"&&r instanceof URL)return{__url:r.href};if(typeof URLSearchParams<"u"&&r instanceof URLSearchParams)return{__urlSearchParams:r.toString()};if(typeof Buffer<"u"&&Buffer.isBuffer(r)||r._isBuffer===!0)return c(f,r);if(ArrayBuffer.isView(r))return{__typedArray:r.constructor?.name||"Uint8Array",data:Array.from(r)};if(r instanceof ArrayBuffer)return{__arrayBuffer:Array.from(new Uint8Array(r))};if(Array.isArray(r))return r.map(n=>i(f,n));if(d==="object"&&m(r)){let n={};for(let[p,h]of Object.entries(r))n[p]=i(f,h);return n}return c(f,r)}function c(f,r){let d=t(f);return e.set(d,r),{__pkgHandle:d}}function o(f,r){if(!r||typeof r!="object")return r;if(r.__fnRef)return(...n)=>a(f,r.__fnRef,n);if(r.__pkgHandleArg){let n=e.get(r.__pkgHandleArg);if(!n)throw new Error(`Package argument handle not found: ${r.__pkgHandleArg}`);return n}if(r.__date)return new Date(r.__date);if(r.__set)return new Set(r.__set.map(n=>o(f,n)));if(r.__map)return new Map(r.__map.map(([n,p])=>[o(f,n),o(f,p)]));if(r.__regexp)return new RegExp(r.__regexp.source,r.__regexp.flags||"");if(r.__error){let n=new Error(r.__error.message||"");return n.name=r.__error.name||"Error",r.__error.stack&&(n.stack=r.__error.stack),n}if(r.__url)return new URL(r.__url);if(r.__urlSearchParams)return new URLSearchParams(r.__urlSearchParams);if(r.__blob)return new Blob([Uint8Array.from(r.__blob.data||[])],{type:r.__blob.type||""});if(r.__file){let n=[Uint8Array.from(r.__file.data||[])],p={type:r.__file.type||"",lastModified:r.__file.lastModified};return typeof File<"u"?new File(n,r.__file.name||"file",p):new Blob(n,p)}if(r.__formData){let n=new FormData;for(let[p,h]of r.__formData)n.append(p,o(f,h));return n}if(r.__typedArray){let n=globalThis[r.__typedArray]||Uint8Array;return new n(r.data||[])}if(r.__arrayBuffer)return Uint8Array.from(r.__arrayBuffer).buffer;if(Array.isArray(r))return r.map(n=>o(f,n));let d={};for(let[n,p]of Object.entries(r))d[n]=o(f,p);return d}function s(f,r){return JSON.parse(r||"[]").map(d=>o(f,d))}return{createPackageHandle:c,deserializePackageArg:o,deserializePackageArgs:s,serializePackageValue:i}}function m(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:!Object.values(e).some(a=>typeof a=="function")}b.exports={createPackageRuntimeCodec:A}});var{createPackageRuntimeCodec:S}=g(),w=new Map,u=new Map,k=new Map,l=new Map,$=0,C=0,E=0,{createPackageHandle:I,deserializePackageArg:R,deserializePackageArgs:U,serializePackageValue:_}=S({handles:u,createHandleId:e=>`${e}:pkg_${++$}`,callIsolateCallback:j});async function B(e){let t=e.fileUrl||e.name;if(w.has(t))return w.get(t);let a=e.name&&e.name.startsWith("node:")?e.name:e.fileUrl||e.name;if(!a)throw new Error(`Package "${e.name}" cannot be imported by package runtime`);let i=await import(a);return w.set(t,i),i}function y(e,t){if(!t||t.length===0)return{target:e&&e.default!==void 0?e.default:e,receiver:void 0};let a=e,i;for(let c=0;c<t.length;c++){let o=t[c];if(a==null&&c===0&&e.default!==void 0&&(a=e.default),a!=null&&o in a){i=a,a=a[o];continue}if(c===0&&e.default!==void 0&&e.default!==a&&o in e.default){i=e.default,a=e.default[o];continue}throw new Error(`Package export not found: ${t.join(".")}`)}return{target:a,receiver:i}}function j(e,t,a){return new Promise((i,c)=>{let o=`cb_${++C}`;k.set(o,{resolve:i,reject:c,taskId:e});try{process.send?.({type:"pkgCallbackCall",id:o,taskId:e,callbackId:t,argsJson:JSON.stringify(a.map(s=>_(e,s)))})}catch(s){k.delete(o),c(s)}})}async function x(e){let t=U(e.taskId,e.argsJson);if(e.op==="handleCall"){let o=u.get(e.handleId);if(!o)throw new Error(`Package handle not found: ${e.handleId}`);let{target:s,receiver:f}=y(o,e.path||[]);if(typeof s!="function")return _(e.taskId,s);let r=await s.apply(f||o,t);return _(e.taskId,r)}if(e.op==="handleGet"){let o=u.get(e.handleId);if(!o)throw new Error(`Package handle not found: ${e.handleId}`);let{target:s,receiver:f}=y(o,e.path||[]);return _(e.taskId,typeof s=="function"&&f?s.bind(f):s)}let a=await B(e.package),{target:i,receiver:c}=y(a,e.path||[]);if(e.op==="construct"){if(typeof i!="function")throw new Error(`Package export is not constructable: ${e.packageName}.${(e.path||[]).join(".")}`);return I(e.taskId,new i(...t))}return typeof i=="function"?_(e.taskId,await i.apply(c,t)):_(e.taskId,i)}function O(e,t,a){return new Promise((i,c)=>{let o=`stream_${++E}`;l.set(o,{resolve:i,reject:c});try{process.send?.({type:"pkgStreamChunk",id:e,ackId:o,taskId:t,chunk:Buffer.from(a).toString("base64")},s=>{s&&(l.delete(o),c(s))})}catch(s){l.delete(o),c(s)}})}async function H(e){let t=u.get(e.handleId);if(!t)throw new Error(`Package handle not found: ${e.handleId}`);let{target:a}=y(t,e.path||[]),i=a||t;if(!i||typeof i[Symbol.asyncIterator]!="function"&&typeof i.on!="function")throw new Error(`Package handle is not a readable stream: ${e.handleId}`);for await(let c of i)await O(e.id,e.taskId,c)}function M(e){for(let t of u.keys())t.startsWith(`${e}:`)&&u.delete(t)}process.on("message",async e=>{if(e){if(e.type==="pkgStreamAck"||e.type==="pkgStreamError"){let t=l.get(e.ackId);if(!t)return;l.delete(e.ackId),e.type==="pkgStreamAck"?t.resolve(!0):t.reject(new Error(e.error?.message||"Package stream failed"));return}if(e.type==="pkgCallbackResult"||e.type==="pkgCallbackError"){let t=k.get(e.id);if(!t)return;k.delete(e.id),e.type==="pkgCallbackResult"?t.resolve(R(t.taskId,e.value)):t.reject(new Error(e.error?.message||"Package callback failed"));return}if(e.op)try{if(e.op==="releaseTask"){M(e.taskId),e.fire||process.send?.({id:e.id,ok:!0,value:!0});return}let t=e.op==="streamHandle"?await H(e):await x(e);process.send?.({id:e.id,ok:!0,value:t})}catch(t){let a=[e.op?`op=${e.op}`:null,e.packageName?`package=${e.packageName}`:null,e.handleId?`handle=${e.handleId}`:null,Array.isArray(e.path)?`path=${e.path.join(".")||"<root>"}`:null].filter(Boolean).join(" ");process.send?.({id:e.id,ok:!1,error:{message:a?`${t.message} (${a})`:t.message,stack:t.stack}})}}});
1
+ "use strict";var A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var m=A((L,b)=>{"use strict";function P({handles:e,createHandleId:t,callIsolateCallback:a}){function c(f,r){if(r==null)return r;let d=typeof r;if(d==="string"||d==="number"||d==="boolean")return r;if(r instanceof Date)return{__date:r.toISOString()};if(r instanceof Set)return{__set:Array.from(r.values()).map(i=>c(f,i))};if(r instanceof Map)return{__map:Array.from(r.entries()).map(([i,u])=>[c(f,i),c(f,u)])};if(r instanceof RegExp)return{__regexp:{source:r.source,flags:r.flags}};if(r instanceof Error)return{__error:{name:r.name,message:r.message,stack:r.stack}};if(typeof URL<"u"&&r instanceof URL)return{__url:r.href};if(typeof URLSearchParams<"u"&&r instanceof URLSearchParams)return{__urlSearchParams:r.toString()};if(typeof Buffer<"u"&&Buffer.isBuffer(r)||r._isBuffer===!0)return n(f,r);if(ArrayBuffer.isView(r))return{__typedArray:r.constructor?.name||"Uint8Array",data:Array.from(r)};if(r instanceof ArrayBuffer)return{__arrayBuffer:Array.from(new Uint8Array(r))};if(Array.isArray(r))return r.map(i=>c(f,i));if(d==="object"&&g(r)){let i={};for(let[u,h]of Object.entries(r))i[u]=c(f,h);return i}return n(f,r)}function n(f,r){let d=t(f);return e.set(d,r),{__pkgHandle:d}}function o(f,r){if(!r||typeof r!="object")return r;if(r.__fnRef)return(...i)=>a(f,r.__fnRef,i);if(r.__pkgHandleArg){let i=e.get(r.__pkgHandleArg);if(!i)throw new Error(`Package argument handle not found: ${r.__pkgHandleArg}`);return i}if(r.__date)return new Date(r.__date);if(r.__set)return new Set(r.__set.map(i=>o(f,i)));if(r.__map)return new Map(r.__map.map(([i,u])=>[o(f,i),o(f,u)]));if(r.__regexp)return new RegExp(r.__regexp.source,r.__regexp.flags||"");if(r.__error){let i=new Error(r.__error.message||"");return i.name=r.__error.name||"Error",r.__error.stack&&(i.stack=r.__error.stack),i}if(r.__url)return new URL(r.__url);if(r.__urlSearchParams)return new URLSearchParams(r.__urlSearchParams);if(r.__blob)return new Blob([Uint8Array.from(r.__blob.data||[])],{type:r.__blob.type||""});if(r.__file){let i=[Uint8Array.from(r.__file.data||[])],u={type:r.__file.type||"",lastModified:r.__file.lastModified};return typeof File<"u"?new File(i,r.__file.name||"file",u):new Blob(i,u)}if(r.__formData){let i=new FormData;for(let[u,h]of r.__formData)i.append(u,o(f,h));return i}if(r.__typedArray){let i=globalThis[r.__typedArray]||Uint8Array;return new i(r.data||[])}if(r.__arrayBuffer)return Uint8Array.from(r.__arrayBuffer).buffer;if(Array.isArray(r))return r.map(i=>o(f,i));let d={};for(let[i,u]of Object.entries(r))d[i]=o(f,u);return d}function s(f,r){return JSON.parse(r||"[]").map(d=>o(f,d))}return{createPackageHandle:n,deserializePackageArg:o,deserializePackageArgs:s,serializePackageValue:c}}function g(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:!Object.values(e).some(a=>typeof a=="function")}b.exports={createPackageRuntimeCodec:P}});var{createPackageRuntimeCodec:$}=m(),w=new Map,l=new Map,k=new Map,_=new Map,S=0,C=0,E=0;function x(e){return Math.max(1,Math.trunc(Number(e)||3e4))}function I(e,t){let a=()=>process.exit(1);try{process.send?.({id:e,ok:!1,error:{message:t}},a),setTimeout(a,50).unref?.()}catch{a()}}var{createPackageHandle:j,deserializePackageArg:B,deserializePackageArgs:R,serializePackageValue:p}=$({handles:l,createHandleId:e=>`${e}:pkg_${++S}`,callIsolateCallback:M});async function U(e){let t=e.fileUrl||e.name;if(w.has(t))return w.get(t);let a=e.name&&e.name.startsWith("node:")?e.name:e.fileUrl||e.name;if(!a)throw new Error(`Package "${e.name}" cannot be imported by package runtime`);let c=await import(a);return w.set(t,c),c}function y(e,t){if(!t||t.length===0)return{target:e&&e.default!==void 0?e.default:e,receiver:void 0};let a=e,c;for(let n=0;n<t.length;n++){let o=t[n];if(a==null&&n===0&&e.default!==void 0&&(a=e.default),a!=null&&o in a){c=a,a=a[o];continue}if(n===0&&e.default!==void 0&&e.default!==a&&o in e.default){c=e.default,a=e.default[o];continue}throw new Error(`Package export not found: ${t.join(".")}`)}return{target:a,receiver:c}}function M(e,t,a){return new Promise((c,n)=>{let o=`cb_${++C}`;k.set(o,{resolve:c,reject:n,taskId:e});try{process.send?.({type:"pkgCallbackCall",id:o,taskId:e,callbackId:t,argsJson:JSON.stringify(a.map(s=>p(e,s)))})}catch(s){k.delete(o),n(s)}})}async function T(e){let t=R(e.taskId,e.argsJson);if(e.op==="handleCall"){let o=l.get(e.handleId);if(!o)throw new Error(`Package handle not found: ${e.handleId}`);let{target:s,receiver:f}=y(o,e.path||[]);if(typeof s!="function")return p(e.taskId,s);let r=await s.apply(f||o,t);return p(e.taskId,r)}if(e.op==="handleGet"){let o=l.get(e.handleId);if(!o)throw new Error(`Package handle not found: ${e.handleId}`);let{target:s,receiver:f}=y(o,e.path||[]);return p(e.taskId,typeof s=="function"&&f?s.bind(f):s)}let a=await U(e.package),{target:c,receiver:n}=y(a,e.path||[]);if(e.op==="construct"){if(typeof c!="function")throw new Error(`Package export is not constructable: ${e.packageName}.${(e.path||[]).join(".")}`);return j(e.taskId,new c(...t))}return typeof c=="function"?p(e.taskId,await c.apply(n,t)):p(e.taskId,c)}function O(e,t,a){return new Promise((c,n)=>{let o=`stream_${++E}`;_.set(o,{resolve:c,reject:n});try{process.send?.({type:"pkgStreamChunk",id:e,ackId:o,taskId:t,chunk:Buffer.from(a).toString("base64")},s=>{s&&(_.delete(o),n(s))})}catch(s){_.delete(o),n(s)}})}async function H(e){let t=l.get(e.handleId);if(!t)throw new Error(`Package handle not found: ${e.handleId}`);let{target:a}=y(t,e.path||[]),c=a||t;if(!c||typeof c[Symbol.asyncIterator]!="function"&&typeof c.on!="function")throw new Error(`Package handle is not a readable stream: ${e.handleId}`);for await(let n of c)await O(e.id,e.taskId,n)}function N(e){for(let t of l.keys())t.startsWith(`${e}:`)&&l.delete(t)}process.on("message",async e=>{if(!e)return;if(e.type==="pkgStreamAck"||e.type==="pkgStreamError"){let n=_.get(e.ackId);if(!n)return;_.delete(e.ackId),e.type==="pkgStreamAck"?n.resolve(!0):n.reject(new Error(e.error?.message||"Package stream failed"));return}if(e.type==="pkgCallbackResult"||e.type==="pkgCallbackError"){let n=k.get(e.id);if(!n)return;k.delete(e.id),e.type==="pkgCallbackResult"?n.resolve(B(n.taskId,e.value)):n.reject(new Error(e.error?.message||"Package callback failed"));return}if(!e.op)return;let t=!1,a=x(e.timeoutMs),c=setTimeout(()=>{if(t)return;t=!0;let n=[e.op?`op=${e.op}`:null,e.packageName?`package=${e.packageName}`:null,e.handleId?`handle=${e.handleId}`:null,Array.isArray(e.path)?`path=${e.path.join(".")||"<root>"}`:null].filter(Boolean).join(" "),o=`Package runtime call timed out after ${a}ms${n?` (${n})`:""}`;I(e.id,o)},a);try{if(e.op==="releaseTask"){t=!0,clearTimeout(c),N(e.taskId),e.fire||process.send?.({id:e.id,ok:!0,value:!0});return}let n=e.op==="streamHandle"?await H(e):await T(e);if(t)return;t=!0,clearTimeout(c),process.send?.({id:e.id,ok:!0,value:n})}catch(n){if(t)return;t=!0,clearTimeout(c);let o=[e.op?`op=${e.op}`:null,e.packageName?`package=${e.packageName}`:null,e.handleId?`handle=${e.handleId}`:null,Array.isArray(e.path)?`path=${e.path.join(".")||"<root>"}`:null].filter(Boolean).join(" ");process.send?.({id:e.id,ok:!1,error:{message:o?`${n.message} (${o})`:n.message,stack:n.stack}})}});process.on("disconnect",()=>{process.exit(1)});
@@ -1,8 +1,9 @@
1
- "use strict";var F=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var L=F((je,U)=>{"use strict";var{fork:oe}=require("child_process"),ie=require("path");function ce({workerDir:e,activeTaskContexts:t}){let s=new Map,r=new Map,n=new Map,a=null,l=0;function _(i){for(let c of r.values())c.reject(i);r.clear()}function d(i){let c=typeof i=="string"?JSON.parse(i):i;if(c?.error)throw new Error(c.error);return c?.value}async function v(i){let c=t.get(i.taskId);if(!c)throw new Error(`Package callback context not found: ${i.taskId}`);let o=JSON.stringify(i.callbackId),f=JSON.stringify(i.argsJson||"[]"),p=await c.evalClosure(`return __invokeRuntimeCallback(${o}, ${f});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return d(p)}function g(){if(a&&a.connected)return a;let i=ie.join(e,"package-runtime.child.js"),c=oe(i,[],{stdio:["ignore","ignore","ignore","ipc"]});return a=c,c.on("message",o=>{if(!o||!o.id)return;if(o.type==="pkgStreamChunk"){let p=n.get(o.id);if(!p)return;p.onChunk(Buffer.from(o.chunk||"","base64")).then(()=>{try{c.send({type:"pkgStreamAck",ackId:o.ackId})}catch{}}).catch(k=>{try{c.send({type:"pkgStreamError",ackId:o.ackId,error:{message:k.message,stack:k.stack}})}catch{}});return}if(o.type==="pkgCallbackCall"){v(o).then(p=>{try{c.send({type:"pkgCallbackResult",id:o.id,value:p})}catch{}}).catch(p=>{try{c.send({type:"pkgCallbackError",id:o.id,error:{message:p.message,stack:p.stack}})}catch{}});return}let f=r.get(o.id);if(f)if(r.delete(o.id),n.delete(o.id),o.ok)f.resolve(o.value);else{let p=new Error(o.error?.message||"Package runtime call failed");p.stack=o.error?.stack||p.stack,f.reject(p)}}),c.on("exit",(o,f)=>{a===c&&(a=null),_(new Error(`Package runtime exited${f?` with signal ${f}`:` with code ${o}`}`))}),c.on("error",o=>{a===c&&(a=null),_(o)}),c}function y(i){return new Promise((c,o)=>{let f=g(),p=`pkg_${++l}`;r.set(p,{resolve:c,reject:o});try{f.send({...i,id:p},k=>{k&&(r.delete(p),o(k))})}catch(k){r.delete(p),o(k)}})}function u(i,c,o,f=[]){return new Promise((p,k)=>{let x=g(),P=`pkg_${++l}`;r.set(P,{resolve:p,reject:k}),n.set(P,{onChunk:o});try{x.send({op:"streamHandle",taskId:i,handleId:c,path:f,id:P},b=>{b&&(r.delete(P),n.delete(P),k(b))})}catch(b){r.delete(P),n.delete(P),k(b)}})}function h(i){try{if(!a||!a.connected)return;a.send({...i,id:`pkg_${++l}`,fire:!0})}catch{}}async function w(i,c){let o=s.get(i);if(!o)throw new Error("Package context is not available");if(c.handleId)return y({op:c.kind==="get"?"handleGet":"handleCall",taskId:i,handleId:c.handleId,path:c.path||[],argsJson:c.argsJson||"[]"});let f=o.get(c.packageName);if(!f)throw new Error(`Package "${c.packageName}" is not available`);return y({op:c.kind==="construct"?"construct":"call",taskId:i,packageName:c.packageName,package:{name:f.name,fileUrl:f.fileUrl},path:c.path||[],argsJson:c.argsJson||"[]"})}function m(i,c){s.set(i,c)}function A(i){s.delete(i),h({op:"releaseTask",taskId:i})}function T(){if(a){try{a.kill()}catch{}a=null}}return{cleanupTaskPackages:A,executePackageRuntimeCall:w,setTaskPackages:m,streamPackageHandle:u,shutdownPackageRuntime:T}}U.exports={createPackageRuntimeBridge:ce}});var D=F((Te,K)=>{"use strict";var le=`
1
+ "use strict";var L=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var q=L((Ie,K)=>{"use strict";var{fork:ce}=require("child_process"),le=require("path");function ue({workerDir:e,activeTaskContexts:t}){let o=new Map,r=new Map,a=new Map,s=null,c=0;function g(f){return Math.max(1,Math.trunc(Number(f)||3e4))}function u(f){for(let n of r.values())clearTimeout(n.timer),n.reject(f);r.clear()}function h(f){let n=typeof f=="string"?JSON.parse(f):f;if(n?.error)throw new Error(n.error);return n?.value}async function v(f){let n=t.get(f.taskId);if(!n)throw new Error(`Package callback context not found: ${f.taskId}`);let i=JSON.stringify(f.callbackId),p=JSON.stringify(f.argsJson||"[]"),_=await n.evalClosure(`return __invokeRuntimeCallback(${i}, ${p});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return h(_)}function y(){if(s&&s.connected)return s;let f=le.join(e,"package-runtime.child.js"),n=ce(f,[],{stdio:["ignore","ignore","ignore","ipc"]});return s=n,n.on("message",i=>{if(!i||!i.id)return;if(i.type==="pkgStreamChunk"){let _=a.get(i.id);if(!_)return;_.onChunk(Buffer.from(i.chunk||"","base64")).then(()=>{try{n.send({type:"pkgStreamAck",ackId:i.ackId})}catch{}}).catch(w=>{try{n.send({type:"pkgStreamError",ackId:i.ackId,error:{message:w.message,stack:w.stack}})}catch{}});return}if(i.type==="pkgCallbackCall"){v(i).then(_=>{try{n.send({type:"pkgCallbackResult",id:i.id,value:_})}catch{}}).catch(_=>{try{n.send({type:"pkgCallbackError",id:i.id,error:{message:_.message,stack:_.stack}})}catch{}});return}let p=r.get(i.id);if(p)if(clearTimeout(p.timer),r.delete(i.id),a.delete(i.id),i.ok)p.resolve(i.value);else{let _=new Error(i.error?.message||"Package runtime call failed");_.stack=i.error?.stack||_.stack,p.reject(_)}}),n.on("exit",(i,p)=>{s===n&&(s=null),u(new Error(`Package runtime exited${p?` with signal ${p}`:` with code ${i}`}`))}),n.on("error",i=>{s===n&&(s=null),u(i)}),n}function l(f){return new Promise((n,i)=>{let p=y(),_=`pkg_${++c}`,w=g(f.timeoutMs),S=setTimeout(()=>{r.delete(_),a.delete(_);try{p.kill()}catch{}i(new Error(`Package runtime call timed out after ${w}ms`))},w);r.set(_,{resolve:n,reject:i,timer:S});try{p.send({...f,id:_},C=>{C&&(clearTimeout(S),r.delete(_),i(C))})}catch(C){clearTimeout(S),r.delete(_),i(C)}})}function m(f,n,i,p=[],_=3e4){return new Promise((w,S)=>{let C=y(),x=`pkg_${++c}`,H=g(_),U=setTimeout(()=>{r.delete(x),a.delete(x);try{C.kill()}catch{}S(new Error(`Package runtime stream timed out after ${H}ms`))},H);r.set(x,{resolve:w,reject:S,timer:U}),a.set(x,{onChunk:i});try{C.send({op:"streamHandle",taskId:f,handleId:n,path:p,id:x},F=>{F&&(clearTimeout(U),r.delete(x),a.delete(x),S(F))})}catch(F){clearTimeout(U),r.delete(x),a.delete(x),S(F)}})}function P(f){try{if(!s||!s.connected)return;s.send({...f,id:`pkg_${++c}`,fire:!0})}catch{}}async function k(f,n){let i=o.get(f);if(!i)throw new Error("Package context is not available");if(n.handleId)return l({op:n.kind==="get"?"handleGet":"handleCall",taskId:f,handleId:n.handleId,path:n.path||[],argsJson:n.argsJson||"[]"});let p=i.get(n.packageName);if(!p)throw new Error(`Package "${n.packageName}" is not available`);return l({op:n.kind==="construct"?"construct":"call",taskId:f,packageName:n.packageName,package:{name:p.name,fileUrl:p.fileUrl},path:n.path||[],argsJson:n.argsJson||"[]"})}function A(f,n){o.set(f,n)}function I(f){o.delete(f),P({op:"releaseTask",taskId:f})}function d(){if(s){try{s.kill()}catch{}s=null}}return{cleanupTaskPackages:I,executePackageRuntimeCall:k,setTaskPackages:A,streamPackageHandle:m,shutdownPackageRuntime:d}}K.exports={createPackageRuntimeBridge:ue}});var V=L((He,B)=>{"use strict";var fe=`
2
2
  "use strict";
3
3
  let $ctx = {};
4
4
  let $pkgs = {};
5
5
  let __taskId = null;
6
+ let __taskDeadlineMs = 0;
6
7
  let __logs = [];
7
8
  let __runtimeCallbackCounter = 0;
8
9
  let __runtimeCallbacks = new Map();
@@ -88,6 +89,15 @@ async function __call(type, dataJson) {
88
89
  return __parseMainThreadResult(r);
89
90
  }
90
91
 
92
+ function __remainingTaskTimeoutMs() {
93
+ if (!__taskDeadlineMs) return 30000;
94
+ return Math.max(1, Math.ceil(__taskDeadlineMs - Date.now()));
95
+ }
96
+
97
+ function __encodePkgCallPayload(payload) {
98
+ return JSON.stringify({ ...payload, timeoutMs: __remainingTaskTimeoutMs() });
99
+ }
100
+
91
101
  async function __encodeRuntimeArg(value, seen) {
92
102
  if (typeof value === 'function') {
93
103
  if (value.__pkgHandlePromise) {
@@ -416,7 +426,7 @@ function __createPkgHandleProxy(handlePromise, path) {
416
426
  return __createAsyncPkgResultProxy(
417
427
  handlePromise.then((handleId) =>
418
428
  __stringifyRuntimeArgs(args).then((argsJson) =>
419
- __call('pkgCall', JSON.stringify({ handleId, path, argsJson, kind: 'call' })),
429
+ __call('pkgCall', __encodePkgCallPayload({ handleId, path, argsJson, kind: 'call' })),
420
430
  ),
421
431
  ),
422
432
  [],
@@ -429,7 +439,7 @@ function __createPkgHandleProxy(handlePromise, path) {
429
439
  if (prop === '__pkgHandlePromise') return handlePromise;
430
440
  return __createAsyncPkgResultProxy(
431
441
  handlePromise.then((handleId) =>
432
- __call('pkgCall', JSON.stringify({
442
+ __call('pkgCall', __encodePkgCallPayload({
433
443
  handleId,
434
444
  path: path.concat(String(prop)),
435
445
  kind: 'get',
@@ -442,7 +452,7 @@ function __createPkgHandleProxy(handlePromise, path) {
442
452
  __createAsyncPkgResultProxy(
443
453
  handlePromise.then((handleId) =>
444
454
  __stringifyRuntimeArgs(args).then((argsJson) =>
445
- __call('pkgCall', JSON.stringify({ handleId, path, argsJson, kind: 'call' })),
455
+ __call('pkgCall', __encodePkgCallPayload({ handleId, path, argsJson, kind: 'call' })),
446
456
  ),
447
457
  ),
448
458
  [],
@@ -572,7 +582,7 @@ function __createPkgProxy(packageName, path) {
572
582
  const fn = function (...args) {
573
583
  return __createAsyncPkgResultProxy(
574
584
  __stringifyRuntimeArgs(args).then((argsJson) =>
575
- __call('pkgCall', JSON.stringify({ packageName, path, argsJson, kind: 'call' })),
585
+ __call('pkgCall', __encodePkgCallPayload({ packageName, path, argsJson, kind: 'call' })),
576
586
  ),
577
587
  [],
578
588
  );
@@ -585,14 +595,14 @@ function __createPkgProxy(packageName, path) {
585
595
  apply: (_target, _thisArg, args) =>
586
596
  __createAsyncPkgResultProxy(
587
597
  __stringifyRuntimeArgs(args).then((argsJson) =>
588
- __call('pkgCall', JSON.stringify({ packageName, path, argsJson, kind: 'call' })),
598
+ __call('pkgCall', __encodePkgCallPayload({ packageName, path, argsJson, kind: 'call' })),
589
599
  ),
590
600
  [],
591
601
  ),
592
602
  construct: (_target, args) => {
593
603
  const handlePromise = __stringifyRuntimeArgs(args)
594
604
  .then((argsJson) =>
595
- __call('pkgCall', JSON.stringify({ packageName, path, argsJson, kind: 'construct' })),
605
+ __call('pkgCall', __encodePkgCallPayload({ packageName, path, argsJson, kind: 'construct' })),
596
606
  )
597
607
  .then((value) => {
598
608
  if (value && value.__pkgHandlePromise) return value.__pkgHandlePromise;
@@ -616,10 +626,11 @@ const console = {
616
626
  info: (...a) => $ctx.$logs(...a),
617
627
  };
618
628
 
619
- function __resetTask(snapshot, taskId) {
629
+ function __resetTask(snapshot, taskId, timeoutMs) {
620
630
  $ctx = snapshot || {};
621
631
  $pkgs = {};
622
632
  __taskId = taskId;
633
+ __taskDeadlineMs = Date.now() + Math.max(1, Math.trunc(Number(timeoutMs) || 30000));
623
634
  __logs = [];
624
635
  __runtimeCallbackCounter = 0;
625
636
  __runtimeCallbacks = new Map();
@@ -700,53 +711,54 @@ function __cleanupTask() {
700
711
  $ctx = {};
701
712
  $pkgs = {};
702
713
  __taskId = null;
714
+ __taskDeadlineMs = 0;
703
715
  __logs = [];
704
716
  __runtimeCallbackCounter = 0;
705
717
  __runtimeCallbacks = new Map();
706
718
  return true;
707
719
  }
708
- `;function ue(e){return le.replace("%%PKG_SETUP%%",e)}K.exports={buildSetupCode:ue}});var{parentPort:j}=require("worker_threads"),q=require("fs"),{fileURLToPath:fe}=require("url"),{createPackageRuntimeBridge:pe}=L(),{buildSetupCode:_e}=D(),M;try{M=require("isolated-vm")}catch(e){j.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var O=new Map,G=0,E=new Map,J=pe({workerDir:__dirname,activeTaskContexts:E}),de=500,ge=5e3,he=32,B=new WeakMap,X=new WeakMap,Z=new WeakMap,N={created:0,reused:0,released:0,evicted:0,scrubFailed:0},S=null,ye=0,V=0,W=0;async function me(){let e=Date.now();if(e-V<ge)return W;if(V=e,!S)return 0;let t=0;for(let s of S){let r=s?.isolate;if(!(!r||r.isDisposed))try{let n=await r.getHeapStatistics(),a=n.heap_size_limit||1,l=n.used_heap_size/a;l>t&&(t=l)}catch{}}return W=t,t}async function R(e){e.heapRatio=await me(),e.contextStats=ke(),j.postMessage(e)}function ke(){let e=0;if(S)for(let t of S)e+=t?.idleContexts?.length||0;return{...N,idle:e}}function Q(e,t){if(!S){let n=Math.max(1,Math.trunc(Number(t)||8));S=new Array(n).fill(null)}let s=ye++%S.length,r=S[s];return(!r||!r.isolate||r.isolate.isDisposed)&&(r={isolate:new M.Isolate({memoryLimit:e}),idleContexts:[]},S[s]=r),r}async function C(e,t,s){let r=B.get(e);r||(r=new Map,B.set(e,r));let n=r.get(t);if(n)return n;let a=await e.compileScript(t,{filename:s});if(r.set(t,a),r.size>de){let l=r.keys().next().value;r.delete(l)}return a}j.on("message",async e=>{if(e.type==="execute")Je(e).catch(async t=>{await R({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Oe(e).catch(async t=>{await R({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="callResult"){let t=O.get(e.callId);t&&(O.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=O.get(e.callId);t&&(O.delete(e.callId),t.reject(new Error(e.error)))}});function $(e,t,s){return new Promise((r,n)=>{let a=`cb_${++G}`;O.set(a,{resolve:r,reject:n}),j.postMessage({type:t,id:e,callId:a,...s})})}function ve(e,t,s){j.postMessage({type:t,id:e,callId:`f_${++G}`,...s})}async function we(e,t){if(t?.method!=="stream")return $(e,"resCall",t);let s=JSON.parse(t.argsJson||"[]"),r=s[0],n=s[1]||{},a=r?.__pkgHandleArg;if(!a)return $(e,"resCall",t);await $(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,n])});try{await J.streamPackageHandle(e,a,l=>$(e,"resCall",{method:"streamChunk",chunk:Buffer.from(l).toString("base64")})),await $(e,"resCall",{method:"streamEnd"})}catch(l){try{await $(e,"resCall",{method:"streamError",error:{message:l.message,stack:l.stack}})}catch{}throw l}return JSON.stringify({__e:"u"})}function Pe(e){if(typeof e.sourceCode=="string"&&e.sourceCode.length>0)return e.sourceCode;let t=e.filePath;return!t&&typeof e.fileUrl=="string"&&e.fileUrl.startsWith("file://")&&(t=fe(e.fileUrl)),!t||!q.existsSync(t)?null:q.readFileSync(t,"utf8")}async function xe(e,t,s){try{let r=Pe(s);if(!r)return null;let n=await e.compileModule(r,{filename:`pkg:${s.safeName}`});await n.instantiate(t,l=>{throw new Error(`Unresolved import in package ${s.safeName}: ${l}`)}),await n.evaluate({timeout:1e4});let a=await n.namespace.get("default");return a!==void 0&&a.typeof!=="undefined"?a.derefInto({release:!1}):n.namespace.derefInto({release:!1})}catch{return null}}function Y(e,t){let s=n=>{let a=2166136261;for(let l=0;l<n.length;l++)a^=n.charCodeAt(l),a=Math.imul(a,16777619);return(a>>>0).toString(36)},r=new Set(t||[]);return e.map(n=>{let a=n.cacheKey||`${n.filePath||""}:${n.fileUrl||""}:${n.mtimeMs||""}:${n.size||""}:${s(n.sourceCode||"")}`,l=r.has(n.name)?"isolate":"proxy";return`${n.name}:${n.version||""}:${a}:${l}`}).join("|")}function ee(e,t){let s=new Set(t.map(d=>d.name)),r=new Set,n=String(e||""),a=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,l=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,_=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let d of[a,l])for(let v of n.matchAll(d)){let g=v[2];s.has(g)&&r.add(g)}for(let d of n.matchAll(_)){let v=d[1];s.has(v)&&r.add(v)}return r}async function Se(e,t,s,r){let n=await e.createContext(),a=n.global;await a.set("global",a.derefInto());let l=[],_=[],d=new Map;for(let u of s){d.set(u.name,u);let h=r.has(u.name)?await xe(e,n,u):null;h!==null?(await a.set(`__pkg_${u.safeName}`,h),l.push(u)):_.push(u)}J.setTaskPackages(t,d),await a.set("__callRef",new M.Reference(async(u,h,w)=>{let m=JSON.parse(w);return h==="pkgCall"?JSON.stringify(await J.executePackageRuntimeCall(u,m)):h==="resCall"?we(u,m):$(u,h,m)})),await a.set("__fireRef",new M.Reference((u,h,w)=>{let m=JSON.parse(w);ve(u,h,m)}));let v=l.map(u=>`$pkgs[${JSON.stringify(u.name)}] = __pkg_${u.safeName};`).concat(_.map(u=>`$pkgs[${JSON.stringify(u.name)}] = __createPkgProxy(${JSON.stringify(u.name)}, []);`)).join(`
709
- `),g=_e(v);return await(await C(e,g,"setup.js")).run(n,{timeout:5e3}),X.set(n,Y(s,r)),Z.set(n,d),n}async function te(e,t,s,r,n){let a=e.isolate,l=Y(s,n),_=null;for(let g=e.idleContexts.length-1;g>=0;g--){let y=e.idleContexts[g];if(e.idleContexts.splice(g,1),X.get(y)===l){_=y,N.reused++;break}try{y.release()}catch{}}_||(_=await Se(a,t,s,n),N.created++),J.setTaskPackages(t,Z.get(_)||new Map);let d=_.global;return await d.set("__snapshot",new M.ExternalCopy(r).copyInto()),await d.set("__nextTaskId",t),await(await C(a,"__resetTask(__snapshot, __nextTaskId);","reset-task.js")).run(_,{timeout:5e3}),_}async function re(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await C(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{N.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=he){try{t.release()}catch{}N.evicted++;return}e.idleContexts.push(t),N.released++}}function Ce(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var be=3,$e=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Re(e){if(!e)return null;let t=e.split(`
710
- `);for(let s of t){let r=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!r)continue;let n=r[1].trim();if($e.includes(n))continue;let l=parseInt(r[2])-be;if(!(l<=0))return{line:l,column:parseInt(r[3]),phase:n.replace(".js","")}}return null}function Ae(e,t,s){if(!e||!t)return;let r=String(e).split(/\r?\n/),n=Math.max(1,t-1),a=Math.min(r.length,t+1),l=String(a).length,_=[];for(let d=n;d<=a;d++){let v=d===t?">":" ";_.push(`${v} ${String(d).padStart(l," ")}. ${r[d-1]??""}`),d===t&&s&&s>0&&_.push(` ${" ".repeat(l)} ${" ".repeat(Math.max(0,s-1))}^`)}return _.join(`
711
- `)}function Ne(e,t){if(!(!e||!t)){if(t[e.phase])return t[e.phase];if(e.phase?.startsWith("preHook"))return t.preHook;if(e.phase?.startsWith("postHook"))return t.postHook}}function I(e,t){let s=Ce(e);if(s)return{message:s.message,statusCode:s.statusCode,details:s.details};let r=Re(e.stack),n=e.message||"Unknown error",a=r?`${n} (${r.phase}, line ${r.line})`:n,l=Ne(r,t),_=r?Ae(l,r.line,r.column):void 0;return{message:a,statusCode:e.statusCode||null,details:r?{...r,codeFrame:_}:void 0}}async function ne(e,t){let s=I(t);await R({type:"result",id:e,success:!1,error:{...s,stack:t.stack,code:t.code}})}async function Je(e){let{id:t,code:s,pkgSources:r,snapshot:n,memoryLimitMb:a,isolatePoolSize:l}=e,_=r||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),v=ee(s,_),g=Q(a,l),y=g.isolate,u=await te(g,t,_,n,v);E.set(t,u);try{let h=`
720
+ `;function pe(e){return fe.replace("%%PKG_SETUP%%",e)}B.exports={buildSetupCode:pe}});var{parentPort:j}=require("worker_threads"),W=require("fs"),{fileURLToPath:_e}=require("url"),{createPackageRuntimeBridge:de}=q(),{buildSetupCode:ge}=V(),O;try{O=require("isolated-vm")}catch(e){j.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var J=new Map,Q=0,E=new Map,T=de({workerDir:__dirname,activeTaskContexts:E}),he=500,ye=5e3,me=32,z=new WeakMap,Y=new WeakMap,ee=new WeakMap,N={created:0,reused:0,released:0,evicted:0,scrubFailed:0},b=null,ke=0,G=0,X=0;async function ve(){let e=Date.now();if(e-G<ye)return X;if(G=e,!b)return 0;let t=0;for(let o of b){let r=o?.isolate;if(!(!r||r.isDisposed))try{let a=await r.getHeapStatistics(),s=a.heap_size_limit||1,c=a.used_heap_size/s;c>t&&(t=c)}catch{}}return X=t,t}async function M(e){e.heapRatio=await ve(),e.contextStats=we(),j.postMessage(e)}function we(){let e=0;if(b)for(let t of b)e+=t?.idleContexts?.length||0;return{...N,idle:e}}function te(e,t){if(!b){let a=Math.max(1,Math.trunc(Number(t)||8));b=new Array(a).fill(null)}let o=ke++%b.length,r=b[o];return(!r||!r.isolate||r.isolate.isDisposed)&&(r={isolate:new O.Isolate({memoryLimit:e}),idleContexts:[]},b[o]=r),r}async function $(e,t,o){let r=z.get(e);r||(r=new Map,z.set(e,r));let a=r.get(t);if(a)return a;let s=await e.compileScript(t,{filename:o});if(r.set(t,s),r.size>he){let c=r.keys().next().value;r.delete(c)}return s}j.on("message",async e=>{if(e.type==="execute")Je(e).catch(async t=>{await M({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Oe(e).catch(async t=>{await M({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="callResult"){let t=J.get(e.callId);t&&(J.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=J.get(e.callId);t&&(J.delete(e.callId),t.reject(new Error(e.error)))}});function R(e,t,o){return new Promise((r,a)=>{let s=`cb_${++Q}`;J.set(s,{resolve:r,reject:a}),j.postMessage({type:t,id:e,callId:s,...o})})}function Pe(e,t,o){j.postMessage({type:t,id:e,callId:`f_${++Q}`,...o})}async function xe(e,t){if(t?.method!=="stream")return R(e,"resCall",t);let o=JSON.parse(t.argsJson||"[]"),r=o[0],a=o[1]||{},s=r?.__pkgHandleArg;if(!s)return R(e,"resCall",t);await R(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,a])});try{await T.streamPackageHandle(e,s,c=>R(e,"resCall",{method:"streamChunk",chunk:Buffer.from(c).toString("base64")})),await R(e,"resCall",{method:"streamEnd"})}catch(c){try{await R(e,"resCall",{method:"streamError",error:{message:c.message,stack:c.stack}})}catch{}throw c}return JSON.stringify({__e:"u"})}function Se(e){if(typeof e.sourceCode=="string"&&e.sourceCode.length>0)return e.sourceCode;let t=e.filePath;return!t&&typeof e.fileUrl=="string"&&e.fileUrl.startsWith("file://")&&(t=_e(e.fileUrl)),!t||!W.existsSync(t)?null:W.readFileSync(t,"utf8")}async function Ce(e,t,o){try{let r=Se(o);if(!r)return null;let a=await e.compileModule(r,{filename:`pkg:${o.safeName}`});await a.instantiate(t,c=>{throw new Error(`Unresolved import in package ${o.safeName}: ${c}`)}),await a.evaluate({timeout:1e4});let s=await a.namespace.get("default");return s!==void 0&&s.typeof!=="undefined"?s.derefInto({release:!1}):a.namespace.derefInto({release:!1})}catch{return null}}function re(e,t){let o=a=>{let s=2166136261;for(let c=0;c<a.length;c++)s^=a.charCodeAt(c),s=Math.imul(s,16777619);return(s>>>0).toString(36)},r=new Set(t||[]);return e.map(a=>{let s=a.cacheKey||`${a.filePath||""}:${a.fileUrl||""}:${a.mtimeMs||""}:${a.size||""}:${o(a.sourceCode||"")}`,c=r.has(a.name)?"isolate":"proxy";return`${a.name}:${a.version||""}:${s}:${c}`}).join("|")}function ae(e,t){let o=new Set(t.map(u=>u.name)),r=new Set,a=String(e||""),s=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,c=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,g=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let u of[s,c])for(let h of a.matchAll(u)){let v=h[2];o.has(v)&&r.add(v)}for(let u of a.matchAll(g)){let h=u[1];o.has(h)&&r.add(h)}return r}async function be(e,t,o,r){let a=await e.createContext(),s=a.global;await s.set("global",s.derefInto());let c=[],g=[],u=new Map;for(let l of o){u.set(l.name,l);let m=r.has(l.name)?await Ce(e,a,l):null;m!==null?(await s.set(`__pkg_${l.safeName}`,m),c.push(l)):g.push(l)}T.setTaskPackages(t,u),await s.set("__callRef",new O.Reference(async(l,m,P)=>{let k=JSON.parse(P);return m==="pkgCall"?JSON.stringify(await T.executePackageRuntimeCall(l,k)):m==="resCall"?xe(l,k):R(l,m,k)})),await s.set("__fireRef",new O.Reference((l,m,P)=>{let k=JSON.parse(P);Pe(l,m,k)}));let h=c.map(l=>`$pkgs[${JSON.stringify(l.name)}] = __pkg_${l.safeName};`).concat(g.map(l=>`$pkgs[${JSON.stringify(l.name)}] = __createPkgProxy(${JSON.stringify(l.name)}, []);`)).join(`
721
+ `),v=ge(h);return await(await $(e,v,"setup.js")).run(a,{timeout:5e3}),Y.set(a,re(o,r)),ee.set(a,u),a}async function ne(e,t,o,r,a,s){let c=e.isolate,g=re(o,a),u=null;for(let y=e.idleContexts.length-1;y>=0;y--){let l=e.idleContexts[y];if(e.idleContexts.splice(y,1),Y.get(l)===g){u=l,N.reused++;break}try{l.release()}catch{}}u||(u=await be(c,t,o,a),N.created++),T.setTaskPackages(t,ee.get(u)||new Map);let h=u.global;return await h.set("__snapshot",new O.ExternalCopy(r).copyInto()),await h.set("__nextTaskId",t),await h.set("__nextTaskTimeoutMs",s),await(await $(c,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs);","reset-task.js")).run(u,{timeout:5e3}),u}async function se(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await $(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{N.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=me){try{t.release()}catch{}N.evicted++;return}e.idleContexts.push(t),N.released++}}function $e(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var Re=3,Me=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Ae(e){if(!e)return null;let t=e.split(`
722
+ `);for(let o of t){let r=o.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!r)continue;let a=r[1].trim();if(Me.includes(a))continue;let c=parseInt(r[2])-Re;if(!(c<=0))return{line:c,column:parseInt(r[3]),phase:a.replace(".js","")}}return null}function Ne(e,t,o){if(!e||!t)return;let r=String(e).split(/\r?\n/),a=Math.max(1,t-1),s=Math.min(r.length,t+1),c=String(s).length,g=[];for(let u=a;u<=s;u++){let h=u===t?">":" ";g.push(`${h} ${String(u).padStart(c," ")}. ${r[u-1]??""}`),u===t&&o&&o>0&&g.push(` ${" ".repeat(c)} ${" ".repeat(Math.max(0,o-1))}^`)}return g.join(`
723
+ `)}function Te(e,t){if(!(!e||!t)){if(t[e.phase])return t[e.phase];if(e.phase?.startsWith("preHook"))return t.preHook;if(e.phase?.startsWith("postHook"))return t.postHook}}function D(e,t){let o=$e(e);if(o)return{message:o.message,statusCode:o.statusCode,details:o.details};let r=Ae(e.stack),a=e.message||"Unknown error",s=r?`${a} (${r.phase}, line ${r.line})`:a,c=Te(r,t),g=r?Ne(c,r.line,r.column):void 0;return{message:s,statusCode:e.statusCode||null,details:r?{...r,codeFrame:g}:void 0}}async function oe(e,t){let o=D(t);await M({type:"result",id:e,success:!1,error:{...o,stack:t.stack,code:t.code}})}async function Je(e){let{id:t,code:o,pkgSources:r,snapshot:a,memoryLimitMb:s,isolatePoolSize:c}=e,g=r||[],u=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),h=ae(o,g),v=te(s,c),y=v.isolate,l=await ne(v,t,g,a,h,u);E.set(t,l);try{let m=`
712
724
  (async () => {
713
725
  "use strict";
714
- ${s}
726
+ ${o}
715
727
  })().then((__result) => __extractResult(__result, __result === undefined));
716
- `,m=await(await C(y,h,"handler.js")).run(u,{timeout:d,promise:!0}),A=JSON.parse(m);await R({type:"result",id:t,success:!0,...A})}catch(h){await ne(t,h)}finally{E.delete(t),await re(g,u),ae(t)}}async function Oe(e){let{id:t,codeBlocks:s,pkgSources:r,snapshot:n,memoryLimitMb:a,isolatePoolSize:l}=e,_=r||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),v=ee((s||[]).map(i=>i.code||"").join(`
717
- `),_),g=Q(a,l),y=g.isolate,u=await te(g,t,_,n,v);E.set(t,u);let h=[],w=[],m={},A=0,T=0;for(let i of s){let c=i.type||"handler";c==="postHook"?(T++,m[`postHook #${T}`]=i.code||"",m.postHook=i.code||"",w.push(i)):(c==="handler"?m.handler=i.code||"":(A++,m[`${c} #${A}`]=i.code||"",m.preHook=i.code||""),h.push(i))}try{let i=null;for(let o=0;o<h.length;o++){let f=h[o],p=f.type||"handler",k=p==="handler"?"handler":`${p} #${o+1}`,x;p==="preHook"?x=`
728
+ `,k=await(await $(y,m,"handler.js")).run(l,{timeout:u,promise:!0}),A=JSON.parse(k);await M({type:"result",id:t,success:!0,...A})}catch(m){await oe(t,m)}finally{E.delete(t),await se(v,l),ie(t)}}async function Oe(e){let{id:t,codeBlocks:o,pkgSources:r,snapshot:a,memoryLimitMb:s,isolatePoolSize:c}=e,g=r||[],u=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),h=ae((o||[]).map(d=>d.code||"").join(`
729
+ `),g),v=te(s,c),y=v.isolate,l=await ne(v,t,g,a,h,u);E.set(t,l);let m=[],P=[],k={},A=0,I=0;for(let d of o){let f=d.type||"handler";f==="postHook"?(I++,k[`postHook #${I}`]=d.code||"",k.postHook=d.code||"",P.push(d)):(f==="handler"?k.handler=d.code||"":(A++,k[`${f} #${A}`]=d.code||"",k.preHook=d.code||""),m.push(d))}try{let d=null;for(let n=0;n<m.length;n++){let i=m[n],p=i.type||"handler",_=p==="handler"?"handler":`${p} #${n+1}`,w;p==="preHook"?w=`
718
730
  (async () => {
719
731
  "use strict";
720
- ${f.code}
732
+ ${i.code}
721
733
  })().then((__r) => {
722
734
  if (__r !== undefined) return JSON.stringify({ __shortCircuit: true, value: __r });
723
735
  return JSON.stringify({ __shortCircuit: false });
724
- });`:x=`
736
+ });`:w=`
725
737
  (async () => {
726
738
  "use strict";
727
- ${f.code}
739
+ ${i.code}
728
740
  })().then((__r) => {
729
741
  $ctx.$data = __r;
730
742
  return "__handler_done__";
731
- });`;try{let b=await(await C(y,x,`${k}.js`)).run(u,{timeout:d,promise:!0});if(p==="preHook"&&typeof b=="string"){let H=JSON.parse(b);if(H.__shortCircuit){let se=await z(y,u,H.value);await R({type:"result",id:t,success:!0,...se,shortCircuit:!0});return}}}catch(P){i=P;break}}if(!i&&w.length>0&&await(await C(y,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(u,{timeout:5e3}),i&&w.length>0){let o=I(i,m),f={message:o.message||"Unknown error",name:i.constructor?.name||"Error",stack:i.stack||"",statusCode:o.statusCode||500,details:o.details||{},timestamp:new Date().toISOString()},p=`
732
- $ctx.$error = ${JSON.stringify(f)};
743
+ });`;try{let C=await(await $(y,w,`${_}.js`)).run(l,{timeout:u,promise:!0});if(p==="preHook"&&typeof C=="string"){let x=JSON.parse(C);if(x.__shortCircuit){let H=await Z(y,l,x.value);await M({type:"result",id:t,success:!0,...H,shortCircuit:!0});return}}}catch(S){d=S;break}}if(!d&&P.length>0&&await(await $(y,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(l,{timeout:5e3}),d&&P.length>0){let n=D(d,k),i={message:n.message||"Unknown error",name:d.constructor?.name||"Error",stack:d.stack||"",statusCode:n.statusCode||500,details:n.details||{},timestamp:new Date().toISOString()},p=`
744
+ $ctx.$error = ${JSON.stringify(i)};
733
745
  $ctx.$data = null;
734
- $ctx.$statusCode = ${f.statusCode};
746
+ $ctx.$statusCode = ${i.statusCode};
735
747
  if ($ctx.$api) {
736
- $ctx.$api.error = ${JSON.stringify(f)};
748
+ $ctx.$api.error = ${JSON.stringify(i)};
737
749
  $ctx.$api.response = {
738
- statusCode: ${f.statusCode},
750
+ statusCode: ${i.statusCode},
739
751
  responseTime: $ctx.$api.request && $ctx.$api.request.timestamp
740
752
  ? Date.now() - new Date($ctx.$api.request.timestamp).getTime()
741
753
  : 0,
742
- timestamp: ${JSON.stringify(f.timestamp)},
754
+ timestamp: ${JSON.stringify(i.timestamp)},
743
755
  };
744
756
  }
745
- "__error_populated__";`;await(await y.compileScript(p,{filename:"populate-error.js"})).run(u,{timeout:5e3})}for(let o=0;o<w.length;o++){let f=w[o],p=`postHook #${o+1}`,k=`
757
+ "__error_populated__";`;await(await y.compileScript(p,{filename:"populate-error.js"})).run(l,{timeout:5e3})}for(let n=0;n<P.length;n++){let i=P[n],p=`postHook #${n+1}`,_=`
746
758
  (async () => {
747
759
  "use strict";
748
- ${f.code}
760
+ ${i.code}
749
761
  })().then((__r) => {
750
762
  if (__r !== undefined) $ctx.$data = __r;
751
763
  return "__posthook_done__";
752
- });`;try{await(await C(y,k,`${p}.js`)).run(u,{timeout:d,promise:!0})}catch{}}if(i){let o=I(i,m),f;try{let x=await(await C(y,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(u,{timeout:5e3,promise:!0});f=JSON.parse(x)}catch{}await R({type:"result",id:t,success:!1,error:{message:o.message,statusCode:o.statusCode,stack:i.stack,code:i.code,details:o.details},ctxChanges:f});return}let c=await z(y,u);await R({type:"result",id:t,success:!0,...c})}catch(i){await ne(t,i)}finally{E.delete(t),await re(g,u),ae(t)}}function ae(e){J.cleanupTaskPackages(e)}function Me(){J.shutdownPackageRuntime()}process.on("exit",Me);async function z(e,t,s){if(s!==void 0){let l=`__extractResult(${JSON.stringify(s)}, false)`,d=await(await e.compileScript(l,{filename:"extract.js"})).run(t,{timeout:5e3,promise:!0});return JSON.parse(d)}let a=await(await C(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3,promise:!0});return JSON.parse(a)}
764
+ });`;try{await(await $(y,_,`${p}.js`)).run(l,{timeout:u,promise:!0})}catch{}}if(d){let n=D(d,k),i;try{let w=await(await $(y,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(l,{timeout:5e3,promise:!0});i=JSON.parse(w)}catch{}await M({type:"result",id:t,success:!1,error:{message:n.message,statusCode:n.statusCode,stack:d.stack,code:d.code,details:n.details},ctxChanges:i});return}let f=await Z(y,l);await M({type:"result",id:t,success:!0,...f})}catch(d){await oe(t,d)}finally{E.delete(t),await se(v,l),ie(t)}}function ie(e){T.cleanupTaskPackages(e)}function Ee(){T.shutdownPackageRuntime()}process.on("exit",Ee);async function Z(e,t,o){if(o!==void 0){let c=`__extractResult(${JSON.stringify(o)}, false)`,u=await(await e.compileScript(c,{filename:"extract.js"})).run(t,{timeout:5e3,promise:!0});return JSON.parse(u)}let s=await(await $(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3,promise:!0});return JSON.parse(s)}
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  `));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
4
4
  "use strict";
5
5
  ${e}
6
- });`)}},ee=new zt;function Vt(r,e){return ee.compileSource(r,e)}function bi(r){return ee.isExecutableJavaScript(r)}function _i(r,e){return ee.normalizeRecord(r,e)}function wi(r,e,t){return ee.normalizePatch(r,e,t)}function $i(r){return ee.getExecutableScript(r)}function Si(r){return ee.resolveExecutableScript(r)}function Ti(r){return ee.normalizeFlowStepScriptConfig(r)}var Ai=ur.join(__dirname,"execution/worker.js"),Oi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],pr=new cr.AsyncLocalStorage;function gr(){return pr.getStore()}var Ft=class{constructor(e,t,n,i,o,s,a,u=6e4){this.scriptPath=o;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=i,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new dr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":"Worker crashed"}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},lr=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$logs","$throw","$trigger","$pkgs"]);function Fn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var ze=class r{constructor(e){this.logger=new Wt(r.name);this.effectiveMemory=Tt();this.isolationTuning=qt();this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ai,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskDurationsMs=[];this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||lr.has(i))continue;let o=this.cloneSnapshotValue(e[i]);o!==void 0&&(t[i]=o)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,i]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||lr.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i){return(async()=>{let o=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort();let d=new Error(`Script execution timed out after ${i}ms`);this.cleanupResponseStream(s,d),this.pool.unregisterTask(o,s),this.taskTimeoutTotal++,q({event:"task_timeout",id:s,timeoutMs:i}),this.pool.terminateEntry(o),d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},i+5e3);this.pool.registerTask(o,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.cleanupResponseStream(s),this.pool.unregisterTask(o,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,q({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,q({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),this.cleanupResponseStream(s,g),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),o.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),o.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),o.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),o.worker,d.callId,g):d.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(d,n),o.worker,d.callId,g):d.type==="resCall"&&this.handleIoCall(()=>this.execResCall(d,n),o.worker,d.callId,g)}}),o.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,i){if(!i?.aborted)try{let o=await(i?pr.run(i,e):e());if(i?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:Fn(o)})}catch{}}catch(o){if(i?.aborted)return;try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return i[e.method](...n)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new fr.PassThrough;return this.responseStreams.set(e.id,{stream:u}),a.call(t.$res,u,s),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((a,u)=>{let l=()=>{c(),a()},f=p=>{c(),u(p)},c=()=>{o.stream.off("drain",l),o.stream.off("error",f)};o.stream.once("drain",l),o.stream.once("error",f)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),t?n.stream.destroy(t):n.stream.end())}isScriptParseFailure(e){let t=e.message||"";return Oi.some(n=>t.includes(n))}async run(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);q({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let u;try{let l={code:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("execute",l,t,i)}catch(f){let c=f,p=Vt(e,"typescript")||"";if(!this.isScriptParseFailure(c)||p===e)throw f;q({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let f=l;if(q({event:"isolated_run_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(i,e);let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw je.createException(void 0,c,f.message||"Unknown error",e,f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),q({event:"isolated_run_ok"}),u.valueAbsent?void 0:u.value}async runBatch(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);q({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let u;try{let l={codeBlocks:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",l,t,i)}catch(f){let c=f,p=e.map(g=>({...g,code:Vt(g.code,"typescript")||""})),d=p.some((g,m)=>g.code!==e[m]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;q({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let f=l;if(q({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(i,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw je.createException(void 0,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),q({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var bn=require("node:fs"),Yr=require("node:path");var Rn=require("mongodb");Ve();function Be(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function G(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Be(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function re(r){if(!r||typeof r!="object")return r;if(r instanceof Rn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>re(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((i,o)=>parseInt(i)-parseInt(o)).map(i=>t[i]);return new Rn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?re(n):n;return e}function fe(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,f=e.junctionTableName||Ct(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=Rt(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,i=t,o=e.junctionTableName||Ct(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=Rt(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function Ht(r,e,t){if(!r)return{scalarFields:[],relations:[]};let n=r.tables?.get(e);if(!n)return{scalarFields:[],relations:[]};let i=new Map;for(let u of t)if(u==="*")i.has("")||i.set("",[]),i.get("").push(u);else if(u.includes(".")){let l=u.split("."),f=l[0],c=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(c)}else n.relations?.some(f=>f.propertyName===u)?i.has(u)||i.set(u,["_id"]):(i.has("")||i.set("",[]),i.get("").push(u));let o=[],s=[],a=i.get("")||[];for(let u of a)if(u==="*"){if(n.columns)for(let l of n.columns)o.includes(l.name)||o.push(l.name);if(n.relations)for(let l of n.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else n.columns?.some(f=>f.name===u)&&!o.includes(u)&&o.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=n.relations?.find(m=>m.propertyName===u);if(!f)continue;let c="",p="",d=!1;f.type==="many-to-one"||f.type==="one-to-one"?Be(f)?(c="_id",p=K(f)||f.propertyName,d=!0):(c=G(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=K(f)||f.propertyName,d=!0):f.type==="many-to-many"&&(f.mappedBy?(c="_id",p=f.mappedBy,d=!0):(c=f.propertyName,p="_id",d=!1));let g=f.type==="one-to-many"||f.type==="many-to-many";s.push({propertyName:u,targetTable:f.targetTableName,localField:c,foreignField:p,type:g?"many":"one",isInverse:d,nestedFields:l})}return{scalarFields:o,relations:s}}var Yt=ue(require("fs")),vn=ue(require("path"));var Ei=new RegExp("\\p{Mark}","gu");function Tr(r){return r==null?"":String(r).normalize("NFKD").replace(Ei,"").toLowerCase()}function xn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Tr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Gt(){return`function() {
6
+ });`)}},ee=new zt;function Vt(r,e){return ee.compileSource(r,e)}function bi(r){return ee.isExecutableJavaScript(r)}function _i(r,e){return ee.normalizeRecord(r,e)}function wi(r,e,t){return ee.normalizePatch(r,e,t)}function $i(r){return ee.getExecutableScript(r)}function Si(r){return ee.resolveExecutableScript(r)}function Ti(r){return ee.normalizeFlowStepScriptConfig(r)}var Ai=ur.join(__dirname,"execution/worker.js"),Oi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],pr=new cr.AsyncLocalStorage;function gr(){return pr.getStore()}var Ft=class{constructor(e,t,n,i,o,s,a,u=6e4){this.scriptPath=o;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=i,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new dr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":"Worker crashed"}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},lr=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$logs","$throw","$trigger","$pkgs","$debug"]);function Fn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var ze=class r{constructor(e){this.logger=new Wt(r.name);this.effectiveMemory=Tt();this.isolationTuning=qt();this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ai,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskDurationsMs=[];this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||lr.has(i))continue;let o=this.cloneSnapshotValue(e[i]);o!==void 0&&(t[i]=o)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,i]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||lr.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i){return(async()=>{let o=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort();let d=new Error(`Script execution timed out after ${i}ms`);this.cleanupResponseStream(s,d),this.pool.unregisterTask(o,s),this.taskTimeoutTotal++,q({event:"task_timeout",id:s,timeoutMs:i}),this.pool.terminateEntry(o),d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},i);this.pool.registerTask(o,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.cleanupResponseStream(s),this.pool.unregisterTask(o,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,q({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,q({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),this.cleanupResponseStream(s,g),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),o.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),o.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),o.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),o.worker,d.callId,g):d.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(d,n),o.worker,d.callId,g):d.type==="resCall"&&this.handleIoCall(()=>this.execResCall(d,n),o.worker,d.callId,g)}}),o.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,i){if(!i?.aborted)try{let o=await(i?pr.run(i,e):e());if(i?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:Fn(o)})}catch{}}catch(o){if(i?.aborted)return;try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return i[e.method](...n)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new fr.PassThrough;return this.responseStreams.set(e.id,{stream:u}),a.call(t.$res,u,s),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((a,u)=>{let l=()=>{c(),a()},f=p=>{c(),u(p)},c=()=>{o.stream.off("drain",l),o.stream.off("error",f)};o.stream.once("drain",l),o.stream.once("error",f)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),t?n.stream.destroy(t):n.stream.end())}isScriptParseFailure(e){let t=e.message||"";return Oi.some(n=>t.includes(n))}async run(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);q({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let u;try{let l={code:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("execute",l,t,i)}catch(f){let c=f,p=Vt(e,"typescript")||"";if(!this.isScriptParseFailure(c)||p===e)throw f;q({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let f=l;if(q({event:"isolated_run_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(i,e);let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw je.createException(void 0,c,f.message||"Unknown error",e,f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),q({event:"isolated_run_ok"}),u.valueAbsent?void 0:u.value}async runBatch(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);q({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let u;try{let l={codeBlocks:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",l,t,i)}catch(f){let c=f,p=e.map(g=>({...g,code:Vt(g.code,"typescript")||""})),d=p.some((g,m)=>g.code!==e[m]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;q({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let f=l;if(q({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(i,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw je.createException(void 0,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),q({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var bn=require("node:fs"),Yr=require("node:path");var Rn=require("mongodb");Ve();function Be(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function G(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Be(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function re(r){if(!r||typeof r!="object")return r;if(r instanceof Rn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>re(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((i,o)=>parseInt(i)-parseInt(o)).map(i=>t[i]);return new Rn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?re(n):n;return e}function fe(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,f=e.junctionTableName||Ct(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=Rt(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,i=t,o=e.junctionTableName||Ct(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=Rt(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function Ht(r,e,t){if(!r)return{scalarFields:[],relations:[]};let n=r.tables?.get(e);if(!n)return{scalarFields:[],relations:[]};let i=new Map;for(let u of t)if(u==="*")i.has("")||i.set("",[]),i.get("").push(u);else if(u.includes(".")){let l=u.split("."),f=l[0],c=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(c)}else n.relations?.some(f=>f.propertyName===u)?i.has(u)||i.set(u,["_id"]):(i.has("")||i.set("",[]),i.get("").push(u));let o=[],s=[],a=i.get("")||[];for(let u of a)if(u==="*"){if(n.columns)for(let l of n.columns)o.includes(l.name)||o.push(l.name);if(n.relations)for(let l of n.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else n.columns?.some(f=>f.name===u)&&!o.includes(u)&&o.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=n.relations?.find(m=>m.propertyName===u);if(!f)continue;let c="",p="",d=!1;f.type==="many-to-one"||f.type==="one-to-one"?Be(f)?(c="_id",p=K(f)||f.propertyName,d=!0):(c=G(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=K(f)||f.propertyName,d=!0):f.type==="many-to-many"&&(f.mappedBy?(c="_id",p=f.mappedBy,d=!0):(c=f.propertyName,p="_id",d=!1));let g=f.type==="one-to-many"||f.type==="many-to-many";s.push({propertyName:u,targetTable:f.targetTableName,localField:c,foreignField:p,type:g?"many":"one",isInverse:d,nestedFields:l})}return{scalarFields:o,relations:s}}var Yt=ue(require("fs")),vn=ue(require("path"));var Ei=new RegExp("\\p{Mark}","gu");function Tr(r){return r==null?"":String(r).normalize("NFKD").replace(Ei,"").toLowerCase()}function xn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Tr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Gt(){return`function() {
7
7
  var M = ${xn()};
8
8
  function foldStr(s) {
9
9
  if (s == null) return '';
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.14",
3
+ "version": "1.1.17",
4
4
  "source": "bundled-compiled-kernel"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.15",
3
+ "version": "1.1.17",
4
4
  "description": "Closed-distribution Enfyra kernel runtime",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "private": false,