@enfyra/kernel 2.0.5 → 2.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/execution/worker.js +31 -31
- package/dist/index.js +1 -1
- package/dist/package-metadata.json +1 -1
- package/package.json +3 -2
package/dist/execution/worker.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var xe=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var lr=(e,t)=>()=>(e&&(t=e(e=0)),t);var
|
|
2
|
-
`);for(let n of t){let r=n.match(/(?:\(|\bat\s+)((?:handler|preHook #\d+|postHook #\d+)\.js):(\d+):(\d+)\)?\s*$/);if(!r)continue;let
|
|
3
|
-
`)}function Fe(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 _r(e,t){let n=Be(e);if(n)return{message:n.message,statusCode:n.statusCode,errorPath:n.errorPath,code:n.code??(Number.isInteger(n.statusCode)?`HTTP_${n.statusCode}`:void 0),details:n.details};let r=De(e.stack),
|
|
1
|
+
"use strict";var xe=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ir=Object.prototype.hasOwnProperty;var lr=(e,t)=>()=>(e&&(t=e(e=0)),t);var A=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),cr=(e,t)=>{for(var n in t)xe(e,n,{get:t[n],enumerable:!0})},ur=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of sr(t))!ir.call(e,c)&&c!==n&&xe(e,c,{get:()=>t[c],enumerable:!(r=or(t,c))||r.enumerable});return e};var $e=e=>ur(xe({},"__esModule",{value:!0}),e);var ie=A((Tn,ze)=>{"use strict";function dr(e){if(e instanceof Error)return e;if(e===null)return new Error("Script threw null");if(e===void 0)return new Error("Script threw undefined");let t;if(typeof e=="string")t=e;else{try{let r=JSON.stringify(e);typeof r=="string"&&(t=r)}catch{}if(t===void 0)try{t=String(e)}catch{t="Script threw a non-Error value"}}let n=new Error(t);if(e&&typeof e=="object"){for(let r of["code","statusCode","errorPath","details","executionStage"])try{e[r]!==void 0&&(n[r]=e[r])}catch{}try{typeof e.stack=="string"&&(n.stack=e.stack)}catch{}}return n}function Be(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var fr=3;function De(e){if(typeof e!="string"||!e)return null;let t=e.split(`
|
|
2
|
+
`);for(let n of t){let r=n.match(/(?:\(|\bat\s+)((?:handler|preHook #\d+|postHook #\d+)\.js):(\d+):(\d+)\)?\s*$/);if(!r)continue;let c=r[1],u=parseInt(r[2])-fr;if(!(u<=0))return{line:u,column:parseInt(r[3]),phase:c.replace(".js","")}}return null}function Le(e,t,n){if(!e||!t)return;let r=String(e).split(/\r?\n/),c=Math.max(1,t-1),i=Math.min(r.length,t+1),u=String(i).length,f=[];for(let p=c;p<=i;p++){let l=p===t?">":" ";f.push(`${l} ${String(p).padStart(u," ")}. ${r[p-1]??""}`),p===t&&n&&n>0&&f.push(` ${" ".repeat(u)} ${" ".repeat(Math.max(0,Math.min(r[p-1]?.length||0,n-1)))}^`)}return f.join(`
|
|
3
|
+
`)}function Fe(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 _r(e,t){let n=Be(e);if(n)return{message:n.message,statusCode:n.statusCode,errorPath:n.errorPath,code:n.code??(Number.isInteger(n.statusCode)?`HTTP_${n.statusCode}`:void 0),details:n.details};let r=De(e.stack),c=e.message||"Unknown error",i=r?`${c} (${r.phase}, line ${r.line})`:c,u=Fe(r,t),f=r?Le(u,r.line,r.column):void 0;return{message:i,statusCode:e.statusCode||null,code:e.code,errorPath:e.errorPath,details:{...e.details&&typeof e.details=="object"?e.details:{},errorName:e.name||null,executionStage:e.executionStage||"runtime",...r?{...r,codeFrame:f}:{}}}}function Je(e){return e?.message==="Script execution timed out."}function je(e){return e?.message==="Isolate was disposed during execution due to memory limit"}function pr(e){Je(e)&&e?.code==null&&(e.code="ERR_SCRIPT_EXECUTION_TIMEOUT"),je(e)&&e?.code==null&&(e.code="ERR_ISOLATE_MEMORY_LIMIT",e.details={outcome:"unknown_outcome",retryable:!1})}ze.exports={normalizeThrownValue:dr,extractThrowInfo:Be,parseUserCodeLocation:De,formatCodeFrame:Le,findSourceForLocation:Fe,buildErrorPayload:_r,isNativeExecutionTimeout:Je,isIsolateMemoryLimit:je,normalizeNativeExecutionError:pr}});var Se=A((En,qe)=>{"use strict";var{createHash:mr}=require("crypto"),He=new WeakMap,yr=500,ve=4*1024*1024,hr=32*1024*1024;async function gr(e,t,n){let r=He.get(e);r||(r={entries:new Map,bytes:0},He.set(e,r));let c=Buffer.byteLength(t,"utf8");if(c>ve)throw new Error(`Executor script exceeds ${ve} bytes`);let i=mr("sha256").update(JSON.stringify([n,t])).digest("hex"),u=r.entries.get(i);if(u)return r.entries.delete(i),r.entries.set(i,u),u.script;let f;try{f=await e.compileScript(t,{filename:n})}catch(l){throw l&&typeof l=="object"&&(l.executionStage="compile"),l}if(r.entries.get(i))return f;for(r.entries.set(i,{script:f,bytes:c}),r.bytes+=c;r.entries.size>0&&(r.entries.size>yr||r.bytes>hr);){let l=r.entries.keys().next().value,_=r.entries.get(l);r.entries.delete(l),r.bytes-=_?.bytes||0}return f}qe.exports={getCachedScript:gr,SCRIPT_MAX_BYTES:ve}});var Ge=A((Mn,Ve)=>{"use strict";var{open:wr}=require("fs/promises"),{fileURLToPath:br}=require("url"),j=require("typescript"),{SCRIPT_MAX_BYTES:re}=Se(),{isNativeExecutionTimeout:kr,isIsolateMemoryLimit:xr}=ie();function vr(e){let t=Symbol("packageProxyFallback");async function n(u){if(typeof u.sourceCode=="string"&&u.sourceCode.length>0){if(Buffer.byteLength(u.sourceCode,"utf8")>re)throw new Error(`Package source exceeds ${re} bytes`);return u.sourceCode}let f=u.filePath;if(!f&&typeof u.fileUrl=="string"&&u.fileUrl.startsWith("file://")&&(f=br(u.fileUrl)),!f)return null;let p;try{if(p=await wr(f,"r"),(await p.stat()).size>re)throw new Error(`Package source exceeds ${re} bytes`);let _=Buffer.allocUnsafe(re+1),g=0;for(;g<_.length;){let{bytesRead:d}=await p.read(_,g,_.length-g,g);if(d===0)break;g+=d}if(g>re)throw new Error(`Package source exceeds ${re} bytes`);return _.subarray(0,g).toString("utf8")}catch(l){if(l?.code==="ENOENT")return null;throw l}finally{try{await p?.close()}catch{}}}async function r(u,f,p,l){let _=await n(p);if(_===null||j.createSourceFile(`pkg:${p.safeName}`,_,j.ScriptTarget.Latest,!1,j.ScriptKind.JS).statements.some(m=>j.isImportDeclaration(m)||j.isExportDeclaration(m)&&m.moduleSpecifier!==void 0))return t;let d;try{d=await u.compileModule(_,{filename:`pkg:${p.safeName}`}),await d.instantiate(f,m=>{throw new Error(`Unresolved import in package ${p.safeName}: ${m}`)})}catch(m){try{d?.release()}catch{}if(u.isDisposed||kr(m)||xr(m))throw m;return t}await d.evaluate({timeout:e(l)});let h=await d.namespace.get("default");return h!==void 0?typeof h?.derefInto=="function"?h.derefInto({release:!1}):h:d.namespace.derefInto({release:!1})}function c(u){if(u==null)return[];if(!Array.isArray(u))throw new Error("Executor pkgSources must be an array");let f=new Set,p=new Set;for(let l of u){if(!l||typeof l!="object")throw new Error("Executor package entries must be objects");if(typeof l.name!="string"||l.name.length===0)throw new Error("Executor package name must be a non-empty string");if(f.has(l.name))throw new Error(`Duplicate executor package name: ${l.name}`);if(typeof l.safeName!="string"||!/^[A-Za-z_$][\w$]*$/.test(l.safeName))throw new Error(`Invalid package safeName: ${l.safeName}`);if(p.has(l.safeName))throw new Error(`Duplicate executor package safeName: ${l.safeName}`);f.add(l.name),p.add(l.safeName)}return u}function i(u,f){let p=new Set(f.map(d=>d.name)),l=new Set,_=j.createSourceFile("package-references.js",String(u||""),j.ScriptTarget.Latest,!1,j.ScriptKind.JS),g=d=>{j.isCallExpression(d)&&j.isIdentifier(d.expression)&&d.expression.text==="require"&&d.arguments.length===1&&j.isStringLiteralLike(d.arguments[0])&&p.has(d.arguments[0].text)&&l.add(d.arguments[0].text),j.forEachChild(d,g)};return g(_),l}return{PACKAGE_PROXY_FALLBACK:t,loadEsmPackageIntoContext:r,validatePackageSources:c,collectIsolatePackageNames:i}}Ve.exports={createWorkerPackages:vr}});var We=A((Cn,Ke)=>{"use strict";Ke.exports=`
|
|
4
4
|
"use strict";
|
|
5
5
|
let $ctx = {};
|
|
6
6
|
let $pkgs = {};
|
|
@@ -220,7 +220,7 @@ function __parseMainThreadResult(s) {
|
|
|
220
220
|
return __unwrapMainThreadPayload(w);
|
|
221
221
|
}
|
|
222
222
|
|
|
223
|
-
`});var Ye=
|
|
223
|
+
`});var Ye=A((Rn,Xe)=>{"use strict";Xe.exports=`// A script may call the host without awaiting the result, and a host call
|
|
224
224
|
// outlives the script that made it: a fire-and-forget call is still pending when
|
|
225
225
|
// the task finishes, and the lifecycle rejects it then. V8 reports that
|
|
226
226
|
// rejection as an unhandled rejection of the isolate, which the next script run
|
|
@@ -528,7 +528,7 @@ async function __stringifyRuntimeArgs(args) {
|
|
|
528
528
|
return JSON.stringify(encoded);
|
|
529
529
|
}
|
|
530
530
|
|
|
531
|
-
`});var Ze=
|
|
531
|
+
`});var Ze=A((An,Qe)=>{"use strict";Qe.exports=`function __utf8IncompleteSuffixLength(bytes) {
|
|
532
532
|
if (bytes.byteLength === 0) return 0;
|
|
533
533
|
let start = bytes.byteLength - 1;
|
|
534
534
|
while (start > 0 && (bytes[start] & 0xc0) === 0x80) start--;
|
|
@@ -704,7 +704,7 @@ async function __invokeRuntimeCallback(id, argsJson) {
|
|
|
704
704
|
}
|
|
705
705
|
}
|
|
706
706
|
|
|
707
|
-
`});var tt=
|
|
707
|
+
`});var tt=A((Nn,et)=>{"use strict";et.exports=`const __safeCloneFailed = Symbol('__safeCloneFailed');
|
|
708
708
|
|
|
709
709
|
async function __safeClone(v, seen, cyclic) {
|
|
710
710
|
if (!seen) {
|
|
@@ -836,7 +836,7 @@ async function __extractResult(result, isAbsent) {
|
|
|
836
836
|
|
|
837
837
|
const __throwDefaults = { 400: 'Bad request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not found', 409: 'Conflict', 422: 'Validation failed', 429: 'Too many requests', 500: 'Internal server error', 503: 'Service unavailable' };
|
|
838
838
|
|
|
839
|
-
`});var nt=
|
|
839
|
+
`});var nt=A((On,rt)=>{"use strict";rt.exports=`if (typeof TextEncoder === 'undefined') {
|
|
840
840
|
globalThis.TextEncoder = class TextEncoder {
|
|
841
841
|
get encoding() { return 'utf-8'; }
|
|
842
842
|
|
|
@@ -1040,7 +1040,7 @@ if (typeof TextDecoder === 'undefined') {
|
|
|
1040
1040
|
};
|
|
1041
1041
|
}
|
|
1042
1042
|
|
|
1043
|
-
`});var ot=
|
|
1043
|
+
`});var ot=A((In,at)=>{"use strict";at.exports=`const __blobStates = new WeakMap();
|
|
1044
1044
|
const __fallbackFiles = new WeakSet();
|
|
1045
1045
|
|
|
1046
1046
|
function __normalizeBlobType(value) {
|
|
@@ -1230,7 +1230,7 @@ if (typeof FormData === 'undefined') {
|
|
|
1230
1230
|
};
|
|
1231
1231
|
}
|
|
1232
1232
|
|
|
1233
|
-
`});var it=
|
|
1233
|
+
`});var it=A((Un,st)=>{"use strict";st.exports=`function __decodeFormComponent(value) {
|
|
1234
1234
|
const text = String(value).replace(/\\+/g, ' ');
|
|
1235
1235
|
const bytes = [];
|
|
1236
1236
|
for (let index = 0; index < text.length;) {
|
|
@@ -1448,7 +1448,7 @@ if (typeof URLSearchParams === 'undefined') {
|
|
|
1448
1448
|
};
|
|
1449
1449
|
}
|
|
1450
1450
|
|
|
1451
|
-
`});var ct=
|
|
1451
|
+
`});var ct=A(($n,lt)=>{"use strict";lt.exports=`function __parseNativeUrl(input, base, mutation) {
|
|
1452
1452
|
const result = __urlParseRef.applySync(
|
|
1453
1453
|
undefined,
|
|
1454
1454
|
[
|
|
@@ -1595,7 +1595,7 @@ if (typeof URL === 'undefined') {
|
|
|
1595
1595
|
};
|
|
1596
1596
|
}
|
|
1597
1597
|
|
|
1598
|
-
`});var dt=
|
|
1598
|
+
`});var dt=A((Bn,ut)=>{"use strict";ut.exports=`function __createPkgHandleProxy(handlePromise, path) {
|
|
1599
1599
|
// The handle promise is created eagerly by the caller, so a script that drops
|
|
1600
1600
|
// this proxy without awaiting it would leave the rejection unobserved and V8
|
|
1601
1601
|
// would report it against the isolate, failing the next task on the lane.
|
|
@@ -1736,7 +1736,7 @@ function __createAsyncPkgResultProxy(valuePromise, path) {
|
|
|
1736
1736
|
});
|
|
1737
1737
|
}
|
|
1738
1738
|
|
|
1739
|
-
`});var _t=
|
|
1739
|
+
`});var _t=A((Dn,ft)=>{"use strict";ft.exports=`const __pkgStreamNextWithTimeout = Symbol('enfyra.packageStreamNextWithTimeout');
|
|
1740
1740
|
const __trustedStreamCleanupIterators = new WeakSet();
|
|
1741
1741
|
|
|
1742
1742
|
function __createPackageStreamError(message, code, details) {
|
|
@@ -1940,7 +1940,7 @@ async function __nextStreamChunk(
|
|
|
1940
1940
|
}
|
|
1941
1941
|
}
|
|
1942
1942
|
|
|
1943
|
-
`});var mt=
|
|
1943
|
+
`});var mt=A((Ln,pt)=>{"use strict";pt.exports=`async function __preflightStream(readable, options) {
|
|
1944
1944
|
const iterator = __getStreamIterator(readable);
|
|
1945
1945
|
const { timeoutMs, idleTimeoutMs } = __normalizeStreamOptions(options);
|
|
1946
1946
|
const requestedMaxFirstChunkBytes = Number(options?.maxFirstChunkBytes);
|
|
@@ -2249,7 +2249,7 @@ function __tapStream(readable, options) {
|
|
|
2249
2249
|
};
|
|
2250
2250
|
}
|
|
2251
2251
|
|
|
2252
|
-
`});var ht=
|
|
2252
|
+
`});var ht=A((Fn,yt)=>{"use strict";yt.exports=`function __createAsyncMainResultProxy(valuePromise, path) {
|
|
2253
2253
|
// The proxy is lazy: a script that ignores a package/helper call never reads
|
|
2254
2254
|
// its then method, so nothing would observe a rejection here and V8 would
|
|
2255
2255
|
// report it as an unhandled rejection of the isolate, failing whichever task
|
|
@@ -2462,7 +2462,7 @@ const console = {
|
|
|
2462
2462
|
info: (...a) => $ctx.$logs(...a),
|
|
2463
2463
|
};
|
|
2464
2464
|
|
|
2465
|
-
`});var wt=
|
|
2465
|
+
`});var wt=A((Jn,gt)=>{"use strict";gt.exports=`function __resetTask(snapshot, taskId, timeoutMs, deadlineMs, innerGuardGraceMs = 500) {
|
|
2466
2466
|
$ctx = snapshot || {};
|
|
2467
2467
|
$pkgs = {};
|
|
2468
2468
|
__taskId = taskId;
|
|
@@ -2842,46 +2842,46 @@ function __cleanupTask() {
|
|
|
2842
2842
|
__streamTimerCounter = 0;
|
|
2843
2843
|
return true;
|
|
2844
2844
|
}
|
|
2845
|
-
`});var kt=
|
|
2846
|
-
`),we=Ur(
|
|
2845
|
+
`});var kt=A((jn,bt)=>{"use strict";var Sr=[We(),Ye(),Ze(),tt(),nt(),ot(),it(),ct(),dt(),_t(),mt(),ht(),wt()].join("");function Pr(e){return Sr.replace("%%PKG_SETUP%%",()=>e)}bt.exports={buildSetupCode:Pr}});var Pe={};cr(Pe,{INNER_GUARD_GRACE_MS:()=>Er,TASK_CANCEL_ACK_GRACE_MS:()=>Tr,TASK_TIMEOUT_TOLERANCE_RATIO:()=>Mr,getTaskCancellationTimeoutMs:()=>xt,getTaskInnerGuardGraceMs:()=>Cr});function xt(e){return Math.min(2147483647,e+Math.ceil(e*.15))}function Cr(e){return xt(e)-e+500}var Tr,Er,Mr,Te=lr(()=>{"use strict";Tr=1e4,Er=500,Mr=.15});var Me=A((zn,vt)=>{"use strict";var{randomUUID:Rr}=require("crypto"),pe=new WeakMap,Ee=new WeakMap;function Ar(e){let t=e.createInspectorSession(),n=new Map,r=new Map,c=new Map,i=0,u,f=Promise.resolve(),p=_=>new Promise((g,d)=>{if(e.isDisposed){d(new Error("Isolate is disposed"));return}let h=++i;c.set(h,{resolve:g,reject:d});try{t.dispatchProtocolMessage(JSON.stringify({id:h,method:_}))}catch(m){c.delete(h),d(m)}});t.onResponse=(_,g)=>{let d=JSON.parse(g),h=c.get(d.id);h&&(c.delete(d.id),d.error?h.reject(new Error(d.error.message)):h.resolve(d.result))},t.onNotification=_=>{let g=JSON.parse(_);if(g.method==="Debugger.scriptParsed"){let{scriptId:d,executionContextId:h,url:m}=g.params;n.set(d,h),m.startsWith("enfyra-task-context:")&&r.set(m,h)}else if(g.method==="Runtime.executionContextDestroyed"){let d=g.params.executionContextId;for(let[h,m]of n)m===d&&n.delete(h);for(let[h,m]of r)m===d&&r.delete(h)}else if(g.method==="Debugger.paused"){let d=u;d&&(d.handling=!0),(async()=>{try{let h=g.params.callFrames[0],m=n.get(h?.location?.scriptId),k=d&&r.get(d.marker);if(k!==void 0&&m===k&&d.isCancelling()){let x=p("Runtime.terminateExecution");await p("Debugger.resume").catch(()=>{}),await x}else await p("Debugger.resume")}finally{d?.complete()}})().catch(()=>d?.complete())}};let l=p("Runtime.enable").then(()=>p("Debugger.enable"));return l.catch(()=>{}),{ready:l,forget(_){let g=pe.get(_),d=r.get(g);r.delete(g);for(let[h,m]of n)m===d&&n.delete(h);pe.delete(_)},interrupt(_,g){let d=f.catch(()=>{}).then(async()=>{if(await l,e.isDisposed||!g())return;let h,m=new Promise(C=>{h=C}),k={marker:pe.get(_),isCancelling:g,complete:h,handling:!1};u=k;let x;try{await p("Debugger.pause"),await Promise.race([m,new Promise(C=>{x=setTimeout(C,250)})]),k.handling&&await m}finally{clearTimeout(x),u===k&&(u=void 0)}});return f=d,d}}}async function Nr(e,t){let n="enfyra-task-context:"+Rr();pe.set(e,n),await e.eval("void 0;",{filename:n,timeout:t})}function Or(e,t){Ee.get(e)?.forget(t)}async function Ir(e,t,n){if(e.isolate.isDisposed||!n())return;let r=Ee.get(e.isolate);r||(r=Ar(e.isolate),Ee.set(e.isolate,r)),await r.interrupt(t,n)}vt.exports={registerTaskContext:Nr,forgetTaskContext:Or,interruptTask:Ir}});var Et=A((Hn,Tt)=>{"use strict";var{URL:St}=require("url"),{buildSetupCode:Ur}=kt(),{normalizeThrownValue:Pt}=ie(),{getTaskInnerGuardGraceMs:$r}=(Te(),$e(Pe)),{registerTaskContext:Br,forgetTaskContext:Dr}=Me();function Lr({ivm:e,packageRuntimeBridge:t,contextStats:n,getCachedScript:r,getTaskRemainingTimeoutMs:c,loadEsmPackageIntoContext:i,PACKAGE_PROXY_FALLBACK:u,executeResCall:f,callMain:p,waitForStreamTimer:l,clearStreamTimer:_,cleanupTaskPackages:g,isTaskCancelled:d}){let h=new WeakMap,m=new WeakMap;function k(b){return new e.Reference((...w)=>{let S=b(...w);return S.catch(()=>{}),S})}async function x(b,w,S,T){let R=await b.createContext({inspector:!0});try{let I=R.global;await I.set("global",I.derefInto());let V=[],K=[],D=new Map;for(let M of S){D.set(M.name,M);let a=T.has(M.name)?await i(b,R,M,w):u;a!==u?(await I.set(`__pkg_${M.safeName}`,a),V.push(M)):K.push(M)}t.setTaskPackages(w,D);let L=new Set(["pkgCall","pkgStreamCall","resCall","repoCall","helpersCall","socketCall","cacheCall","transactionCall","storageCall","dispatchCall"]);await I.set("__callRef",k(async(M,a)=>{if(d(w))throw new Error("Task was cancelled");if(!L.has(M))throw new Error(`Unsupported host call type: ${M}`);let o=JSON.parse(a);if(M==="pkgCall")try{return JSON.stringify(await t.executePackageRuntimeCall(w,o))}catch(s){let y=Pt(s);throw new Error(JSON.stringify({__userThrow:!0,message:y.message,code:y.code,details:y.details}))}if(M==="pkgStreamCall")try{return JSON.stringify(await t.executePackageStreamCall(w,o))}catch(s){let y=Pt(s);return JSON.stringify({__pkgStreamError:{message:y.message,code:y.code,details:y.details}})}return M==="resCall"?f(w,o):p(w,M,o)})),await I.set("__urlParseRef",new e.Reference((M,a,o)=>{let s=a==null?new St(String(M)):new St(String(M),String(a));if(o){let y=JSON.parse(o),E=String(y.property);if(!["href","protocol","username","password","host","hostname","port","pathname","search","hash"].includes(E))throw new TypeError(`Unsupported URL property: ${E}`);s[E]=String(y.value)}return JSON.stringify({href:s.href,origin:s.origin,protocol:s.protocol,username:s.username,password:s.password,host:s.host,hostname:s.hostname,port:s.port,pathname:s.pathname,search:s.search,hash:s.hash})})),await I.set("__streamTimerRef",k(async(M,a,o)=>M==="wait"?await l(w,a,o):M==="clear"?_(w,a):!1));let fe=V.map(M=>`$pkgs[${JSON.stringify(M.name)}] = __pkg_${M.safeName};`).concat(K.map(M=>`$pkgs[${JSON.stringify(M.name)}] = __createPkgProxy(${JSON.stringify(M.name)}, []);`)).join(`
|
|
2846
|
+
`),we=Ur(fe);return await(await r(b,we,"setup.js")).run(R,{timeout:c(w)}),h.set(R,D),R}catch(I){t.cancelTask(w),g(w);try{R.release()}catch{}throw I}}async function C(b,w,S,T,R,I,V){let K=b.isolate,D=await x(K,w,S,R);n.created++;try{t.setTaskPackages(w,h.get(D)||new Map);let L=D.global;return await L.set("__snapshot",new e.ExternalCopy(T).copyInto()),await L.set("__nextTaskId",w),await L.set("__nextTaskTimeoutMs",I),await L.set("__nextTaskDeadlineMs",V),await L.set("__nextTaskInnerGuardGraceMs",$r(I)),await(await r(K,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs, __nextTaskDeadlineMs, __nextTaskInnerGuardGraceMs);","reset-task.js")).run(D,{timeout:c(w)}),await Br(D,c(w)),D}catch(L){try{D.release()}catch{}throw L}}function O(b,w){if(!w)return Promise.resolve();let S=m.get(w);if(S)return S;let T=P(b,w).finally(()=>{Dr(b.isolate,w)});return m.set(w,T),T}async function P(b,w){if(b.isolate.isDisposed){try{w.release()}catch{}return}try{await(await r(b.isolate,"__cleanupTask();","cleanup-task.js")).run(w,{timeout:5e3})}catch{n.scrubFailed++;try{w.release()}catch{}return}try{w.release()}catch{}n.released++}async function v(b,w,S,T){if(T!==void 0){let K=`__extractResult(JSON.parse(${JSON.stringify(JSON.stringify(T))}), false)`,L=await(await b.compileScript(K,{filename:"extract.js"})).run(w,{timeout:c(S),promise:!0});return JSON.parse(L)}let V=await(await r(b,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(w,{timeout:c(S),promise:!0});return JSON.parse(V)}return{prepareContext:C,releaseContext:O,extractFinalResult:v}}Tt.exports={createWorkerContext:Lr}});var Ct=A((qn,Mt)=>{"use strict";function Fr({callMain:e,activeTaskContexts:t,getTaskRemainingTimeoutMs:n,getTaskInnerGuardTimeoutMs:r=n,packageRuntimeBridge:c}){async function i(u,f){if(f?.method!=="stream")return e(u,"resCall",f);let p=JSON.parse(f.argsJson||"[]"),l=p[0],_=p[1]||{},g=l?.__pkgHandleArg;if(!g)return e(u,"resCall",f);let d=_.observer&&typeof _.observer=="object"?_.observer.__fnRef:null,h=_.transform&&typeof _.transform=="object"?_.transform.__fnRef:null,m=d||h?new TextDecoder("utf-8"):null;delete _.observer,delete _.transform;let k={..._};await e(u,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,k])});let x=async(P,v,b)=>{if(!P)return;let w=t.get(u);if(!w)throw new Error("Response callback task is no longer active");let S=await w.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(P)}, ${JSON.stringify(JSON.stringify([v,b]))});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0},timeout:n(u)}),T=JSON.parse(S);if(T?.error)throw new Error(T.error);if(T?.value?.__e!=="u")return T?.value},C=async(P,v)=>{if(d)try{await x(d,P,v)}catch{}},O=async(P,v,b)=>{let w=P;if(h){let T=await x(h,b,v);if(T===null)return;T!==void 0&&(w=Buffer.from(String(T)))}let S=Buffer.from(w);S.length!==0&&await e(u,"resCall",{method:"streamChunk",chunk:S.toString("base64")})};try{await c.streamPackageHandle(u,g,async v=>{let b="";try{b=m?m.decode(Buffer.from(v),{stream:!0}):""}catch{}await C(b,"chunk"),await O(v,"chunk",b)},[],r(u));let P="";try{P=m?m.decode():""}catch{}await C(P,"end"),await O("","end",P),await e(u,"resCall",{method:"streamEnd"})}catch(P){try{await e(u,"resCall",{method:"streamError",error:{message:P.message,stack:P.stack}})}catch{}throw await C("","error"),P}return JSON.stringify({__e:"u"})}return{executeResCall:i}}Mt.exports={createWorkerResponse:Fr}});var Ut=A((Vn,It)=>{"use strict";var{normalizeThrownValue:Rt,normalizeNativeExecutionError:Ce,isNativeExecutionTimeout:At,isIsolateMemoryLimit:Nt,buildErrorPayload:Ot}=ie();function Jr(e){if(!Array.isArray(e))throw new Error("Executor codeBlocks must be an array");let t=new Set(["preHook","handler","postHook"]),n=0;for(let p of e){if(!p||typeof p!="object")throw new Error("Executor codeBlocks entries must be objects");let l=p.type||"handler";if(!t.has(l))throw new Error(`Unsupported executor code block type: ${l}`);l==="handler"&&n++}if(n>1)throw new Error("Executor batch may contain at most one handler block");let r=[],c=[],i={},u=0,f=0;for(let p of e){let l=p.type||"handler",_=p.sourceCode||p.code||"";l==="postHook"?(f++,i[`postHook #${f}`]=_,i.postHook=_,c.push(p)):(l==="handler"?i.handler=_:(u++,i[`${l} #${u}`]=_,i.preHook=_),r.push(p))}return{preHooksAndHandler:r,postHooks:c,sourceByPhase:i}}function jr({getCachedScript:e,getTaskRemainingTimeoutMs:t,extractFinalResult:n,postResultMessage:r,reportTaskFailure:c,runnerPort:i,failIsolateSiblings:u,isLaneUnusable:f}){async function p({id:l,isolate:_,context:g,entry:d,preHooksAndHandler:h,postHooks:m,sourceByPhase:k}){let x=null,C=0;for(let v of h){let b=v.type||"handler";b!=="handler"&&C++;let w=b==="handler"?"handler":`${b} #${C}`,S;b==="preHook"?S=`
|
|
2847
2847
|
(async () => {
|
|
2848
2848
|
"use strict";
|
|
2849
|
-
${
|
|
2849
|
+
${v.code}
|
|
2850
2850
|
})().then((__r) => {
|
|
2851
2851
|
if (__r !== undefined) return JSON.stringify({ __shortCircuit: true, value: __r });
|
|
2852
2852
|
return JSON.stringify({ __shortCircuit: false });
|
|
2853
|
-
});`:
|
|
2853
|
+
});`:S=`
|
|
2854
2854
|
(async () => {
|
|
2855
2855
|
"use strict";
|
|
2856
|
-
${
|
|
2856
|
+
${v.code}
|
|
2857
2857
|
})().then((__r) => {
|
|
2858
2858
|
$ctx.$data = __r;
|
|
2859
2859
|
return "__handler_done__";
|
|
2860
|
-
});`;try{let
|
|
2861
|
-
$ctx.$error = ${JSON.stringify(
|
|
2860
|
+
});`;try{let R=await(await e(_,S,`${w}.js`)).run(g,{timeout:t(l),promise:!0});if(b==="preHook"&&typeof R=="string"){let I=JSON.parse(R);if(I.__shortCircuit){let V=await n(_,g,l,I.value);await r({...V,type:"result",id:l,success:!0,shortCircuit:!0});return}}}catch(T){x=Rt(T);break}}x&&Ce(x);let O=!!(x&&(_.isDisposed||At(x)||Nt(x)));if(!x&&m.length>0&&await(await e(_,'if ($ctx.$statusCode === undefined || $ctx.$statusCode === null) $ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(g,{timeout:t(l)}),x&&m.length>0&&!O){let v=Ot(x,k),b=Number(v.statusCode),w=Number.isInteger(b)&&b>=100&&b<=599?b:500,S={message:v.message||"Unknown error",name:x.constructor?.name||"Error",stack:x.stack||"",statusCode:w,details:v.details||{},timestamp:new Date().toISOString()},T=`
|
|
2861
|
+
$ctx.$error = ${JSON.stringify(S)};
|
|
2862
2862
|
$ctx.$data = null;
|
|
2863
|
-
$ctx.$statusCode = ${JSON.stringify(
|
|
2863
|
+
$ctx.$statusCode = ${JSON.stringify(S.statusCode)};
|
|
2864
2864
|
if ($ctx.$api) {
|
|
2865
|
-
$ctx.$api.error = ${JSON.stringify(
|
|
2865
|
+
$ctx.$api.error = ${JSON.stringify(S)};
|
|
2866
2866
|
$ctx.$api.response = {
|
|
2867
|
-
statusCode: ${
|
|
2867
|
+
statusCode: ${S.statusCode},
|
|
2868
2868
|
responseTime: $ctx.$api.request && $ctx.$api.request.timestamp
|
|
2869
2869
|
? Date.now() - new Date($ctx.$api.request.timestamp).getTime()
|
|
2870
2870
|
: 0,
|
|
2871
|
-
timestamp: ${JSON.stringify(
|
|
2871
|
+
timestamp: ${JSON.stringify(S.timestamp)},
|
|
2872
2872
|
};
|
|
2873
2873
|
}
|
|
2874
|
-
"__error_populated__";`;await(await
|
|
2874
|
+
"__error_populated__";`;await(await _.compileScript(T,{filename:"populate-error.js"})).run(g,{timeout:t(l)})}for(let v=0;v<m.length&&!O;v++){let b=m[v],w=`postHook #${v+1}`,S=`
|
|
2875
2875
|
(async () => {
|
|
2876
2876
|
"use strict";
|
|
2877
|
-
${
|
|
2877
|
+
${b.code}
|
|
2878
2878
|
})().then((__r) => {
|
|
2879
2879
|
if (__r !== undefined) $ctx.$data = __r;
|
|
2880
2880
|
return "__posthook_done__";
|
|
2881
|
-
});`;try{await(await e(p,P,`${C}.js`)).run(w,{timeout:t(l),promise:!0})}catch(S){let M=Rt(S);if(Ce(M),p.isDisposed||At(M)||Nt(M)){x=M,O=!0;break}s.postMessage({type:"executionError",id:l,sourceKind:"postHook",scriptId:f.scriptId,error:{message:M.message,stack:M.stack,code:M.code}})}}if(x){Ce(x),i(l,x,k);let g=Ot(x,k);x.details&&(g.details={...g.details,...x.details});let f;try{let S=await(await e(p,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(w,{timeout:t(l),promise:!0});f=JSON.parse(S)}catch{}await r({type:"result",id:l,success:!1,error:{message:g.message,statusCode:g.statusCode,errorPath:g.errorPath,stack:x.stack,code:g.code??x.code,details:g.details},ctxChanges:f}),_(d,x)&&c(d,l,"sibling_execution_failure");return}let v=await n(p,w,l);await r({...v,type:"result",id:l,success:!0})}return{executeWorkerBatch:m}}It.exports={prepareWorkerBatch:Jr,createWorkerBatch:jr}});var Bt=N((Gn,$t)=>{"use strict";var{fork:zr}=require("child_process"),Hr=require("path"),Re=3e4,qr=2147483647,Vr=1e3;function Gr({workerDir:e,activeTaskContexts:t,getTaskRemainingTimeoutMs:n=()=>Re}){let r=new Map,i=new Map,s=new Map,c=new Map,_=new Map,m=new WeakSet,l=null,p=0,w=!1,d=1e3;function h(o){let a=Number(o);return Number.isFinite(a)?Math.max(1,Math.min(qr,Math.trunc(a))):Re}function y(o,a,u){let b=new Error(o);return b.code=a,b.details=u,b}function k(o){try{if(o instanceof Error)return o}catch{}if(o===null)return new Error("Operation rejected with null");if(o===void 0)return new Error("Operation rejected with undefined");try{return new Error(typeof o=="string"?o:String(o))}catch{return new Error("Operation rejected with a non-Error value")}}function x(o,a){for(let[u,b]of i)b.child===o&&(clearTimeout(b.timer),i.delete(u),s.delete(u),b.reject(a))}function E(o){for(let[a,u]of c)u.child===o&&(clearTimeout(u.timer),c.delete(a))}function O(o,a){if(!o||m.has(o))return;m.add(o),l===o&&(l=null),E(o),x(o,a);try{o.disconnect()}catch{}try{o.kill("SIGTERM")}catch{}let u=setTimeout(()=>{if(!(o.exitCode!==null||o.signalCode!==null))try{o.kill("SIGKILL")}catch{}},Vr);u.unref?.(),o.once("exit",()=>clearTimeout(u))}function v(o,a){if(!o.connected)return;let u=`cancel_${++p}`,b=setTimeout(()=>{c.delete(u),O(o,y("Package runtime did not acknowledge task cancellation","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))},d);b.unref?.(),c.set(u,{child:o,timer:b});try{o.send({op:"cancelTask",taskId:a,id:u})}catch{clearTimeout(b),c.delete(u);try{o.kill()}catch{}}}function g(o,a){if(!o.connected){O(o,y("Package runtime IPC is closed","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}));return}try{o.send(a,u=>{u&&O(o,y(u.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))})}catch(u){let b=k(u);O(o,y(b.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}}function f(o,a,u=0){if(!(u>=128||!o||typeof o!="object")){if(Object.keys(o).length===1&&typeof o.__fnRef=="string"){a.add(o.__fnRef);return}if(Array.isArray(o)){for(let b of o)f(b,a,u+1);return}for(let b of Object.values(o))f(b,a,u+1)}}function C(o,a){let u;try{u=JSON.parse(a||"[]")}catch{return}let b=_.get(o);b||(b=new Set,_.set(o,b)),f(u,b)}function P(o){let a=typeof o=="string"?JSON.parse(o):o;if(a?.error)throw new Error(a.error);return a?.value}async function S(o,a){if(o!==l||m.has(o))throw new Error("Package callback runtime is no longer active");if(!_.get(a.taskId)?.has(a.callbackId))throw new Error("Package callback is not authorized for this task");let b=t.get(a.taskId);if(!b)throw new Error(`Package callback context not found: ${a.taskId}`);let R=JSON.stringify(a.callbackId),j=JSON.stringify(a.argsJson||"[]"),J=await b.evalClosure(`return __invokeRuntimeCallback(${R}, ${j});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0},timeout:n(a.taskId)});return P(J)}function M(){if(w)throw y("Package runtime is shut down","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1});if(l&&l.connected)return l;let o=Hr.join(e,"package-runtime.child.js"),a=zr(o,[],{stdio:["ignore","ignore","ignore","ipc"],env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_ENV:process.env.NODE_ENV||"production",TMPDIR:process.env.TMPDIR||"",LANG:process.env.LANG||""}});return l=a,a.on("message",u=>{if(!u||!u.id)return;if(u.type==="pkgStreamChunk"){let R=s.get(u.id);if(!R)return;Promise.resolve().then(()=>R.onChunk(Buffer.from(u.chunk||"","base64"))).then(()=>{try{a.send({type:"pkgStreamAck",ackId:u.ackId})}catch{}}).catch(j=>{let J=k(j);try{a.send({type:"pkgStreamError",ackId:u.ackId,error:{message:J.message,stack:J.stack}})}catch{}});return}if(u.type==="taskCancelled"){let R=c.get(u.id);if(!R||R.child!==a)return;clearTimeout(R.timer),c.delete(u.id);return}if(u.type==="pkgCallbackCall"){S(a,u).then(R=>{g(a,{type:"pkgCallbackResult",id:u.id,value:R})}).catch(R=>{let j=k(R);g(a,{type:"pkgCallbackError",id:u.id,error:{message:j.message,stack:j.stack}})});return}let b=i.get(u.id);if(b)if(clearTimeout(b.timer),i.delete(u.id),s.delete(u.id),u.ok)b.resolve(u.value);else{u.error?.code==="ERR_PACKAGE_RUNTIME_TIMEOUT"&&v(a,b.taskId);let R=y(u.error?.message||"Package runtime call failed",u.error?.code,u.error?.details);R.stack=u.error?.stack||R.stack,b.reject(R)}}),a.on("exit",(u,b)=>{O(a,y(`Package runtime exited${b?` with signal ${b}`:` with code ${u}`}`,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a.on("disconnect",()=>{O(a,y("Package runtime disconnected","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a.on("error",u=>{O(a,y(u.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a}function U(o){return new Promise((a,u)=>{let b=M();C(o.taskId,o.argsJson);let R=`pkg_${++p}`,j=h(o.timeoutMs),J=setTimeout(()=>{i.delete(R),s.delete(R),v(b,o.taskId),u(y(`Package runtime call timed out after ${j}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},j);i.set(R,{child:b,taskId:o.taskId,resolve:a,reject:u,timer:J});try{b.send({...o,timeoutMs:j,id:R},Z=>{Z&&(clearTimeout(J),i.delete(R),u(Z))})}catch(Z){clearTimeout(J),i.delete(R),u(Z)}})}function q(o,a,u,b=[],R=Re){return new Promise((j,J)=>{let Z=M(),W=`pkg_${++p}`,be=h(R),ke=setTimeout(()=>{i.delete(W),s.delete(W),v(Z,o),J(y(`Package runtime stream timed out after ${be}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},be);i.set(W,{child:Z,taskId:o,resolve:j,reject:J,timer:ke}),s.set(W,{onChunk:u});try{Z.send({op:"streamHandle",taskId:o,handleId:a,path:b,id:W,timeoutMs:be},pe=>{pe&&(clearTimeout(ke),i.delete(W),s.delete(W),J(pe))})}catch(pe){clearTimeout(ke),i.delete(W),s.delete(W),J(pe)}})}function D(o){try{if(!l||!l.connected)return;l.send({...o,id:`pkg_${++p}`,fire:!0})}catch{}}function L(o){try{if(!l||!l.connected)return;v(l,o)}catch{}}async function _e(o,a){let u=r.get(o);if(!u)throw new Error("Package context is not available");if(a.handleId!==null&&a.handleId!==void 0){if(a.kind!=="get"&&a.kind!=="call")throw new Error(`Unsupported package handle call kind: ${a.kind}`);return U({op:a.kind==="get"?"handleGet":"handleCall",taskId:o,handleId:a.handleId,path:a.path||[],argsJson:a.argsJson||"[]",timeoutMs:a.timeoutMs})}let b=u.get(a.packageName);if(!b)throw new Error(`Package "${a.packageName}" is not available`);if(a.kind!=="construct"&&a.kind!=="call")throw new Error(`Unsupported package call kind: ${a.kind}`);return U({op:a.kind==="construct"?"construct":"call",taskId:o,packageName:a.packageName,package:{name:b.name,fileUrl:b.fileUrl},path:a.path||[],argsJson:a.argsJson||"[]",timeoutMs:a.timeoutMs})}async function we(o,a){if(!r.get(o))throw new Error("Package context is not available");if(a.method==="open")return U({op:"streamIteratorOpen",taskId:o,handleId:a.handleId,path:a.path||[],timeoutMs:a.timeoutMs});if(a.method==="next")return U({op:"streamIteratorNext",taskId:o,streamId:a.streamId,streamTimeoutMs:a.streamTimeoutMs,timeoutMs:a.timeoutMs});if(a.method==="return")return U({op:"streamIteratorReturn",taskId:o,streamId:a.streamId,timeoutMs:a.timeoutMs});throw new Error(`Unsupported package stream method: ${a.method}`)}function Ue(o,a){r.set(o,a)}function T(o){r.delete(o),_.delete(o),D({op:"releaseTask",taskId:o})}function F(){w=!0;let o=l;o&&O(o,y("Package runtime was shut down","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}return{cleanupTaskPackages:T,cancelTask:L,executePackageRuntimeCall:_e,executePackageStreamCall:we,setTaskPackages:Ue,streamPackageHandle:q,shutdownPackageRuntime:F}}$t.exports={createPackageRuntimeBridge:Gr}});var{normalizeThrownValue:ue,buildErrorPayload:jt,isNativeExecutionTimeout:Kn,isIsolateMemoryLimit:Kr,normalizeNativeExecutionError:zt}=ie(),{getCachedScript:ye}=Se(),{createWorkerPackages:Wr}=Ge(),{createWorkerContext:Xr}=Et(),{createWorkerResponse:Yr}=Ct(),{prepareWorkerBatch:Qr,createWorkerBatch:Zr}=Ut(),{getTaskInnerGuardGraceMs:en}=(Te(),$e(Pe)),{interruptTask:tn}=Me(),{parentPort:Ht}=require("worker_threads"),A=Ht||{on(e,t){e==="message"&&process.on("message",t)},postMessage(e){process.send?.(e)}},{createPackageRuntimeBridge:rn}=Bt();process.on("unhandledRejection",e=>{let t=ue(e);try{A.postMessage({type:"workerError",source:"unhandledRejection",message:t.message,code:t.code})}catch{}});var Ae;try{Ae=require("isolated-vm")}catch(e){A.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var Y=new Map,nn=0,V=new Map,I=new Map,B=new Map,ee=new Map,X=new Map,H=new Set,ae=new Set,K=new Set,te=new Set,le=new Set,G=rn({workerDir:__dirname,activeTaskContexts:V,getTaskRemainingTimeoutMs:ne}),an=1e5,on=128,sn=5e3,ln=25,qt={created:0,reused:0,released:0,evicted:0,scrubFailed:0},{PACKAGE_PROXY_FALLBACK:cn,loadEsmPackageIntoContext:un,validatePackageSources:Vt,collectIsolatePackageNames:Gt}=Wr(ne),{executeResCall:dn}=Yr({callMain:tr,activeTaskContexts:V,getTaskRemainingTimeoutMs:ne,getTaskInnerGuardTimeoutMs:Oe,packageRuntimeBridge:G}),{prepareContext:Kt,releaseContext:Ne,extractFinalResult:fn}=Xr({ivm:Ae,packageRuntimeBridge:G,contextStats:qt,getCachedScript:ye,getTaskRemainingTimeoutMs:ne,loadEsmPackageIntoContext:un,PACKAGE_PROXY_FALLBACK:cn,executeResCall:dn,callMain:tr,waitForStreamTimer:mn,clearStreamTimer:pn,cleanupTaskPackages:Q,isTaskCancelled:e=>K.has(e)}),{executeWorkerBatch:_n}=Zr({getCachedScript:ye,getTaskRemainingTimeoutMs:ne,extractFinalResult:fn,postResultMessage:he,reportTaskFailure:ge,runnerPort:A,failIsolateSiblings:fe,isLaneUnusable:de});function ne(e){let t=B.get(e);return Math.max(1,Math.ceil((t??Date.now()+3e4)-Date.now()))}function Oe(e){let t=B.get(e)??Date.now()+3e4,n=en(ee.get(e)??3e4);return Math.min(2147483647,Math.max(1,Math.ceil(t+n-Date.now())))}function pn(e,t){let n=X.get(e),r=n?.get(t);return r?(clearTimeout(r.timer),n.delete(t),n.size===0&&X.delete(e),r.resolve(!1),!0):!1}function oe(e){let t=X.get(e);if(t){X.delete(e);for(let n of t.values())clearTimeout(n.timer),n.resolve(!1)}}function se(e,t="Task is no longer active"){for(let[n,r]of Y)r.taskId===e&&(Y.delete(n),clearTimeout(r.timer),r.reject(new Error(t)))}function Wt(e){for(le.add(e);le.size>an;)le.delete(le.values().next().value)}function mn(e,t,n){let r=X.get(e)?.get(t);r&&(clearTimeout(r.timer),X.get(e).delete(t),r.resolve(!1));let i=Math.max(1,Math.min(Math.trunc(Number(n)||1),Oe(e))),s=X.get(e);return s||(s=new Map,X.set(e,s)),new Promise(c=>{let _=setTimeout(()=>{s.delete(t),s.size===0&&X.delete(e),c(!0)},i);s.set(t,{timer:_,resolve:c})})}var $=null,ce=null,Dt=0,Lt=0,Ft=0;async function yn(){let e=Date.now();if(e-Lt<sn)return Ft;if(Lt=e,!$)return 0;let t=$.map(s=>s?.isolate).filter(s=>s&&!s.isDisposed),n,r=await Promise.race([Promise.allSettled(t.map(s=>s.getHeapStatistics())),new Promise(s=>{n=setTimeout(()=>s([]),ln)})]);clearTimeout(n);let i=0;for(let s of r){if(s.status!=="fulfilled")continue;let c=s.value.heap_size_limit||1,_=s.value.used_heap_size/c;_>i&&(i=_)}return Ft=i,i}async function he(e,t={}){let n=e?.id;if(n){if(H.has(n)||ae.has(n)||K.has(n)||!t.allowInactive&&!I.has(n))return!1;ae.add(n)}try{if(e.heapRatio=await yn(),e.runnerRssBytes=process.memoryUsage().rss,e.contextStats=hn(),n){if(!t.allowInactive&&!I.has(n))return!1;H.add(n)}return A.postMessage(e),!0}finally{n&&ae.delete(n)}}function hn(){return{...qt,idle:0}}function Xt(e,t,n){if(!$)ce={memoryLimitMb:e,poolSize:t,tasksPerIsolate:n},$=new Array(t).fill(null);else if(ce.memoryLimitMb!==e||ce.poolSize!==t||ce.tasksPerIsolate!==n)throw new Error("Executor isolate pool configuration cannot change at runtime");for(let r=0;r<$.length;r++){let i=(Dt+r)%$.length,s=$[i];if((!s||!s.isolate||s.isolate.isDisposed)&&(s={isolate:new Ae.Isolate({memoryLimit:e,inspector:!0}),taskIds:new Set},$[i]=s),s.taskIds.size<n)return Dt=(i+1)%$.length,s}throw new Error("No isolate lane is available")}function Yt(e){return`${Array.isArray($)?$.indexOf(e):-1}`}function de(e,t){return!!e?.isolate?.isDisposed||Kr(t)}function fe(e,t,n){for(let r of[...e.taskIds]){if(r===t||ae.has(r))continue;e.taskIds.delete(r),I.delete(r),V.delete(r),B.delete(r),ee.delete(r),oe(r),se(r,n),G.cancelTask(r),Q(r),H.has(r)||(ge(r,Object.assign(new Error("Isolate was disposed because a sibling task could not continue"),{code:"ERR_EXECUTOR_ISOLATE_LOST",details:{outcome:"unknown_outcome",retryable:!1,reason:n}}),{}),H.add(r),A.postMessage({type:"result",id:r,success:!1,error:{message:"Isolate was disposed because a sibling task could not continue",code:"ERR_EXECUTOR_ISOLATE_LOST",details:{outcome:"unknown_outcome",retryable:!1,reason:n}}})),A.postMessage({type:"taskReleased",id:r}),H.delete(r),te.delete(r)}try{e.isolate.dispose()}catch{}}async function gn(e){if(H.has(e)||ae.has(e)||te.has(e)||K.has(e))return;let t=I.get(e);if(!t){A.postMessage({type:"taskCancelled",id:e});return}K.add(e);try{de(t,null)&&fe(t,e,"sibling_cancelled"),G.cancelTask(e),oe(e),se(e,"Task was cancelled"),Q(e);let n=V.get(e),r=!1,i=Ne(t,n).then(()=>{r=!0}),s;for(await Promise.race([i,new Promise(c=>{s=setTimeout(c,25)})]),clearTimeout(s);!r&&n&&!t.isolate.isDisposed;)await tn(t,n,()=>K.has(e)&&!r),r||await new Promise(c=>setTimeout(c,100));await i,I.delete(e),V.delete(e),B.delete(e),ee.delete(e),t.taskIds.delete(e),A.postMessage({type:"taskCancelled",id:e}),H.delete(e)}finally{K.delete(e),te.delete(e)}}function Qt(e,t){K.has(e)||I.get(e)!==t||!t.taskIds.has(e)||(t.taskIds.delete(e),V.delete(e),I.delete(e),B.delete(e),ee.delete(e),oe(e),se(e),Q(e),A.postMessage({type:"taskReleased",id:e}),H.delete(e),te.delete(e))}function Zt(e,t){return t.taskIds.has(e)&&!K.has(e)&&I.get(e)===t&&!t.isolate.isDisposed}function er(e,t,n,r){return!t.taskIds.has(e)||I.get(e)!==t?(B.delete(e),oe(e),se(e,"Task was cancelled during preparation"),G.cancelTask(e),Q(e),Promise.resolve()):(zt(n),de(t,n)&&fe(t,e,"sibling_preparation_failure"),B.delete(e),oe(e),se(e,"Task preparation failed"),I.delete(e),t.taskIds.delete(e),G.cancelTask(e),Q(e),Ie(e,n,r,{allowInactive:!0}).then(()=>{A.postMessage({type:"taskReleased",id:e}),H.delete(e),te.delete(e)}))}function wn(e){if(!e)return;let t=I.get(e);t&&t.taskIds.delete(e),I.delete(e),V.delete(e),B.delete(e),oe(e),se(e,"Task setup failed");try{G.cancelTask(e)}catch{}try{Q(e)}catch{}try{A.postMessage({type:"taskReleased",id:e})}catch{}H.delete(e),ae.delete(e),te.delete(e)}async function bn(e,t){let n=ue(t);if(n.code==="ERR_EXECUTOR_DUPLICATE_TASK_ID"||n.code==="ERR_EXECUTOR_INVALID_TASK_ID"){A.postMessage({type:"protocolError",code:n.code,message:n.message});return}try{ge(e?.id,n,{}),await he({type:"result",id:e?.id,success:!1,error:{message:n.message,stack:n.stack,code:n.code}},{allowInactive:!0})}finally{wn(e?.id)}}function Jt(e,t){bn(e,t).catch(n=>{let r=ue(n);try{A.postMessage({type:"protocolError",code:"ERR_EXECUTOR_RECOVERY_FAILED",message:r.message})}catch{}})}A.on("message",async e=>{if(!e||typeof e!="object"){A.postMessage({type:"protocolError",code:"ERR_EXECUTOR_INVALID_MESSAGE",message:"Executor message must be an object"});return}if(e.type==="execute")xn(e).catch(t=>Jt(e,t));else if(e.type==="executeBatch")vn(e).catch(t=>Jt(e,t));else if(e.type==="invokeRuntimeCallback")kn(e).catch(t=>{let n=ue(t);try{A.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:n.message})}catch{}});else if(e.type==="callResult"){let t=Y.get(e.callId);t&&(Y.delete(e.callId),clearTimeout(t.timer),t.resolve(e.result))}else if(e.type==="callError"){let t=Y.get(e.callId);t&&(Y.delete(e.callId),clearTimeout(t.timer),t.reject(new Error(e.error)))}else e.type==="cancelTask"?gn(e.id).catch(()=>{}):e.type==="shutdown"&&Sn()});async function kn(e){let t=V.get(e.id);if(!t){A.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let n=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0},timeout:ne(e.id)}),r=JSON.parse(n);A.postMessage({...r,type:"runtimeCallbackResult",callId:e.callId})}function tr(e,t,n){return H.has(e)||K.has(e)||!I.has(e)||!B.has(e)?Promise.reject(new Error("Task is no longer active")):new Promise((r,i)=>{let s=`cb_${++nn}`,c=setTimeout(()=>{let _=Y.get(s);_&&(Y.delete(s),_.reject(new Error(`Host callback timed out: ${t}`)))},Oe(e));Y.set(s,{taskId:e,timer:c,resolve:r,reject:i}),A.postMessage({...n,type:t,id:e,callId:s})})}function ge(e,t,n){if(te.has(e)||K.has(e))return;te.add(e);let r=jt(t,n);A.postMessage({type:"taskFailure",id:e,error:{...r,stack:t.stack,code:r.code??t.code}})}async function Ie(e,t,n,r={}){t=ue(t),zt(t),ge(e,t,n);let i=jt(t,n);t.details&&(i.details={...i.details,...t.details});let s,c=V.get(e),_=I.get(e);if(c&&_&&!_.isolate.isDisposed)try{let m=await ye(_.isolate,"JSON.stringify({logs: __logs, truncated: $ctx.$share.$logsTruncated === true})","extract-diagnostic-logs.js");s=JSON.parse(await m.run(c,{timeout:100}))}catch{}await he({type:"result",id:e,success:!1,diagnosticLogs:s,error:{...i,stack:t.stack,code:i.code??t.code}},{allowInactive:r.allowInactive===!0})}function rr(e){if(!e||typeof e!="string"){let t=new Error("Executor task id must be a non-empty string");throw t.code="ERR_EXECUTOR_INVALID_TASK_ID",t}if(I.has(e)||B.has(e)||H.has(e)||le.has(e)){let t=new Error(`Executor task id cannot be reused: ${e}`);throw t.code="ERR_EXECUTOR_DUPLICATE_TASK_ID",t}}function nr(e){let t=Number(e.timeoutMs??3e4),n=Number(e.memoryLimitMb??128),r=Number(e.isolatePoolSize??8),i=Number(e.tasksPerIsolate??1);if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0||t>2147483647)throw new Error("Invalid executor timeoutMs");if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>on)throw new Error("Invalid executor memoryLimitMb");if(!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>128)throw new Error("Invalid executor isolatePoolSize");if(!Number.isFinite(i)||!Number.isInteger(i)||i<1||i>64)throw new Error("Invalid executor tasksPerIsolate");return{timeoutMs:Math.trunc(t),memoryLimitMb:Math.trunc(n),isolatePoolSize:Math.trunc(r),tasksPerIsolate:Math.trunc(i)}}async function xn(e){let{id:t,code:n,pkgSources:r,snapshot:i}=e;rr(t),Wt(t);let{timeoutMs:s,memoryLimitMb:c,isolatePoolSize:_,tasksPerIsolate:m}=nr(e),l={handler:e.sourceCode||n||""},p=Vt(r),w=Date.now()+s;B.set(t,w),ee.set(t,s);let d=Gt(n,p),h=Xt(c,_,m);h.taskIds.add(t),I.set(t,h);let y=h.isolate,k;try{k=await Kt(h,t,p,i,d,s,w)}catch(E){await er(t,h,E,l);return}if(!Zt(t,h)){try{k.release()}catch{}G.cancelTask(t),Q(t);return}V.set(t,k);let x=ee.get(t);x!==void 0&&B.set(t,Date.now()+x),A.postMessage({type:"taskLane",id:t,laneKey:Yt(h)});try{let E=`
|
|
2881
|
+
});`;try{await(await e(_,S,`${w}.js`)).run(g,{timeout:t(l),promise:!0})}catch(T){let R=Rt(T);if(Ce(R),_.isDisposed||At(R)||Nt(R)){x=R,O=!0;break}i.postMessage({type:"executionError",id:l,sourceKind:"postHook",scriptId:b.scriptId,error:{message:R.message,stack:R.stack,code:R.code}})}}if(x){Ce(x),c(l,x,k);let v=Ot(x,k);x.details&&(v.details={...v.details,...x.details});let b;try{let T=await(await e(_,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(g,{timeout:t(l),promise:!0});b=JSON.parse(T)}catch{}await r({type:"result",id:l,success:!1,error:{message:v.message,statusCode:v.statusCode,errorPath:v.errorPath,stack:x.stack,code:v.code??x.code,details:v.details},ctxChanges:b}),f(d,x)&&u(d,l,"sibling_execution_failure");return}let P=await n(_,g,l);await r({...P,type:"result",id:l,success:!0})}return{executeWorkerBatch:p}}It.exports={prepareWorkerBatch:Jr,createWorkerBatch:jr}});var Bt=A((Gn,$t)=>{"use strict";var{fork:zr}=require("child_process"),Hr=require("path"),Re=3e4,qr=2147483647,Vr=1e3;function Gr({workerDir:e,activeTaskContexts:t,getTaskRemainingTimeoutMs:n=()=>Re}){let r=new Map,c=new Map,i=new Map,u=new Map,f=new Map,p=new WeakSet,l=null,_=0,g=!1,d=1e3;function h(a){let o=Number(a);return Number.isFinite(o)?Math.max(1,Math.min(qr,Math.trunc(o))):Re}function m(a,o,s){let y=new Error(a);return y.code=o,y.details=s,y}function k(a){try{if(a instanceof Error)return a}catch{}if(a===null)return new Error("Operation rejected with null");if(a===void 0)return new Error("Operation rejected with undefined");try{return new Error(typeof a=="string"?a:String(a))}catch{return new Error("Operation rejected with a non-Error value")}}function x(a,o){for(let[s,y]of c)y.child===a&&(clearTimeout(y.timer),c.delete(s),i.delete(s),y.reject(o))}function C(a){for(let[o,s]of u)s.child===a&&(clearTimeout(s.timer),u.delete(o))}function O(a,o){if(!a||p.has(a))return;p.add(a),l===a&&(l=null),C(a),x(a,o);try{a.disconnect()}catch{}try{a.kill("SIGTERM")}catch{}let s=setTimeout(()=>{if(!(a.exitCode!==null||a.signalCode!==null))try{a.kill("SIGKILL")}catch{}},Vr);s.unref?.(),a.once("exit",()=>clearTimeout(s))}function P(a,o){if(!a.connected)return;let s=`cancel_${++_}`,y=setTimeout(()=>{u.delete(s),O(a,m("Package runtime did not acknowledge task cancellation","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))},d);y.unref?.(),u.set(s,{child:a,timer:y});try{a.send({op:"cancelTask",taskId:o,id:s})}catch{clearTimeout(y),u.delete(s);try{a.kill()}catch{}}}function v(a,o){if(!a.connected){O(a,m("Package runtime IPC is closed","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}));return}try{a.send(o,s=>{s&&O(a,m(s.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))})}catch(s){let y=k(s);O(a,m(y.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}}function b(a,o,s=0){if(!(s>=128||!a||typeof a!="object")){if(Object.keys(a).length===1&&typeof a.__fnRef=="string"){o.add(a.__fnRef);return}if(Array.isArray(a)){for(let y of a)b(y,o,s+1);return}for(let y of Object.values(a))b(y,o,s+1)}}function w(a,o){let s;try{s=JSON.parse(o||"[]")}catch{return}let y=f.get(a);y||(y=new Set,f.set(a,y)),b(s,y)}function S(a){let o=typeof a=="string"?JSON.parse(a):a;if(o?.error)throw new Error(o.error);return o?.value}async function T(a,o){if(a!==l||p.has(a))throw new Error("Package callback runtime is no longer active");if(!f.get(o.taskId)?.has(o.callbackId))throw new Error("Package callback is not authorized for this task");let y=t.get(o.taskId);if(!y)throw new Error(`Package callback context not found: ${o.taskId}`);let E=JSON.stringify(o.callbackId),J=JSON.stringify(o.argsJson||"[]"),F=await y.evalClosure(`return __invokeRuntimeCallback(${E}, ${J});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0},timeout:n(o.taskId)});return S(F)}function R(){if(g)throw m("Package runtime is shut down","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1});if(l&&l.connected)return l;let a=Hr.join(e,"package-runtime.child.js"),o=zr(a,[],{stdio:["ignore","ignore","ignore","ipc"],env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_ENV:process.env.NODE_ENV||"production",TMPDIR:process.env.TMPDIR||"",LANG:process.env.LANG||""}});return l=o,o.on("message",s=>{if(!s||!s.id)return;if(s.type==="pkgStreamChunk"){let E=i.get(s.id);if(!E)return;Promise.resolve().then(()=>E.onChunk(Buffer.from(s.chunk||"","base64"))).then(()=>{try{o.send({type:"pkgStreamAck",ackId:s.ackId})}catch{}}).catch(J=>{let F=k(J);try{o.send({type:"pkgStreamError",ackId:s.ackId,error:{message:F.message,stack:F.stack}})}catch{}});return}if(s.type==="taskCancelled"){let E=u.get(s.id);if(!E||E.child!==o)return;clearTimeout(E.timer),u.delete(s.id);return}if(s.type==="pkgCallbackCall"){T(o,s).then(E=>{v(o,{type:"pkgCallbackResult",id:s.id,value:E})}).catch(E=>{let J=k(E);v(o,{type:"pkgCallbackError",id:s.id,error:{message:J.message,stack:J.stack}})});return}let y=c.get(s.id);if(y)if(clearTimeout(y.timer),c.delete(s.id),i.delete(s.id),s.ok)y.resolve(s.value);else{s.error?.code==="ERR_PACKAGE_RUNTIME_TIMEOUT"&&P(o,y.taskId);let E=m(s.error?.message||"Package runtime call failed",s.error?.code,s.error?.details);E.stack=s.error?.stack||E.stack,y.reject(E)}}),o.on("exit",(s,y)=>{O(o,m(`Package runtime exited${y?` with signal ${y}`:` with code ${s}`}`,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),o.on("disconnect",()=>{O(o,m("Package runtime disconnected","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),o.on("error",s=>{O(o,m(s.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),o}function I(a){return new Promise((o,s)=>{let y=R();w(a.taskId,a.argsJson);let E=`pkg_${++_}`,J=h(a.timeoutMs),F=setTimeout(()=>{c.delete(E),i.delete(E),P(y,a.taskId),s(m(`Package runtime call timed out after ${J}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},J);c.set(E,{child:y,taskId:a.taskId,resolve:o,reject:s,timer:F});try{y.send({...a,timeoutMs:J,id:E},Z=>{Z&&(clearTimeout(F),c.delete(E),s(Z))})}catch(Z){clearTimeout(F),c.delete(E),s(Z)}})}function V(a,o,s,y=[],E=Re){return new Promise((J,F)=>{let Z=R(),W=`pkg_${++_}`,be=h(E),ke=setTimeout(()=>{c.delete(W),i.delete(W),P(Z,a),F(m(`Package runtime stream timed out after ${be}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},be);c.set(W,{child:Z,taskId:a,resolve:J,reject:F,timer:ke}),i.set(W,{onChunk:s});try{Z.send({op:"streamHandle",taskId:a,handleId:o,path:y,id:W,timeoutMs:be},_e=>{_e&&(clearTimeout(ke),c.delete(W),i.delete(W),F(_e))})}catch(_e){clearTimeout(ke),c.delete(W),i.delete(W),F(_e)}})}function K(a){try{if(!l||!l.connected)return;l.send({...a,id:`pkg_${++_}`,fire:!0})}catch{}}function D(a){try{if(!l||!l.connected)return;P(l,a)}catch{}}async function L(a,o){let s=r.get(a);if(!s)throw new Error("Package context is not available");if(o.handleId!==null&&o.handleId!==void 0){if(o.kind!=="get"&&o.kind!=="call")throw new Error(`Unsupported package handle call kind: ${o.kind}`);return I({op:o.kind==="get"?"handleGet":"handleCall",taskId:a,handleId:o.handleId,path:o.path||[],argsJson:o.argsJson||"[]",timeoutMs:o.timeoutMs})}let y=s.get(o.packageName);if(!y)throw new Error(`Package "${o.packageName}" is not available`);if(o.kind!=="construct"&&o.kind!=="call")throw new Error(`Unsupported package call kind: ${o.kind}`);return I({op:o.kind==="construct"?"construct":"call",taskId:a,packageName:o.packageName,package:{name:y.name,fileUrl:y.fileUrl},path:o.path||[],argsJson:o.argsJson||"[]",timeoutMs:o.timeoutMs})}async function fe(a,o){if(!r.get(a))throw new Error("Package context is not available");if(o.method==="open")return I({op:"streamIteratorOpen",taskId:a,handleId:o.handleId,path:o.path||[],timeoutMs:o.timeoutMs});if(o.method==="next")return I({op:"streamIteratorNext",taskId:a,streamId:o.streamId,streamTimeoutMs:o.streamTimeoutMs,timeoutMs:o.timeoutMs});if(o.method==="return")return I({op:"streamIteratorReturn",taskId:a,streamId:o.streamId,timeoutMs:o.timeoutMs});throw new Error(`Unsupported package stream method: ${o.method}`)}function we(a,o){r.set(a,o)}function Ue(a){r.delete(a),f.delete(a),K({op:"releaseTask",taskId:a})}function M(){g=!0;let a=l;a&&O(a,m("Package runtime was shut down","ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}return{cleanupTaskPackages:Ue,cancelTask:D,executePackageRuntimeCall:L,executePackageStreamCall:fe,setTaskPackages:we,streamPackageHandle:V,shutdownPackageRuntime:M}}$t.exports={createPackageRuntimeBridge:Gr}});var{normalizeThrownValue:me,buildErrorPayload:jt,isNativeExecutionTimeout:Kn,isIsolateMemoryLimit:Kr,normalizeNativeExecutionError:zt}=ie(),{getCachedScript:ye}=Se(),{createWorkerPackages:Wr}=Ge(),{createWorkerContext:Xr}=Et(),{createWorkerResponse:Yr}=Ct(),{prepareWorkerBatch:Qr,createWorkerBatch:Zr}=Ut(),{getTaskInnerGuardGraceMs:en}=(Te(),$e(Pe)),{interruptTask:tn}=Me(),{parentPort:Ht}=require("worker_threads"),N=Ht||{on(e,t){e==="message"&&process.on("message",t)},postMessage(e){process.send?.(e)}},{createPackageRuntimeBridge:rn}=Bt(),Ae;try{Ae=require("isolated-vm")}catch(e){N.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var Y=new Map,nn=0,H=new Map,U=new Map,B=new Map,ee=new Map,X=new Map,z=new Set,ae=new Set,G=new Set,te=new Set,le=new Set,q=rn({workerDir:__dirname,activeTaskContexts:H,getTaskRemainingTimeoutMs:ne}),an=1e5,on=128,sn=5e3,ln=25,qt={created:0,reused:0,released:0,evicted:0,scrubFailed:0},{PACKAGE_PROXY_FALLBACK:cn,loadEsmPackageIntoContext:un,validatePackageSources:Vt,collectIsolatePackageNames:Gt}=Wr(ne),{executeResCall:dn}=Yr({callMain:tr,activeTaskContexts:H,getTaskRemainingTimeoutMs:ne,getTaskInnerGuardTimeoutMs:Oe,packageRuntimeBridge:q}),{prepareContext:Kt,releaseContext:Ne,extractFinalResult:fn}=Xr({ivm:Ae,packageRuntimeBridge:q,contextStats:qt,getCachedScript:ye,getTaskRemainingTimeoutMs:ne,loadEsmPackageIntoContext:un,PACKAGE_PROXY_FALLBACK:cn,executeResCall:dn,callMain:tr,waitForStreamTimer:mn,clearStreamTimer:pn,cleanupTaskPackages:Q,isTaskCancelled:e=>G.has(e)}),{executeWorkerBatch:_n}=Zr({getCachedScript:ye,getTaskRemainingTimeoutMs:ne,extractFinalResult:fn,postResultMessage:he,reportTaskFailure:ge,runnerPort:N,failIsolateSiblings:de,isLaneUnusable:ue});function ne(e){let t=B.get(e);return Math.max(1,Math.ceil((t??Date.now()+3e4)-Date.now()))}function Oe(e){let t=B.get(e)??Date.now()+3e4,n=en(ee.get(e)??3e4);return Math.min(2147483647,Math.max(1,Math.ceil(t+n-Date.now())))}function pn(e,t){let n=X.get(e),r=n?.get(t);return r?(clearTimeout(r.timer),n.delete(t),n.size===0&&X.delete(e),r.resolve(!1),!0):!1}function oe(e){let t=X.get(e);if(t){X.delete(e);for(let n of t.values())clearTimeout(n.timer),n.resolve(!1)}}function se(e,t="Task is no longer active"){for(let[n,r]of Y)r.taskId===e&&(Y.delete(n),clearTimeout(r.timer),r.reject(new Error(t)))}function Wt(e){for(le.add(e);le.size>an;)le.delete(le.values().next().value)}function mn(e,t,n){let r=X.get(e)?.get(t);r&&(clearTimeout(r.timer),X.get(e).delete(t),r.resolve(!1));let c=Math.max(1,Math.min(Math.trunc(Number(n)||1),Oe(e))),i=X.get(e);return i||(i=new Map,X.set(e,i)),new Promise(u=>{let f=setTimeout(()=>{i.delete(t),i.size===0&&X.delete(e),u(!0)},c);i.set(t,{timer:f,resolve:u})})}var $=null,ce=null,Dt=0,Lt=0,Ft=0;async function yn(){let e=Date.now();if(e-Lt<sn)return Ft;if(Lt=e,!$)return 0;let t=$.map(i=>i?.isolate).filter(i=>i&&!i.isDisposed),n,r=await Promise.race([Promise.allSettled(t.map(i=>i.getHeapStatistics())),new Promise(i=>{n=setTimeout(()=>i([]),ln)})]);clearTimeout(n);let c=0;for(let i of r){if(i.status!=="fulfilled")continue;let u=i.value.heap_size_limit||1,f=i.value.used_heap_size/u;f>c&&(c=f)}return Ft=c,c}async function he(e,t={}){let n=e?.id;if(n){if(z.has(n)||ae.has(n)||G.has(n)||!t.allowInactive&&!U.has(n))return!1;ae.add(n)}try{if(e.heapRatio=await yn(),e.runnerRssBytes=process.memoryUsage().rss,e.contextStats=hn(),n){if(!t.allowInactive&&!U.has(n))return!1;z.add(n)}return N.postMessage(e),!0}finally{n&&ae.delete(n)}}function hn(){return{...qt,idle:0}}function Xt(e,t,n){if(!$)ce={memoryLimitMb:e,poolSize:t,tasksPerIsolate:n},$=new Array(t).fill(null);else if(ce.memoryLimitMb!==e||ce.poolSize!==t||ce.tasksPerIsolate!==n)throw new Error("Executor isolate pool configuration cannot change at runtime");for(let r=0;r<$.length;r++){let c=(Dt+r)%$.length,i=$[c];if((!i||!i.isolate||i.isolate.isDisposed)&&(i={isolate:new Ae.Isolate({memoryLimit:e,inspector:!0}),taskIds:new Set},$[c]=i),i.taskIds.size<n)return Dt=(c+1)%$.length,i}throw new Error("No isolate lane is available")}function Yt(e){return`${Array.isArray($)?$.indexOf(e):-1}`}function ue(e,t){return!!e?.isolate?.isDisposed||Kr(t)}function de(e,t,n){for(let r of[...e.taskIds]){if(r===t||ae.has(r))continue;e.taskIds.delete(r),U.delete(r),H.delete(r),B.delete(r),ee.delete(r),oe(r),se(r,n),q.cancelTask(r),Q(r),z.has(r)||(ge(r,Object.assign(new Error("Isolate was disposed because a sibling task could not continue"),{code:"ERR_EXECUTOR_ISOLATE_LOST",details:{outcome:"unknown_outcome",retryable:!1,reason:n}}),{}),z.add(r),N.postMessage({type:"result",id:r,success:!1,error:{message:"Isolate was disposed because a sibling task could not continue",code:"ERR_EXECUTOR_ISOLATE_LOST",details:{outcome:"unknown_outcome",retryable:!1,reason:n}}})),N.postMessage({type:"taskReleased",id:r}),z.delete(r),te.delete(r)}try{e.isolate.dispose()}catch{}}async function gn(e){if(z.has(e)||ae.has(e)||te.has(e)||G.has(e))return;let t=U.get(e);if(!t){N.postMessage({type:"taskCancelled",id:e});return}G.add(e);try{ue(t,null)&&de(t,e,"sibling_cancelled"),q.cancelTask(e),oe(e),se(e,"Task was cancelled"),Q(e);let n=H.get(e),r=!1,c=Ne(t,n).then(()=>{r=!0}),i;for(await Promise.race([c,new Promise(u=>{i=setTimeout(u,25)})]),clearTimeout(i);!r&&n&&!t.isolate.isDisposed;){try{await tn(t,n,()=>G.has(e)&&!r)}catch{break}r||await new Promise(u=>setTimeout(u,100))}await c,U.delete(e),H.delete(e),B.delete(e),ee.delete(e),t.taskIds.delete(e),N.postMessage({type:"taskCancelled",id:e}),z.delete(e)}finally{G.delete(e),te.delete(e)}}function Qt(e,t){G.has(e)||U.get(e)!==t||!t.taskIds.has(e)||(t.taskIds.delete(e),H.delete(e),U.delete(e),B.delete(e),ee.delete(e),oe(e),se(e),Q(e),N.postMessage({type:"taskReleased",id:e}),z.delete(e),te.delete(e))}function Zt(e,t){return t.taskIds.has(e)&&!G.has(e)&&U.get(e)===t&&!t.isolate.isDisposed}function er(e,t,n,r){return!t.taskIds.has(e)||U.get(e)!==t?(B.delete(e),oe(e),se(e,"Task was cancelled during preparation"),q.cancelTask(e),Q(e),Promise.resolve()):(zt(n),ue(t,n)&&de(t,e,"sibling_preparation_failure"),B.delete(e),oe(e),se(e,"Task preparation failed"),U.delete(e),t.taskIds.delete(e),q.cancelTask(e),Q(e),Ie(e,n,r,{allowInactive:!0}).then(()=>{N.postMessage({type:"taskReleased",id:e}),z.delete(e),te.delete(e)}))}function wn(e){if(!e)return;let t=U.get(e);t&&t.taskIds.delete(e),U.delete(e),H.delete(e),B.delete(e),oe(e),se(e,"Task setup failed");try{q.cancelTask(e)}catch{}try{Q(e)}catch{}try{N.postMessage({type:"taskReleased",id:e})}catch{}z.delete(e),ae.delete(e),te.delete(e)}async function bn(e,t){let n=me(t);if(n.code==="ERR_EXECUTOR_DUPLICATE_TASK_ID"||n.code==="ERR_EXECUTOR_INVALID_TASK_ID"){N.postMessage({type:"protocolError",code:n.code,message:n.message});return}try{ge(e?.id,n,{}),await he({type:"result",id:e?.id,success:!1,error:{message:n.message,stack:n.stack,code:n.code}},{allowInactive:!0})}finally{wn(e?.id)}}function Jt(e,t){bn(e,t).catch(n=>{let r=me(n);try{N.postMessage({type:"protocolError",code:"ERR_EXECUTOR_RECOVERY_FAILED",message:r.message})}catch{}})}N.on("message",async e=>{if(!e||typeof e!="object"){N.postMessage({type:"protocolError",code:"ERR_EXECUTOR_INVALID_MESSAGE",message:"Executor message must be an object"});return}if(e.type==="execute")xn(e).catch(t=>Jt(e,t));else if(e.type==="executeBatch")vn(e).catch(t=>Jt(e,t));else if(e.type==="invokeRuntimeCallback")kn(e).catch(t=>{let n=me(t);try{N.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:n.message})}catch{}});else if(e.type==="callResult"){let t=Y.get(e.callId);t&&(Y.delete(e.callId),clearTimeout(t.timer),t.resolve(e.result))}else if(e.type==="callError"){let t=Y.get(e.callId);t&&(Y.delete(e.callId),clearTimeout(t.timer),t.reject(new Error(e.error)))}else e.type==="cancelTask"?gn(e.id).catch(()=>{}):e.type==="shutdown"&&Sn()});async function kn(e){let t=H.get(e.id);if(!t){N.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let n=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0},timeout:ne(e.id)}),r=JSON.parse(n);N.postMessage({...r,type:"runtimeCallbackResult",callId:e.callId})}function tr(e,t,n){return z.has(e)||G.has(e)||!U.has(e)||!B.has(e)?Promise.reject(new Error("Task is no longer active")):new Promise((r,c)=>{let i=`cb_${++nn}`,u=setTimeout(()=>{let f=Y.get(i);f&&(Y.delete(i),f.reject(new Error(`Host callback timed out: ${t}`)))},Oe(e));Y.set(i,{taskId:e,timer:u,resolve:r,reject:c}),N.postMessage({...n,type:t,id:e,callId:i})})}function ge(e,t,n){if(te.has(e)||G.has(e))return;te.add(e);let r=jt(t,n);N.postMessage({type:"taskFailure",id:e,error:{...r,stack:t.stack,code:r.code??t.code}})}async function Ie(e,t,n,r={}){t=me(t),zt(t),ge(e,t,n);let c=jt(t,n);t.details&&(c.details={...c.details,...t.details});let i,u=H.get(e),f=U.get(e);if(u&&f&&!f.isolate.isDisposed)try{let p=await ye(f.isolate,"JSON.stringify({logs: __logs, truncated: $ctx.$share.$logsTruncated === true})","extract-diagnostic-logs.js");i=JSON.parse(await p.run(u,{timeout:100}))}catch{}await he({type:"result",id:e,success:!1,diagnosticLogs:i,error:{...c,stack:t.stack,code:c.code??t.code}},{allowInactive:r.allowInactive===!0})}function rr(e){if(!e||typeof e!="string"){let t=new Error("Executor task id must be a non-empty string");throw t.code="ERR_EXECUTOR_INVALID_TASK_ID",t}if(U.has(e)||B.has(e)||z.has(e)||le.has(e)){let t=new Error(`Executor task id cannot be reused: ${e}`);throw t.code="ERR_EXECUTOR_DUPLICATE_TASK_ID",t}}function nr(e){let t=Number(e.timeoutMs??3e4),n=Number(e.memoryLimitMb??128),r=Number(e.isolatePoolSize??8),c=Number(e.tasksPerIsolate??1);if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0||t>2147483647)throw new Error("Invalid executor timeoutMs");if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>on)throw new Error("Invalid executor memoryLimitMb");if(!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>128)throw new Error("Invalid executor isolatePoolSize");if(!Number.isFinite(c)||!Number.isInteger(c)||c<1||c>64)throw new Error("Invalid executor tasksPerIsolate");return{timeoutMs:Math.trunc(t),memoryLimitMb:Math.trunc(n),isolatePoolSize:Math.trunc(r),tasksPerIsolate:Math.trunc(c)}}async function xn(e){let{id:t,code:n,pkgSources:r,snapshot:c}=e;rr(t),Wt(t);let{timeoutMs:i,memoryLimitMb:u,isolatePoolSize:f,tasksPerIsolate:p}=nr(e),l={handler:e.sourceCode||n||""},_=Vt(r),g=Date.now()+i;B.set(t,g),ee.set(t,i);let d=Gt(n,_),h=Xt(u,f,p);h.taskIds.add(t),U.set(t,h);let m=h.isolate,k;try{k=await Kt(h,t,_,c,d,i,g)}catch(C){await er(t,h,C,l);return}if(!Zt(t,h)){try{k.release()}catch{}q.cancelTask(t),Q(t);return}H.set(t,k);let x=ee.get(t);x!==void 0&&B.set(t,Date.now()+x),N.postMessage({type:"taskLane",id:t,laneKey:Yt(h)});try{let C=`
|
|
2882
2882
|
(async () => {
|
|
2883
2883
|
"use strict";
|
|
2884
2884
|
${n}
|
|
2885
2885
|
})().then((__result) => __extractResult(__result, __result === undefined));
|
|
2886
|
-
`,
|
|
2887
|
-
`),d),k=Xt(l,
|
|
2886
|
+
`,P=await(await ye(m,C,"handler.js")).run(k,{timeout:ne(t),promise:!0}),v=JSON.parse(P);await he({...v,type:"result",id:t,success:!0})}catch(C){h.taskIds.has(t)&&(await Ie(t,C,l),ue(h,C)&&de(h,t,"sibling_execution_failure"))}finally{try{await Ne(h,k)}finally{Qt(t,h)}}}async function vn(e){let{id:t,codeBlocks:n,pkgSources:r,snapshot:c}=e;rr(t),Wt(t);let{preHooksAndHandler:i,postHooks:u,sourceByPhase:f}=Qr(n),{timeoutMs:p,memoryLimitMb:l,isolatePoolSize:_,tasksPerIsolate:g}=nr(e),d=Vt(r),h=Date.now()+p;B.set(t,h),ee.set(t,p);let m=Gt((n||[]).map(P=>P.code||"").join(`
|
|
2887
|
+
`),d),k=Xt(l,_,g);k.taskIds.add(t),U.set(t,k);let x=k.isolate,C;try{C=await Kt(k,t,d,c,m,p,h)}catch(P){await er(t,k,P,f);return}if(!Zt(t,k)){try{C.release()}catch{}q.cancelTask(t),Q(t);return}H.set(t,C);let O=ee.get(t);O!==void 0&&B.set(t,Date.now()+O),N.postMessage({type:"taskLane",id:t,laneKey:Yt(k)});try{await _n({id:t,isolate:x,context:C,entry:k,preHooksAndHandler:i,postHooks:u,sourceByPhase:f})}catch(P){k.taskIds.has(t)&&(await Ie(t,P,f),ue(k,P)&&de(k,t,"sibling_execution_failure"))}finally{try{await Ne(k,C)}finally{Qt(t,k)}}}function Q(e){q.cleanupTaskPackages(e)}function ar(){q.shutdownPackageRuntime()}function Sn(){if(ar(),$){for(let e of $)if(!(!e?.isolate||e.isolate.isDisposed))try{e.isolate.dispose()}catch{}$=null,ce=null}try{N.postMessage({type:"shutdownComplete"})}catch{}Ht?.close()}process.on("exit",ar);
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";var _s=Object.create;var Nr=Object.defineProperty;var Ss=Object.getOwnPropertyDescriptor;var $s=Object.getOwnPropertyNames;var Ts=Object.getPrototypeOf,ks=Object.prototype.hasOwnProperty;var Q=(n,e)=>()=>(n&&(e=n(n=0)),e);var Un=(n,e)=>{for(var t in e)Nr(n,t,{get:e[t],enumerable:!0})},No=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $s(e))!ks.call(n,o)&&o!==t&&Nr(n,o,{get:()=>e[o],enumerable:!(r=Ss(e,o))||r.enumerable});return n};var Je=(n,e,t)=>(t=n!=null?_s(Ts(n)):{},No(e||!n||!n.__esModule?Nr(t,"default",{value:n,enumerable:!0}):t,n)),Es=n=>No(Nr({},"__esModule",{value:!0}),n);function ca(n){return!!(typeof n._bsontype=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof RegExp)}function Xe(n,e=new WeakMap){if(!n||typeof n!="object")return n;let t=e.get(n);if(t)return t;if(Array.isArray(n)){let i=[];e.set(n,i);for(let s of n)i.push(Xe(s,e));return i}if(n instanceof Map){let i=new Map;e.set(n,i);for(let[s,a]of n)i.set(Xe(s,e),Xe(a,e));return i}if(n instanceof Set){let i=new Set;e.set(n,i);for(let s of n)i.add(Xe(s,e));return i}if(n instanceof Date)return new Date(n.getTime());if(ca(n))return n;let r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null)throw new TypeError("Join metadata must contain plain cloneable values");let o=Object.create(r);e.set(n,o);for(let[i,s]of Object.entries(n))Object.defineProperty(o,i,{value:Xe(s,e),enumerable:!0,configurable:!0,writable:!0});return o}function to(n){return{...n,relationMeta:Xe(n.relationMeta),purposes:[...n.purposes]}}var Te,sr=Q(()=>{"use strict";Te=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){let t=this.map.get(e);return t?to(t):void 0}getAll(){return Array.from(this.map.values(),to)}createCheckpoint(){return this.getAll()}restoreCheckpoint(e){let t=new Map;for(let r of e){let o=to(r);if(t.has(o.id))throw new Error(`Duplicate join registry checkpoint ID "${o.id}"`);t.set(o.id,o)}for(let r of t.values()){if(r.parentJoinId===null){if(r.id!==r.propertyName)throw new Error(`Invalid root join ID "${r.id}"`);continue}let o=t.get(r.parentJoinId);if(!o||o.targetTable!==r.parentTable||r.id!==`${r.parentJoinId}.${r.propertyName}`)throw new Error(`Invalid parent join for "${r.id}"`)}this.map.clear();for(let[r,o]of t)this.map.set(r,o)}registerWithParent(e,t,r,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t,c=r?.tables?.get(e);if(!c)return null;let u=c.relations?.find(d=>d.propertyName===t);if(!u)return null;let l=u.targetTableName||u.targetTable;if(!l)return null;if(i!==null){let d=this.map.get(i);if(!d||d.targetTable!==e)throw new Error(`Invalid parent join for "${a}"`)}if(this.map.has(a)){let d=this.map.get(a);if(d.parentTable!==e||d.propertyName!==t||d.targetTable!==l||d.relationType!==u.type||d.parentJoinId!==i)throw new Error(`Join registry collision for "${a}"`);return o==="inner"&&(d.joinType="inner"),d.purposes.includes(s)||d.purposes.push(s),a}let f={id:a,propertyName:t,parentTable:e,targetTable:l,relationType:u.type,parentJoinId:i,joinType:o,relationMeta:Xe(u),purposes:[s]};return this.map.set(a,f),a}}});function ti(n){let e=new Set(n),t={get size(){return e.size},has(r){return e.has(r)},forEach(r,o){for(let i of e)r.call(o,i,i,t)},entries(){return e.entries()},keys(){return e.keys()},values(){return e.values()},[Symbol.iterator](){return e[Symbol.iterator]()}};return Object.freeze(t)}function Qr(n){return Object.prototype.hasOwnProperty.call(ei,n)?ei[n]:null}var de,ro,ar,ei,wt=Q(()=>{"use strict";de=ti(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),ro=ti(["_and","_or","_not"]),ar=Object.freeze([...ro,...de]),ei=Object.assign(Object.create(null),{_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"})});var b,ne=Q(()=>{"use strict";b=class extends Error{constructor(t="Bad Request",r){let o=Array.isArray(t),i;if(o)i=t.join("; ")||"Bad Request";else if(typeof t=="string")i=t;else try{i=JSON.stringify(t)||"Bad Request"}catch{i="Bad Request"}super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=r,o&&(this.messages=[...t])}}});function ri(){let n=process.env.DB_URI||"";return n.startsWith("mongodb://")||n.startsWith("mongodb+srv://")}var ni=Q(()=>{"use strict"});function Ze(n,e,t){throw new b({message:`Unsupported filter operator "${n}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${ar.join(", ")}.`,error:"UnsupportedFilterOperator",operator:n,field:e,supportedOperators:ar})}function no(n,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let r=ri();for(let o of Object.keys(e))if(o.startsWith("_")&&!de.has(o)){if(r&&o==="_id")continue;Ze(o,n,t)}}function oi(n){if(n>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`)}function ii(n,e,t,r){if(!n||typeof n!="object")return;if(oi(e),t.has(n))throw new b("Filter contains a circular reference");let o=r.get(n);if(!(o!==void 0&&o>=e)){t.add(n);try{for(let i of Object.values(n))ii(i,e+1,t,r);r.set(n,Math.max(o??-1,e))}finally{t.delete(n)}}}function fa(n,e,t){let r=t.get(n);if(r)return r;let o=e?.tables?.get(n);if(!o)throw new b(`Filter validation requires metadata for table '${n}'`);let i=o?.columns??[],s={columnNames:new Set(i.map(a=>a.name)),relationMap:new Map((o?.relations??[]).map(a=>[a.propertyName,a])),acceptsIdAlias:i.some(a=>a.name==="_id"&&a.isPrimary)&&!i.some(a=>a.name==="id")};return t.set(n,s),s}function lr(n,e,t,r,o,i,s,a=!1){if(!n||typeof n!="object")return;if(oi(r),o.has(n))throw new b("Filter contains a circular reference");let c=`${e}:${a?"nested":"root"}`,u=s.get(n),l=u?.get(c);if(!(l!==void 0&&l>=r)){o.add(n);try{if(Array.isArray(n)){for(let y of n)lr(y,e,t,r+1,o,i,s,a);let h=u??new Map;h.set(c,Math.max(h.get(c)??-1,r)),s.set(n,h);return}let{columnNames:f,relationMap:d,acceptsIdAlias:p}=fa(e,t,i);for(let[h,y]of Object.entries(n)){if(a&&de.has(h)){if(h==="_is_null"||h==="_is_not_null"){if(typeof y!="boolean")throw new b(`Relation filter operator '${h}' requires a boolean value`)}else if((h==="_in"||h==="_not_in"||h==="_nin"||h==="_between")&&!Array.isArray(y))throw new b(`Relation filter operator '${h}' requires an array value`);continue}if(ua.has(h)){if(h==="_and"||h==="_or"){if(!Array.isArray(y)||y.some($=>!$||typeof $!="object"||Array.isArray($)))throw new b(`Filter '${h}' value must be an array of filter objects`)}else if(!y||typeof y!="object"||Array.isArray(y))throw new b("Filter '_not' value must be a filter object");lr(y,e,t,r+1,o,i,s,a);continue}let m=d.get(h);if(m){if(y===null)continue;if(typeof y!="object"||Array.isArray(y)){lr({id:{_eq:y}},m.targetTableName||m.targetTable,t,r+1,o,i,s,!0);continue}let $=m.targetTableName||m.targetTable;if(typeof $!="string"||!$||!t?.tables?.has($))throw new b(`Filter relation '${h}' on '${e}' has no resolvable target table metadata`);lr(y,$,t,r+1,o,i,s,!0);continue}let w=p&&(h==="id"||h==="_id"),_=f.has("_id")&&h==="_id";if(h.startsWith("_")&&!f.has(h)&&!w&&Ze(h,h,e),!f.has(h)&&!w&&!_)throw new b(`Unknown filter field '${h}' on table '${e}'`);y&&typeof y=="object"&&no(h,y,e)}let g=u??new Map;g.set(c,Math.max(g.get(c)??-1,r)),s.set(n,g)}finally{o.delete(n)}}}function De(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))throw new b("Filter must be an object");ii(n,0,new Set,new WeakMap),lr(n,e,t,0,new Set,new Map,new WeakMap)}var oe,ua,Le=Q(()=>{"use strict";ne();ni();wt();oe=64,ua=new Set(["_and","_or","_not"])});function Me(n,e,t,r){if(n===void 0)return{node:null,hasRelationFilters:!1};if(!n||typeof n!="object"||Array.isArray(n))throw new b("Filter must be an object");let o={tableName:e,metadata:t,registry:r,parentJoinId:null,currentJoinId:null,currentTable:e,depth:0,ancestors:new Set},i=r.createCheckpoint();try{return Jr(n,o)}catch(s){throw r.restoreCheckpoint(i),s}}function Jr(n,e){if(!n||typeof n!="object"||Array.isArray(n))throw new b("Logical filter operand must be a filter object");if(e.depth>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`);if(e.ancestors.has(n))throw new b("Filter contains a circular reference");e.ancestors.add(n);let t=e.registry.createCheckpoint();try{let r=[],o=!1,i=!1;for(let[s,a]of Object.entries(n)){let c=da(s,a,e),u=c.node;if(u?.kind==="false")return e.registry.restoreCheckpoint(t),{node:u,hasRelationFilters:!1};if(u?.kind==="true"){i=!0;continue}c.hasRelationFilters&&(o=!0),u&&r.push(u)}return r.length===0?{node:i?{kind:"true"}:null,hasRelationFilters:o}:r.length===1?{node:r[0],hasRelationFilters:o}:{node:{kind:"and",children:r},hasRelationFilters:o}}finally{e.ancestors.delete(n)}}function ai(n){return{...n,depth:n.depth+1}}function da(n,e,t){if(n==="_and")return si("and",e,t);if(n==="_or")return si("or",e,t);if(n==="_not"){if(!e||typeof e!="object"||Array.isArray(e))throw new b("Filter '_not' value must be a filter object");let u=t.registry.createCheckpoint(),l=Jr(e,ai(t)),f=l.node??{kind:"true"};return f.kind==="true"||f.kind==="false"?(t.registry.restoreCheckpoint(u),{node:{kind:f.kind==="true"?"false":"true"},hasRelationFilters:!1}):{node:{kind:"not",child:f},hasRelationFilters:l.hasRelationFilters}}let r=t.metadata?.tables?.get(t.currentTable);if(!r)throw new b(`Filter parsing requires metadata for table '${t.currentTable}'`);let o=r.columns?.some(u=>u.name==="_id"&&u.isPrimary),i=r?.columns?.some(u=>u.name==="id"),a=n==="id"?o&&!i?"_id":"id":n,c=r?.relations?.find(u=>u.propertyName===a);if(c)return zr(a,e,c,t);if(r&&!r.columns?.find(l=>l.name===a))throw n.startsWith("_")&&n!=="_id"&&Ze(n,n,t.currentTable),new b(`Unknown field '${n}' on table '${t.currentTable}'`);return pa(a,e,t)}function si(n,e,t){if(!Array.isArray(e))throw new b(`Filter '${n}' value must be an array`);let r=t.registry.createCheckpoint(),o=[],i=!1;for(let a of e){if(!a||typeof a!="object"||Array.isArray(a))throw new b(`Filter '${n}' entries must be filter objects`);let c=t.registry.createCheckpoint(),u=Jr(a,ai(t)),l=u.node??{kind:"true"};n==="and"&&l.kind==="true"||n==="or"&&l.kind==="false"?t.registry.restoreCheckpoint(c):u.hasRelationFilters&&(i=!0),o.push(l)}if(o.length===0)return{node:{kind:n==="and"?"true":"false"},hasRelationFilters:i};if(n==="or"&&o.some(a=>a.kind==="true"))return t.registry.restoreCheckpoint(r),{node:{kind:"true"},hasRelationFilters:!1};if(n==="and"&&o.some(a=>a.kind==="false"))return t.registry.restoreCheckpoint(r),{node:{kind:"false"},hasRelationFilters:!1};let s=o.filter(a=>n==="and"?a.kind!=="true":a.kind!=="false");return s.length===0?{node:{kind:n==="and"?"true":"false"},hasRelationFilters:i}:s.length===1?{node:s[0],hasRelationFilters:i}:{node:{kind:n,children:s},hasRelationFilters:i}}function zr(n,e,t,r){if(typeof e!="object"||e===null||Array.isArray(e))return e===null?zr(n,{id:{_is_null:!0}},t,r):Array.isArray(e)?zr(n,{id:{_in:e}},t,r):zr(n,{id:{_eq:e}},t,r);let o=Object.keys(e);if(o.length===0)return{node:null,hasRelationFilters:!1};let i=r.registry.createCheckpoint(),s=o.length===1&&(o[0]==="_is_null"||o[0]==="_is_not_null"||o[0]==="_eq"||o[0]==="_neq"||o[0]==="_in"||o[0]==="_not_in"||o[0]==="_nin"),a=r.registry.registerWithParent(r.currentTable,n,r.metadata,"left",r.currentJoinId,"filter");if(s&&(o[0]==="_is_null"||o[0]==="_is_not_null")&&typeof e[o[0]]!="boolean")throw new b(`Relation null-check operator '${o[0]}' requires a boolean value`);if(!a)throw new b(`Unable to register filter join for relation '${n}'`);if(s&&o[0]==="_is_null")return{node:{kind:"relation_exists",joinId:a,negate:e._is_null===!0},hasRelationFilters:!0};if(s&&o[0]==="_is_not_null")return{node:{kind:"relation_exists",joinId:a,negate:e._is_not_null!==!0},hasRelationFilters:!0};if(s&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return{node:{kind:"relation_exists",joinId:a,negate:o[0]==="_eq"},hasRelationFilters:!0};let c=t.targetTableName||t.targetTable;if(!c)throw new b(`Relation '${n}' has no target table metadata`);let u={...r,parentJoinId:r.currentJoinId,currentJoinId:a,currentTable:c,depth:r.depth+1},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte","_between"]),d=o.length>0&&o.every(g=>l.has(g))?{id:e}:e,p=Jr(d,u);return!p.node||p.node.kind==="true"||p.node.kind==="false"?(r.registry.restoreCheckpoint(i),{node:p.node,hasRelationFilters:!1}):{node:p.node,hasRelationFilters:!0}}function oo(n,e,t){if(!(!n||typeof n!="object")){if(e>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`);if(t.has(n))throw new b("Filter contains a circular reference");t.add(n);try{for(let r of Object.values(n))oo(r,e+1,t)}finally{t.delete(n)}}}function pa(n,e,t){let r={joinId:t.currentJoinId,fieldName:n,isUuid:ha(n,t)};if(e===null)return{node:{kind:"compare",field:r,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:r,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!de.has(s)&&Ze(s,n,t.tableName);let o=Object.entries(e).filter(([s])=>de.has(s));if(o.length>0&&o.length!==Object.keys(e).length)throw new b(`Field '${n}' has mixed filter operators and object properties`);if(o.length===0)return oo(e,t.depth+1,new Set),{node:{kind:"compare",field:r,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){if(oo(a,t.depth+1,new Set),(s==="_in"||s==="_not_in"||s==="_nin")&&!Array.isArray(a))throw new b(`Filter operator '${s}' requires an array value`);if(s==="_between"&&(!Array.isArray(a)||a.length!==2))throw new b("Filter operator '_between' requires an array with exactly two values");let c=ga(r,s,a);c&&i.push(c)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function ga(n,e,t){if(e==="_is_null"||e==="_is_not_null"){if(typeof t!="boolean")throw new b(`Filter operator '${e}' requires a boolean value`);return{kind:"compare",field:n,op:"is_null",value:e==="_is_null"?t:!t}}let r=Qr(e);return r?{kind:"compare",field:n,op:r,value:t}:null}function ha(n,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let r=n.includes(".")?n.split(".").pop():n,o=t.columns?.find(a=>a.name===r);if(!o)return!1;let s=(typeof o.type=="string"?o.type:typeof o.type?.name=="string"?o.type.name:"").toLowerCase();return s==="uuid"||s==="uuidv4"||s.includes("uuid")}var cr=Q(()=>{"use strict";wt();Le();ne()});function ur(n){return Buffer.byteLength(n,"utf8")<=ba}function Xr(n){return n.map(e=>`${Buffer.byteLength(e,"utf8")}:${e}`).join("|")}function fr(n){return co.createHash("md5").update(n).digest("hex").substring(0,8)}function pi(n){let e=`${n}_pk`;return ur(e)?e:`j_${fr(n)}_pk`}function gi(n,e,t){let r=`${n}_${e}_foreign`;return ur(r)?r:`j_${fr(n)}_${t}_fk`}function dr(n,e,t){let r=[n,e,t],o=r.some(s=>s.includes(":"))?Xr(r):r.join(":");return`j_${co.createHash("sha1").update(o).digest("hex").slice(0,12)}`}function X(n){let e=`${n}Id`;return ur(e)?e:`fk_${fr(Xr([n,"Id"]))}`}function pr(n,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function hi(n){return n.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function mi(n){return n.replace(/([A-Z])/g,"_$1").toLowerCase()}function yi(n,e,t){let r=`${n}_${e}_${t}_fk`;return ur(r)?r:`r_${fr(Xr([n,e,t]))}_${t}_fk`}function bi(n,e,t){let r=`${n}_${e}_${t}_idx`;return ur(r)?r:`r_${fr(Xr([n,e,t]))}_${t}_idx`}var co,ba,et=Q(()=>{"use strict";co=Je(require("crypto")),ba=63});var St,ae,hr,mr,$t=Q(()=>{"use strict";St=16,ae=5e3,hr=4,mr=10});var xa,nn,xi=Q(()=>{"use strict";ne();$t();xa=new Set(["many-to-one","one-to-one","one-to-many","many-to-many"]),nn=class{constructor(e,t){this.adapter=e;this.metadataGetter=t}normalizeDeepFields(e,t){if(e===void 0)return t;if(!Array.isArray(e)&&typeof e!="string")throw new b("Deep relation fields must be a string or string array");let r=Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean);if(r.some(o=>typeof o!="string"))throw new b("Deep relation fields must be strings");return r.map(o=>o.trim()).filter(Boolean)}normalizeDeepSort(e){if(e!==void 0){if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new b("Deep relation sort entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new b("Deep relation sort must be a string or string array");return e}}normalizeDeepPagination(e,t){if(e===void 0)return;if(typeof e!="number"&&typeof e!="string")throw new b(`Deep relation ${t} must be an integer`);let r=String(e);if(!/^\d+$/.test(r))throw new b(`Deep relation ${t} must be an integer`);let o=Number(r),i=t==="limit"?0:1;if(!Number.isSafeInteger(o)||o<i)throw new b(`Deep relation ${t} must be a safe integer greater than or equal to ${i}`);return o}normalizeDescriptors(e){let t=new Set;for(let r of e){if(t.has(r.relationName))throw new b(`Duplicate deep relation '${r.relationName}'`);t.add(r.relationName)}return e.map(r=>{if(!xa.has(r.type))throw new b(`Unsupported relation type '${r.type}' for '${r.relationName}'`);return this.withDefaultToManyLimit({...r,fields:this.normalizeDeepFields(r.fields,[]),userSort:this.normalizeDeepSort(r.userSort),userLimit:this.normalizeDeepPagination(r.userLimit,"limit"),userPage:this.normalizeDeepPagination(r.userPage,"page")})})}entryValue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}enrichNestedDescs(e,t,r,o){if(t===void 0)return e;if(!t||typeof t!="object"||Array.isArray(t))throw new b("Nested deep options must be an object");if(Object.keys(t).length===0)return e;let i=e.map(a=>{if(!Object.prototype.hasOwnProperty.call(t,a.relationName))return a;let c=t[a.relationName];if(!c||typeof c!="object"||Array.isArray(c))throw new b(`Nested deep option for relation '${a.relationName}' must be an object`);let u=this.entryValue(c,"fields"),l=this.entryValue(c,"filter"),f=this.entryValue(c,"sort"),d=this.entryValue(c,"limit"),p=this.entryValue(c,"page"),g=this.entryValue(c,"deep");return{...a,fields:this.normalizeDeepFields(u,o?.has(a.relationName)&&a.fields.length>0?a.fields:["*"]),userFilter:l??a.userFilter,userSort:f!==void 0?this.normalizeDeepSort(f):a.userSort,userLimit:d!==void 0?this.normalizeDeepPagination(d,"limit"):a.userLimit,userPage:p!==void 0?this.normalizeDeepPagination(p,"page"):a.userPage,nestedDeep:g??a.nestedDeep}}),s=new Set(i.map(a=>a.relationName));for(let[a,c]of Object.entries(t)){if(s.has(a))continue;if(!c||typeof c!="object"||Array.isArray(c))throw new b(`Nested deep option for relation '${a}' must be an object`);let u=r?.relations?.find(m=>m.propertyName===a);if(!u)throw new b(`Unknown nested deep relation '${a}' on '${r?.name??"unknown"}'`);let l=this.entryValue(c,"fields"),f=this.entryValue(c,"filter"),d=this.entryValue(c,"sort"),p=this.entryValue(c,"limit"),g=this.entryValue(c,"page"),h=this.entryValue(c,"deep"),y=this.normalizeDeepFields(l,["*"]);i.push({relationName:a,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:y,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:f,userSort:this.normalizeDeepSort(d),userLimit:this.normalizeDeepPagination(p,"limit"),userPage:this.normalizeDeepPagination(g,"page"),nestedDeep:h})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:10}:e}projectedRelations(e){let t=new Set;for(let r of e)r==="*"||!r.includes(".")||t.add(r.split(".")[0]);return t}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let r=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))r.has(i)||o.push(i);return o}getMetadata(e,t){let r=t.metadataByTable.get(e);if(r)return r;let o=this.metadataGetter(e);return t.metadataByTable.set(e,o),o}async prepareDescriptor(e,t,r,o){let i=await this.getMetadata(e.targetTable,o);if(!i)throw new Error(`Metadata not found for target table: ${e.targetTable}`);this.assertLocalSortFields(e,i);let{nestedDescs:s,fetchSpec:a}=this.adapter.resolveFields(this.fieldsForNestedResolution(e.fields,e.nestedDeep),i);if(r+1>=t)return{desc:e,targetMeta:i,fetchSpec:a,children:[]};let c=await Promise.all(this.normalizeDescriptors(this.enrichNestedDescs(s,e.nestedDeep,i,this.projectedRelations(e.fields))).map(u=>this.prepareDescriptor(u,t,r+1,o)));return{desc:e,targetMeta:i,fetchSpec:a,children:c}}assertLocalSortFields(e,t){if(!e.userSort)return;let r=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of r){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new b(`Sort field '${i}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(c=>c.name===i),a=i==="id"&&t.columns?.some(c=>c.name==="_id");if(!s&&!a)throw new b(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}}});async function W(n,e,t=5e3){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(n.length===0)return[];if(n.length<=t)return e(n);let r=[];for(let f=0;f<n.length;f+=t)r.push(n.slice(f,f+t));let o=[],i=0,s=!1,a=!1,c;async function u(){for(;!s;){let f=i;if(f>=r.length)return;i+=1;try{o[f]=await e(r[f])}catch(d){a||(a=!0,c=d),s=!0}}}let l=Math.min(4,r.length);if(await Promise.all(Array.from({length:l},()=>u())),a)throw c;return o.flat()}function nt(n){let e=[],t=new Map;for(let r of n)if(r==="*"||!r.includes("."))e.push(r);else{let o=r.split("."),i=o[0],s=o.slice(1).join(".");t.has(i)||t.set(i,[]),t.get(i).push(s)}return{rootFields:e,subRelations:t}}var Ci=Q(()=>{"use strict";$t()});var qe,Ne=Q(()=>{"use strict";ne();xi();$t();Ci();$t();qe=class{constructor(e,t,r){this.adapter=e;this.trace=r;this.plan=new nn(e,t)}uniqueValues(e){let t=new Set,r=[];for(let o of e){if(o==null)continue;let i=this.adapter.keyOf(o);t.has(i)||(t.add(i),r.push(o))}return r}setRelation(e,t,r){let o=Object.getOwnPropertyDescriptor(e,t);if(o&&!o.configurable){Object.defineProperty(e,t,{value:r});return}Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}assertCommitCanApply(e,t,r){for(let o of t){let i=o.desc;for(let s of e){let a=Object.getOwnPropertyDescriptor(s,i.relationName);if(!a&&!Object.isExtensible(s))throw new Error(`Cannot add relation '${i.relationName}' to a non-extensible result`);if(a&&!a.configurable&&(!("writable"in a)||!a.writable))throw new Error(`Cannot replace non-writable relation '${i.relationName}'`);for(let c of i.injectedParentFields??[]){if(r.has(c))continue;let u=Object.getOwnPropertyDescriptor(s,c);if(u&&!u.configurable)throw new Error(`Cannot remove injected relation field '${c}'`)}}}}createStagingParent(e){let t=Object.create(Object.getPrototypeOf(e));for(let r of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,r);"value"in o?Object.defineProperty(t,r,{value:o.value,enumerable:o.enumerable,writable:!0,configurable:!0}):Object.defineProperty(t,r,{get:o.get,set:o.set,enumerable:o.enumerable,configurable:!0})}return t}async execute(e,t,r=3,o=0,i){if(!Number.isSafeInteger(r)||r<0)throw new b("Maximum query depth must be a non-negative safe integer");if(!Number.isSafeInteger(o)||o<0)throw new b("Current query depth must be a non-negative safe integer");if(t.length===0||o>=r)return;let s={metadataByTable:new Map},a;if(i&&(a=await this.plan.getMetadata(i,s)??void 0,!a))throw new Error(`Metadata not found for parent table: ${i}`);let c=await Promise.all(this.plan.normalizeDescriptors(t).map(u=>this.plan.prepareDescriptor(u,r,o,s)));await this.executePrepared(e,c,r,o,a,s)}async executePrepared(e,t,r,o,i,s){if(e.length===0)return;let a=new Array(t.length),c=new Array(t.length),u=0,l=!1,f,d=async()=>{for(;!l&&u<t.length;){let g=u;u+=1;let h=t[g],y=h.desc,m=e.map(w=>this.createStagingParent(w));try{y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse?await this.fetchOwnerRelation(m,h,r,o,s):y.type==="one-to-many"||y.type==="one-to-one"&&y.isInverse?await this.fetchInverseRelation(m,h,r,o,i,s):y.type==="many-to-many"&&await this.fetchM2MRelation(m,h,r,o,i,s),a[g]=m.map(w=>w[y.relationName]),c[g]={status:"fulfilled",value:void 0}}catch(w){c[g]={status:"rejected",reason:w},l||(f=w),l=!0}}};if(await Promise.all(Array.from({length:Math.min(4,t.length)},()=>d())),l)throw f;let p=new Set(t.map(({desc:g})=>g.relationName));this.assertCommitCanApply(e,t,p);for(let g=0;g<t.length;g+=1){let h=t[g].desc,y=a[g];for(let m=0;m<e.length;m+=1){this.setRelation(e[m],h.relationName,y[m]);for(let w of h.injectedParentFields??[])p.has(w)||delete e[m][w]}}}async fetchOwnerRelation(e,t,r,o,i){let{desc:s,targetMeta:a,fetchSpec:c,children:u}=t,l=this.adapter.resolveOwnerFkKey(s),f=new Set,d=[];for(let _ of e){let $=_[l];if($==null)continue;let k=this.adapter.keyOf($);f.has(k)||(f.add(k),d.push($))}if(d.length===0){for(let _ of e)this.setRelation(_,s.relationName,null),l!==s.relationName&&delete _[l],s.fkColumn&&s.fkColumn!==s.relationName&&delete _[s.fkColumn];return}let p=this.adapter.getTargetPkField(a),g=performance.now(),h=await this.adapter.fetchOwner(s.targetTable,d,c,s),y=Array.isArray(h)?h:h.docs,m=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${o}_${s.relationName}`,g,{relationType:s.type,targetTable:s.targetTable,strategy:m?.strategy??"batch-in",roundtrips:m?.roundtrips??(Math.ceil(d.length/5e3)||1),concurrencyWaves:m?.concurrencyWaves,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??y.length,rowsReturned:y.length,rowsDiscarded:0,userFilter:!!s.userFilter,userSort:!!s.userSort});let w=new Map;for(let _ of y)w.set(this.adapter.keyOf(_[p]),_);u.length>0&&await this.executePrepared(y,u,r,o+1,a,i);for(let _ of e){let $=_[l];this.setRelation(_,s.relationName,$!=null&&w.get(this.adapter.keyOf($))||null),l!==s.relationName&&delete _[l],s.fkColumn&&s.fkColumn!==s.relationName&&delete _[s.fkColumn]}}async fetchInverseRelation(e,t,r,o,i,s){let{desc:a,targetMeta:c,fetchSpec:u,children:l}=t,f=this.adapter.resolveParentPk(i),d=this.uniqueValues(e.map(M=>M[f]));if(d.length===0){for(let M of e)this.setRelation(M,a.relationName,a.type==="one-to-one"?null:[]);return}let p=this.adapter.resolveInverseFkField(a),g=performance.now(),{docs:h,groupKeyField:y,stats:m}=await this.adapter.fetchInverse(a.targetTable,p,d,u,a),w=new Map,_=a.fields.includes("*")||a.fields.some(M=>M===p||M.startsWith(`${p}.`));for(let M of h){let N=M[y],j=this.adapter.keyOf(N);w.has(j)||w.set(j,[]),w.get(j).push(M)}let $=a.userLimit!==void 0&&a.userLimit>0,k=$?"per-parent-c16":"batch-in",C=$?d.length:Math.ceil(d.length/5e3)||1,x=$?Math.ceil(d.length/16):void 0,v=Array.from(w.values()).reduce((M,N)=>M+N.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${a.relationName}`,g,{relationType:a.type,targetTable:a.targetTable,strategy:m?.strategy??k,roundtrips:m?.roundtrips??C,concurrencyWaves:m?.concurrencyWaves??x,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??h.length,rowsReturned:v,rowsDiscarded:Math.max(0,(m?.rowsTransferred??h.length)-v),userLimit:a.userLimit,userFilter:!!a.userFilter,userSort:!!a.userSort}),l.length>0&&await this.executePrepared(h,l,r,o+1,c,s),this.adapter.postProcessInverseChild)for(let M of h)this.adapter.postProcessInverseChild(M,p,_);let R=a.type==="one-to-one";for(let M of e){let N=M[f];if(N==null){this.setRelation(M,a.relationName,R?null:[]);continue}let j=w.get(this.adapter.keyOf(N))||[];this.setRelation(M,a.relationName,R?j[0]||null:j)}}async fetchM2MRelation(e,t,r,o,i,s){let{desc:a,targetMeta:c,fetchSpec:u,children:l}=t,f=this.adapter.resolveParentPk(i),d=this.uniqueValues(e.map(x=>x[f]));if(d.length===0){for(let x of e)this.setRelation(x,a.relationName,[]);return}let p=e.filter(x=>x[f]!=null),g=performance.now(),{grouped:h,docs:y,stats:m}=await this.adapter.fetchM2M(p,a,i,c,u),w=a.userLimit!==void 0&&a.userLimit>0,_=w?"m2m-per-parent-c16":"m2m-batch",$=w?d.length:Math.ceil(d.length/5e3)||1,k=w?Math.ceil(d.length/16):void 0,C=Array.from(h.values()).reduce((x,v)=>x+v.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${a.relationName}`,g,{relationType:a.type,targetTable:a.targetTable,strategy:m?.strategy??_,roundtrips:m?.roundtrips??$,concurrencyWaves:m?.concurrencyWaves??k,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??y.length,rowsReturned:C,rowsDiscarded:m?.rowsDiscarded??Math.max(0,(m?.rowsTransferred??y.length)-C),userLimit:a.userLimit,userFilter:!!a.userFilter,userSort:!!a.userSort}),l.length>0){let x=Array.from(new Set(Array.from(h.values()).flat()));x.length>0&&await this.executePrepared(x,l,r,o+1,c,s)}for(let x of e){let v=x[f];if(v==null){this.setRelation(x,a.relationName,[]);continue}let R=this.adapter.keyOf(v);this.setRelation(x,a.relationName,h.get(R)||[])}}}});var Fi,We,on=Q(()=>{"use strict";Fi=2,We=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];this.waiterHead=0;this.failed=!1;if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{if(this.failed)throw this.failure;return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failed)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(!await new Promise(t=>this.waiters.push(t)))throw this.failure;if(this.failed)throw this.active-=1,this.failure}release(){if(this.active<1)throw new Error("Batch execution permit underflow");if(this.failed){this.active-=1;return}let e=this.waiters[this.waiterHead];if(e){this.waiters[this.waiterHead]=void 0,this.waiterHead+=1,this.waiterHead>1024&&this.waiterHead*2>this.waiters.length&&(this.waiters.splice(0,this.waiterHead),this.waiterHead=0),e(!0);return}this.active-=1}cancel(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t=this.waiterHead;t<this.waiters.length;t+=1)this.waiters[t]?.(!1);this.waiters.length=0,this.waiterHead=0}}}});function I(n,e){if(e==="mongodb")return n;let t=["postgres","pg","sqlite"].includes(e)?'"':"`";return t+n.split(t).join(t+t)+t}function ze(n,e){let t=[],r=0;for(;r<n.length;){let o=n[r];if(o==='"'||o==="`"){r++;let i="",s=!1;for(;r<n.length;){let a=n[r++];if(a!==o){i+=a;continue}if(n[r]===o){i+=o,r++;continue}s=!0;break}if(!s||r<n.length&&n[r]!==".")throw new Error("Invalid quoted SQL identifier");t.push(I(i,e))}else{let i=n.indexOf(".",r),s=n.slice(r,i===-1?void 0:i);if(!s)throw new Error("Invalid qualified SQL identifier");t.push(s==="*"?s:I(s,e)),r=i===-1?n.length:i}if(r<n.length&&(r++,r===n.length))throw new Error("Invalid qualified SQL identifier")}if(t.length===0)throw new Error("Invalid qualified SQL identifier");return t.join(".")}var Se=Q(()=>{"use strict"});function te(n){return n.columns.find(e=>e.isPrimary)||null}var ft=Q(()=>{"use strict"});function ue(n,e,t){e&&Pt(n,e,t,"and")}function Pt(n,e,t,r){switch(e.kind){case"true":r==="or"?n.orWhereRaw("1 = 1"):n.whereRaw("1 = 1");return;case"false":r==="or"?n.orWhereRaw("1 = 0"):n.whereRaw("1 = 0");return;case"and":{if(e.children.length===0){Pt(n,{kind:"true"},t,r);return}let o=function(){for(let i of e.children)this.where(function(){Pt(this,i,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"or":{if(e.children.length===0){Pt(n,{kind:"false"},t,r);return}let o=function(){for(let i of e.children)this.orWhere(function(){Pt(this,i,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"not":{let o=function(){this.whereNot(function(){Pt(this,e.child,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"compare":ul(n,e,t,r);return;case"relation_exists":throw new Error(`SQL relation_exists node requires a materialized join: ${e.joinId}`)}}function ul(n,e,t,r){if(e.field.joinId!==null)throw new Error(`SQL comparison requires a materialized join target: ${e.field.joinId}`);let o=dl(e.field,t),i=ze(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",c=r==="or"?"orWhere":"where",u=r==="or"?"orWhereRaw":"whereRaw",l=r==="or"?"orWhereIn":"whereIn",f=r==="or"?"orWhereNotIn":"whereNotIn",d=r==="or"?"orWhereBetween":"whereBetween",p=r==="or"?"orWhereNull":"whereNull",g=r==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":e.value===null?n[p](o):s&&a&&typeof e.value=="string"?n[u](`${i} = ?::uuid`,[e.value]):n[c](o,"=",e.value);return;case"neq":e.value===null?n[g](o):s&&a&&typeof e.value=="string"?n[u](`${i} != ?::uuid`,[e.value]):n[c](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?n[u](`${i} > ?::uuid`,[e.value]):n[c](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?n[u](`${i} >= ?::uuid`,[e.value]):n[c](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?n[u](`${i} < ?::uuid`,[e.value]):n[c](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?n[u](`${i} <= ?::uuid`,[e.value]):n[c](o,"<=",e.value);return;case"in":{let h=ls(e.value);h.length===0?n[u]("1 = 0"):s&&a&&h.every(y=>typeof y=="string")?n[u](`${i} = ANY(?::uuid[])`,[h]):n[l](o,h);return}case"not_in":{let h=ls(e.value);h.length===0?n[u]("1 = 1"):s&&a&&h.every(y=>typeof y=="string")?n[u](`${i} != ALL(?::uuid[])`,[h]):n[f](o,h);return}case"contains":Co(n,i,e.value,"contains",t,r);return;case"starts_with":Co(n,i,e.value,"starts_with",t,r);return;case"ends_with":Co(n,i,e.value,"ends_with",t,r);return;case"between":if(!Array.isArray(e.value)||e.value.length!==2)throw new Error("Invalid between filter value");n[d](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?n[p](o):n[g](o);return}}function fl(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Co(n,e,t,r,o,i){let s=i==="or"?"orWhereRaw":"whereRaw",a=fl(t);if(o.dbType==="postgres"){let u=r==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%' ESCAPE '='`:r==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%' ESCAPE '='`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) ESCAPE '='`;n[s](u,[a]);return}if(o.dbType==="sqlite"){let u=r==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%' ESCAPE '='`:r==="starts_with"?`lower(${e}) LIKE lower(?) || '%' ESCAPE '='`:`lower(${e}) LIKE '%' || lower(?) ESCAPE '='`;n[s](u,[a]);return}let c=r==="contains"?`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(?) COLLATE utf8mb4_general_ci, '%') ESCAPE '='`:r==="starts_with"?`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(?) COLLATE utf8mb4_general_ci, '%') ESCAPE '='`:`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(?) COLLATE utf8mb4_general_ci) ESCAPE '='`;n[s](c,[a])}function dl(n,e){let t=n.fieldName.split(".");if(t.some(r=>!r))throw new Error("Invalid SQL filter field");if(t.length===1)return`${e.rootTable}.${t[0]}`;if(t.length!==2||t[0]!==e.rootTable)throw new Error("Invalid SQL filter field");return n.fieldName}function ls(n){return Array.isArray(n)?n:typeof n=="string"&&n.includes(",")?n.split(",").map(e=>e.trim()):[n]}var Rr=Q(()=>{"use strict";Se()});var fs={};Un(fs,{expandFieldsToJoinsAndSelect:()=>Ro});function us(n,e,t){if(n===void 0)return;let r=typeof n=="number",o=typeof n=="string"&&/^\d+$/.test(n.trim());if(!r&&!o)throw new Error(t);let i=Number(n);if(!Number.isSafeInteger(i)||i<e)throw new Error(t);return i}function pl(n){return us(n,0,"SQL relation limit must be a non-negative safe integer")}function gl(n){return us(n,1,"SQL relation page must be a positive safe integer")}function jt(n,e){return n&&Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0}function cs(n){if(typeof n!="string"&&!Array.isArray(n))throw new Error("SQL relation fields must be a string or string array");let e=typeof n=="string"?n.split(","):n;if(e.some(t=>typeof t!="string"))throw new Error("SQL relation fields must be strings");return e.map(t=>t.trim()).filter(Boolean)}async function Ro(n,e,t,r,o,i){if(o!==void 0&&(!Number.isSafeInteger(o)||o<0))throw new Error("SQL maximum query depth must be a non-negative safe integer");let s=[],a=[],c=await t(n);if(!c)throw new Error(`SQL field expansion requires metadata for '${n}'`);let u=new Map,l=new Set;for(let h of e){let y=h.split(".").map(w=>w.trim());if(y.some(w=>w.length===0))throw new Error(`Malformed SQL field path '${h}'`);let m=y.join(".");if(m==="*"||y.length===1)u.has("")||u.set("",[]),u.get("").push(m);else{let w=y[0],_=y.slice(1).join(".");u.has(w)||u.set(w,[]),u.get(w).push(_)}}if(i&&typeof i=="object")for(let[h,y]of Object.entries(i)){if(u.has(h))continue;let m=y&&typeof y=="object"&&y.fields!=null?cs(y.fields):["*"];u.set(h,m)}let f=u.get("")||[],d=new Set,p=new Set,g=h=>`${I(n,r)}.${I(h,r)}`;for(let h of f){if(h==="*"){let _=new Set;for(let k of c.relations||[])if(k.type==="many-to-one"||k.type==="one-to-one"&&!k.isInverse){let C=k.foreignKeyColumn||X(k.propertyName);C&&_.add(C)}let $=new Set;for(let k of c.columns)_.has(k.name)||(s.push(g(k.name)),d.add(k.name),$.add(k.name));for(let k of c.relations||[])!u.has(k.propertyName)&&!$.has(k.propertyName)&&(u.set(k.propertyName,[]),l.add(k.propertyName));continue}if(h.includes(".")){s.push(g(h));continue}let y=c.relations?.find(_=>(_.type==="many-to-one"||_.type==="one-to-one"&&!_.isInverse)&&(_.foreignKeyColumn||X(_.propertyName))===h);if(y){u.has(y.propertyName)||(u.set(y.propertyName,[]),l.add(y.propertyName));continue}if(c.columns?.find(_=>_.name===h)){s.push(g(h)),d.add(h);continue}if(c.relations?.find(_=>_.propertyName===h)){u.has(h)||(u.set(h,[]),l.add(h));continue}}for(let[h,y]of u){if(h==="")continue;let m=c.relations?.find(v=>v.propertyName===h);if(!m)continue;if(o===0)throw new Error("SQL relation exceeds maximum query depth");if(m.type==="one-to-one"&&typeof m.isInverse!="boolean")throw new Error(`SQL one-to-one relation '${h}' requires ownership metadata`);let w=m.type==="many-to-one"||m.type==="one-to-one"&&m.isInverse===!1,_=[];if(d.has(h))throw new Error(`SQL relation '${h}' on '${n}' conflicts with a selected root column`);if(p.add(h),w){let v=m.foreignKeyColumn||X(m.propertyName);if(!c.columns.some(j=>j.name===v))throw new Error(`SQL relation '${h}' foreign key '${v}' is missing from '${n}' metadata`);let R=I(n,r),M=I(v,r),N=I(h,r);s.push(`${R}.${M} as ${N}`),_.push(h)}else{let v=c.columns.filter(R=>R.isPrimary===!0);if(v.length===0)throw new Error(`SQL relation '${h}' on '${n}' requires parent primary key metadata`);for(let R of v){if(p.has(R.name))throw new Error(`SQL parent key '${R.name}' on '${n}' conflicts with a relation output`);d.has(R.name)||(s.push(g(R.name)),d.add(R.name),_.push(R.name))}}let $=m.targetTableName||m.targetTable,k=i&&Object.prototype.hasOwnProperty.call(i,h)?i[h]:void 0,C=jt(k,"fields"),x=C!=null?cs(C):y;if(C==null&&l.has(h)){let v=await t($);if(!v)throw new Error(`SQL relation '${h}' requires target metadata for '${$}'`);if(x=v.columns.filter(R=>R.isPrimary===!0).map(R=>R.name),x.length===0)throw new Error(`SQL relation '${h}' requires target primary key metadata`)}a.push({relationName:h,type:m.type,targetTable:$,fields:x,isInverse:m.isInverse,fkColumn:w?m.foreignKeyColumn||X(m.propertyName):m.foreignKeyColumn,injectedParentFields:_.length>0?_:void 0,mappedBy:m.mappedBy,junctionTableName:m.junctionTableName,junctionSourceColumn:m.junctionSourceColumn,junctionTargetColumn:m.junctionTargetColumn,userFilter:jt(k,"filter"),userSort:jt(k,"sort"),userLimit:pl(jt(k,"limit")),userPage:gl(jt(k,"page")),nestedDeep:jt(k,"deep")})}return{select:s,batchFetchDescriptors:a}}var Fo=Q(()=>{"use strict";et();Se()});var Mr,Dt,Bn,ds=Q(()=>{"use strict";Ne();cr();sr();et();ft();Se();Mr="__enfyra_row_number__",Dt="__enfyra_partitioned__",Bn=class{constructor(e,t,r){this.knex=e;this.dbType=t;this.metadata=r}getTableMetadata(e){let t=this.metadata?.tables??this.metadata;if(t)return typeof t.get=="function"?t.get(e):t[e]}sortAlias(e){return`__sort_${e.map(t=>`${t.length}_${t}`).join("_")}`}buildPartitionRowNumber(e,t,r){let o=[...t];o.some(s=>s.column===r)||o.push({column:r,order:"asc"});let i=o.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${i}) as ??`,[e,...o.map(s=>s.column),Mr])}buildPartitionSlice(e,t,r,o){return this.knex.from(e.as(Dt)).select(`${Dt}.*`).where(`${Dt}.${Mr}`,">",r).andWhere(`${Dt}.${Mr}`,"<=",r+o).orderBy(`${Dt}.${t}`,"asc").orderBy(`${Dt}.${Mr}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Mr]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let r=new Te,o=this.metadata?.tables?this.metadata:{tables:this.metadata instanceof Map?this.metadata:new Map(Object.entries(this.metadata))},{node:i}=Me(e,t,o,r);return i}parseSortTokens(e,t,r){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),c=(s?i.slice(1):i).split(".");if(c.length===1)return{column:r?`${r}.${c[0]}`:`${t}.${c[0]}`,order:s?"desc":"asc"};let u=c[c.length-1];return{column:`${this.sortAlias(c.slice(0,-1))}.${u}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,r,o){if(!t||!this.metadata)return;let i=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of i){let u=(a.startsWith("-")?a.slice(1):a).split(".");if(u.length<=1)continue;let l=r,f=o||r;for(let d=0;d<u.length-1;d++){let p=u[d],g=this.getTableMetadata(l);if(!g)break;let h=g.relations?.find(w=>w.propertyName===p);if(!h)break;if(h.isInverse||h.type==="one-to-many"||h.type==="many-to-many")throw new Error(`Dotted sort through inverse or to-many relation '${p}' is not supported`);let y=h.targetTableName||h.targetTable,m=this.sortAlias(u.slice(0,d+1));if(!s.has(m)){s.add(m);let w=h.foreignKeyColumn||X(h.propertyName),_=this.getTableMetadata(y),$=_&&te(_)?.name||"id";e.leftJoin(`${y} as ${m}`,`${m}.${$}`,`${f}.${w}`)}l=y,f=m}}}toKnexSelect(e,t){let r=e.indexOf(" as ");if(r!==-1){let o=e.substring(0,r),i=e.substring(r+4),s=I(i,this.dbType),a=t?`${I(t,this.dbType)}.${I(o,this.dbType)}`:I(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${I(t,this.dbType)}.${I(e,this.dbType)} as ${I(e,this.dbType)}`):e}resolveFields(e,t){let{rootFields:r,subRelations:o}=nt(e),i=[];if(r.includes("*")){let u=new Set;for(let l of t.relations||[])if(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse){let f=l.foreignKeyColumn||X(l.propertyName);f&&u.add(f)}for(let l of t.columns)u.has(l.name)||i.push(l.name);for(let l of t.relations||[])o.has(l.propertyName)||o.set(l.propertyName,["id"])}else for(let u of r){let l=t.relations?.find(d=>(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse)&&(d.foreignKeyColumn||X(d.propertyName))===u);if(l){o.has(l.propertyName)||o.set(l.propertyName,["id"]);continue}let f=t.columns.find(d=>d.name===u);f?i.push(f.name):t.relations?.find(p=>p.propertyName===u)&&!o.has(u)&&o.set(u,["id"])}let s=te(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((u,l)=>{let f=t.relations?.find(d=>d.propertyName===l);if(f&&(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse)){let d=f.foreignKeyColumn||X(f.propertyName);d&&i.push(`${d} as ${l}`)}});let a=[];return o.forEach((u,l)=>{let f=t.relations?.find(p=>p.propertyName===l);if(!f)return;let d=f.targetTableName||f.targetTable;d&&a.push({relationName:l,type:f.type,targetTable:d,fields:u,isInverse:f.isInverse,fkColumn:f.foreignKeyColumn,mappedBy:f.mappedBy,junctionTableName:f.junctionTableName,junctionSourceColumn:f.junctionSourceColumn,junctionTargetColumn:f.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}}});var Ar,Dn,ml,Lt,vo=Q(()=>{"use strict";on();Ne();et();ft();ds();Rr();Ar="__sourceId__",Dn="__targetId__",ml=5e4,Lt=class{constructor(e,t="postgres",r,o=new We){this.knex=e;this.dbType=t;this.metadata=r;this.executionBudget=o;this.pkField="id";this.batchQuery=new Bn(e,t,r)}resolveFields(e,t){return this.batchQuery.resolveFields(e,t)}chunkCount(e,t=5e3){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?ml:5e3}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}keyOf(e){if(e===null)return"null:";if(e===void 0)return"undefined:";if(typeof e=="number")return Number.isNaN(e)?"number:nan":Object.is(e,-0)?"number:-0":`number:${e}`;if(typeof e=="bigint")return`bigint:${e}`;if(typeof e=="boolean")return`boolean:${e}`;if(typeof e=="string")return`string:${e.length}:${e}`;if(e instanceof Date)return`date:${e.toISOString()}`;throw new Error("SQL relation identity must be a scalar value")}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return te(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;if(!t&&e.mappedBy&&(t=X(e.mappedBy)),!t)throw new Error(`Missing inverse foreign key metadata for relation: ${e.relationName}`);return t}resolveParentPk(e){return e&&te(e)?.name||"id"}async fetchOwner(e,t,r,o){let i=o?.userFilter?this.batchQuery.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.batchQuery.parseSortTokens(o.userSort,e):[],a=r.selectCols.map(l=>this.batchQuery.toKnexSelect(l,e)),c=this.uniqueValues(t),u=await W(c,l=>{let f=this.knex(e).select(a).whereIn(`${e}.${r.pkCol}`,l);if(i&&ue(f,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.batchQuery.applySortJoins(f,o.userSort,e);for(let d of s)f.orderBy(d.column,d.order)}return this.runQuery(f)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,r,o,i){let s=t,a=o.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let c=i?.userFilter?this.batchQuery.buildFilterTree(i.userFilter,e):null,u=i?.userSort?this.batchQuery.parseSortTokens(i.userSort,e):[],l=i?.userLimit,f=i?.userPage,d=this.uniqueValues(r);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,y=o.selectCols.map(w=>this.batchQuery.toKnexSelect(w,e)),m=await W(d,async w=>{let _=this.knex(e).select(y).select(this.batchQuery.buildPartitionRowNumber(`${e}.${t}`,u,`${e}.${o.pkCol}`)).whereIn(`${e}.${t}`,w);c&&ue(_,c,{dbType:this.dbType,rootTable:e}),this.batchQuery.applySortJoins(_,i.userSort,e);let $=await this.runQuery(this.batchQuery.buildPartitionSlice(_,s,h,l));return this.batchQuery.removePartitionFields($),$});return{docs:m,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(d),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let p=o.selectCols.map(h=>this.batchQuery.toKnexSelect(h,e)),g=await W(d,h=>{let y=this.knex(e).select(p).whereIn(`${e}.${t}`,h);if(c&&ue(y,c,{dbType:this.dbType,rootTable:e}),this.batchQuery.applySortJoins(y,i?.userSort,e),u.length>0)for(let m of u)y.orderBy(m.column,m.order);else y.orderBy(`${e}.${o.pkCol}`,"asc");return this.runQuery(y)});return{docs:g,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(d),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}postProcessInverseChild(e,t,r){r||delete e[t]}async selectM2MEdges(e,t,r,o,i,s,a,c){let u=`t.${s}`,l=!!a||c.some(h=>h.column!==u),f=l?c:c.map(h=>({...h,column:`${r}.${i}`})),d=t.userLimit,p=t.userPage;if(d!==void 0&&d>0){let h=p?(p-1)*d:0;return(await W(e,async m=>{let w=this.knex(r).select({[Ar]:`${r}.${o}`,[Dn]:`${r}.${i}`}).whereIn(`${r}.${o}`,m);l&&(w=w.join(`${t.targetTable} as t`,`${r}.${i}`,`t.${s}`),a&&ue(w,a,{dbType:this.dbType,rootTable:"t"}),this.batchQuery.applySortJoins(w,t.userSort,t.targetTable,"t")),w.select(this.batchQuery.buildPartitionRowNumber(`${r}.${o}`,f,l?u:`${r}.${i}`));let _=await this.runQuery(this.batchQuery.buildPartitionSlice(w,Ar,h,d));return this.batchQuery.removePartitionFields(_),_})).map(m=>({sourceId:m[Ar],targetId:m[Dn]}))}return(await W(e,h=>{let y=this.knex(r).select({[Ar]:`${r}.${o}`,[Dn]:`${r}.${i}`}).whereIn(`${r}.${o}`,h);if(l&&(y=y.join(`${t.targetTable} as t`,`${r}.${i}`,`t.${s}`),a&&ue(y,a,{dbType:this.dbType,rootTable:"t"}),this.batchQuery.applySortJoins(y,t.userSort,t.targetTable,"t")),y.orderBy(`${r}.${o}`,"asc"),f.length>0){for(let m of f)y.orderBy(m.column,m.order);l&&!f.some(m=>m.column===u)&&y.orderBy(u,"asc")}else y.orderBy(`${r}.${i}`,"asc");return this.runQuery(y)})).map(h=>({sourceId:h[Ar],targetId:h[Dn]}))}async loadM2MTargets(e,t,r){if(t.length===0)return[];let o=r.selectCols.map(i=>this.batchQuery.toKnexSelect(i));return W(t,i=>this.runQuery(this.knex(e).select(o).whereIn(r.pkCol,i)),this.m2mTargetChunkSize())}async fetchM2M(e,t,r,o,i){let s=this.resolveParentPk(r),a=this.uniqueValues(e.map(x=>x[s]));if(a.length===0)return{grouped:new Map,docs:[]};let c=t.junctionTableName,u=t.junctionSourceColumn,l=t.junctionTargetColumn;if(!c||!u||!l)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let f=t.userFilter?this.batchQuery.buildFilterTree(t.userFilter,t.targetTable):null,d=t.userSort?this.batchQuery.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,c,u,l,i.pkCol,f,d),g=new Map;for(let x of a)g.set(this.keyOf(x),[]);let h=i.selectCols.length===1&&i.selectCols[0]===i.pkCol,y=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),w=`t.${i.pkCol}`,_=!f&&d.every(x=>x.column===w);if(h){let x=new Map;for(let v of p){let R=this.keyOf(v.targetId);x.has(R)||x.set(R,{[i.pkCol]:v.targetId}),g.get(this.keyOf(v.sourceId))?.push(x.get(R))}return{grouped:g,docs:[],stats:{strategy:_?y?"m2m-junction-partitioned-top-k":"m2m-junction-batch":y?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let $=this.uniqueValues(p.map(x=>x.targetId)),k=await this.loadM2MTargets(t.targetTable,$,i),C=new Map(k.map(x=>[this.keyOf(x[i.pkCol]),x]));for(let x of p){let v=C.get(this.keyOf(x.targetId));v&&g.get(this.keyOf(x.sourceId))?.push(v)}return{grouped:g,docs:k,stats:{strategy:y?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+($.length>0?this.chunkCount($,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+k.length,rowsDiscarded:0}}}}});var ps={};Un(ps,{executeBatchFetches:()=>Mo});async function Mo(n,e,t,r,o=3,i=0,s,a="postgres",c,u){let l=new Lt(n,a,c);await new qe(l,r,u).execute(e,t,o,i,s)}var Ao=Q(()=>{"use strict";Ne();vo()});var bl={};Un(bl,{ALL_SUPPORTED_OPERATORS:()=>ar,AuthenticationException:()=>zt,AuthorizationException:()=>Jt,BadRequestException:()=>b,BatchExecutionBudget:()=>We,BatchFetchEngine:()=>qe,BusinessLogicException:()=>Wt,CHUNKED_FETCH_CONCURRENCY:()=>hr,ConfigurationException:()=>Zt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>mr,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Fi,DEFAULT_TIMEOUT_MS:()=>Or,DOTTED_PATH_MAX_HOPS:()=>me,DatabaseException:()=>ht,DuplicateResourceException:()=>Qt,ErrorHandler:()=>Ve,ExecutorEngineService:()=>gt,ExternalServiceException:()=>Gt,FIELD_OPERATORS:()=>de,FileNotFoundException:()=>tr,FileSizeExceededException:()=>rr,FileUploadException:()=>er,HttpException:()=>Y,InvalidTokenException:()=>Vt,IsolatedExecutorService:()=>bt,JoinRegistry:()=>Te,LOGICAL_OPERATORS:()=>ro,MongoBatchAdapter:()=>Rt,MongoQueryExecutor:()=>lt,PER_PARENT_CONCURRENCY:()=>St,QueryBuilderService:()=>qt,QueryPlanner:()=>pe,ResourceNotFoundException:()=>Ut,SchemaException:()=>Xt,ScriptContractService:()=>Ur,ScriptExecutionException:()=>He,ScriptTimeoutException:()=>Be,ServiceUnavailableException:()=>Yt,SqlBatchAdapter:()=>Lt,SqlQueryExecutor:()=>pt,TokenExpiredException:()=>Ht,ValidationException:()=>Kt,WHERE_IN_CHUNK_SIZE:()=>ae,WorkerPool:()=>Ge,applyOperatorToMatch:()=>$r,applyRelationFilters:()=>Ot,applyWhereToKnex:()=>Bt,assertFieldOperatorValueIsClean:()=>no,buildMongoCharFoldMapJson:()=>ho,buildMongoFoldTextSearchJs:()=>fn,buildMongoSortSpec:()=>po,buildMongoSortSpecFromPlan:()=>gr,buildRelationSortSubquery:()=>On,buildRelationSubquery:()=>ss,buildSqlWherePartsFromFieldAst:()=>vr,buildWhereClause:()=>ut,camelToSnake:()=>mi,checkIfFilterContainsIsNull:()=>zi,chunkedFetch:()=>W,compileScriptSource:()=>ra,computeEngineTuning:()=>Gn,createEnfyraKernel:()=>yl,dslOpToCompareOp:()=>Qr,encodeMainThreadToIsolate:()=>ir,escapeSqlValue:()=>we,executeAggregationPipeline:()=>Fn,executeBatchFetches:()=>Mo,executeCountQueries:()=>Mn,executeMongoBatchFetches:()=>bn,expandFieldsMongo:()=>tt,expandFieldsToJoinsAndSelect:()=>Ro,expandFieldsToSelect:()=>Nn,getEffectiveCpuCount:()=>Vn,getEffectiveMemoryBytes:()=>or,getEngineTuning:()=>Br,getExecutableScript:()=>sa,getForeignKeyColumnName:()=>X,getIoAbortSignal:()=>Xn,getJunctionColumnNames:()=>pr,getJunctionTableName:()=>dr,getMetadataGetter:()=>Fr,getMongoInverseRelationForeignField:()=>H,getMongoMetadataGetter:()=>ko,getMongoStoredRelationField:()=>Z,getPrimaryKeyColumn:()=>te,getScriptLegacyField:()=>Zs,getShortFkConstraintName:()=>gi,getShortFkName:()=>yi,getShortIndexName:()=>bi,getShortPkName:()=>pi,hasLogicalOperators:()=>ct,isExecutableJavaScript:()=>na,isMongoInverseRelation:()=>ge,isScriptTable:()=>ea,normalizeAggregateQuery:()=>At,normalizeFlowStepScriptConfig:()=>la,normalizeMongoDocument:()=>se,normalizeMongoResults:()=>Rn,normalizeScriptLanguage:()=>ta,normalizeScriptPatch:()=>ia,normalizeScriptRecord:()=>oa,parseBatchFields:()=>nt,parseFields:()=>Vr,parseFilter:()=>Me,parseSortInput:()=>gs,perParentRun:()=>bs,quoteIdentifier:()=>I,quoteQualifiedIdentifier:()=>ze,renderFilterToKnex:()=>ue,resolveExecutableScript:()=>aa,resolveMongoJunctionInfo:()=>he,rewriteFilterDenyingFields:()=>ms,rewriteSortDroppingDenied:()=>ys,runWithIoAbortSignal:()=>Zn,scriptContractService:()=>$e,separateFilters:()=>Ae,snakeToCamel:()=>hi,throwUnsupportedFieldOperator:()=>Ze,validateDeepOptions:()=>rt,validateFilterShape:()=>De,whereToMongoFilter:()=>It});module.exports=Es(bl);var Or=3e4,gt=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t,r={}){let o=e.routeData.__codeBlocks||[];return o.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(o,e.routeData.context,t??Or,r)}async run(e,t,r=Or,o={}){return this.isolatedExecutorService.run(e,t,r,o)}};var Zo=Je(require("path"));var Be=class extends Error{constructor(t=0,r,o){let i=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${i}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={...o,timeoutMs:t,scriptId:r,outcome:o?.outcome??"timed_out",retryable:!1}}},He=class extends Error{constructor(t,r,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={...o,scriptId:r}}},z=class extends Error{constructor(t,r,o,i){if(!Number.isInteger(r)||r<400||r>599)throw new TypeError("Kernel exception statusCode must be an integer from 400 to 599");super(t);this.statusCode=r;this.errorCode=o;this.name=this.constructor.name,this.details=i}},Y=class extends z{constructor(e,t,r){super(e,t,`HTTP_${t}`,r)}},Wt=class extends z{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Kt=class extends z{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Ut=class extends z{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},Qt=class extends z{constructor(e,t,r){super(`${e} with ${t} '${r}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:r})}},zt=class extends z{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},Jt=class extends z{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},Ht=class extends z{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},Vt=class extends z{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},ht=class extends z{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},Gt=class extends z{constructor(e,t,r){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:r})}},Yt=class extends z{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},Xt=class extends z{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},Zt=class extends z{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},er=class extends z{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},tr=class extends z{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},rr=class extends z{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Pr=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t!==void 0&&console.error(this.format(t))}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}format(e){let t;try{typeof e=="string"?t=e:e instanceof Error?t=e.stack??e.message:t=JSON.stringify(e,(o,i)=>typeof i=="bigint"?i.toString():i)??String(e)}catch{try{t=String(e)}catch{t="[Unserializable value]"}}return this.context?`[${this.context}] ${t}`:t}};var Qn=new Set(["__proto__","prototype","constructor","caller","callee","arguments"]);function ie(n,e,t=!1){if(Qn.has(e))throw new Error(`Host capability property is forbidden: ${e}`);if((typeof n!="object"||n===null)&&typeof n!="function")return;let r=n,o=new Set;for(;r&&r!==Object.prototype&&r!==Function.prototype;){if(o.size>=64)throw new Error("Host capability prototype traversal limit exceeded");if(o.has(r))throw new Error("Cyclic host capability prototype");if(o.add(r),Object.prototype.hasOwnProperty.call(r,e))return n[e];r=Object.getPrototypeOf(r)}if(t&&!Object.prototype.hasOwnProperty.call(Object.prototype,e)&&!Object.prototype.hasOwnProperty.call(Function.prototype,e)&&e in n)return n[e]}var Oo=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$streams","$debug"]);function Jn(n){let e={$body:n.$body,$query:n.$query,$params:n.$params,$user:n.$user,$share:n.$share,$data:n.$data,$api:{request:n.$api?.request},$uploadedFile:n.$uploadedFile,$req:zn(n.$req)};for(let r of Object.keys(n)){if(!r.startsWith("$")||r in e||Oo.has(r))continue;let o=zn(n[r]);o!==void 0&&(e[r]=o)}let t=n.$flow;if(t!=null)try{e.$flow=zn(t)??{}}catch{e.$flow={}}return e}function zn(n){if(typeof n!="function")try{return JSON.parse(JSON.stringify(n,(e,t)=>{if(typeof t=="bigint")return String(t);if(typeof t!="function")return t}))}catch{return}}function nr(n,e){if(e){for(let t of["$body","$query","$params","$data","$error","$statusCode","$share"])Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=e[t]);if(e.$api&&typeof e.$api=="object"&&n.$api&&typeof n.$api=="object"&&(Object.prototype.hasOwnProperty.call(e.$api,"error")&&(n.$api.error=e.$api.error),Object.prototype.hasOwnProperty.call(e.$api,"response")&&(n.$api.response=e.$api.response)),e.$flow!==void 0&&e.$flow!==null&&typeof e.$flow=="object"&&n.$flow!==null&&n.$flow!==void 0&&typeof n.$flow=="object")for(let[t,r]of Object.entries(e.$flow))Qn.has(t)||Object.defineProperty(n.$flow,t,{value:r,enumerable:!0,configurable:!0,writable:!0});for(let[t,r]of Object.entries(e))t.startsWith("$")&&(t==="$body"||t==="$query"||t==="$params"||t==="$data"||t==="$error"||t==="$statusCode"||t==="$share"||t==="$api"||t==="$flow"||Oo.has(t)||t==="$env"||(n[t]=r));delete n.$pkgs}}var yt=Je(require("os"));var jo=Je(require("fs")),jr=require("path");function mt(n){try{return jo.readFileSync(n,"utf8").trim()}catch{return""}}function Po(n){return n.replace(/\\([0-7]{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function Bo(n,e){let t=new Set([e?"/sys/fs/cgroup":`/sys/fs/cgroup/${n}`]),r=mt("/proc/self/cgroup").split(`
|
|
2
2
|
`);for(let o of mt("/proc/self/mountinfo").split(`
|
|
3
|
-
`)){let[i,s]=o.split(" - ");if(!s)continue;let a=s.split(" ");if(a[0]!==(e?"cgroup2":"cgroup")||!e&&!a[2]?.split(",").includes(n))continue;let c=i.split(" "),u=Po(c[3]??""),l=Po(c[4]??"");if(!(!u.startsWith("/")||!l.startsWith("/")))for(let f of r){let d=/^\d+:([^:]*):(\/.*)$/.exec(f);if(!d||(e?d[1]!=="":!d[1].split(",").includes(n)))continue;let p=jr.posix.normalize(d[2]);if(u!=="/"&&p!==u&&!p.startsWith(`${u}/`))continue;let g=u==="/"?p.slice(1):p.slice(u.length+1),h=jr.posix.join(l,g);for(;(h===l||h.startsWith(`${l}/`))&&(t.add(h),h!==l);)h=jr.posix.dirname(h)}}return t}function Do(n){let e=n;for(let t of[!0,!1])for(let r of Bo("memory",t)){let o=Number(mt(`${r}/${t?"memory.max":"memory.limit_in_bytes"}`));Number.isFinite(o)&&o>0&&(e=Math.min(e,o))}return e}function Lo(n){let e=n;for(let t of[!0,!1])for(let r of Bo("cpu",t)){let[o,i]=t?mt(`${r}/cpu.max`).split(/\s+/).map(Number):[Number(mt(`${r}/cpu.cfs_quota_us`)),Number(mt(`${r}/cpu.cfs_period_us`))];o>0&&i>0&&Number.isFinite(o)&&Number.isFinite(i)&&(e=Math.min(e,Math.max(1,Math.ceil(o/i))))}return e}function or(){return Do(yt.totalmem())}function Vn(){return Lo(yt.availableParallelism?.()||yt.cpus()?.length||1)}var xs=.25,Hn=128,Cs=2,Rs=4,Fs=6,Is=8,vs=2048,Ms=40,As=128,Ns=32;function Os(n){let e=Math.trunc(Number(n));if(!(!Number.isFinite(e)||e<1))return Math.min(Hn,e)}function Ps(n){let e=Math.trunc(Number(n));return!Number.isFinite(e)||e<1?Fs:Math.min(Is,e)}function qo(n){return 2**Math.ceil(Math.log2(Math.max(1,n)))}function Gn(n){let e=Math.max(1,Math.trunc(n.logicalCpuCount)||1),t=Math.max(1,n.totalMemoryBytes/(1024*1024)),r=Math.min(As,Math.max(Ms,Math.round(t/Ns))),o=t*xs,i=Math.max(1,Math.floor(o/r)),s=Math.max(1,Math.min(e,2,i)),a=Math.max(1,Math.floor(o/(s*r))),c=Math.min(Hn,qo(e*Cs)),u=Math.min(Hn,qo(e*Rs)),l=Math.max(c,Math.min(u,a)),f=Os(n.maxLanesPerRunner)??l,d=t<vs?1:f,p=Math.max(1,Math.min(d,a)),g=Ps(n.tasksPerIsolate),h=p*g;return{maxConcurrentWorkers:s,isolateMemoryLimitMb:r,tasksPerWorkerCap:h,isolatePoolSize:p,tasksPerIsolate:g}}function Br(){return Gn({logicalCpuCount:Vn(),totalMemoryBytes:or()})}var Wo={400:"Bad request",401:"Authentication required",403:"Insufficient permissions",404:"Not found",409:"Conflict",422:"Validation failed",429:"Rate limit exceeded",500:"Internal server error",503:"Service unavailable"},Ve=class{static createException(e,t,r,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new Y(r||"Error",t||500,i);case"$throw.businessLogic":return new Wt(r||"Bad request",i);case"$throw.validation":return new Kt(r||"Validation failed",i);case"$throw.notFound":return new Ut(i?.resource||r||"Resource",i?.identifier);case"$throw.duplicate":return new Qt(i?.resource||r||"Resource",i?.field||"field",i?.value??"value");case"$throw.unauthorized":return new zt(r||"Unauthorized");case"$throw.forbidden":return new Jt(r||"Forbidden");case"$throw.tokenExpired":return new Ht;case"$throw.invalidToken":return new Vt;case"$throw.database":return new ht(r||"Database error",i);case"$throw.dbQuery":return new ht(r||"Query error",i);case"$throw.externalService":return new Gt(r||"Service",r||"Error",i);case"$throw.serviceUnavailable":return new Yt(r||"Service");case"$throw.rateLimit":return new Y(r||"Rate limit exceeded",429,i);case"$throw.scriptError":return new He(r||"Script error",o,i);case"$throw.scriptTimeout":return new Be(i?.timeout||5e3,o);case"$throw.schema":return new Xt(r||"Schema error",i);case"$throw.config":return new Zt(r||"Configuration error",i);case"$throw.fileUpload":return new er(r||"File upload error",i);case"$throw.fileNotFound":return new tr(r||"File not found");case"$throw.fileSizeExceeded":return new rr(i?.maxSize??"unknown",i?.actualSize??"unknown");case"$throw.400":return new Y(r||"Bad request",400,i);case"$throw.401":return new Y(r||"Authentication required",401,i);case"$throw.403":return new Y(r||"Insufficient permissions",403,i);case"$throw.404":return new Y(r||"Not found",404,i);case"$throw.409":return new Y(r||"Conflict",409,i);case"$throw.422":return new Y(r||"Validation failed",422,i);case"$throw.429":return new Y(r||"Rate limit exceeded",429,i);case"$throw.500":return new Y(r||"Internal server error",500,i);case"$throw.503":return new Y(r||"Service unavailable",503,i);default:return Number.isInteger(t)&&t>=400&&t<=599?new Y(r||Wo[t]||"Request failed",t,i):new He(r||"Unknown error",o,i)}return Number.isInteger(t)&&t>=400&&t<=599?new Y(r||Wo[t]||"Request failed",t,i):new He(r||"Unknown error",o,i)}};function Ko(n){return Math.min(2147483647,n+Math.ceil(n*.15))}function Yn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0})}function Ie(n,e,t){if(!Object.prototype.hasOwnProperty.call(n,e))return!1;let r=new Set(t);return Object.keys(n).every(o=>r.has(o))}var Uo=Object.freeze({Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,...typeof globalThis.Float16Array>"u"?{}:{Float16Array:globalThis.Float16Array},...typeof BigInt64Array>"u"?{}:{BigInt64Array},...typeof BigUint64Array>"u"?{}:{BigUint64Array}});function fe(n,e){if(!n||typeof n!="object")return n;let t=n;if(Ie(t,"__plainObject",["__plainObject"])){let o={};for(let[i,s]of Object.entries(t.__plainObject||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__nullPrototype",["__nullPrototype"])){let o=Object.create(null);for(let[i,s]of Object.entries(t.__nullPrototype||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__e",["__e"])&&t.__e==="u")return;if(e&&Ie(t,"__fnRef",["__fnRef"])&&typeof t.__fnRef=="string")return e(t.__fnRef);if(Ie(t,"__number",["__number"])){if(t.__number==="nan")return Number.NaN;if(t.__number==="infinity")return Number.POSITIVE_INFINITY;if(t.__number==="-infinity")return Number.NEGATIVE_INFINITY;if(t.__number==="-0")return-0;throw new TypeError(`Unsupported executor number: ${t.__number}`)}if(Ie(t,"__bigint",["__bigint"]))return BigInt(t.__bigint);if(Ie(t,"__map",["__map"]))return new Map((t.__map||[]).map(([o,i])=>[fe(o,e),fe(i,e)]));if(Ie(t,"__arrayBuffer",["__arrayBuffer"]))return Uint8Array.from(t.__arrayBuffer||[]).buffer;if(Ie(t,"__typedArray",["__typedArray","bytes","data"])){let o=Uint8Array.from(t.bytes||t.data||[]);if(t.__typedArray==="DataView")return new DataView(o.buffer);let i=Uo[String(t.__typedArray)];if(!Object.prototype.hasOwnProperty.call(Uo,t.__typedArray)||typeof i!="function")throw new TypeError(`Unsupported executor typed array: ${t.__typedArray}`);return new i(o.buffer)}if(Array.isArray(n))return n.map(o=>fe(o,e));let r={};for(let[o,i]of Object.entries(t))Yn(r,o,fe(i,e));return r}function ve(n){try{if(n instanceof Error)return n}catch{}let e="Unknown error";try{n===void 0?e="Operation rejected with undefined":n===null?e="Operation rejected with null":e=String(n)}catch{}return new Error(e)}function Qo(n){let e=new WeakSet;try{return JSON.stringify(n,(t,r)=>{if(typeof r=="bigint")return r.toString();if(!(typeof r=="function"||typeof r=="symbol")){if(r&&typeof r=="object"){if(e.has(r))return"[Circular]";e.add(r)}return r}})}catch{let t="Host capability call failed",r;try{t=String(n.message||t)}catch{}try{typeof n.code=="string"&&(r=n.code)}catch{}return JSON.stringify({__userThrow:!0,message:t,code:r})}}function ir(n){if(n===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:n},(e,t)=>typeof t=="bigint"?{__bigint:t.toString()}:t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var zo=require("async_hooks"),Dr=new zo.AsyncLocalStorage;function Xn(){return Dr.getStore()}function Zn(n,e){return Dr.run(n,e)}var Lr=class{constructor(e,t){this.taskAbortSignals=e;this.taskDeadlines=t;this.runtimeCallbackCounter=0}postAbortedCallError(e,t){e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})}).catch(()=>{})}async handleIoCall(e,t,r,o){if(o?.aborted){this.postAbortedCallError(t,r);return}try{let i=await(o?Dr.run(o,e):e());if(o?.aborted){this.postAbortedCallError(t,r);return}await t.postMessage({type:"callResult",callId:r,result:ir(i)})}catch(i){if(o?.aborted){this.postAbortedCallError(t,r);return}let s=ve(i),a={__userThrow:!0,message:s.message,statusCode:s.statusCode,code:s.errorCode??s.code,errorPath:s.errorPath,details:s.details,messages:s.messages};await t.postMessage({type:"callError",callId:r,error:Qo(a)}).catch(()=>{})}}parseExecutorArgs(e,t,r){let o=JSON.parse(e||"[]");return fe(o,t&&r?s=>(...a)=>this.invokeRuntimeCallback(t,r,s,a):void 0)}async execRepoCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=e.access==="secure"?ie(t?.$repos,"secure",!0):t?.$repos,i=ie(o,String(e.table),!0),s=ie(i,String(e.method));if(!i||typeof s!="function"){let a=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${a}${e.table}.${e.method}`)}return s.apply(i,r)}async execTransactionCall(e,t,r){let i=this.parseExecutorArgs(e.argsJson,r,e.id)[0];if(typeof i!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,i)}async execHelpersCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=String(e.name).split("."),i=t?.$helpers,s=i;for(let a of o)i=s,s=ie(s,a);if(typeof s!="function")throw new Error(`Helper not found: ${e.name}`);return s.apply(i,r)}async execSocketCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$socket,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i.apply(o,r)}async execCacheCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$cache,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Cache not found: ${e.method}`);return i.apply(o,r)}async execStorageCall(e,t,r){let o=this.parseStorageArgs(e.argsJson,r,e.id),i=t?.$storage,s=ie(i,String(e.method));if(typeof s!="function")throw new Error(`Storage method not found: ${e.method}`);return s.apply(i,o)}parseStorageArgs(e,t,r){return this.parseExecutorArgs(e,t,r)}invokeRuntimeCallback(e,t,r,o){let i=`rtcb_${++this.runtimeCallbackCounter}`,s=this.taskAbortSignals.get(t),a=this.taskDeadlines.get(t)??Date.now()+3e4,c=Math.max(1,a-Date.now())+500;return new Promise((u,l)=>{let f=!1,d=w=>{f||(f=!0,m(),w())},p=setTimeout(()=>{d(()=>l(new Error(`Runtime callback timed out: ${r}`)))},c),g=()=>{d(()=>l(new Error("Runtime callback was cancelled")))},h=()=>{d(()=>l(new Error("Runtime callback worker exited")))},y=w=>{if(!(w?.type!=="runtimeCallbackResult"||w.callId!==i)){if(w.error){let _=new Error(String(w.error));try{let $=JSON.parse(String(w.error));$?.__userThrow&&(_.message=String($.message??_.message),_.statusCode=$.statusCode,_.code=$.code??(Number.isInteger($.statusCode)?`HTTP_${$.statusCode}`:void 0),_.errorCode=_.code,_.errorPath=$.errorPath,_.details=$.details,_.messages=$.messages)}catch{}d(()=>l(_));return}d(()=>u(w.value))}},m=()=>{clearTimeout(p),e.off("message",y),e.off("exit",h),s?.removeEventListener("abort",g)};if(e.on("message",y),e.on("exit",h),s?.addEventListener("abort",g,{once:!0}),s?.aborted){g();return}try{e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:r,argsJson:JSON.stringify(o)}).catch(w=>d(()=>l(w)))}catch(w){d(()=>l(w))}})}async execDispatchCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=ie(t,"$trigger");if(typeof o!="function")throw new Error("$trigger is not available");return o.apply(t,r)}};var Ho=require("stream");var eo=32*1024*1024,Jo=Math.ceil(eo/3)*4,qr=class{constructor(e,t){this.cancelTask=e;this.parseExecutorArgs=t;this.responseStreams=new Map}async execResCall(e,t){if(e.method==="json"){let s=ie(t?.$res,"__enfyraJson");if(typeof s!="function")throw new Error("Native JSON response is not available");return await s.call(t.$res,String(e.jsonText),e.options||{})}if(e.method==="bytes"){let s=ie(t?.$res,"__enfyraBytes");if(typeof s!="function")throw new Error("Native binary response is not available");let a=String(e.bytes||"");if(a.length>Jo)throw new Error("Native binary response exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Native binary response exceeded 32 MiB");return await s.call(t.$res,c,e.options||{})}if(e.method==="streamStart"){if(this.responseStreams.has(e.id))throw new Error(`Response stream already exists: ${e.id}`);let a=JSON.parse(e.argsJson||"[]")[1]||{},c=ie(t?.$res,"stream");if(typeof c!="function")throw new Error("Response method not found: stream");let u=new Ho.PassThrough;u.on("error",()=>{});let l={stream:u};this.responseStreams.set(e.id,l);let f=t?.$res;if(f&&typeof f.once=="function"){let d=()=>{f.writableEnded!==!0&&this.cancelTask(e.id)};f.once("close",d),l.closeCleanup=()=>{typeof f.off=="function"?f.off("close",d):typeof f.removeListener=="function"&&f.removeListener("close",d)}}try{let d=c.call(t.$res,u,a);return d&&typeof d.then=="function"&&(l.completion=Promise.resolve(d).then(()=>{},p=>{let g=ve(p);throw this.responseStreams.get(e.id)===l&&(this.cleanupResponseStream(e.id,g),this.cancelTask(e.id)),g}),l.completion.catch(()=>{})),!0}catch(d){let p=ve(d);throw this.cleanupResponseStream(e.id,p),p}}if(e.method==="streamChunk"){let s=this.responseStreams.get(e.id);if(!s)throw new Error(`Response stream not found: ${e.id}`);let a=String(e.chunk||"");if(a.length>Jo)throw new Error("Response stream chunk exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Response stream chunk exceeded 32 MiB");if(s.stream.destroyed)throw new Error("Response stream closed before drain");return s.stream.write(c)||await new Promise((u,l)=>{let f=()=>{g(),u()},d=h=>{g(),l(h)},p=()=>{g(),l(new Error("Response stream closed before drain"))},g=()=>{s.stream.off("drain",f),s.stream.off("error",d),s.stream.off("close",p)};s.stream.once("drain",f),s.stream.once("error",d),s.stream.once("close",p)}),!0}if(e.method==="streamEnd"){let s=this.responseStreams.get(e.id);if(s){s.stream.end();try{await s.completion}finally{this.responseStreams.get(e.id)===s&&(s.closeCleanup?.(),this.responseStreams.delete(e.id))}}return!0}if(e.method==="streamError"){let s=this.responseStreams.get(e.id);if(s){s.closeCleanup?.();let a=e.error?.message||"Response stream failed";s.stream.destroy(new Error(a)),this.responseStreams.delete(e.id)}return!0}let r=this.parseExecutorArgs(e.argsJson),o=t?.$res,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(o,r)}cleanupResponseStream(e,t){let r=this.responseStreams.get(e);r&&(this.responseStreams.delete(e),r.closeCleanup?.(),t?r.stream.destroy(t):r.stream.end())}};var Vo=require("child_process"),Go=require("string_decoder"),Bs=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function Ds(){let n={};for(let e of Bs){let t=process.env[e];t!==void 0&&(n[e]=t)}return n}var Wr=class{constructor(e){this.terminated=!1;this.stderrTail="";this.stderrDecoder=new Go.StringDecoder("utf8");this.child=(0,Vo.fork)(e,[],{stdio:["ignore","ignore","pipe","ipc"],env:Ds(),execArgv:[],serialization:"advanced"}),this.child.on("error",t=>{this.stderrTail=(this.stderrTail+t.message).slice(-8192)}),this.child.stderr?.on("data",t=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.write(t)).slice(-8192)}),this.child.stderr?.on("end",()=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.end()).slice(-8192)})}get stderr(){return this.stderrTail}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){return this.child.connected?new Promise((t,r)=>{try{this.child.send(e,o=>{o?r(o):t()})}catch(o){r(o)}}):Promise.reject(new Error("Executor runner IPC is closed"))}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var Ge=class{constructor(e,t,r,o,i,s,a,c=6e4){this.scriptPath=i;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=r,this.tasksCap=o,this.drainTimeoutMs=c;for(let u=0;u<e;u++)this.spawnEntry()}getEntries(){return this.entries}clearDrainTimeout(e){e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0)}reportObserverError(e,t){let r=t instanceof Error?t.message:String(t);console.error(`[executor-pool] ${e}: ${r}`)}spawnEntry(){let e=new Wr(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",r=>{if(r&&r.type==="workerError"){this.reportObserverError(`[executor-worker ${r.source??"error"}]`,r.message);return}let o=t.tasks.get(r.id);if(o)if(r.type==="taskReleased")o.onRelease?.();else if(r.type==="taskLane")o.onLane?.(r.laneKey);else if(r.type==="taskFailure")o.onFailure?.(r.error);else if(r.type==="result"||r.type==="taskCancelled"){typeof r.heapRatio=="number"&&(t.lastHeapRatio=r.heapRatio),typeof r.runnerRssBytes=="number"&&(t.lastRssBytes=r.runnerRssBytes),r.contextStats&&(t.contextStats=r.contextStats);let i=r;r.type==="taskCancelled"&&(i={type:"result",id:r.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}});try{o.onResult(i)}catch(s){this.reportObserverError("task result callback failed",s)}!t.draining&&typeof r.heapRatio=="number"&&r.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(r.heapRatio*100)}%`)}else o.onIoCall(r)}),e.on("exit",(r,o)=>{let i=t.draining,s=this.destroying;t.draining=!0;let a={entryId:t.id,pid:t.worker.pid,exitCode:r,exitSignal:o??null,lastError:t.lastError||t.worker.stderr||void 0,terminationReason:t.terminationReason,lastHeapRatio:t.lastHeapRatio,lastRssBytes:t.lastRssBytes,activeTasks:[...t.tasks.values()].map(l=>l.diagnostics)};this.clearDrainTimeout(t);let c="Worker crashed";s?c="Worker terminated":t.lastError&&(c=`Worker crashed: ${t.lastError}`);for(let[,l]of t.tasks){l.abortController.abort();try{l.onResult({type:"result",success:!1,error:{message:c,code:s?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:s?void 0:{outcome:"unknown_outcome",retryable:!1}}})}catch(f){this.reportObserverError("worker-exit task callback failed",f)}}t.tasks.clear();let u=this.entries.indexOf(t);if(u!==-1&&this.entries.splice(u,1),(!i||t.replaceOnExit)&&!s){try{this.onCrash?.(a)}catch(f){this.reportObserverError("worker crash observer failed",f)}this.entries.filter(f=>!f.draining).length<this.max&&this.spawnEntry()}this.drainWaiting()}),e.on("error",r=>{t.lastError=r.message}),this.entries.push(t),t}rotateEntry(e,t){if(this.destroying||e.draining)return;e.draining=!0;let r=Date.now()-e.spawnedAt;try{this.onRotate?.({reason:t,ageMs:r})}catch(o){this.reportObserverError("worker rotation observer failed",o)}if(this.spawnEntry(),this.drainWaiting(),e.tasks.size===0&&e.reservations===0){this.clearDrainTimeout(e),e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,this.abortEntryTasks(e),e.worker.terminate()},this.drainTimeoutMs)}abortEntryTasks(e){for(let t of e.tasks.values())t.abortController.abort()}isMemoryAvailable(){let e=Date.now();if(e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs){let t=this.entries.reduce((r,o)=>r+(o.lastRssBytes??0),0);this.cachedMemoryOk=(process.memoryUsage().rss+t)/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e}return this.cachedMemoryOk}hasActiveWork(){return this.entries.some(e=>e.tasks.size>0||e.reservations>0)}canDispatch(){return!this.hasActiveWork()||this.isMemoryAvailable()}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let r=t.tasks.size+t.reservations;r<this.tasksCap&&(!e||r<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(e){if(this.destroying)return Promise.reject(new Error("Executor worker pool is shutting down"));if(e?.aborted)return Promise.reject(new Error("Execution aborted before dispatch"));let t=this.findLeastBusy();return t&&this.canDispatch()?(t.reservations++,Promise.resolve(t)):new Promise((r,o)=>{let i={resolve:r,reject:o,signal:e};e&&(i.onAbort=()=>{let s=this.waiting.indexOf(i);s!==-1&&this.waiting.splice(s,1),o(new Error("Execution aborted before dispatch"))},e.addEventListener("abort",i.onAbort,{once:!0})),this.waiting.push(i)})}registerTask(e,t,r){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,r)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(!e||!this.canDispatch())break;let t=this.waiting.shift();if(t.signal?.aborted){t.reject(new Error("Execution aborted before dispatch"));continue}t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),e.reservations++,t.resolve(e)}}terminateEntry(e,t="host_requested"){e.draining&&e.terminationReason||(e.draining=!0,e.replaceOnExit=!0,e.terminationReason=t,this.clearDrainTimeout(e),this.abortEntryTasks(e),e.worker.terminate())}resize(e){this.max=Math.max(1,e);let t=this.entries.filter(i=>!i.draining);for(;t.length<this.max;)t.push(this.spawnEntry());let r=t.length-this.max;if(r<=0){this.drainWaiting();return}let o=t.sort((i,s)=>i.tasks.size+i.reservations-(s.tasks.size+s.reservations)).slice(0,r);for(let i of o)i.draining=!0;this.drainWaiting();for(let i of o)i.tasks.size===0&&i.reservations===0?(this.clearDrainTimeout(i),i.worker.terminate()):(this.clearDrainTimeout(i),i.drainTimeout=setTimeout(()=>{i.drainTimeout=void 0,this.abortEntryTasks(i),i.worker.terminate()},this.drainTimeoutMs))}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,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,lastRssBytes:e.lastRssBytes??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;let e=new Error("Executor worker pool was destroyed");for(let t of this.waiting.splice(0))t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),t.reject(e);for(let t of this.entries)t.draining=!0,t.terminationReason="pool_destroyed",this.clearDrainTimeout(t),this.abortEntryTasks(t),t.worker.terminate();this.entries.length=0}};var Gs=Zo.join(__dirname,"execution/worker.js"),Ys=3e4,Xs=2147483647;function Xo(n){let e=Number(n);return Number.isFinite(e)?Math.max(1,Math.min(Xs,Math.trunc(e))):Ys}var bt=class n{constructor(e){this.logger=new Pr(n.name);this.effectiveMemory=or();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.taskCancellers=new Map;this.taskAbortSignals=new Map;this.taskDeadlines=new Map;this.taskDurationsMs=[];this.queueWaitDurationsMs=[];this.hostIo=new Lr(this.taskAbortSignals,this.taskDeadlines);this.responseBridge=new qr(e=>this.cancelTask(e),e=>this.hostIo.parseExecutorArgs(e));this.packageCacheService=e.packageCacheService,this.onExecutionFinished=e.onExecutionFinished,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??Br(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Ge(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Gs,t=>{this.crashesTotal++;let r={event:"executor_worker_crashed",occurredAt:new Date().toISOString(),...t};this.logger.warn(r);try{e.onExecutorWorkerCrash?.(r)}catch(o){this.logger.warn({event:"executor_worker_crash_report_failed",error:o instanceof Error?o.message:String(o)})}},({reason:t,ageMs:r})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(r/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerIsolate} tasks/isolate, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let e=this.pool.getEntries().reduce((g,h)=>g+(h.lastRssBytes??0),0),r=(process.memoryUsage().rss+e)/this.effectiveMemory,o=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),s=Number(o-this.prevCpuTime)/1e3,a=s>0?(i.user+i.system)/s:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=o;let c=this.pool.getMax(),u=this.pool.getWaitingCount(),l=r>.85||a>.7,f=r<.7&&a<.5,d=u>0,p=c;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,c-1))):f&&d?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,c+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==c&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${c} -> ${p} (rss=${Math.round(r*100)}% cpu=${Math.round(a*100)}% queue=${u})`))}spawnAndExecute(e,t,r,o,i){return(async()=>{let s=Date.now(),a;try{a=await this.pool.dispatch(i)}catch(l){if(i?.aborted){let f=new Error("Execution aborted before dispatch");throw f.code="ERR_EXECUTION_ABORTED",f.isAbort=!0,f}throw l}if(this.recordQueueWait(Date.now()-s),i?.aborted){this.pool.releaseReservation(a);let l=new Error("Execution aborted after client disconnect");return l.code="ERR_EXECUTION_ABORTED",l.isAbort=!0,Promise.reject(l)}let c=`t_${++this.taskCounter}`,u=Date.now();return new Promise((l,f)=>{let d=!1,p=new AbortController;this.taskAbortSignals.set(c,p.signal);let g=Ko(o);this.taskDeadlines.set(c,u+g);let h=!1,y,m,w=()=>{let E=new Error("Execution aborted after client disconnect");return E.code="ERR_EXECUTION_ABORTED",E.isAbort=!0,E},_=()=>{let E=new Error(`Script execution timed out after ${o}ms`);return E.code="ERR_SCRIPT_EXECUTION_TIMEOUT",E.isTimeout=!0,E},$,k,C=!1,x=E=>{if(!(d||h)){h=!0,y=E,p.abort(),this.responseBridge.cleanupResponseStream(c,E);try{a.worker.postMessage({type:"cancelTask",id:c}).catch(()=>{})}catch{}$=setTimeout(()=>{d||(d=!0,k&&clearTimeout(k),M(),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),this.recordTaskDuration(Date.now()-u),this.pool.terminateEntry(a,E.isTimeout?"timeout_cancel_grace":E.isAbort?"client_abort_cancel_grace":"failure_cancel_grace"),this.pool.unregisterTask(a,c),this.taskErrorTotal++,E.details={...E.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},f(E))},1e4),$.unref?.()}},v=()=>x(w());this.taskCancellers.set(c,v);let R=()=>v(),M=()=>{i?.removeEventListener("abort",R)};i&&(i.addEventListener("abort",R,{once:!0}),i.aborted&&v());let N=()=>{k&&clearTimeout(k),$&&clearTimeout($),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),M(),this.responseBridge.cleanupResponseStream(c),this.recordTaskDuration(Date.now()-u)},j=()=>{N(),this.pool.unregisterTask(a,c)},O=25,P=()=>{d||(this.taskTimeoutTotal++,x(_()))},G=u+g+[...a.tasks.keys()].reduce((E,S)=>{if(S===c)return E;let T=this.taskDeadlines.get(S);return E+(T===void 0?0:Math.max(0,T-u))},0),re=()=>{if(!(d||h)){if(!C&&Date.now()>=G){this.taskTimeoutTotal++,x(_());return}if(!C){k=setTimeout(re,O),k.unref?.();return}this.taskDeadlines.set(c,Date.now()+g),k=setTimeout(P,g),k.unref?.()}};k=setTimeout(re,O),k.unref?.(),this.pool.registerTask(a,c,{abortController:p,onLane:()=>{d||h||C||(C=!0,k&&clearTimeout(k),re())},diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),onFailure:E=>{if(d||h)return;m=E;let S=new Error(E.message);S.code=E.code,S.errorCode=E.code,S.statusCode=E.statusCode,S.errorPath=E.errorPath,S.details=E.details,E.stack&&(S.stack=E.stack),S.isTimeout=E.code==="ERR_SCRIPT_EXECUTION_TIMEOUT",S.isTimeout&&!h&&!d&&this.taskTimeoutTotal++,x(S)},onResult:E=>{if(!d){d=!0;try{this.onExecutionFinished?.({diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),logs:Array.isArray(E.diagnosticLogs?.logs)?E.diagnosticLogs.logs:Array.isArray(E.ctxChanges?.$share?.$logs)?E.ctxChanges.$share.$logs:[],logsTruncated:E.diagnosticLogs?.truncated===!0||E.ctxChanges?.$share?.$logsTruncated===!0,statusCode:E.error?.statusCode??E.ctxChanges?.$statusCode,error:m??(E.success||h?void 0:E.error)})}catch(S){this.logger.error("Executor diagnostic callback failed",S)}if(E.taskCancelled===!0&&this.pool.unregisterTask(a,c),N(),h){this.taskErrorTotal++;try{E.ctxChanges&&y&&(y.ctxChanges=fe(E.ctxChanges)),f(y??w())}catch(S){f(ve(S))}return}if(E.success)try{let S={value:fe(E.value),valueAbsent:E.valueAbsent===!0,ctxChanges:fe(E.ctxChanges)};E.shortCircuit&&(S.shortCircuit=!0),this.taskDoneTotal++,l(S)}catch(S){p.abort();let T=ve(S);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}else try{let S=new Error(E.error?.message||"Handler execution failed");S.statusCode=E.error?.statusCode,S.code=E.error?.code,S.errorCode=E.error?.code,S.details=E.error?.details,E.error?.stack&&(S.stack=E.error.stack),E.ctxChanges&&(S.ctxChanges=fe(E.ctxChanges)),this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,S),f(S)}catch(S){p.abort();let T=ve(S);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}}},onRelease:()=>{this.pool.unregisterTask(a,c)},onIoCall:E=>{if(d||E.type==="executionError")return;let S=p.signal;E.type==="repoCall"?this.hostIo.handleIoCall(()=>this.hostIo.execRepoCall(E,r),a.worker,E.callId,S):E.type==="transactionCall"?this.hostIo.handleIoCall(()=>this.hostIo.execTransactionCall(E,r,a.worker),a.worker,E.callId,S):E.type==="helpersCall"?this.hostIo.handleIoCall(()=>this.hostIo.execHelpersCall(E,r),a.worker,E.callId,S):E.type==="socketCall"?this.hostIo.handleIoCall(()=>this.hostIo.execSocketCall(E,r),a.worker,E.callId,S):E.type==="cacheCall"?this.hostIo.handleIoCall(()=>this.hostIo.execCacheCall(E,r),a.worker,E.callId,S):E.type==="storageCall"?this.hostIo.handleIoCall(()=>this.hostIo.execStorageCall(E,r,a.worker),a.worker,E.callId,S):E.type==="dispatchCall"?this.hostIo.handleIoCall(()=>this.hostIo.execDispatchCall(E,r),a.worker,E.callId,S):E.type==="resCall"&&this.hostIo.handleIoCall(()=>this.responseBridge.execResCall(E,r),a.worker,E.callId,S)}}),a.worker.postMessage({type:e,id:c,...t}).then(()=>{i?.aborted&&v()}).catch(E=>{d||(d=!0,p.abort(),j(),this.taskErrorTotal++,f(E))})})})()}cancelTask(e){this.taskCancellers.get(e)?.()}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,scriptId:e.scriptId,type:e.type}}createWorkerTaskDiagnostics(e,t,r,o){let i=r?.$api?.request?.correlationId,s=Array.isArray(t.codeBlocks)?t.codeBlocks.map(a=>({type:a?.type==="preHook"||a?.type==="postHook"||a?.type==="handler"?a.type:"run",...a?.scriptId!==void 0&&a?.scriptId!==null?{scriptId:String(a.scriptId)}:{}})):[{type:typeof t.sourceKind=="string"?t.sourceKind:"run",...t.scriptId==null?{}:{scriptId:String(t.scriptId)}}];return{...typeof i=="string"&&i?{correlationId:i}:{},timeoutMs:o,isolateMemoryLimitMb:Number(t.memoryLimitMb||0),isolatePoolSize:Number(t.isolatePoolSize||0),tasksPerIsolate:Number(t.tasksPerIsolate||0),scriptBlocks:s}}async run(e,t,r,o={}){let i=Xo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let l={code:e,scriptId:o.scriptId,sourceKind:o.sourceKind,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("execute",l,t,i)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,e,f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error",e,f.details||{})}return nr(t,u.ctxChanges||{}),u.valueAbsent?void 0:u.value}async runBatch(e,t,r,o={}){let i=Xo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let f={codeBlocks:e.map(d=>this.toWorkerCodeBlock(d)),pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("executeBatch",f,t,i,o.signal)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,"(batch execution)",f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error","(batch execution)",f.details||{})}return nr(t,u.ctxChanges||{}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((i,s)=>i-s),o=Math.min(r.length-1,Math.max(0,Math.ceil(t/100*r.length)-1));return r[o]}resetLatencyMetrics(){this.taskDurationsMs.length=0,this.queueWaitDurationsMs.length=0}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,r=t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,o=this.queueWaitDurationsMs,i=o.length===0?0:o.reduce((s,a)=>s+a,0)/o.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:r,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),avgQueueWaitMs:i,p95QueueWaitMs:this.percentile(o,95),p99QueueWaitMs:this.percentile(o,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var Ye=Je(require("typescript")),Kr={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Zs(n){return $e.getLegacyField(n)}function ea(n){return $e.isScriptTable(n)}function ta(n){return $e.normalizeLanguage(n)}var Ur=class{getLegacyField(e){return Object.prototype.hasOwnProperty.call(Kr,e)?Kr[e]:void 0}isScriptTable(e){return Object.prototype.hasOwnProperty.call(Kr,e)}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let r=String(e),i=this.normalizeLanguage(t)==="javascript"?r:this.transpileTypeScript(r);return this.assertExecutableJavaScript(i),i}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let r={...t},o=this.getLegacyField(e);return o&&(r.sourceCode===void 0||r.sourceCode===null||r.sourceCode==="")&&r[o]!==void 0&&(r.sourceCode=r[o]),r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage),o&&o in r&&delete r[o],r}normalizePatch(e,t,r){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode"),s=o?Object.prototype.hasOwnProperty.call(t,o):!1,a=i||s,c=Object.prototype.hasOwnProperty.call(t,"scriptLanguage"),u={...t};if(!a&&!c)return delete u.compiledCode,u;if(!a&&!r)throw new Error("Existing script data is required when changing scriptLanguage.");let l;i?l=t.sourceCode:s&&o?l=t[o]:(l=r?.sourceCode,l===void 0&&o&&r&&(l=r[o]));let f=c?t.scriptLanguage:r?.scriptLanguage;return a&&(u.sourceCode=l??null),u.scriptLanguage=this.normalizeLanguage(f),u.compiledCode=this.compileSource(l,u.scriptLanguage),o&&o in u&&delete u[o],u}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let r=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==e.compiledCode}}let t=Object.values(Kr).filter(r=>r!=="").map(r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:void 0).find(r=>typeof r=="string"&&r!=="");if(typeof t=="string"){let r=this.compileSource(t,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==e.compiledCode}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let r={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};r.sourceCode=r.sourceCode??i.sourceCode??i.code??null,r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage??i.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...r,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),r=e?.sourceCode??null,o=this.compileSource(r,t);return{sourceCode:r,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Ye.default.transpileModule(e,{compilerOptions:{target:Ye.default.ScriptTarget.ES2022,module:Ye.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ye.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),r=t.diagnostics?.find(o=>o.category===Ye.default.DiagnosticCategory.Error);if(r)throw new Error(Ye.default.flattenDiagnosticMessageText(r.messageText,`
|
|
3
|
+
`)){let[i,s]=o.split(" - ");if(!s)continue;let a=s.split(" ");if(a[0]!==(e?"cgroup2":"cgroup")||!e&&!a[2]?.split(",").includes(n))continue;let c=i.split(" "),u=Po(c[3]??""),l=Po(c[4]??"");if(!(!u.startsWith("/")||!l.startsWith("/")))for(let f of r){let d=/^\d+:([^:]*):(\/.*)$/.exec(f);if(!d||(e?d[1]!=="":!d[1].split(",").includes(n)))continue;let p=jr.posix.normalize(d[2]);if(u!=="/"&&p!==u&&!p.startsWith(`${u}/`))continue;let g=u==="/"?p.slice(1):p.slice(u.length+1),h=jr.posix.join(l,g);for(;(h===l||h.startsWith(`${l}/`))&&(t.add(h),h!==l);)h=jr.posix.dirname(h)}}return t}function Do(n){let e=n;for(let t of[!0,!1])for(let r of Bo("memory",t)){let o=Number(mt(`${r}/${t?"memory.max":"memory.limit_in_bytes"}`));Number.isFinite(o)&&o>0&&(e=Math.min(e,o))}return e}function Lo(n){let e=n;for(let t of[!0,!1])for(let r of Bo("cpu",t)){let[o,i]=t?mt(`${r}/cpu.max`).split(/\s+/).map(Number):[Number(mt(`${r}/cpu.cfs_quota_us`)),Number(mt(`${r}/cpu.cfs_period_us`))];o>0&&i>0&&Number.isFinite(o)&&Number.isFinite(i)&&(e=Math.min(e,Math.max(1,Math.ceil(o/i))))}return e}function or(){return Do(yt.totalmem())}function Vn(){return Lo(yt.availableParallelism?.()||yt.cpus()?.length||1)}var xs=.25,Hn=128,Cs=2,Rs=4,Fs=6,Is=8,vs=2048,Ms=40,As=128,Ns=32;function Os(n){let e=Math.trunc(Number(n));if(!(!Number.isFinite(e)||e<1))return Math.min(Hn,e)}function Ps(n){let e=Math.trunc(Number(n));return!Number.isFinite(e)||e<1?Fs:Math.min(Is,e)}function qo(n){return 2**Math.ceil(Math.log2(Math.max(1,n)))}function Gn(n){let e=Math.max(1,Math.trunc(n.logicalCpuCount)||1),t=Math.max(1,n.totalMemoryBytes/(1024*1024)),r=Math.min(As,Math.max(Ms,Math.round(t/Ns))),o=t*xs,i=Math.max(1,Math.floor(o/r)),s=Math.max(1,Math.min(e,2,i)),a=Math.max(1,Math.floor(o/(s*r))),c=Math.min(Hn,qo(e*Cs)),u=Math.min(Hn,qo(e*Rs)),l=Math.max(c,Math.min(u,a)),f=Os(n.maxLanesPerRunner)??l,d=t<vs?1:f,p=Math.max(1,Math.min(d,a)),g=Ps(n.tasksPerIsolate),h=p*g;return{maxConcurrentWorkers:s,isolateMemoryLimitMb:r,tasksPerWorkerCap:h,isolatePoolSize:p,tasksPerIsolate:g}}function Br(){return Gn({logicalCpuCount:Vn(),totalMemoryBytes:or()})}var Wo={400:"Bad request",401:"Authentication required",403:"Insufficient permissions",404:"Not found",409:"Conflict",422:"Validation failed",429:"Rate limit exceeded",500:"Internal server error",503:"Service unavailable"},Ve=class{static createException(e,t,r,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new Y(r||"Error",t||500,i);case"$throw.businessLogic":return new Wt(r||"Bad request",i);case"$throw.validation":return new Kt(r||"Validation failed",i);case"$throw.notFound":return new Ut(i?.resource||r||"Resource",i?.identifier);case"$throw.duplicate":return new Qt(i?.resource||r||"Resource",i?.field||"field",i?.value??"value");case"$throw.unauthorized":return new zt(r||"Unauthorized");case"$throw.forbidden":return new Jt(r||"Forbidden");case"$throw.tokenExpired":return new Ht;case"$throw.invalidToken":return new Vt;case"$throw.database":return new ht(r||"Database error",i);case"$throw.dbQuery":return new ht(r||"Query error",i);case"$throw.externalService":return new Gt(r||"Service",r||"Error",i);case"$throw.serviceUnavailable":return new Yt(r||"Service");case"$throw.rateLimit":return new Y(r||"Rate limit exceeded",429,i);case"$throw.scriptError":return new He(r||"Script error",o,i);case"$throw.scriptTimeout":return new Be(i?.timeout||5e3,o);case"$throw.schema":return new Xt(r||"Schema error",i);case"$throw.config":return new Zt(r||"Configuration error",i);case"$throw.fileUpload":return new er(r||"File upload error",i);case"$throw.fileNotFound":return new tr(r||"File not found");case"$throw.fileSizeExceeded":return new rr(i?.maxSize??"unknown",i?.actualSize??"unknown");case"$throw.400":return new Y(r||"Bad request",400,i);case"$throw.401":return new Y(r||"Authentication required",401,i);case"$throw.403":return new Y(r||"Insufficient permissions",403,i);case"$throw.404":return new Y(r||"Not found",404,i);case"$throw.409":return new Y(r||"Conflict",409,i);case"$throw.422":return new Y(r||"Validation failed",422,i);case"$throw.429":return new Y(r||"Rate limit exceeded",429,i);case"$throw.500":return new Y(r||"Internal server error",500,i);case"$throw.503":return new Y(r||"Service unavailable",503,i);default:return Number.isInteger(t)&&t>=400&&t<=599?new Y(r||Wo[t]||"Request failed",t,i):new He(r||"Unknown error",o,i)}return Number.isInteger(t)&&t>=400&&t<=599?new Y(r||Wo[t]||"Request failed",t,i):new He(r||"Unknown error",o,i)}};function Ko(n){return Math.min(2147483647,n+Math.ceil(n*.15))}function Yn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0})}function Ie(n,e,t){if(!Object.prototype.hasOwnProperty.call(n,e))return!1;let r=new Set(t);return Object.keys(n).every(o=>r.has(o))}var Uo=Object.freeze({Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,...typeof globalThis.Float16Array>"u"?{}:{Float16Array:globalThis.Float16Array},...typeof BigInt64Array>"u"?{}:{BigInt64Array},...typeof BigUint64Array>"u"?{}:{BigUint64Array}});function fe(n,e){if(!n||typeof n!="object")return n;let t=n;if(Ie(t,"__plainObject",["__plainObject"])){let o={};for(let[i,s]of Object.entries(t.__plainObject||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__nullPrototype",["__nullPrototype"])){let o=Object.create(null);for(let[i,s]of Object.entries(t.__nullPrototype||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__e",["__e"])&&t.__e==="u")return;if(e&&Ie(t,"__fnRef",["__fnRef"])&&typeof t.__fnRef=="string")return e(t.__fnRef);if(Ie(t,"__number",["__number"])){if(t.__number==="nan")return Number.NaN;if(t.__number==="infinity")return Number.POSITIVE_INFINITY;if(t.__number==="-infinity")return Number.NEGATIVE_INFINITY;if(t.__number==="-0")return-0;throw new TypeError(`Unsupported executor number: ${t.__number}`)}if(Ie(t,"__bigint",["__bigint"]))return BigInt(t.__bigint);if(Ie(t,"__map",["__map"]))return new Map((t.__map||[]).map(([o,i])=>[fe(o,e),fe(i,e)]));if(Ie(t,"__arrayBuffer",["__arrayBuffer"]))return Uint8Array.from(t.__arrayBuffer||[]).buffer;if(Ie(t,"__typedArray",["__typedArray","bytes","data"])){let o=Uint8Array.from(t.bytes||t.data||[]);if(t.__typedArray==="DataView")return new DataView(o.buffer);let i=Uo[String(t.__typedArray)];if(!Object.prototype.hasOwnProperty.call(Uo,t.__typedArray)||typeof i!="function")throw new TypeError(`Unsupported executor typed array: ${t.__typedArray}`);return new i(o.buffer)}if(Array.isArray(n))return n.map(o=>fe(o,e));let r={};for(let[o,i]of Object.entries(t))Yn(r,o,fe(i,e));return r}function ve(n){try{if(n instanceof Error)return n}catch{}let e="Unknown error";try{n===void 0?e="Operation rejected with undefined":n===null?e="Operation rejected with null":e=String(n)}catch{}return new Error(e)}function Qo(n){let e=new WeakSet;try{return JSON.stringify(n,(t,r)=>{if(typeof r=="bigint")return r.toString();if(!(typeof r=="function"||typeof r=="symbol")){if(r&&typeof r=="object"){if(e.has(r))return"[Circular]";e.add(r)}return r}})}catch{let t="Host capability call failed",r;try{t=String(n.message||t)}catch{}try{typeof n.code=="string"&&(r=n.code)}catch{}return JSON.stringify({__userThrow:!0,message:t,code:r})}}function ir(n){if(n===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:n},(e,t)=>typeof t=="bigint"?{__bigint:t.toString()}:t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var zo=require("async_hooks"),Dr=new zo.AsyncLocalStorage;function Xn(){return Dr.getStore()}function Zn(n,e){return Dr.run(n,e)}var Lr=class{constructor(e,t){this.taskAbortSignals=e;this.taskDeadlines=t;this.runtimeCallbackCounter=0}postAbortedCallError(e,t){e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})}).catch(()=>{})}async handleIoCall(e,t,r,o){if(o?.aborted){this.postAbortedCallError(t,r);return}try{let i=await(o?Dr.run(o,e):e());if(o?.aborted){this.postAbortedCallError(t,r);return}await t.postMessage({type:"callResult",callId:r,result:ir(i)})}catch(i){if(o?.aborted){this.postAbortedCallError(t,r);return}let s=ve(i),a={__userThrow:!0,message:s.message,statusCode:s.statusCode,code:s.errorCode??s.code,errorPath:s.errorPath,details:s.details,messages:s.messages};await t.postMessage({type:"callError",callId:r,error:Qo(a)}).catch(()=>{})}}parseExecutorArgs(e,t,r){let o=JSON.parse(e||"[]");return fe(o,t&&r?s=>(...a)=>this.invokeRuntimeCallback(t,r,s,a):void 0)}async execRepoCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=e.access==="secure"?ie(t?.$repos,"secure",!0):t?.$repos,i=ie(o,String(e.table),!0),s=ie(i,String(e.method));if(!i||typeof s!="function"){let a=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${a}${e.table}.${e.method}`)}return s.apply(i,r)}async execTransactionCall(e,t,r){let i=this.parseExecutorArgs(e.argsJson,r,e.id)[0];if(typeof i!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,i)}async execHelpersCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=String(e.name).split("."),i=t?.$helpers,s=i;for(let a of o)i=s,s=ie(s,a);if(typeof s!="function")throw new Error(`Helper not found: ${e.name}`);return s.apply(i,r)}async execSocketCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$socket,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i.apply(o,r)}async execCacheCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$cache,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Cache not found: ${e.method}`);return i.apply(o,r)}async execStorageCall(e,t,r){let o=this.parseStorageArgs(e.argsJson,r,e.id),i=t?.$storage,s=ie(i,String(e.method));if(typeof s!="function")throw new Error(`Storage method not found: ${e.method}`);return s.apply(i,o)}parseStorageArgs(e,t,r){return this.parseExecutorArgs(e,t,r)}invokeRuntimeCallback(e,t,r,o){let i=`rtcb_${++this.runtimeCallbackCounter}`,s=this.taskAbortSignals.get(t),a=this.taskDeadlines.get(t)??Date.now()+3e4,c=Math.max(1,a-Date.now())+500;return new Promise((u,l)=>{let f=!1,d=w=>{f||(f=!0,m(),w())},p=setTimeout(()=>{d(()=>l(new Error(`Runtime callback timed out: ${r}`)))},c),g=()=>{d(()=>l(new Error("Runtime callback was cancelled")))},h=()=>{d(()=>l(new Error("Runtime callback worker exited")))},y=w=>{if(!(w?.type!=="runtimeCallbackResult"||w.callId!==i)){if(w.error){let _=new Error(String(w.error));try{let $=JSON.parse(String(w.error));$?.__userThrow&&(_.message=String($.message??_.message),_.statusCode=$.statusCode,_.code=$.code??(Number.isInteger($.statusCode)?`HTTP_${$.statusCode}`:void 0),_.errorCode=_.code,_.errorPath=$.errorPath,_.details=$.details,_.messages=$.messages)}catch{}d(()=>l(_));return}d(()=>u(w.value))}},m=()=>{clearTimeout(p),e.off("message",y),e.off("exit",h),s?.removeEventListener("abort",g)};if(e.on("message",y),e.on("exit",h),s?.addEventListener("abort",g,{once:!0}),s?.aborted){g();return}try{e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:r,argsJson:JSON.stringify(o)}).catch(w=>d(()=>l(w)))}catch(w){d(()=>l(w))}})}async execDispatchCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=ie(t,"$trigger");if(typeof o!="function")throw new Error("$trigger is not available");return o.apply(t,r)}};var Ho=require("stream");var eo=32*1024*1024,Jo=Math.ceil(eo/3)*4,qr=class{constructor(e,t){this.cancelTask=e;this.parseExecutorArgs=t;this.responseStreams=new Map}async execResCall(e,t){if(e.method==="json"){let s=ie(t?.$res,"__enfyraJson");if(typeof s!="function")throw new Error("Native JSON response is not available");return await s.call(t.$res,String(e.jsonText),e.options||{})}if(e.method==="bytes"){let s=ie(t?.$res,"__enfyraBytes");if(typeof s!="function")throw new Error("Native binary response is not available");let a=String(e.bytes||"");if(a.length>Jo)throw new Error("Native binary response exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Native binary response exceeded 32 MiB");return await s.call(t.$res,c,e.options||{})}if(e.method==="streamStart"){if(this.responseStreams.has(e.id))throw new Error(`Response stream already exists: ${e.id}`);let a=JSON.parse(e.argsJson||"[]")[1]||{},c=ie(t?.$res,"stream");if(typeof c!="function")throw new Error("Response method not found: stream");let u=new Ho.PassThrough;u.on("error",()=>{});let l={stream:u};this.responseStreams.set(e.id,l);let f=t?.$res;if(f&&typeof f.once=="function"){let d=()=>{f.writableEnded!==!0&&this.cancelTask(e.id)};f.once("close",d),l.closeCleanup=()=>{typeof f.off=="function"?f.off("close",d):typeof f.removeListener=="function"&&f.removeListener("close",d)}}try{let d=c.call(t.$res,u,a);return d&&typeof d.then=="function"&&(l.completion=Promise.resolve(d).then(()=>{},p=>{let g=ve(p);throw this.responseStreams.get(e.id)===l&&(this.cleanupResponseStream(e.id,g),this.cancelTask(e.id)),g}),l.completion.catch(()=>{})),!0}catch(d){let p=ve(d);throw this.cleanupResponseStream(e.id,p),p}}if(e.method==="streamChunk"){let s=this.responseStreams.get(e.id);if(!s)throw new Error(`Response stream not found: ${e.id}`);let a=String(e.chunk||"");if(a.length>Jo)throw new Error("Response stream chunk exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Response stream chunk exceeded 32 MiB");if(s.stream.destroyed)throw new Error("Response stream closed before drain");return s.stream.write(c)||await new Promise((u,l)=>{let f=()=>{g(),u()},d=h=>{g(),l(h)},p=()=>{g(),l(new Error("Response stream closed before drain"))},g=()=>{s.stream.off("drain",f),s.stream.off("error",d),s.stream.off("close",p)};s.stream.once("drain",f),s.stream.once("error",d),s.stream.once("close",p)}),!0}if(e.method==="streamEnd"){let s=this.responseStreams.get(e.id);if(s){s.stream.end();try{await s.completion}finally{this.responseStreams.get(e.id)===s&&(s.closeCleanup?.(),this.responseStreams.delete(e.id))}}return!0}if(e.method==="streamError"){let s=this.responseStreams.get(e.id);if(s){s.closeCleanup?.();let a=e.error?.message||"Response stream failed";s.stream.destroy(new Error(a)),this.responseStreams.delete(e.id)}return!0}let r=this.parseExecutorArgs(e.argsJson),o=t?.$res,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(o,r)}cleanupResponseStream(e,t){let r=this.responseStreams.get(e);r&&(this.responseStreams.delete(e),r.closeCleanup?.(),t?r.stream.destroy(t):r.stream.end())}};var Vo=require("child_process"),Go=require("string_decoder"),Bs=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function Ds(){let n={};for(let e of Bs){let t=process.env[e];t!==void 0&&(n[e]=t)}return n}var Wr=class{constructor(e){this.terminated=!1;this.stderrTail="";this.stderrDecoder=new Go.StringDecoder("utf8");this.child=(0,Vo.fork)(e,[],{stdio:["ignore","ignore","pipe","ipc"],env:Ds(),execArgv:[],serialization:"advanced"}),this.child.on("error",t=>{this.stderrTail=(this.stderrTail+t.message).slice(-8192)}),this.child.stderr?.on("data",t=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.write(t)).slice(-8192)}),this.child.stderr?.on("end",()=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.end()).slice(-8192)})}get stderr(){return this.stderrTail}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){return this.child.connected?new Promise((t,r)=>{try{this.child.send(e,o=>{o?r(o):t()})}catch(o){r(o)}}):Promise.reject(new Error("Executor runner IPC is closed"))}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var Ge=class{constructor(e,t,r,o,i,s,a,c=6e4){this.scriptPath=i;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=r,this.tasksCap=o,this.drainTimeoutMs=c;for(let u=0;u<e;u++)this.spawnEntry()}getEntries(){return this.entries}clearDrainTimeout(e){e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0)}reportObserverError(e,t){let r=t instanceof Error?t.message:String(t);console.error(`[executor-pool] ${e}: ${r}`)}spawnEntry(){let e=new Wr(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",r=>{let o=t.tasks.get(r.id);if(o)if(r.type==="taskReleased")o.onRelease?.();else if(r.type==="taskLane")o.onLane?.(r.laneKey);else if(r.type==="taskFailure")o.onFailure?.(r.error);else if(r.type==="result"||r.type==="taskCancelled"){typeof r.heapRatio=="number"&&(t.lastHeapRatio=r.heapRatio),typeof r.runnerRssBytes=="number"&&(t.lastRssBytes=r.runnerRssBytes),r.contextStats&&(t.contextStats=r.contextStats);let i=r;r.type==="taskCancelled"&&(i={type:"result",id:r.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}});try{o.onResult(i)}catch(s){this.reportObserverError("task result callback failed",s)}!t.draining&&typeof r.heapRatio=="number"&&r.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(r.heapRatio*100)}%`)}else o.onIoCall(r)}),e.on("exit",(r,o)=>{let i=t.draining,s=this.destroying;t.draining=!0;let a={entryId:t.id,pid:t.worker.pid,exitCode:r,exitSignal:o??null,lastError:t.lastError||t.worker.stderr||void 0,terminationReason:t.terminationReason,lastHeapRatio:t.lastHeapRatio,lastRssBytes:t.lastRssBytes,activeTasks:[...t.tasks.values()].map(l=>l.diagnostics)};this.clearDrainTimeout(t);let c="Worker crashed";s?c="Worker terminated":t.lastError&&(c=`Worker crashed: ${t.lastError}`);for(let[,l]of t.tasks){l.abortController.abort();try{l.onResult({type:"result",success:!1,error:{message:c,code:s?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:s?void 0:{outcome:"unknown_outcome",retryable:!1}}})}catch(f){this.reportObserverError("worker-exit task callback failed",f)}}t.tasks.clear();let u=this.entries.indexOf(t);if(u!==-1&&this.entries.splice(u,1),(!i||t.replaceOnExit)&&!s){try{this.onCrash?.(a)}catch(f){this.reportObserverError("worker crash observer failed",f)}this.entries.filter(f=>!f.draining).length<this.max&&this.spawnEntry()}this.drainWaiting()}),e.on("error",r=>{t.lastError=r.message}),this.entries.push(t),t}rotateEntry(e,t){if(this.destroying||e.draining)return;e.draining=!0;let r=Date.now()-e.spawnedAt;try{this.onRotate?.({reason:t,ageMs:r})}catch(o){this.reportObserverError("worker rotation observer failed",o)}if(this.spawnEntry(),this.drainWaiting(),e.tasks.size===0&&e.reservations===0){this.clearDrainTimeout(e),e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,this.abortEntryTasks(e),e.worker.terminate()},this.drainTimeoutMs)}abortEntryTasks(e){for(let t of e.tasks.values())t.abortController.abort()}isMemoryAvailable(){let e=Date.now();if(e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs){let t=this.entries.reduce((r,o)=>r+(o.lastRssBytes??0),0);this.cachedMemoryOk=(process.memoryUsage().rss+t)/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e}return this.cachedMemoryOk}hasActiveWork(){return this.entries.some(e=>e.tasks.size>0||e.reservations>0)}canDispatch(){return!this.hasActiveWork()||this.isMemoryAvailable()}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let r=t.tasks.size+t.reservations;r<this.tasksCap&&(!e||r<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(e){if(this.destroying)return Promise.reject(new Error("Executor worker pool is shutting down"));if(e?.aborted)return Promise.reject(new Error("Execution aborted before dispatch"));let t=this.findLeastBusy();return t&&this.canDispatch()?(t.reservations++,Promise.resolve(t)):new Promise((r,o)=>{let i={resolve:r,reject:o,signal:e};e&&(i.onAbort=()=>{let s=this.waiting.indexOf(i);s!==-1&&this.waiting.splice(s,1),o(new Error("Execution aborted before dispatch"))},e.addEventListener("abort",i.onAbort,{once:!0})),this.waiting.push(i)})}registerTask(e,t,r){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,r)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(!e||!this.canDispatch())break;let t=this.waiting.shift();if(t.signal?.aborted){t.reject(new Error("Execution aborted before dispatch"));continue}t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),e.reservations++,t.resolve(e)}}terminateEntry(e,t="host_requested"){e.draining&&e.terminationReason||(e.draining=!0,e.replaceOnExit=!0,e.terminationReason=t,this.clearDrainTimeout(e),this.abortEntryTasks(e),e.worker.terminate())}resize(e){this.max=Math.max(1,e);let t=this.entries.filter(i=>!i.draining);for(;t.length<this.max;)t.push(this.spawnEntry());let r=t.length-this.max;if(r<=0){this.drainWaiting();return}let o=t.sort((i,s)=>i.tasks.size+i.reservations-(s.tasks.size+s.reservations)).slice(0,r);for(let i of o)i.draining=!0;this.drainWaiting();for(let i of o)i.tasks.size===0&&i.reservations===0?(this.clearDrainTimeout(i),i.worker.terminate()):(this.clearDrainTimeout(i),i.drainTimeout=setTimeout(()=>{i.drainTimeout=void 0,this.abortEntryTasks(i),i.worker.terminate()},this.drainTimeoutMs))}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,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,lastRssBytes:e.lastRssBytes??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;let e=new Error("Executor worker pool was destroyed");for(let t of this.waiting.splice(0))t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),t.reject(e);for(let t of this.entries)t.draining=!0,t.terminationReason="pool_destroyed",this.clearDrainTimeout(t),this.abortEntryTasks(t),t.worker.terminate();this.entries.length=0}};var Gs=Zo.join(__dirname,"execution/worker.js"),Ys=3e4,Xs=2147483647;function Xo(n){let e=Number(n);return Number.isFinite(e)?Math.max(1,Math.min(Xs,Math.trunc(e))):Ys}var bt=class n{constructor(e){this.logger=new Pr(n.name);this.effectiveMemory=or();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.taskCancellers=new Map;this.taskAbortSignals=new Map;this.taskDeadlines=new Map;this.taskDurationsMs=[];this.queueWaitDurationsMs=[];this.hostIo=new Lr(this.taskAbortSignals,this.taskDeadlines);this.responseBridge=new qr(e=>this.cancelTask(e),e=>this.hostIo.parseExecutorArgs(e));this.packageCacheService=e.packageCacheService,this.onExecutionFinished=e.onExecutionFinished,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??Br(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Ge(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Gs,t=>{this.crashesTotal++;let r={event:"executor_worker_crashed",occurredAt:new Date().toISOString(),...t};this.logger.warn(r);try{e.onExecutorWorkerCrash?.(r)}catch(o){this.logger.warn({event:"executor_worker_crash_report_failed",error:o instanceof Error?o.message:String(o)})}},({reason:t,ageMs:r})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(r/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerIsolate} tasks/isolate, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let e=this.pool.getEntries().reduce((g,h)=>g+(h.lastRssBytes??0),0),r=(process.memoryUsage().rss+e)/this.effectiveMemory,o=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),s=Number(o-this.prevCpuTime)/1e3,a=s>0?(i.user+i.system)/s:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=o;let c=this.pool.getMax(),u=this.pool.getWaitingCount(),l=r>.85||a>.7,f=r<.7&&a<.5,d=u>0,p=c;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,c-1))):f&&d?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,c+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==c&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${c} -> ${p} (rss=${Math.round(r*100)}% cpu=${Math.round(a*100)}% queue=${u})`))}spawnAndExecute(e,t,r,o,i){return(async()=>{let s=Date.now(),a;try{a=await this.pool.dispatch(i)}catch(l){if(i?.aborted){let f=new Error("Execution aborted before dispatch");throw f.code="ERR_EXECUTION_ABORTED",f.isAbort=!0,f}throw l}if(this.recordQueueWait(Date.now()-s),i?.aborted){this.pool.releaseReservation(a);let l=new Error("Execution aborted after client disconnect");return l.code="ERR_EXECUTION_ABORTED",l.isAbort=!0,Promise.reject(l)}let c=`t_${++this.taskCounter}`,u=Date.now();return new Promise((l,f)=>{let d=!1,p=new AbortController;this.taskAbortSignals.set(c,p.signal);let g=Ko(o);this.taskDeadlines.set(c,u+g);let h=!1,y,m,w=()=>{let E=new Error("Execution aborted after client disconnect");return E.code="ERR_EXECUTION_ABORTED",E.isAbort=!0,E},_=()=>{let E=new Error(`Script execution timed out after ${o}ms`);return E.code="ERR_SCRIPT_EXECUTION_TIMEOUT",E.isTimeout=!0,E},$,k,C=!1,x=E=>{if(!(d||h)){h=!0,y=E,p.abort(),this.responseBridge.cleanupResponseStream(c,E);try{a.worker.postMessage({type:"cancelTask",id:c}).catch(()=>{})}catch{}$=setTimeout(()=>{d||(d=!0,k&&clearTimeout(k),M(),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),this.recordTaskDuration(Date.now()-u),this.pool.terminateEntry(a,E.isTimeout?"timeout_cancel_grace":E.isAbort?"client_abort_cancel_grace":"failure_cancel_grace"),this.pool.unregisterTask(a,c),this.taskErrorTotal++,E.details={...E.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},f(E))},1e4),$.unref?.()}},v=()=>x(w());this.taskCancellers.set(c,v);let R=()=>v(),M=()=>{i?.removeEventListener("abort",R)};i&&(i.addEventListener("abort",R,{once:!0}),i.aborted&&v());let N=()=>{k&&clearTimeout(k),$&&clearTimeout($),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),M(),this.responseBridge.cleanupResponseStream(c),this.recordTaskDuration(Date.now()-u)},j=()=>{N(),this.pool.unregisterTask(a,c)},O=25,P=()=>{d||(this.taskTimeoutTotal++,x(_()))},G=u+g+[...a.tasks.keys()].reduce((E,S)=>{if(S===c)return E;let T=this.taskDeadlines.get(S);return E+(T===void 0?0:Math.max(0,T-u))},0),re=()=>{if(!(d||h)){if(!C&&Date.now()>=G){this.taskTimeoutTotal++,x(_());return}if(!C){k=setTimeout(re,O),k.unref?.();return}this.taskDeadlines.set(c,Date.now()+g),k=setTimeout(P,g),k.unref?.()}};k=setTimeout(re,O),k.unref?.(),this.pool.registerTask(a,c,{abortController:p,onLane:()=>{d||h||C||(C=!0,k&&clearTimeout(k),re())},diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),onFailure:E=>{if(d||h)return;m=E;let S=new Error(E.message);S.code=E.code,S.errorCode=E.code,S.statusCode=E.statusCode,S.errorPath=E.errorPath,S.details=E.details,E.stack&&(S.stack=E.stack),S.isTimeout=E.code==="ERR_SCRIPT_EXECUTION_TIMEOUT",S.isTimeout&&!h&&!d&&this.taskTimeoutTotal++,x(S)},onResult:E=>{if(!d){d=!0;try{this.onExecutionFinished?.({diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),logs:Array.isArray(E.diagnosticLogs?.logs)?E.diagnosticLogs.logs:Array.isArray(E.ctxChanges?.$share?.$logs)?E.ctxChanges.$share.$logs:[],logsTruncated:E.diagnosticLogs?.truncated===!0||E.ctxChanges?.$share?.$logsTruncated===!0,statusCode:E.error?.statusCode??E.ctxChanges?.$statusCode,error:m??(E.success||h?void 0:E.error)})}catch(S){this.logger.error("Executor diagnostic callback failed",S)}if(E.taskCancelled===!0&&this.pool.unregisterTask(a,c),N(),h){this.taskErrorTotal++;try{E.ctxChanges&&y&&(y.ctxChanges=fe(E.ctxChanges)),f(y??w())}catch(S){f(ve(S))}return}if(E.success)try{let S={value:fe(E.value),valueAbsent:E.valueAbsent===!0,ctxChanges:fe(E.ctxChanges)};E.shortCircuit&&(S.shortCircuit=!0),this.taskDoneTotal++,l(S)}catch(S){p.abort();let T=ve(S);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}else try{let S=new Error(E.error?.message||"Handler execution failed");S.statusCode=E.error?.statusCode,S.code=E.error?.code,S.errorCode=E.error?.code,S.details=E.error?.details,E.error?.stack&&(S.stack=E.error.stack),E.ctxChanges&&(S.ctxChanges=fe(E.ctxChanges)),this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,S),f(S)}catch(S){p.abort();let T=ve(S);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}}},onRelease:()=>{this.pool.unregisterTask(a,c)},onIoCall:E=>{if(d||E.type==="executionError")return;let S=p.signal;E.type==="repoCall"?this.hostIo.handleIoCall(()=>this.hostIo.execRepoCall(E,r),a.worker,E.callId,S):E.type==="transactionCall"?this.hostIo.handleIoCall(()=>this.hostIo.execTransactionCall(E,r,a.worker),a.worker,E.callId,S):E.type==="helpersCall"?this.hostIo.handleIoCall(()=>this.hostIo.execHelpersCall(E,r),a.worker,E.callId,S):E.type==="socketCall"?this.hostIo.handleIoCall(()=>this.hostIo.execSocketCall(E,r),a.worker,E.callId,S):E.type==="cacheCall"?this.hostIo.handleIoCall(()=>this.hostIo.execCacheCall(E,r),a.worker,E.callId,S):E.type==="storageCall"?this.hostIo.handleIoCall(()=>this.hostIo.execStorageCall(E,r,a.worker),a.worker,E.callId,S):E.type==="dispatchCall"?this.hostIo.handleIoCall(()=>this.hostIo.execDispatchCall(E,r),a.worker,E.callId,S):E.type==="resCall"&&this.hostIo.handleIoCall(()=>this.responseBridge.execResCall(E,r),a.worker,E.callId,S)}}),a.worker.postMessage({type:e,id:c,...t}).then(()=>{i?.aborted&&v()}).catch(E=>{d||(d=!0,p.abort(),j(),this.taskErrorTotal++,f(E))})})})()}cancelTask(e){this.taskCancellers.get(e)?.()}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,scriptId:e.scriptId,type:e.type}}createWorkerTaskDiagnostics(e,t,r,o){let i=r?.$api?.request?.correlationId,s=Array.isArray(t.codeBlocks)?t.codeBlocks.map(a=>({type:a?.type==="preHook"||a?.type==="postHook"||a?.type==="handler"?a.type:"run",...a?.scriptId!==void 0&&a?.scriptId!==null?{scriptId:String(a.scriptId)}:{}})):[{type:typeof t.sourceKind=="string"?t.sourceKind:"run",...t.scriptId==null?{}:{scriptId:String(t.scriptId)}}];return{...typeof i=="string"&&i?{correlationId:i}:{},timeoutMs:o,isolateMemoryLimitMb:Number(t.memoryLimitMb||0),isolatePoolSize:Number(t.isolatePoolSize||0),tasksPerIsolate:Number(t.tasksPerIsolate||0),scriptBlocks:s}}async run(e,t,r,o={}){let i=Xo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let l={code:e,scriptId:o.scriptId,sourceKind:o.sourceKind,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("execute",l,t,i)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,e,f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error",e,f.details||{})}return nr(t,u.ctxChanges||{}),u.valueAbsent?void 0:u.value}async runBatch(e,t,r,o={}){let i=Xo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let f={codeBlocks:e.map(d=>this.toWorkerCodeBlock(d)),pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("executeBatch",f,t,i,o.signal)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,"(batch execution)",f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error","(batch execution)",f.details||{})}return nr(t,u.ctxChanges||{}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((i,s)=>i-s),o=Math.min(r.length-1,Math.max(0,Math.ceil(t/100*r.length)-1));return r[o]}resetLatencyMetrics(){this.taskDurationsMs.length=0,this.queueWaitDurationsMs.length=0}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,r=t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,o=this.queueWaitDurationsMs,i=o.length===0?0:o.reduce((s,a)=>s+a,0)/o.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:r,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),avgQueueWaitMs:i,p95QueueWaitMs:this.percentile(o,95),p99QueueWaitMs:this.percentile(o,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var Ye=Je(require("typescript")),Kr={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Zs(n){return $e.getLegacyField(n)}function ea(n){return $e.isScriptTable(n)}function ta(n){return $e.normalizeLanguage(n)}var Ur=class{getLegacyField(e){return Object.prototype.hasOwnProperty.call(Kr,e)?Kr[e]:void 0}isScriptTable(e){return Object.prototype.hasOwnProperty.call(Kr,e)}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let r=String(e),i=this.normalizeLanguage(t)==="javascript"?r:this.transpileTypeScript(r);return this.assertExecutableJavaScript(i),i}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let r={...t},o=this.getLegacyField(e);return o&&(r.sourceCode===void 0||r.sourceCode===null||r.sourceCode==="")&&r[o]!==void 0&&(r.sourceCode=r[o]),r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage),o&&o in r&&delete r[o],r}normalizePatch(e,t,r){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode"),s=o?Object.prototype.hasOwnProperty.call(t,o):!1,a=i||s,c=Object.prototype.hasOwnProperty.call(t,"scriptLanguage"),u={...t};if(!a&&!c)return delete u.compiledCode,u;if(!a&&!r)throw new Error("Existing script data is required when changing scriptLanguage.");let l;i?l=t.sourceCode:s&&o?l=t[o]:(l=r?.sourceCode,l===void 0&&o&&r&&(l=r[o]));let f=c?t.scriptLanguage:r?.scriptLanguage;return a&&(u.sourceCode=l??null),u.scriptLanguage=this.normalizeLanguage(f),u.compiledCode=this.compileSource(l,u.scriptLanguage),o&&o in u&&delete u[o],u}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let r=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==e.compiledCode}}let t=Object.values(Kr).filter(r=>r!=="").map(r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:void 0).find(r=>typeof r=="string"&&r!=="");if(typeof t=="string"){let r=this.compileSource(t,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==e.compiledCode}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let r={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};r.sourceCode=r.sourceCode??i.sourceCode??i.code??null,r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage??i.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...r,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),r=e?.sourceCode??null,o=this.compileSource(r,t);return{sourceCode:r,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Ye.default.transpileModule(e,{compilerOptions:{target:Ye.default.ScriptTarget.ES2022,module:Ye.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ye.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),r=t.diagnostics?.find(o=>o.category===Ye.default.DiagnosticCategory.Error);if(r)throw new Error(Ye.default.flattenDiagnosticMessageText(r.messageText,`
|
|
4
4
|
`));return t.outputText.trimEnd()}assertExecutableJavaScript(e){if(!e)return;let t=Object.getPrototypeOf(async function(){}).constructor;new t(`"use strict";
|
|
5
5
|
${e}`)}},$e=new Ur;function ra(n,e){return $e.compileSource(n,e)}function na(n){return $e.isExecutableJavaScript(n)}function oa(n,e){return $e.normalizeRecord(n,e)}function ia(n,e,t){return $e.normalizePatch(n,e,t)}function sa(n){return $e.getExecutableScript(n)}function aa(n){return $e.resolveExecutableScript(n)}function la(n){return $e.normalizeFlowStepScriptConfig(n)}sr();cr();ne();var li=64;function ci(n){let e=(n?.columns??[]).filter(t=>t.isPrimary===!0).map(t=>t.name);return e.length>0?e:n?.columns?.some(t=>t.name==="id")?["id"]:n?.columns?.some(t=>t.name==="_id")?["_id"]:[]}function ui(n,e){if(n!=="id")return n;if(e.columns?.some(r=>r.name==="id"))return"id";let t=ci(e);return t.length===1?t[0]:n}function Hr(n,e){let t=n.targetTableName||n.targetTable,r=e?.tables?.get(t);if(!r)throw new b(`Field relation '${n.propertyName}' has no target table metadata`);let o=ci(r);if(o.length===0)throw new b(`Field relation '${n.propertyName}' target '${t}' has no primary key metadata`);return o}function Vr(n,e,t,r){let o={rootTable:e,nodes:[]};if(n===void 0)return o;if(!Array.isArray(n))throw new b("Query fields must be an array");if(n.some(a=>typeof a!="string"))throw new b("Query field entries must be strings");if(n.length===0)return o;let i=t?.tables?.get(e);if(!i)throw new b(`Field parsing requires metadata for table '${e}'`);let s=r.createCheckpoint();try{let a=new Map,c=[],u=new Set(n.map(l=>ui(l,i)));for(let l of u)if(l==="*")c.push("*");else if(l.includes(".")){let f=l.indexOf("."),d=l.substring(0,f),p=l.substring(f+1);if(!d||!p)throw new b(`Invalid field path '${l}'`);if(!i.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(p)}else if(i.relations?.some(d=>d.propertyName===l)){a.has(l)||a.set(l,[]);let d=i.relations.find(p=>p.propertyName===l);for(let p of Hr(d,t))a.get(l).includes(p)||a.get(l).push(p)}else{if(!i.columns?.some(p=>p.name===l))continue;c.push(l)}if(c.includes("*")){o.nodes.push({kind:"wildcard"});for(let l of i.relations||[])a.has(l.propertyName)||a.set(l.propertyName,Hr(l,t))}else for(let l of c)o.nodes.push({kind:"scalar",name:l});for(let[l,f]of a.entries()){let d=i.relations?.find(y=>y.propertyName===l);if(!d)continue;let p=d.targetTableName||d.targetTable;if(typeof p!="string"||!p||!t?.tables?.has(p))throw new b(`Field relation '${l}' on '${e}' has no resolvable target table metadata`);let g=fi(f,p,t,1);if(g.length===0)continue;let h={kind:"relation",propertyName:l,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:p,children:g};if(d.type==="many-to-one"||d.type==="one-to-one"){let y=r.registerWithParent(e,l,t,"left",null,"data");h.joinId=y}o.nodes.push(h)}return o}catch(a){throw r.restoreCheckpoint(s),a}}function fi(n,e,t,r){if(r>li)throw new b(`Field nesting depth exceeds maximum of ${li}`);let o=t?.tables?.get(e);if(!o)throw new b(`Field parsing requires metadata for table '${e}'`);let i=new Map,s=[],a=new Set(n.map(u=>ui(u,o)));for(let u of a)if(u==="*")s.push("*");else if(u.includes(".")){let l=u.indexOf("."),f=u.substring(0,l),d=u.substring(l+1);if(!f||!d)throw new b(`Invalid field path '${u}'`);if(!o.relations?.some(g=>g.propertyName===f))continue;i.has(f)||i.set(f,[]),i.get(f).push(d)}else if(o.relations?.some(f=>f.propertyName===u)){i.has(u)||i.set(u,[]);let f=o.relations.find(d=>d.propertyName===u);for(let d of Hr(f,t))i.get(u).includes(d)||i.get(u).push(d)}else{if(!o.columns?.some(d=>d.name===u))continue;s.push(u)}let c=[];if(s.includes("*")){c.push({kind:"wildcard"});for(let u of o.relations||[])i.has(u.propertyName)||i.set(u.propertyName,Hr(u,t))}else for(let u of s)c.push({kind:"scalar",name:u});for(let[u,l]of i.entries()){let f=o.relations?.find(g=>g.propertyName===u);if(!f)continue;let d=f.targetTableName||f.targetTable;if(typeof d!="string"||!d||!t?.tables?.has(d))throw new b(`Field relation '${u}' on '${e}' has no resolvable target table metadata`);let p=fi(l,d,t,r+1);p.length!==0&&c.push({kind:"relation",propertyName:u,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:d,children:p})}return c}ne();function di(n,e,t){return n.filter(r=>{let o=r.split(".");if(o.some(s=>!s))throw new b(`Invalid field path '${r}'`);let i=e;for(let s=0;s<o.length;s++){let a=t?.tables?.get(i);if(!a)throw new b(`Field parsing requires metadata for table '${i}'`);let c=o[s],u=s===o.length-1;if(u&&c==="*"||u&&a.columns?.some(f=>f.name===c||c==="id"&&f.name==="_id"))return!0;let l=a.relations?.find(f=>f.propertyName===c);if(!l)return!1;if(u)return!0;i=l.targetTableName||l.targetTable}return!1})}ne();ne();Le();var ma=new Set(["_and","_or","_not"]);function lo(n,e){return n?.tables?.get(e)??null}function io(n,e,t){return lo(n,e)?.columns?.find(r=>r.name===t)}function so(n,e,t){return lo(n,e)?.relations?.find(r=>r.propertyName===t)}function ya(n){let e=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],r=e[2].trim();if(t==="count")return{functionName:t,relationName:r};let o=r.indexOf(".");return o<=0||o!==r.lastIndexOf(".")?null:{functionName:t,relationName:r.slice(0,o).trim(),fieldName:r.slice(o+1).trim()}}function ao(n,e,t,r){if(!lo(n,e))throw new b(`${r==="filter"?"Filter":"Sort"} validation requires metadata for table '${e}'`);let i=io(n,e,t)??(t==="id"?io(n,e,"_id"):void 0);if(!i)throw new b(`${r==="filter"?"Filter":"Sort"} field '${t}' does not exist on '${e}'`);if(i.isEncrypted===!0)throw new b(`Encrypted field '${t}' on '${e}' cannot be used for ${r}.`)}function Gr(n,e,t,r,o){if(!(!n||typeof n!="object")){if(r>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`);if(o.has(n))throw new b("Filter contains a circular reference");o.add(n);try{if(Array.isArray(n)){for(let i of n)Gr(i,e,t,r+1,o);return}for(let[i,s]of Object.entries(n)){if(ma.has(i)){Gr(s,e,t,r+1,o);continue}let a=so(t,e,i),c=a?null:io(t,e,i);if(c?.isEncrypted===!0)throw new b(`Encrypted field '${i}' on '${e}' cannot be used for filter.`);if(!(i.startsWith("_")&&!c&&!a)){if(a){let u=a.targetTableName||a.targetTable;if(typeof u!="string"||!u)throw new b(`Filter relation '${i}' on '${e}' has no target table metadata`);Gr(s,u,t,r+1,o);continue}ao(t,e,i,"filter")}}}finally{o.delete(n)}}}function Yr(n,e,t){Gr(n,e,t,0,new Set)}function _t(n,e,t){if(n===void 0)return;if(typeof n!="string"&&!Array.isArray(n))throw new b("Sort must be a string or string array");let r=Array.isArray(n)?n:n.split(",");if(r.some(i=>typeof i!="string"))throw new b("Sort entries must be strings");let o=r.map(i=>i.trim()).filter(Boolean);for(let i of o){let s=i.startsWith("-")?i.slice(1):i;if(!s)continue;let a=ya(s);if(a){let l=so(t,e,a.relationName);if(!l)throw new b(`Sort relation '${a.relationName}' does not exist on '${e}'`);if(a.functionName==="count")continue;let f=l.targetTableName||l.targetTable;if(typeof f!="string"||!f)throw new b(`Sort relation '${a.relationName}' on '${e}' has no target table metadata`);ao(t,f,a.fieldName,"sort");continue}let c=s.split("."),u=e;for(let l=0;l<c.length;l++){let f=c[l];if(l===c.length-1){ao(t,u,f,"sort");break}let p=so(t,u,f);if(!p)throw new b(`Sort path '${s}' references unknown relation '${f}' on '${u}'`);let g=p.targetTableName||p.targetTable;if(typeof g!="string"||!g)throw new b(`Sort relation '${f}' on '${u}' has no target table metadata`);u=g}}}var pe=class{plan(e){let{tableName:t,fields:r,filter:o,sort:i,page:s,limit:a,meta:c,metadata:u,dbType:l}=e,f=u?.tables?.get(t);if(!f)throw new b(`Query planning requires metadata for table '${t}'`);let d=new Te,p=this.parseFields(r),g=p===void 0?void 0:di(p,t,u),h=null;g&&f&&(h=Vr(g,t,u,d));let y=!1,m=null;if(o!=null){Yr(o,t,u);let O=Me(o,t,u,d);m=O.node,y=O.hasRelationFilters}let w=this.parseLimit(a),_=this.parsePage(s),$=this.parseSort(i);f&&_t($,t,u);let k=[],C=!1;for(let O of $){let P=O.startsWith("-"),G=P?O.substring(1):O,re=P?"desc":"asc";if(f){let E=this.parseRelationAggregateSort(t,f,G,u,l);if(E){C=!0,k.push({joinId:null,field:G,direction:re,fullPath:G,function:E.functionName,relationName:E.relationName,aggregateField:E.aggregateField,relationMeta:E.relationMeta});continue}let S=this.resolveLocalSortField(t,f,G,l);k.push({joinId:null,field:S,direction:re,fullPath:S});continue}k.push({joinId:null,field:G,direction:re,fullPath:G})}if(_!==void 0&&w===void 0)throw new b("Query page requires limit to be present");let x=(f?.columns??[]).filter(O=>O.isPrimary===!0).map(O=>O.name);if(x.length===0&&l==="mongodb"&&f?.columns?.some(O=>O.name==="_id")&&x.push("_id"),k.length===0)for(let O of x)_t([O],t,u),k.push({joinId:null,field:O,direction:"asc",fullPath:O});else if(_!==void 0&&w!==void 0)for(let O of x)k.some(P=>P.joinId===null&&P.field===O)||(_t([O],t,u),k.push({joinId:null,field:O,direction:"asc",fullPath:O}));if(_!==void 0&&w!==void 0&&x.length===0)throw new b(`Query pagination requires a deterministic primary key on '${t}'`);let v=_!==void 0&&w!==void 0?(_-1)*w:void 0;if(v!==void 0&&!Number.isSafeInteger(v))throw new b("Query pagination offset exceeds safe integer range");let R=this.parseMeta(c),M=R.includes("totalCount")||R.includes("*"),N=R.includes("filterCount")||R.includes("*"),j=d.getAll();return{table:t,dbType:l,rawFields:g,rawFilter:o??null,joins:j,sortItems:k,limit:w,offset:v,needsTotalCount:M,needsFilterCount:N,hasRelationFilters:y,hasRelationSort:C,filterTree:m,fieldTree:h}}parseFields(e){if(e!=null){if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new b("Query field entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new b("Query fields must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}}parseSort(e){if(e==null)return[];if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new b("Query sort entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new b("Query sort must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}parseLimit(e){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))throw new b("Query limit must be a non-negative integer");let r=Number(t);if(!Number.isSafeInteger(r))throw new b("Query limit must be a safe integer");return r}parsePage(e){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))throw new b("Query page must be a positive integer");let r=Number(t);if(!Number.isSafeInteger(r)||r<1)throw new b("Query page must be a positive safe integer");return r}parseMeta(e){if(e==null)return[];if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new b("Query meta entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new b("Query meta must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}resolveLocalSortField(e,t,r,o){if(r.includes("."))throw new b(`Sort field '${r}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(a=>a.name===r),s=!i&&o==="mongodb"&&r==="id"&&t.columns?.some(a=>a.name==="_id");if(!i&&!s)throw new b(`Sort field '${r}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`);return s?"_id":r}parseRelationAggregateSort(e,t,r,o,i){let s=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!s){if(/^_(count|max|min)\(/.test(r))throw new b(`Sort function '${r}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let a=s[1],c=s[2].trim();if(a==="count"){let y=c;if(!y||y.includes("."))throw new b(`Sort function '${r}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(w=>w.propertyName===y);if(!m)throw new b(`Sort relation '${y}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new b(`Sort function '_count(${y})' is only supported for list relations on '${e}'.`);return{functionName:a,relationName:y,relationMeta:m}}let u=c.indexOf(".");if(u<=0||u!==c.lastIndexOf("."))throw new b(`Sort function '${r}' is not supported on '${e}'. Use _${a}(relationName.fieldName).`);let l=c.slice(0,u).trim(),f=c.slice(u+1).trim();if(!l||!f)throw new b(`Sort function '${r}' is not supported on '${e}'. Use _${a}(relationName.fieldName).`);let d=t.relations?.find(y=>y.propertyName===l);if(!d)throw new b(`Sort relation '${l}' does not exist on '${e}'.`);if(d.type!=="one-to-many"&&d.type!=="many-to-many")throw new b(`Sort function '_${a}(${l}.${f})' is only supported for list relations on '${e}'.`);let p=d.targetTableName||d.targetTable,g=o?.tables?.get(p);if(!g)throw new b(`Sort function '${r}' references unknown target table '${p}' on '${e}'.`);let h=g.columns?.find(y=>y.name===f)??(i==="mongodb"&&f==="id"?g.columns?.find(y=>y.name==="_id"):void 0);if(!h)throw new b(`Sort field '${f}' does not exist on '${p}' for function '_${a}(${l}.${f})'.`);if(h?.isEncrypted===!0)throw new b(`Encrypted field '${f}' on '${p}' cannot be used for sort.`);return{functionName:a,relationName:l,aggregateField:h.name,relationMeta:d}}};var Zr=require("mongodb");et();function ge(n){return n.type==="one-to-many"||n.isInverse===!0||n.type==="one-to-one"&&!!n.mappedBy}function Z(n){return(n.type==="many-to-one"||n.type==="one-to-one")&&!ge(n)&&(n.foreignKeyColumn||n.propertyName)||null}function H(n){return n.foreignKeyColumn||n.mappedBy||n.propertyName||null}function wa(n){return n instanceof Zr.ObjectId?!0:n==null||typeof n!="object"?!1:n._bsontype==="ObjectId"||n._bsontype==="ObjectID"?typeof n.toHexString=="function"||n.id instanceof Uint8Array:!1}function _a(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let e=Object.keys(n);if(e.length!==1||e[0]!=="buffer")return!1;let t=n.buffer;return!!t&&typeof t=="object"&&Object.keys(t).length===12}function se(n){if(!n||typeof n!="object")return n;if(wa(n))return typeof n.toHexString=="function"?n.toHexString():new Zr.ObjectId(Buffer.from(n.id??n.buffer)).toString();if(n instanceof Date)return n.toISOString();if(Buffer.isBuffer(n))return n;if(Array.isArray(n))return n.map(t=>se(t));if(_a(n))try{let t=n.buffer,r=Object.keys(t).sort((o,i)=>parseInt(o,10)-parseInt(i,10)).map(o=>t[o]);return new Zr.ObjectId(Buffer.from(r)).toString()}catch{}let e={};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{value:se(r),enumerable:!0,configurable:!0,writable:!0});return e}function he(n,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,c=e.mappedBy,u=n,l=e.junctionTableName||dr(a,c,u);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:l,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:u};let f=pr(a,c,u);return{junctionName:l,selfColumn:f.targetColumn,otherColumn:f.sourceColumn,owningTable:a,inverseTable:u}}let r=n,o=t,i=e.junctionTableName||dr(r,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:r,inverseTable:o};let s=pr(r,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:r,inverseTable:o}}var tn=require("node:fs"),wi=require("node:path"),en=class{constructor(e,t,r,o){this.dbType=e;this.knexService=t;this.mongoService=r;this.runMongoMutationInSaga=o;this.batchInserts={items:[],flushing:!1};if(this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile)try{(0,tn.mkdirSync)((0,wi.dirname)(this.batchInsertTraceFile),{recursive:!0})}catch{}}async flush(){let e=this.batchInserts.failure;for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)try{await this.flushBatchInsertBuffer()}catch(t){e??={reason:t}}if(e??=this.batchInserts.failure,this.batchInserts.failure=void 0,e)throw e.reason}async enqueue(e,t){let r=Array.isArray(t)?t:[t],o=r.map(i=>({table:e,data:this.cloneBatchInsertRow(i)}));for(let i of o)this.batchInserts.items.push(i);return this.traceBatchInsert("enqueue",{tableName:e,count:r.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:r.length}}cloneBatchInsertRow(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async flushBatchInsertBuffer(){for(;this.batchInserts.flushing;)if(await this.batchInserts.flushPromise,this.batchInserts.items.length===0)return;let e=this.batchInserts.items.splice(0,this.batchInsertMaxSize);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let r=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...r.entries()].map(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...r.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}catch(r){throw this.batchInserts.failure??={reason:r},r}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(r=>this.logBatchInsertError("QueryBuilder batch insert flush failed",r))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let r=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-r})}async runBatchInsertWithIsolation(e,t){if(t.length===0)return;if(!(this.dbType==="mongodb"?typeof this.mongoService?.insertManyWithCascade=="function":typeof this.knexService?.insertManyWithCascade=="function")){let o=async()=>{await this.runLimited(t,async i=>{this.dbType==="mongodb"?await this.mongoService.insertOne(e,i.data):await this.knexService.insertWithCascade(e,i.data)})};this.dbType==="mongodb"?await this.runMongoMutationInSaga(o):await o();return}try{this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.insertManyWithCascade(e,t.map(o=>o.data))):await this.knexService.insertManyWithCascade(e,t.map(o=>o.data))}catch(o){if(t.length===1)throw this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,o),o;let i=Math.ceil(t.length/2),s;for(let a of[t.slice(0,i),t.slice(i)])try{await this.runBatchInsertWithIsolation(e,a)}catch(c){s??={reason:c}}if(s)throw s.reason}}groupBatchInsertsByTable(e){let t=new Map;for(let r of e){let o=t.get(r.table);o?o.push(r):t.set(r.table,[r])}return t}async runLimited(e,t){let r=0,o,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;r<e.length;){let s=e[r++];try{await t(s)}catch(a){o??={reason:a}}}});if(await Promise.all(i),o)throw o.reason}readPositiveEnv(e,t){let r=Number(process.env[e]);return!Number.isSafeInteger(r)||r<=0?t:r}traceBatchInsert(e,t){if(this.batchInsertTraceFile)try{(0,tn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
6
6
|
`)}catch{}}logBatchInsertError(e,t){let r=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:r,code:t?.code,detail:t?.detail}),console.error(`${e}: ${r}`)}};async function tt(n,e,t,r){if(!n)return{scalarFields:[],relations:[]};let o=n.tables?.get(e);if(!o)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(".")&&o.relations?.some(l=>l.propertyName===u.split(".")[0])){let l=u.split("."),f=l[0],d=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(d)}else if(o.relations?.some(f=>f.propertyName===u)){let f=i.get(u)??[];f.includes("_id")||f.push("_id"),i.set(u,f)}else i.has("")||i.set("",[]),i.get("").push(u);if(r&&typeof r=="object")for(let[u,l]of Object.entries(r)){if(i.has(u))continue;let f=l&&typeof l=="object"&&l.fields!=null?Array.isArray(l.fields)?l.fields:String(l.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.set(u,f)}let s=[],a=[],c=i.get("")||[];for(let u of c)if(u==="*"){if(o.columns)for(let l of o.columns)s.includes(l.name)||s.push(l.name);if(o.relations)for(let l of o.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else o.columns?.some(f=>f.name===u)&&!s.includes(u)&&s.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=o.relations?.find(y=>y.propertyName===u);if(!f)continue;let d="",p="",g=!1;f.type==="many-to-one"||f.type==="one-to-one"?ge(f)?(d="_id",p=H(f)||f.propertyName,g=!0):(d=Z(f)||f.propertyName,p="_id",g=!1):f.type==="one-to-many"?(d="_id",p=H(f)||f.propertyName,g=!0):f.type==="many-to-many"&&(f.mappedBy?(d="_id",p=f.mappedBy,g=!0):(d=f.propertyName,p="_id",g=!1));let h=f.type==="one-to-many"||f.type==="many-to-many";a.push({propertyName:u,targetTable:f.targetTableName,localField:d,foreignField:p,type:h?"many":"one",isInverse:g,nestedFields:l})}return{scalarFields:s,relations:a}}ne();Le();var _i=new Set(["fields","filter","sort","limit","page","deep"]),me=3;function Sa(n,e,t,r,o){let i=Array.isArray(n)?n:typeof n=="string"?n.split(","):null;if(!i||i.some(s=>typeof s!="string"))throw new b(`Deep fields for relation '${r}' on '${o}' must be strings`);for(let s of i){let a=s.trim();if(!a||a==="*")continue;let c=a.split(".");if(c.some(l=>!l))throw new b(`Invalid deep field path '${a}'`);let u=e;for(let l=0;l<c.length;l+=1){let f=c[l],d=t?.tables?.get(u);if(!d)throw new b(`Deep fields require metadata for target table '${u}'`);let p=l===c.length-1,g=d.columns?.find(w=>w.name===f),h=f==="id"&&d.columns?.some(w=>w.name==="_id");if(p&&(g||h))break;let y=d.relations?.find(w=>w.propertyName===f);if(!y)break;if(l+1>me)throw new b(`Deep field path exceeds max relation hops of ${me} at '${f}'`);let m=y.targetTableName||y.targetTable;if(typeof m!="string"||!m||!t?.tables?.has(m))throw new b(`Deep field relation '${f}' on '${u}' has no resolvable target table metadata`);if(p)break;u=m}}}function Si(n,e,t,r){if(!Number.isSafeInteger(n)||(e==="limit"?Number(n)<0:Number(n)<1))throw new b(`Deep ${e} for relation '${t}' on '${r}' must be a ${e==="limit"?"non-negative":"positive"} safe integer`);return n}function rt(n,e,t,r=0,o=3){if(!e||typeof e!="object"||Array.isArray(e))throw new b("deep option must be an object");if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(o)||o<1||o>64)throw new b("Deep option recursion bounds must be safe integers within 0..64");if(r>=o)throw new b(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(n),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,c]of Object.entries(e)){let u=s.get(a);if(!u)throw new b(`Unknown relation '${a}' on '${n}'`);if(!c||typeof c!="object"||Array.isArray(c))throw new b(`Deep option for relation '${a}' must be an object`);for(let d of Object.keys(c))if(!_i.has(d))throw new b(`Unknown deep option key '${d}' for relation '${a}'. Allowed: ${[..._i].join(", ")}`);let l=u.type;if(c.limit!==void 0&&(l==="many-to-one"||l==="one-to-one"))throw new b(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${n}')`);if(c.limit!==void 0&&Si(c.limit,"limit",a,n),c.page!==void 0&&Si(c.page,"page",a,n),c.page!==void 0&&c.limit===void 0)throw new b(`'page' requires 'limit' to be present (relation '${a}' on '${n}')`);let f=u.targetTableName||u.targetTable;if(typeof f!="string"||!f||!t?.tables?.has(f))throw new b(`Relation '${a}' on '${n}' has no resolvable target table metadata`);if(c.fields!==void 0&&Sa(c.fields,f,t,a,n),c.filter!==void 0){if(!c.filter||typeof c.filter!="object"||Array.isArray(c.filter))throw new b(`Deep filter for relation '${a}' on '${n}' must be an object`);rn(c.filter,0,a,n,f,t,0,new Set),De(c.filter,f,t),Yr(c.filter,f,t)}if(c.sort!==void 0){if(typeof c.sort!="string"&&!Array.isArray(c.sort))throw new b(`Deep sort for relation '${a}' on '${n}' must be a string or string array`);let d=Array.isArray(c.sort)?c.sort:c.sort.split(",").map(p=>p.trim()).filter(Boolean);if(d.some(p=>typeof p!="string"))throw new b(`Sort entries must be strings (relation '${a}' on '${n}')`);_t(d,f,t);for(let p of d){let g=p.startsWith("-")?p.slice(1):p;$a(g,f,t,a,n)}}c.deep!==void 0&&rt(f,c.deep,t,r+1,o)}}function $a(n,e,t,r,o){if(n.includes("."))throw new b(`Sort field '${n}' is not supported for relation '${r}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new b(`Sort field '${n}' references unknown table '${e}' (relation '${r}' on '${o}')`);let s=i.columns?.some(c=>c.name===n),a=n==="id"&&i.columns?.some(c=>c.name==="_id");if(!s&&!a)throw new b(`Sort field '${n}' does not exist on '${e}' (relation '${r}' on '${o}')`)}var Ta=new Set(["_and","_or","_not"]);function ka(n,e,t,r,o,i){let s=n.split(".");if(s.some(p=>!p))throw new b(`Invalid dotted filter path '${n}'`);let a=e,c=r;for(let p of s.slice(0,-1)){let g=t?.tables?.get(a);if(!g)throw new b(`Filter path '${n}' references unknown table '${a}'`);let h=g.relations?.find(m=>m.propertyName===p);if(!h)throw new b(`Filter path '${n}' references unknown relation '${p}' on '${a}'`);if(c+=1,c>me)throw new b(`Filter path exceeds max dotted hops of ${me} at '${p}' (relation '${o}' on '${i}')`);let y=h.targetTableName||h.targetTable;if(!y)throw new b(`Filter relation '${p}' on '${a}' has no target table`);a=y}let u=s[s.length-1],l=t?.tables?.get(a);if(!l)throw new b(`Filter path '${n}' references unknown table '${a}'`);let f=l.columns?.some(p=>p.name===u),d=u==="id"&&l.columns?.some(p=>p.name==="_id");if(!f&&!d)throw new b(`Filter path '${n}' references unknown field '${u}' on '${a}'`);return{tableName:a,relationDepth:c}}function rn(n,e,t,r,o,i,s,a){if(!(!n||typeof n!="object")){if(s>64)throw new b("Filter nesting depth exceeds maximum of 64");if(a.has(n))throw new b("Filter contains a circular reference");a.add(n);try{if(Array.isArray(n)){for(let l of n)rn(l,e,t,r,o,i,s+1,a);return}let c=i?.tables?.get(o);if(!c)throw new b(`Filter validation requires metadata for table '${o}'`);let u=new Map((c?.relations??[]).map(l=>[l.propertyName,l]));for(let[l,f]of Object.entries(n)){if(Ta.has(l)){rn(f,e,t,r,o,i,s+1,a);continue}if(l.includes(".")){if(ka(l,o,i,e,t,r).relationDepth>me)throw new b(`Filter path exceeds max dotted hops of ${me} at '${l}' (relation '${t}' on '${r}')`);continue}let d=u.get(l);if(!d){if(l.startsWith("_"))continue;continue}let p=e+1;if(p>me)throw new b(`Filter path exceeds max dotted hops of ${me} at '${l}' (relation '${t}' on '${r}')`);let g=d.targetTableName||d.targetTable;g&&rn(f,p,t,r,g,i,s+1,a)}}finally{a.delete(n)}}}function ye(n,e){if(!n||typeof n!="object")return!1;for(let[t,r]of Object.entries(n))if(t==="_and"||t==="_or"){if(Array.isArray(r)){for(let o of r)if(ye(o,e))return!0}}else if(t==="_not"){if(ye(r,e))return!0}else if(e.has(t))return!0;return!1}function Ae(n,e){if(!n||typeof n!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},r={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(n)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let c=Object.keys(a);if(c.some(l=>l.startsWith("_"))){let l=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];c.length>0&&c.every(f=>l.includes(f))?r[s]={id:a}:r[s]=a}else r[s]=a}else r[s]=a;else t[s]=a}let i=ye(n,o);return{fieldFilters:t,relationFilters:r,hasRelations:i}}function uo(n){return`__sort_count_${n.relationName||n.field}`}function fo(n){let e=n.relationName||n.field,t=n.aggregateField||"value";return`__sort_${n.function}_${e.length}_${e}_${t.length}_${t}`}function $i(n){return n.filter(e=>e.function==="count").map(uo)}function Ti(n){return n.filter(e=>(e.function==="max"||e.function==="min")&&e.aggregateField).map(fo)}function ki(n,e,t,r){for(let i of t){if(i.function!=="count")continue;let s=i.relationMeta,a=i.relationName||i.field,c=s?.targetTableName||s?.targetTable,u=uo(i);if(!(!s||!c)){if(s.type==="one-to-many"){let l=H(s)||a;n.push({$lookup:{from:c,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:u}}),n.push({$addFields:{[u]:{$ifNull:[{$arrayElemAt:[`$${u}.value`,0]},0]}}});continue}if(s.type==="many-to-many"){let l=he(e,s);if(!l)continue;n.push({$lookup:{from:l.junctionName,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:u}}),n.push({$addFields:{[u]:{$ifNull:[{$arrayElemAt:[`$${u}.value`,0]},0]}}})}}}}function Ei(n,e,t,r){for(let i of t){if(i.function!=="max"&&i.function!=="min")continue;let s=i.relationMeta,a=i.relationName||i.field,c=s?.targetTableName||s?.targetTable,u=i.aggregateField;if(!s||!c||!u)continue;let l="_id",f=u,d=fo(i),p=i.function==="min"?"$min":"$max";if(s.type==="one-to-many"){let g=H(s)||a;n.push({$lookup:{from:c,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${g}`,"$$localId"]}}},{$group:{_id:null,value:{[p]:`$${f}`}}}],as:d}}),n.push({$addFields:{[d]:{$arrayElemAt:[`$${d}.value`,0]}}});continue}if(s.type==="many-to-many"){let g=he(e,s);if(!g)continue;let h="__enfyra_relation_aggregate_target__";n.push({$lookup:{from:g.junctionName,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${g.selfColumn}`,"$$localId"]}}},{$lookup:{from:c,localField:g.otherColumn,foreignField:l,as:h}},{$unwind:`$${h}`},{$group:{_id:null,value:{[p]:`$${h}.${f}`}}}],as:d}}),n.push({$addFields:{[d]:{$arrayElemAt:[`$${d}.value`,0]}}})}}}function Ea(n){let e=n.split(".");return e[e.length-1]==="id"&&(e[e.length-1]="_id"),e.join(".")}function po(n){let e=Object.create(null);for(let t of n){let r=Ea(t.field);Object.defineProperty(e,r,{value:t.direction==="asc"?1:-1,enumerable:!0,configurable:!0,writable:!0})}return e}function gr(n){let e=Object.create(null);for(let t of n){if((t.function==="max"||t.function==="min")&&!t.aggregateField)continue;let r=t.function==="count"?uo(t):t.function==="max"||t.function==="min"?fo(t):t.joinId!==null?t.fullPath:t.field;Object.defineProperty(e,r,{value:t.direction==="asc"?1:-1,enumerable:!0,configurable:!0,writable:!0})}return e}Ne();var Di=require("mongodb");on();Ne();Ne();function Ii(n,e,t){let{rootFields:r,subRelations:o}=nt(n),i={},s=!1;if(r.includes("*")){s=!0;for(let d of e.relations||[])o.has(d.propertyName)||o.set(d.propertyName,["_id"])}else for(let d of r){let p=e.columns.find(g=>g.name===d);p?i[p.name]=1:e.relations?.find(h=>h.propertyName===d)&&!o.has(d)&&o.set(d,["_id"])}o.forEach((d,p)=>{let g=e.relations?.find(h=>h.propertyName===p);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[Z(g)||g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((d,p)=>{let g=e.relations?.find(w=>w.propertyName===p);if(!g)return;let h=g.targetTableName||g.targetTable;if(!h)return;let y,m;g.type==="many-to-one"||g.type==="one-to-one"?ge(g)?(y="_id",m=H(g)||g.propertyName):(y=Z(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(y="_id",m=H(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(y="_id",m=g.mappedBy):(y=g.propertyName,m="_id")),a.push({relationName:p,type:g.type,targetTable:h,fields:d,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:y,foreignField:m})});let c=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,u=t?.get(e.name)??[],l=[];if(!s&&u.length>0)for(let d of u)i[d.newName]===1&&i[d.oldName]!==1&&(i[d.oldName]=1,l.push(d.oldName));return{isPkOnly:c,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:u,hiddenFields:l}}}function Oe(n,e){let t=e.pendingRenames??[];if(n.length===0||t.length===0)return n;let r=new Set(e.hiddenFields??[]);for(let o of n){let i=Object.getOwnPropertyDescriptors(o),s=[],a=new Set;for(let c of t){let u=Object.prototype.hasOwnProperty.call(i,c.newName),l=Object.prototype.hasOwnProperty.call(i,c.oldName)?i[c.oldName]:void 0;!u&&l&&s.push({name:c.newName,value:l.value}),(r.has(c.oldName)||u||l)&&a.add(c.oldName)}for(let c of s)Object.defineProperty(o,c.name,{value:c.value,enumerable:!0,configurable:!0,writable:!0});for(let c of a)delete o[c]}return n}Ne();var sn=require("mongodb");function vi(n){return`__sort_${n.map(e=>`${e.length}_${e}`).join("_")}`}function Ke(n){let e={};for(let t of ke(n)){let r=t.field.split("."),o=r[r.length-1]==="id"?"_id":r[r.length-1];if(r.length===1)Object.defineProperty(e,o,{value:t.order,enumerable:!0,writable:!0,configurable:!0});else{let i=vi(r.slice(0,-1));e[`${i}.${o}`]=t.order}}return Object.keys(e).length>0?e:void 0}function ke(n){return n?(Array.isArray(n)?n:n.split(",")).map(t=>String(t).trim()).filter(Boolean).map(t=>{let r=t.startsWith("-"),o=r?t.slice(1):t;return{field:o==="id"?"_id":o,order:r?-1:1}}):[]}function yr(n){return ke(n).some(e=>e.field.includes("."))}function an(n,e,t,r=!1,o){let i=ke(t).map(p=>`${p.order===-1?"-":""}${p.field}`),s=[{$match:e}],a=new Set,c=new Map,u=new Set((o?.tables?.get(n)?.columns??[]).map(p=>p.name)),l=p=>{let g=p.join("."),h=c.get(g);if(h)return h;let y=vi(p),m=y,w=1;for(;u.has(m);)m=`${y}_${w++}`;return u.add(m),c.set(g,m),m};for(let p of i){let h=(p.startsWith("-")?p.slice(1):p).split(".");if(h.length<=1)continue;let y=n;for(let m=0;m<h.length-1;m++){let w=h[m],_=o?.tables?.get(y);if(!_)throw new Error(`MongoDB sort metadata not found for table '${y}'`);let $=_.relations?.find(x=>x.propertyName===w);if(!$)throw new Error(`MongoDB dotted sort relation '${y}.${w}' was not found`);let k=$.targetTableName||$.targetTable,C=l(h.slice(0,m+1));if(ge($)||$.type==="one-to-many"||$.type==="many-to-many")throw new Error(`Dotted sort through inverse or to-many relation '${w}' is not supported`);if(!a.has(C)){a.add(C);let x=Z($)||$.propertyName,v=m===0?null:l(h.slice(0,m)),R=v?`${v}.${x}`:x;s.push({$lookup:{from:k,localField:R,foreignField:"_id",as:C}},{$unwind:{path:`$${C}`,preserveNullAndEmptyArrays:!0}})}y=k}}let f={};for(let p of ke(t)){let g=p.field.split(".");if(g.length===1)Object.defineProperty(f,g[0],{value:p.order,enumerable:!0,writable:!0,configurable:!0});else{let h=g[g.length-1]==="id"?"_id":g[g.length-1];f[`${l(g.slice(0,-1))}.${h}`]=p.order}}f._id===void 0&&(f._id=1),s.push({$sort:f});let d={};for(let p of a)d[p]=0;return!r&&Object.keys(d).length>0&&s.push({$project:d}),s}function ot(n,e){let t=i=>i==null?1:typeof i=="number"?2:typeof i=="string"?3:i instanceof sn.ObjectId?7:typeof i=="boolean"?8:i instanceof Date?9:typeof i=="object"&&!Array.isArray(i)?4:Array.isArray(i)?5:100,r=t(n),o=t(e);if(r!==o)return r<o?-1:1;if(n==null&&e==null)return 0;if(typeof n=="number"&&typeof e=="number")return n===e||Number.isNaN(n)&&Number.isNaN(e)?0:Number.isNaN(n)?-1:Number.isNaN(e)?1:n<e?-1:1;if(n instanceof Date&&e instanceof Date){let i=n.getTime(),s=e.getTime();return Number.isNaN(i)&&Number.isNaN(s)?0:Number.isNaN(i)?-1:Number.isNaN(s)?1:i===s?0:i<s?-1:1}if(n instanceof sn.ObjectId&&e instanceof sn.ObjectId)return Buffer.compare(n.id,e.id);if(typeof n=="string"&&typeof e=="string")return Buffer.compare(Buffer.from(n),Buffer.from(e));if(typeof n=="boolean"&&typeof e=="boolean")return n===e?0:n?1:-1;throw new Error("MongoDB in-memory merge does not support object sort keys")}function Mi(n,e){let t=ke(e).filter(r=>!r.field.includes("."));t.length!==0&&n.sort((r,o)=>{for(let i of t){let s=ot(r[i.field],o[i.field]);if(s!==0)return s*i.order}return ot(r._id,o._id)})}function Ai(n){n.sort((e,t)=>ot(e._id,t._id))}var Ca=new Set(["__proto__","constructor","prototype"]);function le(n){return n===0||n===!1}function go(n){let e=Object.entries(n??{});return e.length===0?!1:e.every(([t])=>t==="_id")?e.some(([,t])=>le(t)):e.some(([t,r])=>t!=="_id"&&le(r))}function it(n,e){if(!n||Object.keys(n).length===0)return;let t={...n},r=go(t);for(let o of e){let i=Object.keys(t).filter(s=>s===o||o.startsWith(s+".")||s.startsWith(o+"."));if(r)for(let s of i)le(t[s])&&delete t[s];else if(!i.some(s=>!le(t[s])&&(s===o||o.startsWith(s+".")))){for(let s of i)delete t[s];Object.defineProperty(t,o,{value:1,enumerable:!0,configurable:!0,writable:!0})}}return Object.keys(t).length>0?t:void 0}function Ni(n,e,t){let r=it(e,t);r&&n.push({$project:r})}function ln(n,e){if(!n||Object.keys(n).length===0)return{projection:void 0,hiddenFields:[]};let t=[],r=go(n),o=[...ke(e).map(a=>a.field),"_id"],i=[...new Set(o)],s=it(n,i.filter(a=>!(a==="_id"&&n._id===void 0)));for(let a of i)if(r)for(let[c,u]of Object.entries(n))le(u)&&(c===a||a.startsWith(c+".")||c.startsWith(a+"."))&&t.push(c);else!(a==="_id"&&n._id===void 0)&&!Object.keys(n).some(c=>!le(n[c])&&(c===a||a.startsWith(c+".")))&&t.push(a);return{projection:s,hiddenFields:[...new Set(t)]}}function cn(n,e){if(e)for(let t of n)delete t._id}function un(n,e,t=[]){if(e&&Object.keys(e).length===0&&(e=void 0),!e&&t.length===0)return;let r=e?go(e):!1,o=e?Object.entries(e):[],i=u=>{if(u.some(l=>Ca.has(l)))throw new Error("Unsafe MongoDB projection path")},s=(u,l)=>{if(u==null)return;if(l.length===0)return u;if(Array.isArray(u))return u.map(h=>s(h,l));let[f,...d]=l;if(!Object.prototype.hasOwnProperty.call(u,f))return;let p=s(u[f],d);if(p===void 0)return;let g=Object.create(null);return Object.defineProperty(g,f,{value:p,enumerable:!0,configurable:!0,writable:!0}),g},a=(u,l)=>{if(l===void 0)return u;if(Array.isArray(l)){let p=Array.isArray(u)?u:[];return l.forEach((g,h)=>{p[h]=a(p[h],g)}),p}if(!l||typeof l!="object")return l;let f=Object.getPrototypeOf(l);if(f!==null&&f!==Object.prototype)return l;let d=u&&typeof u=="object"&&!Array.isArray(u)?u:Object.create(null);for(let[p,g]of Object.entries(l))Object.defineProperty(d,p,{value:a(d[p],g),enumerable:!0,configurable:!0,writable:!0});return d},c=(u,l)=>{if(u==null||l.length===0)return;if(Array.isArray(u)){for(let p of u)c(p,l);return}let[f,...d]=l;if(Object.prototype.hasOwnProperty.call(u,f)){if(d.length===0){delete u[f];return}c(u[f],d)}};for(let u of n){if(e)if(r)for(let[l,f]of o){let d=l.split(".");i(d),le(f)&&c(u,d)}else{let l=Object.create(null);for(let[f,d]of o){if(le(d))continue;let p=f.split(".");i(p),l=a(l,s(u,p))}!le(e._id)&&u._id!==void 0&&Object.defineProperty(l,"_id",{value:u._id,enumerable:!0,configurable:!0,writable:!0});for(let f of Object.keys(u))delete u[f];for(let[f,d]of Object.entries(l))Object.defineProperty(u,f,{value:d,enumerable:!0,configurable:!0,writable:!0})}for(let l of Object.keys(u))t.some(f=>l.startsWith(f))&&delete u[l]}}var wr=require("mongodb");$t();var br="__enfyra_top_n_documents__";function ee(n){return Math.ceil(n.length/5e3)||1}function st(n){return Array.from(new Map(n.filter(e=>e!=null).map(e=>[D(e),e])).values())}function Tt(n,e="_id"){let t=Ke(n)||{};return t[e]===void 0&&(t[e]=1),t}function Pe(n,e){return!e||Object.keys(e).length===0?n:{$and:[n,e]}}function _r(n,e,t,r,o){n.push({$group:{_id:`$${e}`,[br]:{$topN:{sortBy:t,output:"$$ROOT",n:r+o}}}},{$project:{[br]:{$slice:[`$${br}`,r,o]}}},{$unwind:`$${br}`},{$replaceRoot:{newRoot:`$${br}`}})}function D(n){return n instanceof wr.ObjectId?`objectId:${n.toHexString()}`:typeof n=="object"&&typeof n?.toHexString=="function"?`objectId:${n.toHexString()}`:n===void 0?"undefined:":typeof n=="object"&&n!==null?`bson:${Buffer.from(wr.BSON.serialize({value:n})).toString("base64")}`:`${typeof n}:${wr.BSON.EJSON.stringify(n,{relaxed:!1})}`}var dn=Je(require("fs")),mo=Je(require("path"));var Ra=new RegExp("\\p{Mark}","gu");function Oi(n){return n==null?"":String(n).normalize("NFKD").replace(Ra,"").toLowerCase()}function ho(){let n={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),r=Oi(t);r!==t&&(n[t]=r)}catch{}return JSON.stringify(n)}function fn(){return`function() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enfyra/kernel",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.7",
|
|
4
4
|
"description": "Closed-distribution Enfyra kernel runtime",
|
|
5
5
|
"license": "Elastic-2.0",
|
|
6
6
|
"packageManager": "yarn@4.17.0",
|
|
@@ -32,13 +32,14 @@
|
|
|
32
32
|
"test:executor-error-metadata": "yarn build && node scripts/test-executor-error-metadata.mjs",
|
|
33
33
|
"test:executor-lanes": "yarn build && node scripts/test-executor-lane-tuning.mjs",
|
|
34
34
|
"test:executor-multiplexing": "yarn build && node scripts/test-executor-multiplexing.mjs",
|
|
35
|
+
"test:executor-crash": "yarn build && node scripts/test-inspector-dispose-race.mjs && node scripts/test-cancel-throw-kills-worker.mjs && node scripts/test-acceptance-worker-host-rejection.mjs",
|
|
35
36
|
"test:query-builder-many-contract": "yarn build && node scripts/test-query-builder-many-contract.mjs",
|
|
36
37
|
"bench:executor-lanes": "yarn build && node scripts/benchmark-executor-lanes.mjs",
|
|
37
38
|
"test:sql-identifiers": "yarn build && node scripts/test-sql-identifier-quoting.mjs",
|
|
38
39
|
"test:relation-aggregate-sort": "node scripts/test-relation-aggregate-sort.mjs",
|
|
39
40
|
"test:deep-inverse-nested": "node scripts/test-deep-inverse-nested.mjs",
|
|
40
41
|
"test:package-runtime-env-sanitize": "node scripts/test-package-runtime-env-sanitize.mjs",
|
|
41
|
-
"test:all": "yarn test:acceptance && yarn test:executor-error-metadata && yarn test:executor-lanes && yarn test:executor-multiplexing && yarn test:query-builder-many-contract && yarn test:sql-identifiers && yarn test:relation-aggregate-sort && yarn test:deep-inverse-nested && yarn test:package-runtime-env-sanitize",
|
|
42
|
+
"test:all": "yarn test:acceptance && yarn test:executor-error-metadata && yarn test:executor-lanes && yarn test:executor-multiplexing && yarn test:executor-crash && yarn test:query-builder-many-contract && yarn test:sql-identifiers && yarn test:relation-aggregate-sort && yarn test:deep-inverse-nested && yarn test:package-runtime-env-sanitize",
|
|
42
43
|
"verify": "node scripts/verify-no-source-leak.mjs && node -e \"const k=require('./dist'); if (typeof k.createEnfyraKernel !== 'function') process.exit(1)\"",
|
|
43
44
|
"prepack": "yarn build && yarn verify",
|
|
44
45
|
"pack:local": "yarn pack --filename enfyra-kernel.tgz"
|