@enfyra/kernel 1.1.28 → 1.1.29

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/index.js CHANGED
@@ -4,7 +4,8 @@
4
4
  `));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
5
5
  "use strict";
6
6
  ${e}
7
- });`)}},ne=new Yt;function Xt(r,e){return ne.compileSource(r,e)}function Ai(r){return ne.isExecutableJavaScript(r)}function Oi(r,e){return ne.normalizeRecord(r,e)}function Ei(r,e,t){return ne.normalizePatch(r,e,t)}function Pi(r){return ne.getExecutableScript(r)}function ji(r){return ne.resolveExecutableScript(r)}function Li(r){return ne.normalizeFlowStepScriptConfig(r)}var Vi=Sr.join(__dirname,"execution/worker.js"),Hi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Expression expected","Missing initializer in const declaration","await is only valid"],Cr=new $r.AsyncLocalStorage;function Fr(){return Cr.getStore()}var xt=class{constructor(e,t,n,o,i,s,a,u=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=n,this.tasksCap=o,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new kr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let o=t.tasks.get(n.id);o&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),o.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):o.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,o=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:o?"Worker terminated":"Worker crashed"}});t.tasks.clear();let i=this.entries.indexOf(t);i!==-1&&this.entries.splice(i,1),!n&&!o&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},wr=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Mn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var Ue=class r{constructor(e){this.logger=new qt(r.name);this.effectiveMemory=Ft();this.isolationTuning=Gt();this.pool=new xt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Vi,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),o=process.cpuUsage(this.prevCpuUsage),i=Number(n-this.prevCpuTime)/1e3,s=i>0?(o.user+o.system)/i:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let o of Object.keys(e)){if(!o.startsWith("$")||o in t||wr.has(o))continue;let i=this.cloneSnapshotValue(e[o]);i!==void 0&&(t[o]=i)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,o]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||wr.has(n)||n==="$env"||(e[n]=o));delete e.$pkgs}}spawnAndExecute(e,t,n,o){return(async()=>{let i=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort();let d=new Error(`Script execution timed out after ${o}ms`);this.cleanupResponseStream(s,d),this.pool.unregisterTask(i,s),this.taskTimeoutTotal++,Q({event:"task_timeout",id:s,timeoutMs:o}),this.pool.terminateEntry(i),d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},o);this.pool.registerTask(i,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.cleanupResponseStream(s),this.pool.unregisterTask(i,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,Q({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,Q({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),this.cleanupResponseStream(s,g),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),i.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),i.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),i.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),i.worker,d.callId,g):d.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(d,n,i.worker),i.worker,d.callId,g):d.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(d,n),i.worker,d.callId,g):d.type==="resCall"&&this.handleIoCall(()=>this.execResCall(d,n),i.worker,d.callId,g)}}),i.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,o){if(!o?.aborted)try{let i=await(o?Cr.run(o,e):e());if(o?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:Mn(i)})}catch{}}catch(i){if(o?.aborted)return;try{let s={__userThrow:!0,message:i.message,statusCode:i.statusCode,code:i.errorCode??i.code,details:i.details,messages:i.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$repos?.[e.table];if(!o||typeof o[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return o[e.method](...n)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),o=e.name.split("."),i=t?.$helpers;for(let s of o)i=i?.[s];if(typeof i!="function")throw new Error(`Helper not found: ${e.name}`);return i(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$socket?.[e.method];if(typeof o!="function")throw new Error(`Socket method not found: ${e.method}`);return o(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$cache?.[e.method];if(typeof o!="function")throw new Error(`Cache method not found: ${e.method}`);return o(...n)}async execStorageCall(e,t,n){let o=this.parseStorageArgs(e.argsJson,n,e.id),i=t?.$storage?.[e.method];if(typeof i!="function")throw new Error(`Storage method not found: ${e.method}`);return i(...o)}parseStorageArgs(e,t,n){return JSON.parse(e,(o,i)=>{if(i?.__fnRef&&typeof i.__fnRef=="string"){let s=i.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return i})}invokeRuntimeCallback(e,t,n,o){let i=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{f(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),l=c=>{if(!(c?.type!=="runtimeCallbackResult"||c.callId!==i)){if(f(),c.error){a(new Error(c.error));return}s(c.value)}},f=()=>{clearTimeout(u),e.off("message",l)};e.on("message",l),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:n,argsJson:JSON.stringify(o)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$trigger;if(typeof o!="function")throw new Error("$trigger is not available");return o(...n)}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new Tr.PassThrough;return this.responseStreams.set(e.id,{stream:u}),a.call(t.$res,u,s),!0}if(e.method==="streamChunk"){let i=this.responseStreams.get(e.id);if(!i)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return i.stream.write(s)||await new Promise((a,u)=>{let l=()=>{c(),a()},f=p=>{c(),u(p)},c=()=>{i.stream.off("drain",l),i.stream.off("error",f)};i.stream.once("drain",l),i.stream.once("error",f)}),!0}if(e.method==="streamEnd"){let i=this.responseStreams.get(e.id);return i&&(i.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let i=this.responseStreams.get(e.id);if(i){let s=e.error?.message||"Response stream failed";i.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),o=t?.$res?.[e.method];if(typeof o!="function")throw new Error(`Response method not found: ${e.method}`);return o.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),t?n.stream.destroy(t):n.stream.end())}isScriptParseFailure(e){let t=e.message||"";return Hi.some(n=>t.includes(n))}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}scheduleCompiledCodeRepair(e,t){e&&Promise.resolve(e(t)).catch(n=>{Q({event:"isolated_compiled_code_repair_failed",message:n.message})})}async run(e,t,n,o={}){let i=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let l;try{let f={code:e,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{l=await this.spawnAndExecute("execute",f,t,i)}catch(c){let p=c;if(!this.isScriptParseFailure(p))throw c;let d=o.sourceCode??e,g=Xt(d,o.scriptLanguage||"typescript")||"";if(g===e)throw c;Q({event:"isolated_run_ts_retry",message:p.message}),this.scheduleCompiledCodeRepair(o.onCompiledCodeRepair,g),l=await this.spawnAndExecute("execute",{...f,code:g,sourceCode:d},t,i)}}catch(f){let c=f;if(Q({event:"isolated_run_error",message:c.message,code:c.code,isTimeout:!!c.isTimeout}),c.isTimeout||c.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,e);let p=c.statusCode??(typeof c.status=="number"?c.status:void 0);throw Me.createException(c.errorPath,p,c.message||"Unknown error",e,c.details||{})}return this.mergeCtxChanges(t,l.ctxChanges||{}),Q({event:"isolated_run_ok"}),l.valueAbsent?void 0:l.value}async runBatch(e,t,n){let o=Math.max(1,Math.trunc(Number(n)||3e4)),i=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(i),a=this.createSnapshot(t);Q({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let u;try{let f={codeBlocks:e.map(c=>this.toWorkerCodeBlock(c)),pkgSources:s,snapshot:a,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",f,t,o)}catch(c){let p=c;if(!this.isScriptParseFailure(p))throw c;let d=e.map(m=>({...m,code:Xt(m.sourceCode??m.code,m.scriptLanguage||"typescript")||"",sourceCode:m.sourceCode??m.code}));if(!d.some((m,h)=>m.code!==e[h]?.code))throw c;Q({event:"isolated_batch_ts_retry",message:p.message});for(let[m,h]of e.entries()){let y=d[m]?.code;y&&y!==h.code&&this.scheduleCompiledCodeRepair(h.onCompiledCodeRepair,y)}u=await this.spawnAndExecute("executeBatch",{...f,codeBlocks:d.map(m=>this.toWorkerCodeBlock(m))},t,o)}}catch(l){let f=l;if(Q({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(o,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Me.createException(f.errorPath,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),Q({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((i,s)=>i-s),o=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[o]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((o,i)=>o+i,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(o=>o.lastHeapRatio||0))}}};var kn=require("node:fs"),fi=require("node:path");var On=require("mongodb");Qe();function Oe(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function H(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Oe(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ae(r){if(!r||typeof r!="object")return r;if(r instanceof On.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ae(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((o,i)=>parseInt(o)-parseInt(i)).map(o=>t[o]);return new On.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?ae(n):n;return e}function de(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,f=e.junctionTableName||vt(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=It(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,o=t,i=e.junctionTableName||vt(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=It(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function Nt(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let o=r.tables?.get(e);if(!o)return{scalarFields:[],relations:[]};let i=new Map;for(let l of t)if(l==="*")i.has("")||i.set("",[]),i.get("").push(l);else if(l.includes(".")){let f=l.split("."),c=f[0],p=f.slice(1).join(".");i.has(c)||i.set(c,[]),i.get(c).push(p)}else o.relations?.some(c=>c.propertyName===l)?i.has(l)||i.set(l,["_id"]):(i.has("")||i.set("",[]),i.get("").push(l));if(n&&typeof n=="object")for(let[l,f]of Object.entries(n)){if(i.has(l))continue;let c=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(p=>p.trim()).filter(Boolean):["*"];i.set(l,c)}let s=[],a=[],u=i.get("")||[];for(let l of u)if(l==="*"){if(o.columns)for(let f of o.columns)s.includes(f.name)||s.push(f.name);if(o.relations)for(let f of o.relations)i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else o.columns?.some(c=>c.name===l)&&!s.includes(l)&&s.push(l);for(let[l,f]of i.entries()){if(l==="")continue;let c=o.relations?.find(h=>h.propertyName===l);if(!c)continue;let p="",d="",g=!1;c.type==="many-to-one"||c.type==="one-to-one"?Oe(c)?(p="_id",d=K(c)||c.propertyName,g=!0):(p=H(c)||c.propertyName,d="_id",g=!1):c.type==="one-to-many"?(p="_id",d=K(c)||c.propertyName,g=!0):c.type==="many-to-many"&&(c.mappedBy?(p="_id",d=c.mappedBy,g=!0):(p=c.propertyName,d="_id",g=!1));let m=c.type==="one-to-many"||c.type==="many-to-many";a.push({propertyName:l,targetTable:c.targetTableName,localField:p,foreignField:d,type:m?"many":"one",isInverse:g,nestedFields:f})}return{scalarFields:s,relations:a}}var en=fe(require("fs")),Pn=fe(require("path"));var Gi=new RegExp("\\p{Mark}","gu");function Er(r){return r==null?"":String(r).normalize("NFKD").replace(Gi,"").toLowerCase()}function En(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Er(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Zt(){return`function() {
7
+ });`)}},ne=new Yt;function Xt(r,e){return ne.compileSource(r,e)}function Ai(r){return ne.isExecutableJavaScript(r)}function Oi(r,e){return ne.normalizeRecord(r,e)}function Ei(r,e,t){return ne.normalizePatch(r,e,t)}function Pi(r){return ne.getExecutableScript(r)}function ji(r){return ne.resolveExecutableScript(r)}function Li(r){return ne.normalizeFlowStepScriptConfig(r)}var Vi=Sr.join(__dirname,"execution/worker.js"),Hi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Expression expected","Missing initializer in const declaration","await is only valid"],Cr=new $r.AsyncLocalStorage;function Fr(){return Cr.getStore()}var xt=class{constructor(e,t,n,o,i,s,a,u=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=n,this.tasksCap=o,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new kr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let o=t.tasks.get(n.id);o&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),o.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):o.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,o=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:o?"Worker terminated":"Worker crashed"}});t.tasks.clear();let i=this.entries.indexOf(t);i!==-1&&this.entries.splice(i,1),!n&&!o&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},wr=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Mn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var Ue=class r{constructor(e){this.logger=new qt(r.name);this.effectiveMemory=Ft();this.isolationTuning=Gt();this.pool=new xt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Vi,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),o=process.cpuUsage(this.prevCpuUsage),i=Number(n-this.prevCpuTime)/1e3,s=i>0?(o.user+o.system)/i:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let o of Object.keys(e)){if(!o.startsWith("$")||o in t||wr.has(o))continue;let i=this.cloneSnapshotValue(e[o]);i!==void 0&&(t[o]=i)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,o]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||wr.has(n)||n==="$env"||(e[n]=o));delete e.$pkgs}}spawnAndExecute(e,t,n,o){return(async()=>{let i=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort();let d=new Error(`Script execution timed out after ${o}ms`);this.cleanupResponseStream(s,d),this.pool.unregisterTask(i,s),this.taskTimeoutTotal++,Q({event:"task_timeout",id:s,timeoutMs:o}),this.pool.terminateEntry(i),d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},o);this.pool.registerTask(i,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.cleanupResponseStream(s),this.pool.unregisterTask(i,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,Q({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,Q({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),this.cleanupResponseStream(s,g),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),i.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),i.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),i.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),i.worker,d.callId,g):d.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(d,n,i.worker),i.worker,d.callId,g):d.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(d,n),i.worker,d.callId,g):d.type==="resCall"&&this.handleIoCall(()=>this.execResCall(d,n),i.worker,d.callId,g)}}),i.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,o){if(!o?.aborted)try{let i=await(o?Cr.run(o,e):e());if(o?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:Mn(i)})}catch{}}catch(i){if(o?.aborted)return;try{let s={__userThrow:!0,message:i.message,statusCode:i.statusCode,code:i.errorCode??i.code,details:i.details,messages:i.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$repos?.[e.table];if(!o||typeof o[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return o[e.method](...n)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),o=e.name.split("."),i=t?.$helpers;for(let s of o)i=i?.[s];if(typeof i!="function")throw new Error(`Helper not found: ${e.name}`);return i(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$socket?.[e.method];if(typeof o!="function")throw new Error(`Socket method not found: ${e.method}`);return o(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$cache?.[e.method];if(typeof o!="function")throw new Error(`Cache method not found: ${e.method}`);return o(...n)}async execStorageCall(e,t,n){let o=this.parseStorageArgs(e.argsJson,n,e.id),i=t?.$storage?.[e.method];if(typeof i!="function")throw new Error(`Storage method not found: ${e.method}`);return i(...o)}parseStorageArgs(e,t,n){return JSON.parse(e,(o,i)=>{if(i?.__fnRef&&typeof i.__fnRef=="string"){let s=i.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return i})}invokeRuntimeCallback(e,t,n,o){let i=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{f(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),l=c=>{if(!(c?.type!=="runtimeCallbackResult"||c.callId!==i)){if(f(),c.error){a(new Error(c.error));return}s(c.value)}},f=()=>{clearTimeout(u),e.off("message",l)};e.on("message",l),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:n,argsJson:JSON.stringify(o)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$trigger;if(typeof o!="function")throw new Error("$trigger is not available");return o(...n)}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new Tr.PassThrough;return this.responseStreams.set(e.id,{stream:u}),a.call(t.$res,u,s),!0}if(e.method==="streamChunk"){let i=this.responseStreams.get(e.id);if(!i)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return i.stream.write(s)||await new Promise((a,u)=>{let l=()=>{c(),a()},f=p=>{c(),u(p)},c=()=>{i.stream.off("drain",l),i.stream.off("error",f)};i.stream.once("drain",l),i.stream.once("error",f)}),!0}if(e.method==="streamEnd"){let i=this.responseStreams.get(e.id);return i&&(i.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let i=this.responseStreams.get(e.id);if(i){let s=e.error?.message||"Response stream failed";i.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),o=t?.$res?.[e.method];if(typeof o!="function")throw new Error(`Response method not found: ${e.method}`);return o.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),t?n.stream.destroy(t):n.stream.end())}isScriptParseFailure(e){let t=e.message||"";return((e.stack||"").split(`
8
+ `)[0]||"").includes("SyntaxError")?Hi.some(o=>t.includes(o)):!1}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}scheduleCompiledCodeRepair(e,t){e&&Promise.resolve(e(t)).catch(n=>{Q({event:"isolated_compiled_code_repair_failed",message:n.message})})}async run(e,t,n,o={}){let i=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let l;try{let f={code:e,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{l=await this.spawnAndExecute("execute",f,t,i)}catch(c){let p=c;if(!this.isScriptParseFailure(p))throw c;let d=o.sourceCode??e,g=Xt(d,o.scriptLanguage||"typescript")||"";if(g===e)throw c;Q({event:"isolated_run_ts_retry",message:p.message}),this.scheduleCompiledCodeRepair(o.onCompiledCodeRepair,g),l=await this.spawnAndExecute("execute",{...f,code:g,sourceCode:d},t,i)}}catch(f){let c=f;if(Q({event:"isolated_run_error",message:c.message,code:c.code,isTimeout:!!c.isTimeout}),c.isTimeout||c.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,e);let p=c.statusCode??(typeof c.status=="number"?c.status:void 0);throw Me.createException(c.errorPath,p,c.message||"Unknown error",e,c.details||{})}return this.mergeCtxChanges(t,l.ctxChanges||{}),Q({event:"isolated_run_ok"}),l.valueAbsent?void 0:l.value}async runBatch(e,t,n){let o=Math.max(1,Math.trunc(Number(n)||3e4)),i=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(i),a=this.createSnapshot(t);Q({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let u;try{let f={codeBlocks:e.map(c=>this.toWorkerCodeBlock(c)),pkgSources:s,snapshot:a,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",f,t,o)}catch(c){let p=c;if(!this.isScriptParseFailure(p))throw c;let d=e.map(m=>({...m,code:Xt(m.sourceCode??m.code,m.scriptLanguage||"typescript")||"",sourceCode:m.sourceCode??m.code}));if(!d.some((m,h)=>m.code!==e[h]?.code))throw c;Q({event:"isolated_batch_ts_retry",message:p.message});for(let[m,h]of e.entries()){let y=d[m]?.code;y&&y!==h.code&&this.scheduleCompiledCodeRepair(h.onCompiledCodeRepair,y)}u=await this.spawnAndExecute("executeBatch",{...f,codeBlocks:d.map(m=>this.toWorkerCodeBlock(m))},t,o)}}catch(l){let f=l;if(Q({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(o,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Me.createException(f.errorPath,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),Q({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((i,s)=>i-s),o=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[o]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((o,i)=>o+i,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(o=>o.lastHeapRatio||0))}}};var kn=require("node:fs"),fi=require("node:path");var On=require("mongodb");Qe();function Oe(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function H(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Oe(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ae(r){if(!r||typeof r!="object")return r;if(r instanceof On.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ae(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((o,i)=>parseInt(o)-parseInt(i)).map(o=>t[o]);return new On.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?ae(n):n;return e}function de(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,f=e.junctionTableName||vt(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=It(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,o=t,i=e.junctionTableName||vt(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=It(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function Nt(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let o=r.tables?.get(e);if(!o)return{scalarFields:[],relations:[]};let i=new Map;for(let l of t)if(l==="*")i.has("")||i.set("",[]),i.get("").push(l);else if(l.includes(".")){let f=l.split("."),c=f[0],p=f.slice(1).join(".");i.has(c)||i.set(c,[]),i.get(c).push(p)}else o.relations?.some(c=>c.propertyName===l)?i.has(l)||i.set(l,["_id"]):(i.has("")||i.set("",[]),i.get("").push(l));if(n&&typeof n=="object")for(let[l,f]of Object.entries(n)){if(i.has(l))continue;let c=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(p=>p.trim()).filter(Boolean):["*"];i.set(l,c)}let s=[],a=[],u=i.get("")||[];for(let l of u)if(l==="*"){if(o.columns)for(let f of o.columns)s.includes(f.name)||s.push(f.name);if(o.relations)for(let f of o.relations)i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else o.columns?.some(c=>c.name===l)&&!s.includes(l)&&s.push(l);for(let[l,f]of i.entries()){if(l==="")continue;let c=o.relations?.find(h=>h.propertyName===l);if(!c)continue;let p="",d="",g=!1;c.type==="many-to-one"||c.type==="one-to-one"?Oe(c)?(p="_id",d=K(c)||c.propertyName,g=!0):(p=H(c)||c.propertyName,d="_id",g=!1):c.type==="one-to-many"?(p="_id",d=K(c)||c.propertyName,g=!0):c.type==="many-to-many"&&(c.mappedBy?(p="_id",d=c.mappedBy,g=!0):(p=c.propertyName,d="_id",g=!1));let m=c.type==="one-to-many"||c.type==="many-to-many";a.push({propertyName:l,targetTable:c.targetTableName,localField:p,foreignField:d,type:m?"many":"one",isInverse:g,nestedFields:f})}return{scalarFields:s,relations:a}}var en=fe(require("fs")),Pn=fe(require("path"));var Gi=new RegExp("\\p{Mark}","gu");function Er(r){return r==null?"":String(r).normalize("NFKD").replace(Gi,"").toLowerCase()}function En(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Er(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Zt(){return`function() {
8
9
  var M = ${En()};
9
10
  function foldStr(s) {
10
11
  if (s == null) return '';
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.28",
3
+ "version": "1.1.29",
4
4
  "source": "bundled-compiled-kernel"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.28",
3
+ "version": "1.1.29",
4
4
  "description": "Closed-distribution Enfyra kernel runtime",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "packageManager": "yarn@4.17.0",
@@ -28,6 +28,7 @@
28
28
  },
29
29
  "scripts": {
30
30
  "build": "node scripts/build.mjs",
31
+ "test:executor-repair-guard": "yarn build && node scripts/test-executor-repair-guard.mjs",
31
32
  "test:sql-identifiers": "yarn build && node scripts/test-sql-identifier-quoting.mjs",
32
33
  "test:relation-aggregate-sort": "node scripts/test-relation-aggregate-sort.mjs",
33
34
  "verify": "node scripts/verify-no-source-leak.mjs && node -e \"const k=require('./dist'); if (typeof k.createEnfyraKernel !== 'function') process.exit(1)\"",