@enfyra/kernel 1.1.28 → 1.1.30

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.
@@ -872,7 +872,7 @@ function __cleanupTask() {
872
872
  `;function de(e){return fe.replace("%%PKG_SETUP%%",e)}q.exports={buildSetupCode:de}});var{parentPort:R}=require("worker_threads"),W=require("fs"),{fileURLToPath:_e}=require("url"),{createPackageRuntimeBridge:pe}=B(),{buildSetupCode:ge}=V(),j;try{j=require("isolated-vm")}catch(e){R.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var I=new Map,Q=0,O=new Map,E=pe({workerDir:__dirname,activeTaskContexts:O}),he=500,ye=5e3,me=32,z=new WeakMap,Y=new WeakMap,ee=new WeakMap,J={created:0,reused:0,released:0,evicted:0,scrubFailed:0},C=null,ke=0,G=0,X=0;async function we(){let e=Date.now();if(e-G<ye)return X;if(G=e,!C)return 0;let t=0;for(let s of C){let r=s?.isolate;if(!(!r||r.isDisposed))try{let a=await r.getHeapStatistics(),o=a.heap_size_limit||1,c=a.used_heap_size/o;c>t&&(t=c)}catch{}}return X=t,t}async function A(e){e.heapRatio=await we(),e.contextStats=ve(),R.postMessage(e)}function ve(){let e=0;if(C)for(let t of C)e+=t?.idleContexts?.length||0;return{...J,idle:e}}function te(e,t){if(!C){let a=Math.max(1,Math.trunc(Number(t)||8));C=new Array(a).fill(null)}let s=ke++%C.length,r=C[s];return(!r||!r.isolate||r.isolate.isDisposed)&&(r={isolate:new j.Isolate({memoryLimit:e}),idleContexts:[]},C[s]=r),r}async function $(e,t,s){let r=z.get(e);r||(r=new Map,z.set(e,r));let a=r.get(t);if(a)return a;let o=await e.compileScript(t,{filename:s});if(r.set(t,o),r.size>he){let c=r.keys().next().value;r.delete(c)}return o}R.on("message",async e=>{if(e.type==="execute")Oe(e).catch(async t=>{await A({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Ee(e).catch(async t=>{await A({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="invokeRuntimeCallback")Pe(e).catch(t=>{R.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:t?.message||String(t)})});else if(e.type==="callResult"){let t=I.get(e.callId);t&&(I.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=I.get(e.callId);t&&(I.delete(e.callId),t.reject(new Error(e.error)))}});async function Pe(e){let t=O.get(e.id);if(!t){R.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let s=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),r=JSON.parse(s);R.postMessage({type:"runtimeCallbackResult",callId:e.callId,...r})}function M(e,t,s){return new Promise((r,a)=>{let o=`cb_${++Q}`;I.set(o,{resolve:r,reject:a}),R.postMessage({type:t,id:e,callId:o,...s})})}function be(e,t,s){R.postMessage({type:t,id:e,callId:`f_${++Q}`,...s})}async function Se(e,t){if(t?.method!=="stream")return M(e,"resCall",t);let s=JSON.parse(t.argsJson||"[]"),r=s[0],a=s[1]||{},o=r?.__pkgHandleArg;if(!o)return M(e,"resCall",t);await M(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,a])});try{await E.streamPackageHandle(e,o,c=>M(e,"resCall",{method:"streamChunk",chunk:Buffer.from(c).toString("base64")})),await M(e,"resCall",{method:"streamEnd"})}catch(c){try{await M(e,"resCall",{method:"streamError",error:{message:c.message,stack:c.stack}})}catch{}throw c}return JSON.stringify({__e:"u"})}function xe(e){if(typeof e.sourceCode=="string"&&e.sourceCode.length>0)return e.sourceCode;let t=e.filePath;return!t&&typeof e.fileUrl=="string"&&e.fileUrl.startsWith("file://")&&(t=_e(e.fileUrl)),!t||!W.existsSync(t)?null:W.readFileSync(t,"utf8")}async function Ce(e,t,s){try{let r=xe(s);if(!r)return null;let a=await e.compileModule(r,{filename:`pkg:${s.safeName}`});await a.instantiate(t,c=>{throw new Error(`Unresolved import in package ${s.safeName}: ${c}`)}),await a.evaluate({timeout:1e4});let o=await a.namespace.get("default");return o!==void 0&&o.typeof!=="undefined"?o.derefInto({release:!1}):a.namespace.derefInto({release:!1})}catch{return null}}function re(e,t){let s=a=>{let o=2166136261;for(let c=0;c<a.length;c++)o^=a.charCodeAt(c),o=Math.imul(o,16777619);return(o>>>0).toString(36)},r=new Set(t||[]);return e.map(a=>{let o=a.cacheKey||`${a.filePath||""}:${a.fileUrl||""}:${a.mtimeMs||""}:${a.size||""}:${s(a.sourceCode||"")}`,c=r.has(a.name)?"isolate":"proxy";return`${a.name}:${a.version||""}:${o}:${c}`}).join("|")}function ne(e,t){let s=new Set(t.map(u=>u.name)),r=new Set,a=String(e||""),o=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,c=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,g=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let u of[o,c])for(let y of a.matchAll(u)){let P=y[2];s.has(P)&&r.add(P)}for(let u of a.matchAll(g)){let y=u[1];s.has(y)&&r.add(y)}return r}async function $e(e,t,s,r){let a=await e.createContext(),o=a.global;await o.set("global",o.derefInto());let c=[],g=[],u=new Map;for(let l of s){u.set(l.name,l);let m=r.has(l.name)?await Ce(e,a,l):null;m!==null?(await o.set(`__pkg_${l.safeName}`,m),c.push(l)):g.push(l)}E.setTaskPackages(t,u),await o.set("__callRef",new j.Reference(async(l,m,w)=>{let k=JSON.parse(w);return m==="pkgCall"?JSON.stringify(await E.executePackageRuntimeCall(l,k)):m==="resCall"?Se(l,k):M(l,m,k)})),await o.set("__fireRef",new j.Reference((l,m,w)=>{let k=JSON.parse(w);be(l,m,k)}));let y=c.map(l=>`$pkgs[${JSON.stringify(l.name)}] = __pkg_${l.safeName};`).concat(g.map(l=>`$pkgs[${JSON.stringify(l.name)}] = __createPkgProxy(${JSON.stringify(l.name)}, []);`)).join(`
873
873
  `),P=ge(y);return await(await $(e,P,"setup.js")).run(a,{timeout:5e3}),Y.set(a,re(s,r)),ee.set(a,u),a}async function ae(e,t,s,r,a,o){let c=e.isolate,g=re(s,a),u=null;for(let h=e.idleContexts.length-1;h>=0;h--){let l=e.idleContexts[h];if(e.idleContexts.splice(h,1),Y.get(l)===g){u=l,J.reused++;break}try{l.release()}catch{}}u||(u=await $e(c,t,s,a),J.created++),E.setTaskPackages(t,ee.get(u)||new Map);let y=u.global;return await y.set("__snapshot",new j.ExternalCopy(r).copyInto()),await y.set("__nextTaskId",t),await y.set("__nextTaskTimeoutMs",o),await(await $(c,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs);","reset-task.js")).run(u,{timeout:5e3}),u}async function se(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await $(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{J.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=me){try{t.release()}catch{}J.evicted++;return}e.idleContexts.push(t),J.released++}}function Re(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var Me=3,Ae=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Ne(e){if(!e)return null;let t=e.split(`
874
874
  `);for(let s of t){let r=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!r)continue;let a=r[1].trim();if(Ae.includes(a))continue;let c=parseInt(r[2])-Me;if(!(c<=0))return{line:c,column:parseInt(r[3]),phase:a.replace(".js","")}}return null}function Te(e,t,s){if(!e||!t)return;let r=String(e).split(/\r?\n/),a=Math.max(1,t-1),o=Math.min(r.length,t+1),c=String(o).length,g=[];for(let u=a;u<=o;u++){let y=u===t?">":" ";g.push(`${y} ${String(u).padStart(c," ")}. ${r[u-1]??""}`),u===t&&s&&s>0&&g.push(` ${" ".repeat(c)} ${" ".repeat(Math.max(0,s-1))}^`)}return g.join(`
875
- `)}function Je(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 L(e,t){let s=Re(e);if(s)return{message:s.message,statusCode:s.statusCode,errorPath:s.errorPath,details:s.details};let r=Ne(e.stack),a=e.message||"Unknown error",o=r?`${a} (${r.phase}, line ${r.line})`:a,c=Je(r,t),g=r?Te(c,r.line,r.column):void 0;return{message:o,statusCode:e.statusCode||null,details:r?{...r,codeFrame:g}:void 0}}async function oe(e,t,s){let r=L(t,s);await A({type:"result",id:e,success:!1,error:{...r,stack:t.stack,code:t.code}})}async function Oe(e){let{id:t,code:s,pkgSources:r,snapshot:a,memoryLimitMb:o,isolatePoolSize:c}=e,g={handler:e.sourceCode||s||""},u=r||[],y=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),P=ne(s,u),h=te(o,c),l=h.isolate,m=await ae(h,t,u,a,P,y);O.set(t,m);try{let w=`
875
+ `)}function Je(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 L(e,t){let s=Re(e);if(s)return{message:s.message,statusCode:s.statusCode,errorPath:s.errorPath,details:s.details};let r=Ne(e.stack),a=e.message||"Unknown error",o=r?`${a} (${r.phase}, line ${r.line})`:a,c=Je(r,t),g=r?Te(c,r.line,r.column):void 0;return{message:o,statusCode:e.statusCode||null,details:{errorName:e.name||null,...r?{...r,codeFrame:g}:{}}}}async function oe(e,t,s){let r=L(t,s);await A({type:"result",id:e,success:!1,error:{...r,stack:t.stack,code:t.code}})}async function Oe(e){let{id:t,code:s,pkgSources:r,snapshot:a,memoryLimitMb:o,isolatePoolSize:c}=e,g={handler:e.sourceCode||s||""},u=r||[],y=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),P=ne(s,u),h=te(o,c),l=h.isolate,m=await ae(h,t,u,a,P,y);O.set(t,m);try{let w=`
876
876
  (async () => {
877
877
  "use strict";
878
878
  ${s}
package/dist/index.js CHANGED
@@ -1,11 +1,10 @@
1
- "use strict";var hi=Object.create;var Qt=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var yi=Object.getOwnPropertyNames;var bi=Object.getPrototypeOf,_i=Object.prototype.hasOwnProperty;var U=(r,e)=>()=>(r&&(e=r(r=0)),e);var xn=(r,e)=>{for(var t in e)Qt(r,t,{get:e[t],enumerable:!0})},pr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yi(e))!_i.call(r,o)&&o!==t&&Qt(r,o,{get:()=>e[o],enumerable:!(n=mi(e,o))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?hi(bi(r)):{},pr(e||!r||!r.__esModule?Qt(t,"default",{value:r,enumerable:!0}):t,r)),wi=r=>pr(Qt({},"__esModule",{value:!0}),r);function xr(r){return An.createHash("md5").update(r).digest("hex").substring(0,8)}function vr(r){return r.length<=Rr-3?`${r}_pk`:`j_${xr(r)}_pk`}function Ir(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=Rr?n:`j_${xr(r)}_${t}_fk`}function vt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${An.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function V(r){return`${r}Id`}function It(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Nr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Mr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Ar(r,e,t){return`${r}_${e}_${t}_fk`}function Or(r,e,t){return`${r}_${e}_${t}_idx`}var An,Rr,Qe=U(()=>{"use strict";An=fe(require("crypto")),Rr=63});function on(r){return eo[r]??null}var ie,jn,Mt,eo,At=U(()=>{"use strict";ie=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),jn=new Set(["_and","_or","_not"]),Mt=[...Array.from(jn),...Array.from(ie)],eo={_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 v,pe=U(()=>{"use strict";v=class extends Error{constructor(t="Bad Request",n){let o=Array.isArray(t),i=o?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,o&&(this.messages=t)}}});function Lr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Br=U(()=>{"use strict"});function Ee(r,e,t){throw new v({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Mt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Mt})}function sn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Lr();for(let o of Object.keys(e))if(o.startsWith("_")&&!ie.has(o)){if(n&&o==="_id")continue;Ee(o,r,t)}}function J(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),o=new Set((n?.columns??[]).map(s=>s.name)),i=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(to.has(s)){if(Array.isArray(a))for(let l of a)J(l,e,t);else a&&typeof a=="object"&&J(a,e,t);continue}let u=i.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){sn(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let f=Object.keys(a).filter(c=>!c.startsWith("_"));if(f.length>0){let c={};for(let p of f)c[p]=a[p];J(c,l,t)}}}continue}s.startsWith("_")&&!o.has(s)&&s!=="_id"&&Ee(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&sn(s,a,e)}}var to,Ve=U(()=>{"use strict";pe();At();Br();to=new Set(["_and","_or","_not"])});function ge(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:an(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function an(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[o,i]of Object.entries(r)){let s=no(o,i,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function no(r,e,t){if(r==="_and")return Dr("and",e,t);if(r==="_or")return Dr("or",e,t);if(r==="_not"){let l=an(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),o=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),i=n?.columns?.some(l=>l.name==="id"),a=r==="id"?o&&!i?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?ro(a,e,u,t):n&&!n.columns?.find(f=>f.name===a)?(r.startsWith("_")&&r!=="_id"&&Ee(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):io(a,e,t)}function Dr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],o=!1;for(let i of e){let s=an(i,t);s.hasRelationFilters&&(o=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:o}:n.length===1?{node:n[0],hasRelationFilters:o}:{node:{kind:r,children:n},hasRelationFilters:o}}function ro(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let o=Object.keys(e),i=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"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(i&&o[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&o[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:o[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=o.length>0&&o.every(d=>l.has(d))?{id:e}:e;return{node:an(c,u).node,hasRelationFilters:!0}}function io(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:so(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!ie.has(s)&&Ee(s,r,t.tableName);let o=Object.entries(e).filter(([s])=>ie.has(s));if(o.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){let u=oo(n,s,a);u&&i.push(u)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function oo(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=on(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function so(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.find(s=>s.name===n);if(!o)return!1;let i=(o.type||"").toLowerCase();return i==="uuid"||i==="uuidv4"||i.includes("uuid")}var Ot=U(()=>{"use strict";At();Ve()});var oe,Et=U(()=>{"use strict";oe=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t;if(this.map.has(a)){let p=this.map.get(a);return o==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let f=l.targetTableName||l.targetTable;if(!f)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:f,relationType:l.type,parentJoinId:i,joinType:o,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function ee(r,e){if(r.length<=Fe)return e(r);let t=[];for(let a=0;a<r.length;a+=Fe)t.push(r.slice(a,a+Fe));let n=[],o=0;async function i(){for(;o<t.length;){let a=o++;n[a]=await e(t[a])}}let s=Math.min(Jn,t.length);return await Promise.all(Array.from({length:s},i)),n.flat()}function Ge(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let o=n.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 se,Fe,Jn,qn,Re,Ye=U(()=>{"use strict";pe();se=16,Fe=5e3,Jn=4,qn=10;Re=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let o=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(l=>l.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),i=new Set(o.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(i.has(s))continue;let u=n?.relations?.find(f=>f.propertyName===s);if(!u)continue;let l=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];o.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:l,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return o}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:qn}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))n.has(i)||o.push(i);return o}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new v(`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(u=>u.name===i),a=i==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new v(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,o=0,i){if(e.length===0||t.length===0||o>=n)return;let s;i&&(s=await this.metadataGetter(i)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,o):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,o,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,o,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,o){let i=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let y of e){let b=y[i];if(b==null)continue;let S=this.adapter.keyOf(b);s.has(S)||(s.add(S),a.push(b))}if(a.length===0){for(let y of e)y[t.relationName]=null,i!==t.relationName&&delete y[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete y[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:l,nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),p=this.adapter.getTargetPkField(u);if(l){for(let y of e){let b=y[i];y[t.relationName]=b!=null?this.adapter.buildScalarRef(b,p):null,i!==t.relationName&&delete y[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete y[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/Fe)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(f,t.nestedDeep,u);m.length>0&&await this.execute(g,m,n,o+1,t.targetTable);let h=new Map;for(let y of g)h.set(this.adapter.keyOf(y[p]),y);for(let y of e){let b=y[i];y[t.relationName]=b!=null&&h.get(this.adapter.keyOf(b))||null,i!==t.relationName&&delete y[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete y[t.fkColumn]}}async fetchInverseRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=e.map(R=>R[s]).filter(R=>R!=null);if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,l);let{nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),m=new Map,h=t.fields.includes(u)||t.fields.includes("*");for(let R of d){let M=R[g],T=this.adapter.keyOf(M);m.has(T)||m.set(T,[]),m.get(T).push(R)}let y=t.userLimit!==void 0&&t.userLimit>0,b=y?"per-parent-c16":"batch-in",S=y?a.length:Math.ceil(a.length/Fe)||1,_=y?Math.ceil(a.length/se):void 0,$=Array.from(m.values()).reduce((R,M)=>R+M.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:b,roundtrips:S,concurrencyWaves:_,rowsTransferred:d.length,rowsReturned:$,rowsDiscarded:d.length-$,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let R of d)this.adapter.postProcessInverseChild(R,u,h);let k=this.enrichNestedDescs(f,t.nestedDeep,l);k.length>0&&await this.execute(d,k,n,o+1,t.targetTable);let N=t.type==="one-to-one";for(let R of e){let M=this.adapter.keyOf(R[s]),T=m.get(M)||[];R[t.relationName]=N?T[0]||null:T}}async fetchM2MRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=e.map(_=>_[s]).filter(_=>_!=null);if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:l,fetchSpec:f}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,i,u,f),g=t.userLimit!==void 0&&t.userLimit>0,m=g?"m2m-per-parent-c16":"m2m-batch",h=g?a.length:Math.ceil(a.length/Fe)||1,y=g?Math.ceil(a.length/se):void 0,b=Array.from(p.values()).reduce((_,$)=>_+$.length,0);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:m,roundtrips:h,concurrencyWaves:y,rowsTransferred:d.length,rowsReturned:b,rowsDiscarded:d.length-b,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let S=this.enrichNestedDescs(l,t.nestedDeep,u);S.length>0&&d.length>0&&await this.execute(d,S,n,o+1,t.targetTable);for(let _ of e){let $=this.adapter.keyOf(_[s]);_[t.relationName]=p.get($)||[]}}}});async function be(r,e,t){let n=new Map,o=0;async function i(){for(;o<r.length;){let u=o++,l=r[u];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},i);return await Promise.all(a),n}var gn=U(()=>{"use strict"});function F(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function Ie(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:F(t,e)).join(".")}var le=U(()=>{"use strict"});function te(r,e,t){e&&Sn(r,e,t,"and")}function Sn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let o=function(){for(let i of e.children)this.where(function(){Sn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"or":{let o=function(){for(let i of e.children)this.orWhere(function(){Sn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"not":{let o=function(){this.whereNot(function(){Sn(this,e.child,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"compare":Po(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function Po(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let o=jo(e.field,t),i=Ie(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",l=n==="or"?"orWhereRaw":"whereRaw",f=n==="or"?"orWhereIn":"whereIn",c=n==="or"?"orWhereNotIn":"whereNotIn",p=n==="or"?"orWhereBetween":"whereBetween",d=n==="or"?"orWhereNull":"whereNull",g=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[l](`${i} = ?::uuid`,[e.value]):r[u](o,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[l](`${i} != ?::uuid`,[e.value]):r[u](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[l](`${i} > ?::uuid`,[e.value]):r[u](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[l](`${i} >= ?::uuid`,[e.value]):r[u](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[l](`${i} < ?::uuid`,[e.value]):r[u](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[l](`${i} <= ?::uuid`,[e.value]):r[u](o,"<=",e.value);return;case"in":{let m=oi(e.value);s&&a&&m.every(h=>typeof h=="string")?r[l](`${i} = ANY(?::uuid[])`,[m]):r[f](o,m);return}case"not_in":{let m=oi(e.value);s&&a&&m.every(h=>typeof h=="string")?r[l](`${i} != ALL(?::uuid[])`,[m]):r[c](o,m);return}case"contains":ir(r,i,e.value,"contains",t,n);return;case"starts_with":ir(r,i,e.value,"starts_with",t,n);return;case"ends_with":ir(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[p](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[d](o):r[g](o);return}}function ir(r,e,t,n,o,i){let s=i==="or"?"orWhereRaw":"whereRaw";if(o.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(o.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function jo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function oi(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var or=U(()=>{"use strict";le()});function Y(r){return r.columns.find(e=>e.isPrimary)||null}var Kt=U(()=>{"use strict"});var ai={};xn(ai,{expandFieldsToJoinsAndSelect:()=>sr});async function sr(r,e,t,n,o,i){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}if(i&&typeof i=="object")for(let[c,p]of Object.entries(i)){if(l.has(c))continue;let d=p&&typeof p=="object"&&p.fields!=null?Array.isArray(p.fields)?p.fields:String(p.fields).split(",").map(g=>g.trim()).filter(Boolean):["*"];l.set(c,d)}let f=l.get("")||[];for(let c of f){if(c==="*"){let g=new Set;for(let h of u.relations||[])if(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse){let y=h.foreignKeyColumn||V(h.propertyName);y&&g.add(y)}let m=new Set;for(let h of u.columns)g.has(h.name)||(s.push(`${r}.${h.name}`),m.add(h.name));for(let h of u.relations||[])!l.has(h.propertyName)&&!m.has(h.propertyName)&&l.set(h.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=u.relations?.find(b=>b.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let b=d.foreignKeyColumn||V(d.propertyName),S=F(r,n),_=F(b,n),$=F(p,n);s.push(`${S}.${_} as ${$}`)}let m=d.targetTableName||d.targetTable,h=i?.[p],y=h?.fields!=null?Array.isArray(h.fields)?h.fields:String(h.fields).split(",").map(b=>b.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:m,fields:y,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:h?.filter,userSort:h?.sort,userLimit:h?.limit!==void 0?Number(h.limit):void 0,userPage:h?.page!==void 0?Number(h.page):void 0,nestedDeep:h?.deep})}),{select:s,batchFetchDescriptors:a}}var ar=U(()=>{"use strict";Qe();le()});var st,cr=U(()=>{"use strict";Qe();le();Kt();Ye();or();Et();Ot();gn();st=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new oe,o=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:i}=ge(e,t,o,n);return i}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),u=(s?i.slice(1):i).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,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 l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let f=n,c=o||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(f);if(!g)break;let m=g.relations?.find(b=>b.propertyName===d);if(!m)break;let h=m.targetTableName||m.targetTable,y=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(y)){s.add(y);let b=m.foreignKeyColumn||V(m.propertyName),S=this.metadata?.tables?.get(h),_=S&&Y(S)?.name||"id";e.leftJoin(`${h} as ${y}`,`${y}.${_}`,`${c}.${b}`)}f=h,c=y}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let o=e.substring(0,n),i=e.substring(n+4),s=F(i,this.dbType),a=t?`${t}.${F(o,this.dbType)}`:F(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${F(e,this.dbType)} as ${F(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return Y(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=V(e.mappedBy)),t||(t=V(e.targetTable)),t}resolveParentPk(e){return e&&Y(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:o}=Ge(e),i=[];if(n.includes("*")){let l=new Set;for(let f of t.relations||[])if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let c=f.foreignKeyColumn||V(f.propertyName);c&&l.add(c)}for(let f of t.columns)l.has(f.name)||i.push(f.name);for(let f of t.relations||[])o.has(f.propertyName)||o.set(f.propertyName,["id"])}else for(let l of n){let f=t.columns.find(c=>c.name===l);f?i.push(f.name):t.relations?.find(p=>p.propertyName===l)&&!o.has(l)&&o.set(l,["id"])}let s=Y(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((l,f)=>{let c=t.relations?.find(p=>p.propertyName===f);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||V(c.propertyName);p&&i.push(`${p} as ${f}`)}});let a=[];return o.forEach((l,f)=>{let c=t.relations?.find(d=>d.propertyName===f);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:f,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.parseSortTokens(o.userSort,e):[],a=n.selectCols.map(u=>this.toKnexSelect(u));return ee(t,u=>{let l=this.knex(e).select(a).whereIn(n.pkCol,u);if(i&&te(l,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,o.userSort,e);for(let f of s)l.orderBy(f.column,f.order)}return l})}async fetchInverse(e,t,n,o,i){let s=t,a=o.selectCols.find(g=>g.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let u=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,l=i?.userSort?this.parseSortTokens(i.userSort,e):[],f=i?.userLimit,c=i?.userPage;if(f!==void 0&&f>0){let g=c?(c-1)*f:0,m=o.selectCols.map(b=>this.toKnexSelect(b)),h=await be(n,async b=>{let S=this.knex(e).select(m).where(t,b);if(u&&te(S,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(S,i.userSort,e),l.length>0)for(let _ of l)S.orderBy(_.column,_.order);else S.orderBy(o.pkCol,"asc");return g>0&&S.offset(g),S.limit(f),S},se),y=[];for(let[b,S]of h.entries()){let _=n.find($=>String($)===b);for(let $ of S)$[t]||($[t]=_??b),y.push($)}return{docs:y,groupKeyField:s}}let p=o.selectCols.map(g=>this.toKnexSelect(g));return{docs:await ee(n,g=>{let m=this.knex(e).select(p).whereIn(t,g);if(u&&te(m,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(m,i?.userSort,e),l.length>0)for(let h of l)m.orderBy(h.column,h.order);else m.orderBy(o.pkCol,"asc");return m}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,o,i){let s=this.resolveParentPk(n),a=e.map(S=>S[s]).filter(S=>S!=null);if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,f=t.junctionTargetColumn;if(!u||!l||!f)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(i.selectCols.length===1&&i.selectCols[0]===i.pkCol&&!c&&!d){let S=await ee(a,$=>this.knex(u).select([`${l} as __sourceId__`,`${f} as __targetId__`]).whereIn(l,$).orderBy(f,"asc")),_=new Map;for(let $ of S){let k=this.keyOf($.__sourceId__);_.has(k)||_.set(k,[]),_.get(k).push({[i.pkCol]:$.__targetId__})}return{grouped:_,docs:[]}}let h=i.selectCols.map(S=>this.toKnexSelect(S,"t"));if(d!==void 0&&d>0){let S=g?(g-1)*d:0,_=new Map;for(let N of a)_.set(this.keyOf(N),[]);let $=await be(a,async N=>{let R=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${i.pkCol}`).select(h).where(`${u}.${l}`,N);if(c&&te(R,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(R,t.userSort,t.targetTable,"t"),p.length>0)for(let M of p)R.orderBy(M.column,M.order);else R.orderBy(`t.${i.pkCol}`,"asc");return S>0&&R.offset(S),R.limit(d),R},se),k=[];for(let[N,R]of $.entries()){_.set(N,R);for(let M of R)k.push(M)}return{grouped:_,docs:k}}let y=await ee(a,S=>{let _=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${i.pkCol}`).select([`${u}.${l} as __sourceId__`,...h]).whereIn(`${u}.${l}`,S);if(c&&te(_,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(_,t.userSort,t.targetTable,"t"),p.length>0)for(let $ of p)_.orderBy($.column,$.order);else _.orderBy(`t.${i.pkCol}`,"asc");return _}),b=new Map;for(let S of y){let _=S.__sourceId__;delete S.__sourceId__;let $=this.keyOf(_);b.has($)||b.set($,[]),b.get($).push(S)}return{grouped:b,docs:y}}}});var ui={};xn(ui,{executeBatchFetches:()=>ur});async function ur(r,e,t,n,o=3,i=0,s,a="postgres",u,l){let f=new st(r,a,u);await new Re(f,n,l).execute(e,t,o,i,s)}var fr=U(()=>{"use strict";Ye();cr()});var Wo={};xn(Wo,{ALL_SUPPORTED_OPERATORS:()=>Mt,AuthenticationException:()=>ht,AuthorizationException:()=>mt,BadRequestException:()=>v,BatchFetchEngine:()=>Re,BusinessLogicException:()=>ft,CHUNKED_FETCH_CONCURRENCY:()=>Jn,ConfigurationException:()=>St,DEEP_TO_MANY_DEFAULT_LIMIT:()=>qn,DEFAULT_TIMEOUT_MS:()=>Jt,DOTTED_PATH_MAX_HOPS:()=>Fn,DatabaseException:()=>We,DuplicateResourceException:()=>gt,ErrorHandler:()=>Me,ExecutorEngineService:()=>De,ExternalServiceException:()=>_t,FIELD_OPERATORS:()=>ie,FileNotFoundException:()=>kt,FileSizeExceededException:()=>Ct,FileUploadException:()=>Tt,HttpException:()=>E,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>zt,InvalidTokenException:()=>bt,IsolatedExecutorService:()=>Ue,JoinRegistry:()=>oe,LOGICAL_OPERATORS:()=>jn,MongoBatchAdapter:()=>Xe,MongoQueryExecutor:()=>nt,PER_PARENT_CONCURRENCY:()=>se,QueryBuilderService:()=>lt,QueryPlanner:()=>q,ResourceNotFoundException:()=>pt,SchemaException:()=>$t,ScriptContractService:()=>Yt,ScriptExecutionException:()=>$e,ScriptTimeoutException:()=>we,ServiceUnavailableException:()=>wt,SqlBatchAdapter:()=>st,SqlQueryExecutor:()=>at,TokenExpiredException:()=>yt,ValidationException:()=>dt,WHERE_IN_CHUNK_SIZE:()=>Fe,WorkerPool:()=>xt,appendIsolatedExecutorRuntimeLog:()=>Q,applyOperatorToMatch:()=>rn,applyRelationFilters:()=>Be,applyWhereToKnex:()=>ot,assertFieldOperatorValueIsClean:()=>sn,buildAggregateFilter:()=>tt,buildMongoCharFoldMapJson:()=>En,buildMongoFoldTextSearchJs:()=>Zt,buildRelationSubquery:()=>Bt,buildSqlWherePartsFromFieldAst:()=>Wt,buildWhereClause:()=>ce,camelToSnake:()=>Mr,chunkedFetch:()=>ee,compileScriptSource:()=>Xt,computeEngineTuning:()=>In,createEnfyraKernel:()=>Do,dslOpToCompareOp:()=>on,encodeMainThreadToIsolate:()=>Mn,escapeSqlValue:()=>si,executeBatchFetches:()=>ur,executeMongoBatchFetches:()=>hn,expandFieldsToJoinsAndSelect:()=>sr,getEffectiveCpuCount:()=>vn,getEffectiveMemoryBytes:()=>Ft,getEngineTuning:()=>Gt,getExecutableScript:()=>Pi,getForeignKeyColumnName:()=>V,getIoAbortSignal:()=>Fr,getJunctionColumnNames:()=>It,getJunctionTableName:()=>vt,getPrimaryKeyColumn:()=>Y,getScriptLegacyField:()=>Ii,getShortFkConstraintName:()=>Ir,getShortFkName:()=>Ar,getShortIndexName:()=>Or,getShortPkName:()=>vr,hasAggregateQuery:()=>Xn,hasLogicalOperators:()=>_e,isExecutableJavaScript:()=>Ai,isScriptTable:()=>Ni,mergeAggregateValue:()=>ve,normalizeAggregateQuery:()=>et,normalizeFlowStepScriptConfig:()=>Li,normalizeScriptLanguage:()=>Mi,normalizeScriptPatch:()=>Ei,normalizeScriptRecord:()=>Oi,parseBatchFields:()=>Ge,parseFields:()=>mn,parseFilter:()=>ge,perParentRun:()=>be,quoteIdentifier:()=>F,quoteQualifiedIdentifier:()=>Ie,resolveExecutableScript:()=>ji,rewriteFilterDenyingFields:()=>pi,rewriteSortDroppingDenied:()=>gi,scriptContractService:()=>ne,separateFilters:()=>G,snakeToCamel:()=>Nr,throwUnsupportedFieldOperator:()=>Ee,validateDeepOptions:()=>dr,validateFilterShape:()=>J,whereToMongoFilter:()=>ze});module.exports=wi(Wo);var Jt=3e4,De=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){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Jt)}async run(e,t,n=Jt,o={}){return this.isolatedExecutorService.run(e,t,n,o)}};var qt=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&&console.error(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=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var $r=require("async_hooks"),Sr=fe(require("path")),Tr=require("stream"),kr=require("worker_threads");var we=class extends Error{constructor(t=0,n){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},$e=class extends Error{constructor(t,n,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...o}}},D=class extends Error{constructor(t,n,o,i){super(t);this.statusCode=n;this.errorCode=o;this.name=this.constructor.name,this.details=i}},E=class extends D{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ft=class extends D{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},dt=class extends D{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},pt=class extends D{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},gt=class extends D{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},ht=class extends D{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},mt=class extends D{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},yt=class extends D{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},bt=class extends D{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},We=class extends D{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},_t=class extends D{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},wt=class extends D{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},$t=class extends D{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},St=class extends D{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Tt=class extends D{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},kt=class extends D{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},Ct=class extends D{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Me=class{static createException(e,t,n,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new E(n||"Error",t||500,i);case"$throw.businessLogic":return new ft(n||"Bad request",i);case"$throw.validation":return new dt(n||"Validation failed",i);case"$throw.notFound":return new pt(i?.resource||n||"Resource",i?.identifier);case"$throw.duplicate":return new gt(i?.resource||n||"Resource",i?.field||"field",i?.value||"value");case"$throw.unauthorized":return new ht(n||"Unauthorized");case"$throw.forbidden":return new mt(n||"Forbidden");case"$throw.tokenExpired":return new yt;case"$throw.invalidToken":return new bt;case"$throw.database":return new We(n||"Database error",i);case"$throw.dbQuery":return new We(n||"Query error",i);case"$throw.externalService":return new _t(n||"Service",n||"Error",i);case"$throw.serviceUnavailable":return new wt(n||"Service");case"$throw.rateLimit":return new E(n||"Rate limit exceeded",429);case"$throw.scriptError":return new $e(n||"Script error",o,i);case"$throw.scriptTimeout":return new we(i?.timeout||5e3,o);case"$throw.schema":return new $t(n||"Schema error",i);case"$throw.config":return new St(n||"Configuration error",i);case"$throw.fileUpload":return new Tt(n||"File upload error",i);case"$throw.fileNotFound":return new kt(n||"File not found");case"$throw.fileSizeExceeded":return new Ct(i?.maxSize||"unknown",i?.actualSize||"unknown");case"$throw.400":return new E(n||"Bad request",400,i);case"$throw.401":return new E(n||"Authentication required",401,i);case"$throw.403":return new E(n||"Insufficient permissions",403,i);case"$throw.404":return new E(n||"Not found",404,i);case"$throw.409":return new E(n||"Conflict",409,i);case"$throw.422":return new E(n||"Validation failed",422,i);case"$throw.429":return new E(n||"Rate limit exceeded",429,i);case"$throw.500":return new E(n||"Internal server error",500,i);case"$throw.503":return new E(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o)}if(t)switch(t){case 400:return new E(n||"Bad request",400,i);case 401:return new E(n||"Authentication required",401,i);case 403:return new E(n||"Insufficient permissions",403,i);case 404:return new E(n||"Not found",404,i);case 409:return new E(n||"Conflict",409,i);case 422:return new E(n||"Validation failed",422,i);case 429:return new E(n||"Rate limit exceeded",429,i);case 500:return new E(n||"Internal server error",500,i);case 503:return new E(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o,i)}return new $e(n||"Unknown error",o,i)}};var Vt=fe(require("fs")),Ht=fe(require("path")),zt=Ht.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function $i(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var Si=$i();function Q(r){if(Si)try{let e=Ht.dirname(zt);Vt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
- `;Vt.appendFileSync(zt,t)}catch{}}var Se=fe(require("os")),Ke=fe(require("fs"));function Ft(){try{let r=Ke.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Se.totalmem())return e}}catch{}try{let r=Ke.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Se.totalmem())return e}catch{}return Se.totalmem()}function vn(){let r=Se.availableParallelism?.()||Se.cpus()?.length||1;try{let e=Ke.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let o=parseInt(t,10),i=parseInt(n,10);if(o>0&&i>0)return Math.max(1,Math.ceil(o/i))}}catch{}try{let e=parseInt(Ke.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Ke.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var Ti=.25,ki=2,Ci=2048,Fi=40,Ri=128,xi=32;function In(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Ri,Math.max(Fi,Math.round(t/xi))),o=t*Ti,i=Math.max(1,Math.floor(o/n)),s=Math.max(1,Math.min(e,2,i)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<Ci?1:ki,l=Math.max(1,Math.min(u,Math.floor(o/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:l}}function Gt(){return In({logicalCpuCount:vn(),totalMemoryBytes:Ft()})}var Ae=fe(require("typescript"));var vi={"@CACHE":"$ctx.$cache","@REPOS":"$ctx.$repos","@HELPERS":"$ctx.$helpers","@STORAGE":"$ctx.$storage","@FETCH":"$ctx.$helpers.$fetch","@LOGS":"$ctx.$logs","@BODY":"$ctx.$body","@ENV":"$ctx.$env","@DATA":"$ctx.$data","@PARAMS":"$ctx.$params","@QUERY":"$ctx.$query","@USER":"$ctx.$user","@REQ":"$ctx.$req","@RES":"$ctx.$res","@SHARE":"$ctx.$share","@API":"$ctx.$api","@UPLOADED_FILE":"$ctx.$uploadedFile","@PKGS":"$ctx.$pkgs","@SOCKET":"$ctx.$socket","@TRIGGER":"$ctx.$trigger","@FLOW":"$ctx.$flow","@FLOW_PAYLOAD":"$ctx.$flow.$payload","@FLOW_LAST":"$ctx.$flow.$last","@FLOW_META":"$ctx.$flow.$meta","@THROW400":"$ctx.$throw['400']","@THROW401":"$ctx.$throw['401']","@THROW403":"$ctx.$throw['403']","@THROW404":"$ctx.$throw['404']","@THROW409":"$ctx.$throw['409']","@THROW422":"$ctx.$throw['422']","@THROW429":"$ctx.$throw['429']","@THROW500":"$ctx.$throw['500']","@THROW503":"$ctx.$throw['503']","@THROW":"$ctx.$throw","@ERROR":"$ctx.$error","@STATUS":"$ctx.$statusCode"},Te=0,gr=1,hr=2,Nn=3,mr=4,yr=5;function br(r){let e=r.length,t="",n=0,o=Te,i=0,s=0;for(;n<e;){let a=r[n],u=r[n+1];switch(o){case Te:if(a==='"')o=gr,t+=a,n++;else if(a==="'")o=hr,t+=a,n++;else if(a==="`")o=Nn,t+=a,n++;else if(a==="/"&&u==="/")o=mr,t+=a+u,n+=2;else if(a==="/"&&u==="*")o=yr,t+=a+u,n+=2;else if(a==="@"||a==="#"||a==="%"){let l=n,f=a;for(n++;n<e;){let p=r[n];if(p>="A"&&p<="Z"||p>="0"&&p<="9"||p==="_")n++;else break}let c=r.substring(l,n);if(f==="@"){let p=vi[c];t+=p||c}else f==="#"?t+="$ctx.$repos."+c.substring(1):t+="$ctx.$pkgs."+c.substring(1)}else a==="{"?(i>0&&s++,t+=a,n++):a==="}"&&i>0?s>0?(s--,t+=a,n++):(i--,t+=a,n++,o=Nn):(t+=a,n++);break;case gr:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==='"'&&(o=Te),n++);break;case hr:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==="'"&&(o=Te),n++);break;case Nn:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):a==="`"?(o=Te,n++):a==="$"&&u==="{"?(i++,s=0,t+=u,n+=2,o=Te):n++;break;case mr:t+=a,n++,a===`
3
- `&&(o=Te);break;case yr:t+=a,a==="*"&&u==="/"?(t+=u,n+=2,o=Te):n++;break}}return t}var Rt={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 Ii(r){return ne.getLegacyField(r)}function Ni(r){return ne.isScriptTable(r)}function Mi(r){return ne.normalizeLanguage(r)}var Yt=class{getLegacyField(e){return Rt[e]}isScriptTable(e){return e in Rt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=br(String(e)),i=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);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 n={...t},o=this.getLegacyField(e);return o&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[o]!==void 0&&(n.sourceCode=n[o]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),o&&o in n&&delete n[o],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(o?Object.prototype.hasOwnProperty.call(t,o):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!i&&!s)return t;let a=i?t.sourceCode??(o?t[o]:void 0):n?.sourceCode??(o&&n?n[o]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,l={...t};return i&&(l.sourceCode=a??null),l.scriptLanguage=this.normalizeLanguage(u),l.compiledCode=this.compileSource(a,l.scriptLanguage),o&&o in l&&delete l[o],l}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 n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(Rt).find(n=>Rt[n]in e);if(t){let n=e[Rt[t]];if(typeof n=="string"&&n!==""){let o=this.compileSource(n,e.scriptLanguage);return{code:o,compiledCode:o,shouldPersistCompiledCode:o!==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 n={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};n.sourceCode=n.sourceCode??i.sourceCode??i.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??i.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,o=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Ae.default.transpileModule(e,{compilerOptions:{target:Ae.default.ScriptTarget.ES2022,module:Ae.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ae.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(o=>o.category===Ae.default.DiagnosticCategory.Error);if(n)throw new Error(Ae.default.flattenDiagnosticMessageText(n.messageText,`
1
+ "use strict";var ai=Object.create;var Ut=Object.defineProperty;var li=Object.getOwnPropertyDescriptor;var ci=Object.getOwnPropertyNames;var ui=Object.getPrototypeOf,fi=Object.prototype.hasOwnProperty;var U=(r,e)=>()=>(r&&(e=r(r=0)),e);var Cn=(r,e)=>{for(var t in e)Ut(r,t,{get:e[t],enumerable:!0})},ur=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ci(e))!fi.call(r,o)&&o!==t&&Ut(r,o,{get:()=>e[o],enumerable:!(n=li(e,o))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?ai(ui(r)):{},ur(e||!r||!r.__esModule?Ut(t,"default",{value:r,enumerable:!0}):t,r)),di=r=>ur(Ut({},"__esModule",{value:!0}),r);function wr(r){return In.createHash("md5").update(r).digest("hex").substring(0,8)}function $r(r){return r.length<=_r-3?`${r}_pk`:`j_${wr(r)}_pk`}function Sr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=_r?n:`j_${wr(r)}_${t}_fk`}function xt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${In.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function z(r){return`${r}Id`}function vt(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Tr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function kr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Fr(r,e,t){return`${r}_${e}_${t}_fk`}function Cr(r,e,t){return`${r}_${e}_${t}_idx`}var In,_r,Ue=U(()=>{"use strict";In=fe(require("crypto")),_r=63});function nn(r){return Ji[r]??null}var ie,On,Nt,Ji,Mt=U(()=>{"use strict";ie=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),On=new Set(["_and","_or","_not"]),Nt=[...Array.from(On),...Array.from(ie)],Ji={_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 v,pe=U(()=>{"use strict";v=class extends Error{constructor(t="Bad Request",n){let o=Array.isArray(t),i=o?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,o&&(this.messages=t)}}});function Ir(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Nr=U(()=>{"use strict"});function Oe(r,e,t){throw new v({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Nt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Nt})}function rn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Ir();for(let o of Object.keys(e))if(o.startsWith("_")&&!ie.has(o)){if(n&&o==="_id")continue;Oe(o,r,t)}}function Q(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),o=new Set((n?.columns??[]).map(s=>s.name)),i=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(qi.has(s)){if(Array.isArray(a))for(let l of a)Q(l,e,t);else a&&typeof a=="object"&&Q(a,e,t);continue}let u=i.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){rn(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let f=Object.keys(a).filter(c=>!c.startsWith("_"));if(f.length>0){let c={};for(let p of f)c[p]=a[p];Q(c,l,t)}}}continue}s.startsWith("_")&&!o.has(s)&&s!=="_id"&&Oe(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&rn(s,a,e)}}var qi,ze=U(()=>{"use strict";pe();Mt();Nr();qi=new Set(["_and","_or","_not"])});function ge(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:on(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function on(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[o,i]of Object.entries(r)){let s=zi(o,i,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function zi(r,e,t){if(r==="_and")return Mr("and",e,t);if(r==="_or")return Mr("or",e,t);if(r==="_not"){let l=on(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),o=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),i=n?.columns?.some(l=>l.name==="id"),a=r==="id"?o&&!i?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?Vi(a,e,u,t):n&&!n.columns?.find(f=>f.name===a)?(r.startsWith("_")&&r!=="_id"&&Oe(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):Hi(a,e,t)}function Mr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],o=!1;for(let i of e){let s=on(i,t);s.hasRelationFilters&&(o=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:o}:n.length===1?{node:n[0],hasRelationFilters:o}:{node:{kind:r,children:n},hasRelationFilters:o}}function Vi(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let o=Object.keys(e),i=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"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(i&&o[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&o[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:o[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=o.length>0&&o.every(d=>l.has(d))?{id:e}:e;return{node:on(c,u).node,hasRelationFilters:!0}}function Hi(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:Yi(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!ie.has(s)&&Oe(s,r,t.tableName);let o=Object.entries(e).filter(([s])=>ie.has(s));if(o.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){let u=Gi(n,s,a);u&&i.push(u)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function Gi(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=nn(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function Yi(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.find(s=>s.name===n);if(!o)return!1;let i=(o.type||"").toLowerCase();return i==="uuid"||i==="uuidv4"||i.includes("uuid")}var At=U(()=>{"use strict";Mt();ze()});var oe,Ot=U(()=>{"use strict";oe=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t;if(this.map.has(a)){let p=this.map.get(a);return o==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let f=l.targetTableName||l.targetTable;if(!f)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:f,relationType:l.type,parentJoinId:i,joinType:o,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function ee(r,e){if(r.length<=Fe)return e(r);let t=[];for(let a=0;a<r.length;a+=Fe)t.push(r.slice(a,a+Fe));let n=[],o=0;async function i(){for(;o<t.length;){let a=o++;n[a]=await e(t[a])}}let s=Math.min(Wn,t.length);return await Promise.all(Array.from({length:s},i)),n.flat()}function He(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let o=n.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 se,Fe,Wn,Un,Ce,Ge=U(()=>{"use strict";pe();se=16,Fe=5e3,Wn=4,Un=10;Ce=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let o=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(l=>l.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),i=new Set(o.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(i.has(s))continue;let u=n?.relations?.find(f=>f.propertyName===s);if(!u)continue;let l=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];o.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:l,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return o}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Un}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))n.has(i)||o.push(i);return o}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new v(`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(u=>u.name===i),a=i==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new v(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,o=0,i){if(e.length===0||t.length===0||o>=n)return;let s;i&&(s=await this.metadataGetter(i)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,o):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,o,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,o,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,o){let i=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let m of e){let b=m[i];if(b==null)continue;let S=this.adapter.keyOf(b);s.has(S)||(s.add(S),a.push(b))}if(a.length===0){for(let m of e)m[t.relationName]=null,i!==t.relationName&&delete m[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:l,nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),p=this.adapter.getTargetPkField(u);if(l){for(let m of e){let b=m[i];m[t.relationName]=b!=null?this.adapter.buildScalarRef(b,p):null,i!==t.relationName&&delete m[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/Fe)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(f,t.nestedDeep,u);y.length>0&&await this.execute(g,y,n,o+1,t.targetTable);let h=new Map;for(let m of g)h.set(this.adapter.keyOf(m[p]),m);for(let m of e){let b=m[i];m[t.relationName]=b!=null&&h.get(this.adapter.keyOf(b))||null,i!==t.relationName&&delete m[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn]}}async fetchInverseRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=e.map(R=>R[s]).filter(R=>R!=null);if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,l);let{nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),y=new Map,h=t.fields.includes(u)||t.fields.includes("*");for(let R of d){let M=R[g],T=this.adapter.keyOf(M);y.has(T)||y.set(T,[]),y.get(T).push(R)}let m=t.userLimit!==void 0&&t.userLimit>0,b=m?"per-parent-c16":"batch-in",S=m?a.length:Math.ceil(a.length/Fe)||1,_=m?Math.ceil(a.length/se):void 0,$=Array.from(y.values()).reduce((R,M)=>R+M.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:b,roundtrips:S,concurrencyWaves:_,rowsTransferred:d.length,rowsReturned:$,rowsDiscarded:d.length-$,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let R of d)this.adapter.postProcessInverseChild(R,u,h);let k=this.enrichNestedDescs(f,t.nestedDeep,l);k.length>0&&await this.execute(d,k,n,o+1,t.targetTable);let N=t.type==="one-to-one";for(let R of e){let M=this.adapter.keyOf(R[s]),T=y.get(M)||[];R[t.relationName]=N?T[0]||null:T}}async fetchM2MRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=e.map(_=>_[s]).filter(_=>_!=null);if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:l,fetchSpec:f}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,i,u,f),g=t.userLimit!==void 0&&t.userLimit>0,y=g?"m2m-per-parent-c16":"m2m-batch",h=g?a.length:Math.ceil(a.length/Fe)||1,m=g?Math.ceil(a.length/se):void 0,b=Array.from(p.values()).reduce((_,$)=>_+$.length,0);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:y,roundtrips:h,concurrencyWaves:m,rowsTransferred:d.length,rowsReturned:b,rowsDiscarded:d.length-b,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let S=this.enrichNestedDescs(l,t.nestedDeep,u);S.length>0&&d.length>0&&await this.execute(d,S,n,o+1,t.targetTable);for(let _ of e){let $=this.adapter.keyOf(_[s]);_[t.relationName]=p.get($)||[]}}}});async function be(r,e,t){let n=new Map,o=0;async function i(){for(;o<r.length;){let u=o++,l=r[u];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},i);return await Promise.all(a),n}var dn=U(()=>{"use strict"});function C(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function ve(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:C(t,e)).join(".")}var le=U(()=>{"use strict"});function te(r,e,t){e&&wn(r,e,t,"and")}function wn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let o=function(){for(let i of e.children)this.where(function(){wn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"or":{let o=function(){for(let i of e.children)this.orWhere(function(){wn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"not":{let o=function(){this.whereNot(function(){wn(this,e.child,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"compare":Ro(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function Ro(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let o=xo(e.field,t),i=ve(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",l=n==="or"?"orWhereRaw":"whereRaw",f=n==="or"?"orWhereIn":"whereIn",c=n==="or"?"orWhereNotIn":"whereNotIn",p=n==="or"?"orWhereBetween":"whereBetween",d=n==="or"?"orWhereNull":"whereNull",g=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[l](`${i} = ?::uuid`,[e.value]):r[u](o,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[l](`${i} != ?::uuid`,[e.value]):r[u](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[l](`${i} > ?::uuid`,[e.value]):r[u](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[l](`${i} >= ?::uuid`,[e.value]):r[u](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[l](`${i} < ?::uuid`,[e.value]):r[u](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[l](`${i} <= ?::uuid`,[e.value]):r[u](o,"<=",e.value);return;case"in":{let y=Yr(e.value);s&&a&&y.every(h=>typeof h=="string")?r[l](`${i} = ANY(?::uuid[])`,[y]):r[f](o,y);return}case"not_in":{let y=Yr(e.value);s&&a&&y.every(h=>typeof h=="string")?r[l](`${i} != ALL(?::uuid[])`,[y]):r[c](o,y);return}case"contains":tr(r,i,e.value,"contains",t,n);return;case"starts_with":tr(r,i,e.value,"starts_with",t,n);return;case"ends_with":tr(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[p](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[d](o):r[g](o);return}}function tr(r,e,t,n,o,i){let s=i==="or"?"orWhereRaw":"whereRaw";if(o.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(o.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function xo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function Yr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var nr=U(()=>{"use strict";le()});function G(r){return r.columns.find(e=>e.isPrimary)||null}var Kt=U(()=>{"use strict"});var Zr={};Cn(Zr,{expandFieldsToJoinsAndSelect:()=>rr});async function rr(r,e,t,n,o,i){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}if(i&&typeof i=="object")for(let[c,p]of Object.entries(i)){if(l.has(c))continue;let d=p&&typeof p=="object"&&p.fields!=null?Array.isArray(p.fields)?p.fields:String(p.fields).split(",").map(g=>g.trim()).filter(Boolean):["*"];l.set(c,d)}let f=l.get("")||[];for(let c of f){if(c==="*"){let g=new Set;for(let h of u.relations||[])if(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse){let m=h.foreignKeyColumn||z(h.propertyName);m&&g.add(m)}let y=new Set;for(let h of u.columns)g.has(h.name)||(s.push(`${r}.${h.name}`),y.add(h.name));for(let h of u.relations||[])!l.has(h.propertyName)&&!y.has(h.propertyName)&&l.set(h.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=u.relations?.find(b=>b.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let b=d.foreignKeyColumn||z(d.propertyName),S=C(r,n),_=C(b,n),$=C(p,n);s.push(`${S}.${_} as ${$}`)}let y=d.targetTableName||d.targetTable,h=i?.[p],m=h?.fields!=null?Array.isArray(h.fields)?h.fields:String(h.fields).split(",").map(b=>b.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:y,fields:m,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:h?.filter,userSort:h?.sort,userLimit:h?.limit!==void 0?Number(h.limit):void 0,userPage:h?.page!==void 0?Number(h.page):void 0,nestedDeep:h?.deep})}),{select:s,batchFetchDescriptors:a}}var ir=U(()=>{"use strict";Ue();le()});var ot,sr=U(()=>{"use strict";Ue();le();Kt();Ge();nr();Ot();At();dn();ot=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new oe,o=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:i}=ge(e,t,o,n);return i}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),u=(s?i.slice(1):i).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,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 l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let f=n,c=o||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(f);if(!g)break;let y=g.relations?.find(b=>b.propertyName===d);if(!y)break;let h=y.targetTableName||y.targetTable,m=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(m)){s.add(m);let b=y.foreignKeyColumn||z(y.propertyName),S=this.metadata?.tables?.get(h),_=S&&G(S)?.name||"id";e.leftJoin(`${h} as ${m}`,`${m}.${_}`,`${c}.${b}`)}f=h,c=m}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let o=e.substring(0,n),i=e.substring(n+4),s=C(i,this.dbType),a=t?`${t}.${C(o,this.dbType)}`:C(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${C(e,this.dbType)} as ${C(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return G(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=z(e.mappedBy)),t||(t=z(e.targetTable)),t}resolveParentPk(e){return e&&G(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:o}=He(e),i=[];if(n.includes("*")){let l=new Set;for(let f of t.relations||[])if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let c=f.foreignKeyColumn||z(f.propertyName);c&&l.add(c)}for(let f of t.columns)l.has(f.name)||i.push(f.name);for(let f of t.relations||[])o.has(f.propertyName)||o.set(f.propertyName,["id"])}else for(let l of n){let f=t.columns.find(c=>c.name===l);f?i.push(f.name):t.relations?.find(p=>p.propertyName===l)&&!o.has(l)&&o.set(l,["id"])}let s=G(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((l,f)=>{let c=t.relations?.find(p=>p.propertyName===f);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||z(c.propertyName);p&&i.push(`${p} as ${f}`)}});let a=[];return o.forEach((l,f)=>{let c=t.relations?.find(d=>d.propertyName===f);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:f,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.parseSortTokens(o.userSort,e):[],a=n.selectCols.map(u=>this.toKnexSelect(u));return ee(t,u=>{let l=this.knex(e).select(a).whereIn(n.pkCol,u);if(i&&te(l,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,o.userSort,e);for(let f of s)l.orderBy(f.column,f.order)}return l})}async fetchInverse(e,t,n,o,i){let s=t,a=o.selectCols.find(g=>g.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let u=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,l=i?.userSort?this.parseSortTokens(i.userSort,e):[],f=i?.userLimit,c=i?.userPage;if(f!==void 0&&f>0){let g=c?(c-1)*f:0,y=o.selectCols.map(b=>this.toKnexSelect(b)),h=await be(n,async b=>{let S=this.knex(e).select(y).where(t,b);if(u&&te(S,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(S,i.userSort,e),l.length>0)for(let _ of l)S.orderBy(_.column,_.order);else S.orderBy(o.pkCol,"asc");return g>0&&S.offset(g),S.limit(f),S},se),m=[];for(let[b,S]of h.entries()){let _=n.find($=>String($)===b);for(let $ of S)$[t]||($[t]=_??b),m.push($)}return{docs:m,groupKeyField:s}}let p=o.selectCols.map(g=>this.toKnexSelect(g));return{docs:await ee(n,g=>{let y=this.knex(e).select(p).whereIn(t,g);if(u&&te(y,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(y,i?.userSort,e),l.length>0)for(let h of l)y.orderBy(h.column,h.order);else y.orderBy(o.pkCol,"asc");return y}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,o,i){let s=this.resolveParentPk(n),a=e.map(S=>S[s]).filter(S=>S!=null);if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,f=t.junctionTargetColumn;if(!u||!l||!f)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(i.selectCols.length===1&&i.selectCols[0]===i.pkCol&&!c&&!d){let S=await ee(a,$=>this.knex(u).select([`${l} as __sourceId__`,`${f} as __targetId__`]).whereIn(l,$).orderBy(f,"asc")),_=new Map;for(let $ of S){let k=this.keyOf($.__sourceId__);_.has(k)||_.set(k,[]),_.get(k).push({[i.pkCol]:$.__targetId__})}return{grouped:_,docs:[]}}let h=i.selectCols.map(S=>this.toKnexSelect(S,"t"));if(d!==void 0&&d>0){let S=g?(g-1)*d:0,_=new Map;for(let N of a)_.set(this.keyOf(N),[]);let $=await be(a,async N=>{let R=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${i.pkCol}`).select(h).where(`${u}.${l}`,N);if(c&&te(R,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(R,t.userSort,t.targetTable,"t"),p.length>0)for(let M of p)R.orderBy(M.column,M.order);else R.orderBy(`t.${i.pkCol}`,"asc");return S>0&&R.offset(S),R.limit(d),R},se),k=[];for(let[N,R]of $.entries()){_.set(N,R);for(let M of R)k.push(M)}return{grouped:_,docs:k}}let m=await ee(a,S=>{let _=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${i.pkCol}`).select([`${u}.${l} as __sourceId__`,...h]).whereIn(`${u}.${l}`,S);if(c&&te(_,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(_,t.userSort,t.targetTable,"t"),p.length>0)for(let $ of p)_.orderBy($.column,$.order);else _.orderBy(`t.${i.pkCol}`,"asc");return _}),b=new Map;for(let S of m){let _=S.__sourceId__;delete S.__sourceId__;let $=this.keyOf(_);b.has($)||b.set($,[]),b.get($).push(S)}return{grouped:b,docs:m}}}});var ni={};Cn(ni,{executeBatchFetches:()=>ar});async function ar(r,e,t,n,o=3,i=0,s,a="postgres",u,l){let f=new ot(r,a,u);await new Ce(f,n,l).execute(e,t,o,i,s)}var lr=U(()=>{"use strict";Ge();sr()});var Mo={};Cn(Mo,{ALL_SUPPORTED_OPERATORS:()=>Nt,AuthenticationException:()=>gt,AuthorizationException:()=>ht,BadRequestException:()=>v,BatchFetchEngine:()=>Ce,BusinessLogicException:()=>ut,CHUNKED_FETCH_CONCURRENCY:()=>Wn,ConfigurationException:()=>$t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Un,DEFAULT_TIMEOUT_MS:()=>Qt,DOTTED_PATH_MAX_HOPS:()=>kn,DatabaseException:()=>De,DuplicateResourceException:()=>pt,ErrorHandler:()=>Ne,ExecutorEngineService:()=>Be,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>ie,FileNotFoundException:()=>Tt,FileSizeExceededException:()=>kt,FileUploadException:()=>St,HttpException:()=>E,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>qt,InvalidTokenException:()=>mt,IsolatedExecutorService:()=>We,JoinRegistry:()=>oe,LOGICAL_OPERATORS:()=>On,MongoBatchAdapter:()=>Ye,MongoQueryExecutor:()=>tt,PER_PARENT_CONCURRENCY:()=>se,QueryBuilderService:()=>at,QueryPlanner:()=>J,ResourceNotFoundException:()=>dt,SchemaException:()=>wt,ScriptContractService:()=>Gt,ScriptExecutionException:()=>$e,ScriptTimeoutException:()=>we,ServiceUnavailableException:()=>_t,SqlBatchAdapter:()=>ot,SqlQueryExecutor:()=>st,TokenExpiredException:()=>yt,ValidationException:()=>ft,WHERE_IN_CHUNK_SIZE:()=>Fe,WorkerPool:()=>Ct,appendIsolatedExecutorRuntimeLog:()=>X,applyOperatorToMatch:()=>tn,applyRelationFilters:()=>Le,applyWhereToKnex:()=>it,assertFieldOperatorValueIsClean:()=>rn,buildAggregateFilter:()=>et,buildMongoCharFoldMapJson:()=>Mn,buildMongoFoldTextSearchJs:()=>Yt,buildRelationSubquery:()=>Lt,buildSqlWherePartsFromFieldAst:()=>Dt,buildWhereClause:()=>ce,camelToSnake:()=>kr,chunkedFetch:()=>ee,compileScriptSource:()=>Oi,computeEngineTuning:()=>xn,createEnfyraKernel:()=>No,dslOpToCompareOp:()=>nn,encodeMainThreadToIsolate:()=>vn,escapeSqlValue:()=>Xr,executeBatchFetches:()=>ar,executeMongoBatchFetches:()=>pn,expandFieldsToJoinsAndSelect:()=>rr,getEffectiveCpuCount:()=>Rn,getEffectiveMemoryBytes:()=>Ft,getEngineTuning:()=>Ht,getExecutableScript:()=>Li,getForeignKeyColumnName:()=>z,getIoAbortSignal:()=>br,getJunctionColumnNames:()=>vt,getJunctionTableName:()=>xt,getPrimaryKeyColumn:()=>G,getScriptLegacyField:()=>Ni,getShortFkConstraintName:()=>Sr,getShortFkName:()=>Fr,getShortIndexName:()=>Cr,getShortPkName:()=>$r,hasAggregateQuery:()=>Hn,hasLogicalOperators:()=>_e,isExecutableJavaScript:()=>Ei,isScriptTable:()=>Mi,mergeAggregateValue:()=>xe,normalizeAggregateQuery:()=>Ze,normalizeFlowStepScriptConfig:()=>Di,normalizeScriptLanguage:()=>Ai,normalizeScriptPatch:()=>ji,normalizeScriptRecord:()=>Pi,parseBatchFields:()=>He,parseFields:()=>gn,parseFilter:()=>ge,perParentRun:()=>be,quoteIdentifier:()=>C,quoteQualifiedIdentifier:()=>ve,resolveExecutableScript:()=>Bi,rewriteFilterDenyingFields:()=>oi,rewriteSortDroppingDenied:()=>si,scriptContractService:()=>ne,separateFilters:()=>H,snakeToCamel:()=>Tr,throwUnsupportedFieldOperator:()=>Oe,validateDeepOptions:()=>cr,validateFilterShape:()=>Q,whereToMongoFilter:()=>qe});module.exports=di(Mo);var Qt=3e4,Be=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){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Qt)}async run(e,t,n=Qt,o={}){return this.isolatedExecutorService.run(e,t,n,o)}};var Jt=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&&console.error(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=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var pr=require("async_hooks"),gr=fe(require("path")),hr=require("stream"),yr=require("worker_threads");var we=class extends Error{constructor(t=0,n){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},$e=class extends Error{constructor(t,n,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...o}}},D=class extends Error{constructor(t,n,o,i){super(t);this.statusCode=n;this.errorCode=o;this.name=this.constructor.name,this.details=i}},E=class extends D{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ut=class extends D{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},ft=class extends D{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},dt=class extends D{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},pt=class extends D{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},gt=class extends D{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},ht=class extends D{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},yt=class extends D{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},mt=class extends D{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},De=class extends D{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},bt=class extends D{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},_t=class extends D{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},wt=class extends D{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},$t=class extends D{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},St=class extends D{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Tt=class extends D{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},kt=class extends D{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Ne=class{static createException(e,t,n,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new E(n||"Error",t||500,i);case"$throw.businessLogic":return new ut(n||"Bad request",i);case"$throw.validation":return new ft(n||"Validation failed",i);case"$throw.notFound":return new dt(i?.resource||n||"Resource",i?.identifier);case"$throw.duplicate":return new pt(i?.resource||n||"Resource",i?.field||"field",i?.value||"value");case"$throw.unauthorized":return new gt(n||"Unauthorized");case"$throw.forbidden":return new ht(n||"Forbidden");case"$throw.tokenExpired":return new yt;case"$throw.invalidToken":return new mt;case"$throw.database":return new De(n||"Database error",i);case"$throw.dbQuery":return new De(n||"Query error",i);case"$throw.externalService":return new bt(n||"Service",n||"Error",i);case"$throw.serviceUnavailable":return new _t(n||"Service");case"$throw.rateLimit":return new E(n||"Rate limit exceeded",429);case"$throw.scriptError":return new $e(n||"Script error",o,i);case"$throw.scriptTimeout":return new we(i?.timeout||5e3,o);case"$throw.schema":return new wt(n||"Schema error",i);case"$throw.config":return new $t(n||"Configuration error",i);case"$throw.fileUpload":return new St(n||"File upload error",i);case"$throw.fileNotFound":return new Tt(n||"File not found");case"$throw.fileSizeExceeded":return new kt(i?.maxSize||"unknown",i?.actualSize||"unknown");case"$throw.400":return new E(n||"Bad request",400,i);case"$throw.401":return new E(n||"Authentication required",401,i);case"$throw.403":return new E(n||"Insufficient permissions",403,i);case"$throw.404":return new E(n||"Not found",404,i);case"$throw.409":return new E(n||"Conflict",409,i);case"$throw.422":return new E(n||"Validation failed",422,i);case"$throw.429":return new E(n||"Rate limit exceeded",429,i);case"$throw.500":return new E(n||"Internal server error",500,i);case"$throw.503":return new E(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o)}if(t)switch(t){case 400:return new E(n||"Bad request",400,i);case 401:return new E(n||"Authentication required",401,i);case 403:return new E(n||"Insufficient permissions",403,i);case 404:return new E(n||"Not found",404,i);case 409:return new E(n||"Conflict",409,i);case 422:return new E(n||"Validation failed",422,i);case 429:return new E(n||"Rate limit exceeded",429,i);case 500:return new E(n||"Internal server error",500,i);case 503:return new E(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o,i)}return new $e(n||"Unknown error",o,i)}};var zt=fe(require("fs")),Vt=fe(require("path")),qt=Vt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function pi(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var gi=pi();function X(r){if(gi)try{let e=Vt.dirname(qt);zt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
+ `;zt.appendFileSync(qt,t)}catch{}}var Se=fe(require("os")),Ke=fe(require("fs"));function Ft(){try{let r=Ke.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Se.totalmem())return e}}catch{}try{let r=Ke.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Se.totalmem())return e}catch{}return Se.totalmem()}function Rn(){let r=Se.availableParallelism?.()||Se.cpus()?.length||1;try{let e=Ke.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let o=parseInt(t,10),i=parseInt(n,10);if(o>0&&i>0)return Math.max(1,Math.ceil(o/i))}}catch{}try{let e=parseInt(Ke.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Ke.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var hi=.25,yi=2,mi=2048,bi=40,_i=128,wi=32;function xn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(_i,Math.max(bi,Math.round(t/wi))),o=t*hi,i=Math.max(1,Math.floor(o/n)),s=Math.max(1,Math.min(e,2,i)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<mi?1:yi,l=Math.max(1,Math.min(u,Math.floor(o/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:l}}function Ht(){return xn({logicalCpuCount:Rn(),totalMemoryBytes:Ft()})}var Ii=gr.join(__dirname,"execution/worker.js"),mr=new pr.AsyncLocalStorage;function br(){return mr.getStore()}var Ct=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 yr.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}},dr=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function vn(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 We=class r{constructor(e){this.logger=new Jt(r.name);this.effectiveMemory=Ft();this.isolationTuning=Ht();this.pool=new Ct(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ii,()=>{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||dr.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"||dr.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++,X({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++,X({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++,X({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?mr.run(o,e):e());if(o?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:vn(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 hr.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())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}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);X({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};l=await this.spawnAndExecute("execute",f,t,i)}catch(f){let c=f;if(X({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 Ne.createException(c.errorPath,p,c.message||"Unknown error",e,c.details||{})}return this.mergeCtxChanges(t,l.ctxChanges||{}),X({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);X({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};u=await this.spawnAndExecute("executeBatch",f,t,o)}catch(l){let f=l;if(X({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 Ne.createException(f.errorPath,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),X({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 Me=fe(require("typescript")),Rt={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 Ni(r){return ne.getLegacyField(r)}function Mi(r){return ne.isScriptTable(r)}function Ai(r){return ne.normalizeLanguage(r)}var Gt=class{getLegacyField(e){return Rt[e]}isScriptTable(e){return e in Rt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),i=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);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 n={...t},o=this.getLegacyField(e);return o&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[o]!==void 0&&(n.sourceCode=n[o]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),o&&o in n&&delete n[o],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(o?Object.prototype.hasOwnProperty.call(t,o):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!i&&!s)return t;let a=i?t.sourceCode??(o?t[o]:void 0):n?.sourceCode??(o&&n?n[o]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,l={...t};return i&&(l.sourceCode=a??null),l.scriptLanguage=this.normalizeLanguage(u),l.compiledCode=this.compileSource(a,l.scriptLanguage),o&&o in l&&delete l[o],l}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 n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(Rt).find(n=>Rt[n]in e);if(t){let n=e[Rt[t]];if(typeof n=="string"&&n!==""){let o=this.compileSource(n,e.scriptLanguage);return{code:o,compiledCode:o,shouldPersistCompiledCode:o!==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 n={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};n.sourceCode=n.sourceCode??i.sourceCode??i.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??i.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,o=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Me.default.transpileModule(e,{compilerOptions:{target:Me.default.ScriptTarget.ES2022,module:Me.default.ModuleKind.CommonJS,importsNotUsedAsValues:Me.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(o=>o.category===Me.default.DiagnosticCategory.Error);if(n)throw new Error(Me.default.flattenDiagnosticMessageText(n.messageText,`
4
3
  `));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
5
4
  "use strict";
6
5
  ${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() {
8
- var M = ${En()};
6
+ });`)}},ne=new Gt;function Oi(r,e){return ne.compileSource(r,e)}function Ei(r){return ne.isExecutableJavaScript(r)}function Pi(r,e){return ne.normalizeRecord(r,e)}function ji(r,e,t){return ne.normalizePatch(r,e,t)}function Li(r){return ne.getExecutableScript(r)}function Bi(r){return ne.resolveExecutableScript(r)}function Di(r){return ne.normalizeFlowStepScriptConfig(r)}var Sn=require("node:fs"),ri=require("node:path");var Nn=require("mongodb");Ue();function Ae(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function V(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ae(r)&&(r.foreignKeyColumn||r.propertyName)||null}function W(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ae(r){if(!r||typeof r!="object")return r;if(r instanceof Nn.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 Nn.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||xt(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=vt(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,o=t,i=e.junctionTableName||xt(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=vt(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function It(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"?Ae(c)?(p="_id",d=W(c)||c.propertyName,g=!0):(p=V(c)||c.propertyName,d="_id",g=!1):c.type==="one-to-many"?(p="_id",d=W(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 y=c.type==="one-to-many"||c.type==="many-to-many";a.push({propertyName:l,targetTable:c.targetTableName,localField:p,foreignField:d,type:y?"many":"one",isInverse:g,nestedFields:f})}return{scalarFields:s,relations:a}}var Xt=fe(require("fs")),An=fe(require("path"));var Ki=new RegExp("\\p{Mark}","gu");function Rr(r){return r==null?"":String(r).normalize("NFKD").replace(Ki,"").toLowerCase()}function Mn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Rr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Yt(){return`function() {
7
+ var M = ${Mn()};
9
8
  function foldStr(s) {
10
9
  if (s == null) return '';
11
10
  s = String(s);
@@ -50,5 +49,5 @@ ${e}
50
49
  }
51
50
  }
52
51
  return true;
53
- }`}var Pr="mongo-fold-text-search.body.txt",Je=null;function Yi(){let r=[Pn.join(__dirname,Pr),Pn.join(process.cwd(),"dist","kernel","query","utils",Pr)];for(let e of r)try{if(en.existsSync(e))return en.readFileSync(e,"utf8")}catch{}return null}function tn(){if(Je!==null)return Je;let r=Yi();return r?(Je=r,Je):(Je=Zt(),Je)}var ke=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof ke.ObjectId)return n;if(typeof n=="string")try{return new ke.ObjectId(n)}catch{return n}return n}let o=r?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new ke.ObjectId(n)}catch{return n}return n}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new ke.ObjectId(n)}catch{return n}return n}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new ke.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new ke.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new ke.ObjectId(n)}catch{return n}return n;default:return n}}var nn="__mongoFoldTextTriples";function Xi(r){return r==="_id"?"$_id":`$${r}`}function qe(r,e,t,n){let o=Xi(e),i=r[nn]??[];i.push({ref:o,needle:t,mode:n}),r[nn]=i}function Zi(r){let e=r[nn];if(delete r[nn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:tn(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}function ze(r,e,t,n){let o={},i=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";i&&a==="id"&&(a="_id");let l=W(r,u,a,s.value);switch(s.operator){case"=":o[a]=l;break;case"!=":o[a]={$ne:l};break;case">":o[a]={$gt:l};break;case"<":o[a]={$lt:l};break;case">=":o[a]={$gte:l};break;case"<=":o[a]={$lte:l};break;case"like":o[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(y=>y.trim()):[f]);let c=f.map(y=>W(r,u,a,y));o[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(y=>y.trim()):[p]);let d=p.map(y=>W(r,u,a,y));o[a]={$nin:d};break;case"is null":o[a]=null;break;case"is not null":o[a]={$ne:null};break;case"_contains":qe(o,a,String(l),"contains");break;case"_starts_with":qe(o,a,String(l),"starts");break;case"_ends_with":qe(o,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(y=>y.trim())),Array.isArray(g)&&g.length===2){let y=W(r,u,a,g[0]),b=W(r,u,a,g[1]);o[a]={$gte:y,$lte:b}}break;case"_is_null":let m=l===!0||l==="true";o[a]=m?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=l===!0||l==="true";o[a]=h?{$ne:null}:{$eq:null};break}}return Zi(o),o}function jr(r,e,t){let o=r?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function rn(r,e,t,n,o,i){switch(o){case"_contains":qe(e,n,String(i),"contains");break;case"_starts_with":qe(e,n,String(i),"starts");break;case"_ends_with":qe(e,n,String(i),"ends");break;case"_eq":e[n]=W(r,t,n,i);break;case"_neq":{let c=W(r,t,n,i);jr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=i;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>W(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>W(r,t,n,c));jr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:W(r,t,n,i)};break;case"_gte":e[n]={$gte:W(r,t,n,i)};break;case"_lt":e[n]={$lt:W(r,t,n,i)};break;case"_lte":e[n]={$lte:W(r,t,n,i)};break;case"_is_null":let u=i===!0||i==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=i===!0||i==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=i;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=W(r,t,n,f[0]),p=W(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var Un=require("mongodb");function re(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let o of n)if(re(o,e))return!0}}else if(t==="_not"){if(re(n,e))return!0}else if(e.has(t))return!0;return!1}function G(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let i=re(r,o);return{fieldFilters:t,relationFilters:n,hasRelations:i}}Ot();Et();var ln="__mongoFoldTextTriples";function Pe(r,e){if(!r)return{};let t={};return Pt(r,t,e),Ce(t),t}function ao(r,e){if(!r)return{};let t={};return Bn(r,t,e),Ce(t),t}function me(r,e,t){if(!e)return{};let n=new oe,{node:o}=ge(e,t,r,n);return Pe(o,{metadata:r,rootTable:t})}function cn(r,e,t){if(!e)return{};let n=new oe,{node:o}=ge(e,t,r,n);return ao(o,{metadata:r,rootTable:t})}function Pt(r,e,t){switch(r.kind){case"true":return;case"false":he(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=r.children.map(i=>{let s={};return Pt(i,s,t),Ce(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}he(e,...o);return}case"or":{let o=r.children.map(s=>{let a={};return Pt(s,a,t),Ce(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;let i=e.$or;e.$or=i?[...i,...o]:o;return}case"not":{let n={};Pt(r.child,n,t),Ce(n);let o=e.$nor;e.$nor=o?[...o,n]:[n];return}case"compare":Kr(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Kr(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let o=i=>W(t.metadata,t.rootTable,n,i);switch(r.op){case"eq":Z(e,n,o(r.value));return;case"neq":{let i=o(r.value);Dn(t,n)?he(e,{[n]:{$ne:null}},{[n]:{$ne:i}}):Z(e,n,{$ne:i});return}case"gt":Z(e,n,{$gt:o(r.value)});return;case"gte":Z(e,n,{$gte:o(r.value)});return;case"lt":Z(e,n,{$lt:o(r.value)});return;case"lte":Z(e,n,{$lte:o(r.value)});return;case"in":{let i=Wr(r.value).map(o);Z(e,n,{$in:i});return}case"not_in":{let i=Wr(r.value).map(o);Dn(t,n)?he(e,{[n]:{$ne:null}},{[n]:{$nin:i}}):Z(e,n,{$nin:i});return}case"between":{let i=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&Z(e,n,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":Z(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Ln(e,n,String(r.value),"contains");return;case"starts_with":Ln(e,n,String(r.value),"starts");return;case"ends_with":Ln(e,n,String(r.value),"ends");return}}function Bn(r,e,t){switch(r.kind){case"true":he(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let o=r.children.map(s=>{let a={};return Bn(s,a,t),Ce(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}let i=e.$or;e.$or=i?[...i,...o]:o;return}case"or":{let o=r.children.map(i=>{let s={};return Bn(i,s,t),Ce(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}he(e,...o);return}case"not":Pt(r.child,e,t);return;case"compare":lo(r,e,t);return;case"relation_exists":{Z(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function lo(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){Z(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let o={};Kr(r,o,t),Ce(o);let i={$nor:[o]};Dn(t,n)?he(e,i,{[n]:{$ne:null}}):he(e,i)}function Z(r,e,t){r[e]===void 0?r[e]=t:(he(r,{[e]:r[e]},{[e]:t}),delete r[e])}function he(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Dn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(o=>o.name===e);return n?n.isNullable!==!1:!0}function Wr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function co(r){return r==="_id"?"$_id":`$${r}`}function Ln(r,e,t,n){let o=co(e),i=r[ln]??[];i.push({ref:o,needle:t,mode:n}),r[ln]=i}function Ce(r){let e=r[ln];if(delete r[ln],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:tn(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}async function ye(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return me(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!re(r,i))return me(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>ye(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>ye(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not)return await Kn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=G(r,o),u=[];if(s&&Object.keys(s).length>0){let l=me(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await uo(l,f,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Kn(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return cn(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!re(r,i))return cn(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>Kn(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$or:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>Kn(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._not)return ye(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=G(r,o),u=[];if(s&&Object.keys(s).length>0){let l=cn(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await po(l,f,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function uo(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?fo(e,s,r,a,u,o,i):s.type==="one-to-many"?Jr(e,s,t,a,u,o,i):s.type==="many-to-many"?qr(e,s,t,a,u,o,i):{}}async function fo(r,e,t,n,o,i,s){let a=H(e)||t,u=fn(r),l=dn(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Qn(u);if(f!==null){let g=pn(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await un(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{__impossible__:!0}:{[a]:{$in:d}}}async function po(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return go(e,s,r,a,u,o,i);if(s.type==="one-to-many"){let l=await Jr(e,s,t,a,u,o,i);return Qr(l)}if(s.type==="many-to-many"){let l=await qr(e,s,t,a,u,o,i);return Qr(l)}return{}}async function go(r,e,t,n,o,i,s){let a=H(e)||t,u=fn(r),l=dn(u);if(l!==null)return l?{[a]:{$ne:null}}:{[a]:null};let f=Qn(u);if(f!==null){let g=pn(f.value);if(f.op==="eq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(f.op==="neq")return{[a]:g};if(f.op==="in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]};if(f.op==="not_in")return{[a]:{$in:g}}}let c=await un(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{[a]:null};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:d}},{[a]:{$ne:null}}]}}async function Jr(r,e,t,n,o,i,s){let a=K(e)||t,u=fn(r),l=dn(u);if(l!==null){let p=await Ur(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await un(u,n,o,i,s);if(!f||Object.keys(f).length===0)return{};let c=await Ur(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function qr(r,e,t,n,o,i,s){let a=de(t,e);if(!a)return{};let u=fn(r),l=dn(u);if(l!==null){let m=await Wn(s,a,n,null);return l?m.length===0?{}:{_id:{$nin:m}}:m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let f=Qn(u);if(f!==null){let m=pn(f.value),h=Array.isArray(m)?m:[m],y=await Wn(s,a,n,{_id:{$in:h}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let c=await un(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await Wn(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function un(r,e,t,n,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return re(r,i)?ye(r,e,n,o):me(n,r,e)}async function Ur(r,e,t,n){let o=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let u=a[t];if(u==null)continue;let l=String(u);i.has(l)||(i.add(l),s.push(u))}return s}function Qr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function Wn(r,e,t,n){let o=null;n&&t&&(o=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(Boolean));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await r.collection(e.junctionName).find(i,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function fn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function dn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function pn(r){if(Array.isArray(r))return r.map(e=>pn(e));if(typeof r!="string")return r;try{return new Un.ObjectId(r)}catch{return r}}function Qn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Un.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function jt(r,e,t,n){let o=await Nt(r,e,t),i=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let m=Object.keys(g)[0];m&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(m)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,m]of Object.entries(s))if(typeof m=="object"&&m!==null)for(let[h,y]of Object.entries(m))rn(r,d,e,g,h,y);else d[g]=m;Object.keys(d).length>0&&i.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!o.relations.some(h=>h.propertyName===d)){let h=l.find(y=>y.propertyName===d);if(h){let y="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")y=H(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")y="_id",b=K(h)||h.propertyName;else if(h.type==="many-to-many")continue;let S=h.type==="one-to-many"||h.type==="many-to-many";f.push({propertyName:d,targetTable:h.targetTableName,localField:y,foreignField:b,type:S?"many":"one",nestedFields:[]})}}let c=[...o.relations,...f];for(let d of c){let g=a[d.propertyName],m=d.nestedFields&&d.nestedFields.length>0?await jt(r,d.targetTable,d.nestedFields,g):g?await jt(r,d.targetTable,["_id"],g):[];d.type==="one"&&m.length>0&&m.push({$limit:1}),i.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:m.length>0?m:void 0}}),d.type==="one"&&(i.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(He(g)||i.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(o.scalarFields.length>0||o.relations.length>0||p.length>0){let d={_id:1};for(let m of o.scalarFields)d[m]=1;for(let m of c)d[m.propertyName]=1,m.type==="one"&&m.localField&&m.localField!==m.propertyName&&(d[m.localField]=1);if(t.includes("*"))for(let m of p){if(m.type==="one-to-many"||m.type==="many-to-many")continue;m.type==="many-to-many"?d[m.propertyName]={$map:{input:`$${m.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[m.propertyName]={$cond:{if:{$ne:[`$${m.propertyName}`,null]},then:{_id:`$${m.propertyName}`},else:null}}}i.push({$project:d})}return i}async function zr(r,e,t,n,o){let i=r?.tables?.get(t),s=i?.relations||[],a=i?.columns||[],u=s.filter(f=>!o.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&o.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of o)f[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(f[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function He(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>He(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>He(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>He(e));if("_not"in r)return He(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||He(t)))return!0}return!1}Ye();var Lt=require("mongodb");Ye();gn();var Xe=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let o=n.field.split(".");if(o.length===1)t[o[0]]=n.order;else{let i=`__sort_${o.slice(0,-1).join("_")}`;t[`${i}.${o[o.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let o=n.startsWith("-");return{field:o?n.slice(1):n,order:o?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let o=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),i=[{$match:t}],s=new Set;for(let l of o){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],m=this.normalizeMetadata()?.tables?.get(p);if(!m)break;let h=m.relations?.find(S=>S.propertyName===g);if(!h)break;let y=h.targetTableName||h.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let S=H(h)||h.propertyName,_=d===0?null:`__sort_${c.slice(0,d).join("_")}`,$=_?`${_}.${S}`:S;i.push({$lookup:{from:y,localField:$,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=y}}let a=this.buildSortFromTokens(n);a&&i.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&i.push({$project:u}),i}toObjectId(e){try{return typeof e=="string"?new Lt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Lt.ObjectId||t instanceof Lt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(o=>!o.field.includes("."));n.length!==0&&e.sort((o,i)=>{for(let s of n){let a=this.compareSortValues(o[s.field],i[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(o._id,i._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},o=[];for(let i of this.parseSortTokens(t))i.field.includes(".")||n[i.field]===void 0&&(n[i.field]=1,o.push(i.field));return{projection:n,hiddenFields:o}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let o of t)delete n[o]}keyOf(e){return e==null?"":e instanceof Lt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:o}=Ge(e),i={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])o.has(p.propertyName)||o.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?i[d.name]=1:t.relations?.find(m=>m.propertyName===p)&&!o.has(p)&&o.set(p,["_id"])}o.forEach((p,d)=>{let g=t.relations?.find(m=>m.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[H(g)||g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let m=g.targetTableName||g.targetTable;if(!m)return;let h,y;g.type==="many-to-one"||g.type==="one-to-one"?Oe(g)?(h="_id",y=K(g)||g.propertyName):(h=H(g)||g.propertyName,y="_id"):g.type==="one-to-many"?(h="_id",y=K(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(h="_id",y=g.mappedBy):(h=g.propertyName,y="_id")),a.push({relationName:d,type:g.type,targetTable:m,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:h,foreignField:y})});let u=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)i[p.newName]===1&&i[p.oldName]!==1&&(i[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?me(this.normalizeMetadata(),o.userFilter,e):null,s=this.buildSortFromTokens(o?.userSort),a=await ee(t,u=>{let l={_id:{$in:u}};i&&Object.keys(i).length>0&&Object.assign(l,i);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,o,i){let s=o.projection?{...o.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(h=>h!=null).map(h=>this.toObjectId(h)),u=i?.userFilter?me(this.normalizeMetadata(),i.userFilter,e):null,l=i?.userLimit,f=i?.userPage,c=this.hasDottedSort(i?.userSort);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,y=await be(a,async S=>{let _={[t]:S};if(u&&Object.keys(u).length>0&&Object.assign(_,u),c){let R=this.buildSortAggregatePipeline(e,_,i.userSort);h>0&&R.push({$skip:h}),R.push({$limit:l}),s&&R.push({$project:s});let M=await this.db.collection(e).aggregate(R).toArray();return this.applyReadFallback(M,o)}let k={sort:this.buildSortFromTokens(i?.userSort)||{_id:1}};s&&(k.projection=s);let N=this.db.collection(e).find(_,k);return h>0&&N.skip(h),N.limit(l),this.applyReadFallback(await N.toArray(),o)},se),b=[];for(let[S,_]of y.entries()){let $=a.find(k=>this.keyOf(k)===S);for(let k of _)k[t]||(k[t]=$??S),b.push(k)}return{docs:b,groupKeyField:t}}if(s&&(s[t]=1),c){let h=[],y=await be(a,async b=>{let S={[t]:b};u&&Object.keys(u).length>0&&Object.assign(S,u);let _=this.buildSortAggregatePipeline(e,S,i.userSort);s&&_.push({$project:s});let $=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback($,o)},se);for(let b of y.values())for(let S of b)h.push(S);return{docs:h,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(i?.userSort)||{_id:1},g={projection:s,sort:d},m=await ee(a,h=>this.db.collection(e).find({[t]:{$in:h},...u||{}},g).toArray());return{docs:this.applyReadFallback(m,o),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,o,i){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=de(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(_=>_._id).filter(_=>_!=null),l=new Map;for(let _ of e)l.set(this.keyOf(_._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await ee(u,_=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:_}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?me(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let _=d?(d-1)*p:0,$=await be(u,async N=>{let M=(await this.db.collection(a.junctionName).find({[a.selfColumn]:N},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(P=>P[a.otherColumn]).filter(P=>P!=null);if(M.length===0)return[];let T={_id:{$in:M}};if(c&&Object.keys(c).length>0&&Object.assign(T,c),this.hasDottedSort(t.userSort)){let P=this.buildSortAggregatePipeline(t.targetTable,T,t.userSort);_>0&&P.push({$skip:_}),P.push({$limit:p}),i.projection&&P.push({$project:i.projection});let w=await this.db.collection(t.targetTable).aggregate(P).toArray();return this.applyReadFallback(w,i)}let O={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};i.projection&&(O.projection=i.projection);let B=this.db.collection(t.targetTable).find(T,O);return _>0&&B.skip(_),B.limit(p),this.applyReadFallback(await B.toArray(),i)},se),k=[];for(let[N,R]of $.entries()){l.set(N,R);for(let M of R)k.push(M)}return{grouped:l,docs:k}}let g=new Set,m=[];for(let _ of f){let $=_[a.otherColumn];if($==null)continue;let k=this.keyOf($);g.has(k)||(g.add(k),m.push($))}let h=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1&&!c,y=[],b=new Map;if(h)y=m.map(_=>({_id:_})),this.sortDocsByPk(y);else{let _={_id:{$in:m}};c&&Object.keys(c).length>0&&Object.assign(_,c);let $=this.hasDottedSort(t.userSort),k;if($){let N=this.buildSortAggregatePipeline(t.targetTable,_,t.userSort);i.projection&&N.push({$project:i.projection}),k=await this.db.collection(t.targetTable).aggregate(N).toArray()}else{let N=this.buildSortFromTokens(t.userSort)||{_id:1},R=this.projectionWithSortFields(i.projection,t.userSort),M={sort:N};R.projection&&(M.projection=R.projection),k=await ee(m,T=>this.db.collection(t.targetTable).find({_id:{$in:T},...c||{}},M).toArray()),t.userSort?this.sortDocsInMemory(k,t.userSort):this.sortDocsByPk(k),this.removeHiddenFields(k,R.hiddenFields)}y=this.applyReadFallback(k,i)}for(let _ of y)b.set(this.keyOf(_._id),_);let S=new Map;for(let _ of f){let $=this.keyOf(_[a.selfColumn]),k=this.keyOf(_[a.otherColumn]);b.has(k)&&(S.has(k)||S.set(k,[]),S.get(k).push($))}for(let _ of y){let $=S.get(this.keyOf(_._id))||[];for(let k of $)l.get(k)?.push(_)}return{grouped:l,docs:y}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let o=new Set(t.hiddenFields??[]);for(let i of e)for(let s of n)i[s.newName]===void 0&&i[s.oldName]!==void 0&&(i[s.newName]=i[s.oldName]),(o.has(s.oldName)||i[s.newName]!==void 0)&&delete i[s.oldName];return e}};async function hn(r,e,t,n,o=3,i=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new Xe(r,a,f);await new Re(c,n,u).execute(e,t,o,i,s)}async function zn(r,e,t){let n=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,u=i?.tables?.get(e.table),l=new Set((u?.relations??[]).map(T=>T.propertyName)),f=!!e.mongoRawFilter&&!!i&&re(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&f){let T=await ye(e.mongoRawFilter,e.table,i,o);T&&Object.keys(T).length>0&&n.push({$match:T})}else if(p){let T=Pe(c.filterTree,{metadata:i,rootTable:e.table});Object.keys(T).length>0&&n.push({$match:T})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let T=ze(i,e.where,e.table,s);n.push({$match:T})}let d=e.plan,m=d?d.hasRelationSort:e.sort?.some(T=>{if(!T.field.includes("."))return!1;let L=T.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(I=>I.propertyName===L)??!1})??!1,h=()=>d?.sortItems?$o(d.sortItems):e.sort?wo(e.sort):null,y=d?.sortItems?ho(d.sortItems):[],b=d?.sortItems?mo(d.sortItems):[],S=()=>{!d||y.length===0||yo(n,e.table,d.sortItems,i)},_=()=>{!d||b.length===0||bo(n,e.table,d.sortItems,i)},$=()=>{let T=[...y,...b];T.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(T.map(L=>[L,0]))})};if(!e.mongoFieldsExpanded){S(),_();let T=h();if(T&&n.push({$sort:T}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),$(),e.select){let I={};for(let O of e.select)I[O]=1;n.push({$project:I})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let L=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:L,pipeline:n}:{results:Vr(L),pipeline:n}}let{scalarFields:k,relations:N}=e.mongoFieldsExpanded;if(!m){S(),_();let T=h();T&&n.push({$sort:T}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let R=[];for(let T of N)if(e.sort?.some(I=>I.field.startsWith(`${T.propertyName}.`))){let I=e.mongoRawFilter?.[T.propertyName];if(T.nestedFields&&T.nestedFields.length>0){let B=await jt(i,T.targetTable,T.nestedFields??[],I);T.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName,pipeline:B.length>0?B:void 0}})}else if(I){let B=await jt(i,T.targetTable,["_id"],I);T.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName,pipeline:B.length>0?B:void 0}})}else n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName}});T.type==="one"&&(n.push({$unwind:{path:`$${T.propertyName}`,preserveNullAndEmptyArrays:!0}}),I&&(Ze(I)||n.push({$match:{[T.propertyName]:{$ne:null}}})))}else R.push(T);if(m){S(),_();let T=h();T&&n.push({$sort:T}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}$(),await zr(i,n,e.table,k,[...N]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let M=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:M,pipeline:n};if(R.length>0&&M.length>0){let T=e.deep||{},L=R.map(O=>{let P=i?.tables?.get(e.table)?.relations?.find(x=>x.propertyName===O.propertyName),w=T[O.propertyName],C=w?.fields!=null?Array.isArray(w.fields)?w.fields:String(w.fields).split(",").map(x=>x.trim()).filter(Boolean):O.nestedFields&&O.nestedFields.length>0?O.nestedFields:["_id"];return{relationName:O.propertyName,type:P?.type,targetTable:O.targetTable,fields:C,isInverse:P?.isInverse,mappedBy:P?.mappedBy,junctionTableName:P?.junctionTableName,localField:O.localField,foreignField:O.foreignField,userFilter:w?.filter,userSort:w?.sort,userLimit:w?.limit!==void 0?Number(w.limit):void 0,userPage:w?.page!==void 0?Number(w.page):void 0,nestedDeep:w?.deep}}),I=_o(i);I&&await hn(o,M,L,I,3,0,e.table,i,void 0,t.mongoPhysicalMigrationService)}return{results:Vr(M),pipeline:n}}function Vn(r){return`__sort_count_${r.relationName||r.field}`}function Hn(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function ho(r){return r.filter(e=>e.function==="count").map(Vn)}function mo(r){return r.filter(e=>e.function==="max"||e.function==="min").map(Hn)}function yo(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=Vn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=K(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=de(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function bo(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=n?.tables?.get(l),c=f?.columns?.find(h=>h.isPrimary)?.name||(f?.columns?.some(h=>h.name==="_id")?"_id":"id"),p=s.aggregateField,d=p==="id"&&f?.columns?.some(h=>h.name==="_id")?"_id":p,g=Hn(s),m=s.function==="min"?"$min":"$max";if(!(!a||!l||!p)){if(a.type==="one-to-many"){let h=K(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[m]:`$${d}`}}}],as:g}}),r.push({$addFields:{[g]:{$arrayElemAt:[`$${g}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=de(e,a);if(!h)continue;let y=`${g}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:y}}),r.push({$lookup:{from:l,let:{targetIds:`$${y}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${c}`,"$$targetIds"]}}},{$group:{_id:null,value:{[m]:`$${d}`}}}],as:g}}),r.push({$addFields:{[g]:{$arrayElemAt:[`$${g}.value`,0]}}}),r.push({$project:{[y]:0}})}}}}function _o(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function wo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function $o(r){let e={};for(let t of r){let n=t.function==="count"?Vn(t):t.function==="max"||t.function==="min"?Hn(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Ze(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ze(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ze(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ze(e));if("_not"in r)return Ze(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ze(t)))return!0}return!1}function Vr(r){return r.map(ae)}function Hr(r,e){let t=[],n=[],o=e?.tables?.get(r.rootTable);if(!o)return{scalarFields:t,relations:n};for(let i of r.nodes)if(i.kind==="wildcard")for(let s of o.columns||[])t.includes(s.name)||t.push(s.name);else i.kind==="scalar"?o.columns?.some(a=>a.name===i.name)&&!t.includes(i.name)&&t.push(i.name):i.kind==="relation"&&n.push(So(i,o,e));return{scalarFields:t,relations:n}}function So(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),o,i,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Oe(n)?(o="_id",i=K(n)||r.propertyName,s=!0):(o=n&&H(n)||r.propertyName,i="_id",s=!1):r.relationType==="one-to-many"?(o="_id",i=n&&K(n)||r.propertyName,s=!0):n?.mappedBy?(o="_id",i=n.mappedBy,s=!0):(o=r.propertyName,i="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Gr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:u}}function Gr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Gr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let o of n)e.push(`${t.propertyName}.${o}`)}return e}Ve();Et();Ot();function mn(r,e,t,n){let o={rootTable:e,nodes:[]};if(!r||r.length===0)return o;let i=t?.tables?.get(e);if(!i)return o;let s=i.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=i.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),m=p.substring(d+1);if(!i.relations?.some(y=>y.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(m)}else if(i.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!i.columns?.some(m=>m.name===p))continue;f.push(p)}}if(f.includes("*")){o.nodes.push({kind:"wildcard"});for(let c of i.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)o.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=i.relations?.find(h=>h.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,m={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Yr(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let h=n.registerWithParent(e,c,t,"left",null,"data");m.joinId=h}o.nodes.push(m)}return o}function Yr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let o=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),i=n.columns?.some(f=>f.name==="id"),s=o&&!i?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Yr(c,d,t)})}return l}pe();pe();var To=new Set(["_and","_or","_not"]);function Xr(r,e){return r?.tables?.get(e)??null}function ko(r,e,t){return Xr(r,e)?.columns?.find(n=>n.name===t)}function Gn(r,e,t){return Xr(r,e)?.relations?.find(n=>n.propertyName===t)}function Co(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let o=n.indexOf(".");return o<=0||o!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,o).trim(),fieldName:n.slice(o+1).trim()}}function Yn(r,e,t,n){if(ko(r,e,t)?.isEncrypted===!0)throw new v(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function je(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)je(n,e,t);return}for(let[n,o]of Object.entries(r)){if(To.has(n)){je(o,e,t);continue}if(n.startsWith("_"))continue;let i=Gn(t,e,n);if(i){let s=i.targetTableName||i.targetTable;s&&je(o,s,t);continue}Yn(t,e,n,"filter")}}}function yn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(!i)continue;let s=Co(i);if(s){if(s.functionName==="count")continue;let l=Gn(t,e,s.relationName),f=l?.targetTableName||l?.targetTable;f&&Yn(t,f,s.fieldName,"sort");continue}let a=i.split("."),u=e;for(let l=0;l<a.length;l++){let f=a[l];if(l===a.length-1){Yn(t,u,f,"sort");break}let p=Gn(t,u,f);if(!p)break;u=p.targetTableName||p.targetTable||u}}}var q=class{plan(e){let{tableName:t,fields:n,filter:o,sort:i,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new oe,d=this.parseFields(n),g=null;d&&c&&(g=mn(d,t,l,p));let m=!1,h=null;if(o&&c){je(o,t,l);let L=ge(o,t,l,p);h=L.node,m=L.hasRelationFilters}let y=this.parseSort(i);c&&yn(y,t,l);let b=[],S=!1;for(let L of y){let I=L.startsWith("-"),O=I?L.substring(1):L,B=I?"desc":"asc";if(c){let P=this.parseRelationAggregateSort(t,c,O,l);if(P){b.push({joinId:null,field:O,direction:B,fullPath:O,function:P.functionName,relationName:P.relationName,aggregateField:P.aggregateField,relationMeta:P.relationMeta});continue}this.assertLocalSortField(t,c,O)}b.push({joinId:null,field:O,direction:B,fullPath:O})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let _=this.parseLimit(a),$=this.parsePage(s),k=$!==void 0&&_!==void 0?($-1)*_:void 0,N=this.parseMeta(u),R=N.includes("totalCount")||N.includes("*"),M=N.includes("filterCount")||N.includes("*"),T=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:o??null,joins:T,sortItems:b,limit:_,offset:k,needsTotalCount:R,needsFilterCount:M,hasRelationFilters:m,hasRelationSort:S,filterTree:h,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new v(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let o=t.columns?.some(s=>s.name===n),i=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!o&&!i)throw new v(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,o){let i=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!i){if(/^_(count|max|min)\(/.test(n))throw new v(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=i[1],a=i[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new v(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let y=t.relations?.find(b=>b.propertyName===h);if(!y)throw new v(`Sort relation '${h}' does not exist on '${e}'.`);if(y.type!=="one-to-many"&&y.type!=="many-to-many")throw new v(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:y}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new v(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=a.slice(0,u).trim(),f=a.slice(u+1).trim();if(!l||!f)throw new v(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=t.relations?.find(h=>h.propertyName===l);if(!c)throw new v(`Sort relation '${l}' does not exist on '${e}'.`);if(c.type!=="one-to-many"&&c.type!=="many-to-many")throw new v(`Sort function '_${s}(${l}.${f})' is only supported for list relations on '${e}'.`);let p=c.targetTableName||c.targetTable,d=o?.tables?.get(p);if(!d)throw new v(`Sort function '${n}' references unknown target table '${p}' on '${e}'.`);let g=d.columns?.find(h=>h.name===f),m=f==="id"&&d.columns?.some(h=>h.name==="_id");if(!g&&!m)throw new v(`Sort field '${f}' does not exist on '${p}' for function '_${s}(${l}.${f})'.`);if(g?.isEncrypted===!0)throw new v(`Encrypted field '${f}' on '${p}' cannot be used for sort.`);return{functionName:s,relationName:l,aggregateField:f,relationMeta:c}}registerSortJoinChain(e,t,n,o,i){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=o.registerWithParent(t,a,n,"left",i,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,o,c)}};pe();At();var Fo=new Set(["count","sum","avg","min","max","countRecords"]),Ro=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),xo=new Set(["_and","_or","_not"]);function xe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function j(r,e){let t=r.replace(/^aggregate\./,"");throw new v(e,{path:r,aggregate:{[t]:e}})}function vo(r){return typeof r!="string"?!1:Ro.has(r.toLowerCase())}function Zr(r){return Object.keys(r).length===0}function Io(r,e,t){return r===!0?{}:(r==null&&j(t,`aggregate.${e} condition must be true or an object`),xe(r)||j(t,`aggregate.${e} condition must be true or an object`),r)}function No(r,e,t){let n=r?.tables?.get(e);return n||j(t,`Table "${e}" metadata is not available`),n}function ei(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&j(e,"aggregate.countRecords relation target is not available"),t}function bn(r,e,t,n){let o=No(t,e,n);for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){Array.isArray(s)||j(n,`aggregate.countRecords ${i} condition must be an array`);for(let f of s)xe(f)||j(n,`aggregate.countRecords ${i} items must be objects`),bn(f,e,t,n);continue}if(i==="_not"){xe(s)||j(n,"aggregate.countRecords _not condition must be an object"),bn(s,e,t,n);continue}(i.startsWith("_")||xo.has(i))&&j(n,`Unsupported aggregate.countRecords condition key "${i}"`);let a=o.columns?.find(f=>f.name===i),u=o.relations?.find(f=>f.propertyName===i);if(!a&&!u&&j(n,`Unknown aggregate.countRecords field or relation "${i}" on table "${e}"`),xe(s)||j(n,`aggregate.countRecords condition for "${i}" must be an object`),a){for(let f of Object.keys(s))ie.has(f)||j(n,`aggregate.countRecords condition for "${i}" only supports field operators`);continue}let l=ei(u,n);bn(s,l,t,n)}}function Xn(r){return xe(r)&&Object.keys(r).length>0}function et(r,e,t){if(!Xn(r))return[];xe(r)||j("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||j("aggregate",`Table "${e}" metadata is not available`);let o=[];for(let[i,s]of Object.entries(r)){let a=`aggregate.${i}`;(!i||typeof i!="string")&&j("aggregate","aggregate field name must be a non-empty string"),xe(s)||j(a,"aggregate field config must be an object");let u=i,l=a,f=n.columns?.find(d=>d.name===i),c=n.relations?.find(d=>d.propertyName===i);!f&&!c&&j(l,`Unknown aggregate field or relation "${i}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&j(l,"aggregate field must define at least one operation");for(let[d,g]of p){Fo.has(d)||j(l,`Unsupported aggregate operation "${d}"`);let m=Io(g,d,l);if(c&&d!=="countRecords"&&j(l,`aggregate.${d} is not supported on relation "${i}"; use countRecords`),f&&d==="countRecords"&&j(l,`aggregate.countRecords requires a relation, but "${i}" is a field`),f&&(d==="sum"||d==="avg")&&!vo(f.type)&&j(l,`aggregate.${d} requires a numeric field, but "${i}" is "${f.type}"`),f)for(let h of Object.keys(m))ie.has(h)||j(l,`aggregate.${d} condition for "${i}" only supports field operators`);if(c&&d==="countRecords"){let h=ei(c,l);bn(m,h,t,l)}o.push({field:i,outputKey:u,path:l,op:d,condition:m})}}return o}function tt(r,e){let t=[];return xe(r)&&!Zr(r)&&t.push(r),Zr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function ve(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var nt=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new q;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(J(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let o=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),i=0,s=0;(o.includes("totalCount")||o.includes("*"))&&(i=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&re(n.mongoRawFilter,u);if((o.includes("filterCount")||o.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?Pe(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(o.includes("filterCount")||o.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(o.length>0||c)&&{meta:{...o.includes("totalCount")||o.includes("*")?{totalCount:i}:{},...o.includes("filterCount")||o.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,o=this.metadata?.tables?.get(e.table),i=o?.relations&&o.relations.length>0;if(e.fields&&e.fields.length>0||n||i){let l=e.plan,f=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&l?.fieldTree){if(e.mongoFieldsExpanded=Hr(l.fieldTree,this.metadata),n){let c=await Nt(this.metadata,e.table,[],e.deep),p=new Set(e.mongoFieldsExpanded.relations.map(d=>d.propertyName));e.mongoFieldsExpanded.relations.push(...c.relations.filter(d=>!p.has(d.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await Nt(this.metadata,e.table,f,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let c=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:c.scalarFields},t=c.hiddenFields}}e.where&&(e.where=e.where.map(l=>l.field.includes(".")?l:{...l,field:`${e.table}.${l.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(ae);let{results:a,pipeline:u}=await zn(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:o}=await zn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,n}async executeAggregate(e,t){let n=et(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={},i=this.db.collection(e.table);for(let s of n){let a=tt(t,s);J(a,e.table,e.metadata);let l=new q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);ve(o,s,p);continue}let f=l.hasRelationFilters?await ye(a,e.table,e.metadata,this.db):l.filterTree?Pe(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await i.countDocuments(f);else{let[{value:p}={value:null}]=await i.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}ve(o,s,c)}return o}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(i.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[i.foreignKeyColumn]:{$in:c}}]})}if(i.type==="many-to-many"){let f=de(e.table,i);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(m=>m!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(m=>m[f.otherColumn]).filter(m=>m!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(i.type==="many-to-one"||i.type==="one-to-one"){let f=i.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};J(t,e,n);let i=new q().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return i.hasRelationFilters?await ye(t,e,n,this.db):i.filterTree?Pe(i.filterTree,{metadata:n,rootTable:e}):{}}};var _n=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&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};pe();le();var Mo=["_and","_or","_not"];function _e(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>_e(e));for(let e of Object.keys(r))if(Mo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&_e(r[e]))return!0;return!1}var ti=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Ao(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function wn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let o=t.columns.find(s=>s.name===n);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function Oo(r,e,t,n,o){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||wn(r,t,o),e}function ni(r,e,t,n,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,u=Ie(a,i??"postgres"),l=wn(e,o,s),f=Oo(e,n,o,i,s);switch(t){case"_eq":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",f);break;case"_neq":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",f);break;case"_gt":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",f);break;case"_gte":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",f);break;case"_lt":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",f);break;case"_lte":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",f);break;case"_in":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]),l&&i==="postgres"&&c.every(d=>typeof d=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[c]):r.whereIn(a,c);break;case"_not_in":case"_nin":let p=n;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(d=>d.trim()):[p]),l&&i==="postgres"&&p.every(d=>typeof d=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[p]):r.whereNotIn(a,p);break;case"_contains":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,Ao(t),n)}}function Eo(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.some(s=>s.name===n),i=t.relations?.some(s=>s.propertyName===n);return o||i}function rt(r,e,t,n="and",o,i){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){rt(this,s,t,"and",o,i)}):r.orWhere(function(){rt(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e))if(Eo(s,t,i)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){rt(this,u,t,"and",o,i)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){rt(this,u,t,"and",o,i)})});continue}if(s==="_not"){r.whereNot(function(){rt(this,a,t,"and",o,i)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>ti.includes(l)))for(let[l,f]of Object.entries(a))ti.includes(l)&&(n==="and"?r.where(function(){ni(this,s,l,f,t,o,i)}):r.orWhere(function(){ni(this,s,l,f,t,o,i)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s,f=Ie(l,o??"postgres");wn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${f} = ?::uuid`,[a]):r.orWhereRaw(`${f} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,l=Ie(u,o??"postgres");wn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function ce(r,e,t,n,o){return!e||typeof e!="object"||rt(r,e,t,"and",n,o),r}le();function tr(r,e,t){return`${F(r,t)}.${F(e,t)}`}function Ne(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function ri(r,e){if(!e)return!1;let t=e.columns.find(o=>o.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function it(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function nr(r,e,t,n,o,i){let s=[];for(let[a,u]of Object.entries(i)){let l=await Bt(r,e,a,u,t,n,o);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=tr(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=it(d._is_null),m=it(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(m===!0)s.push(`${c} IS NOT NULL`);else if(m===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let h=Ne(d._eq,n);s.push(`${c} = ${h}`)}else if(d._neq!==void 0){let h=Ne(d._neq,n);s.push(`${c} != ${h}`)}else if(d._in!==void 0){let y=(Array.isArray(d._in)?d._in:[d._in]).map(b=>Ne(b,n)).join(", ");s.push(`${c} IN (${y})`)}else if(d._not_in!==void 0||d._nin!==void 0){let h=d._not_in??d._nin,b=(Array.isArray(h)?h:[h]).map(S=>Ne(S,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let h=Ne(d._gt,n);s.push(`${c} > ${h}`)}else if(d._gte!==void 0){let h=Ne(d._gte,n);s.push(`${c} >= ${h}`)}else if(d._lt!==void 0){let h=Ne(d._lt,n);s.push(`${c} < ${h}`)}else if(d._lte!==void 0){let h=Ne(d._lte,n);s.push(`${c} <= ${h}`)}}}}}return s}function rr(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function Zn(r,e,t,n,o,i){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(rr(l)){let f=e(t).select(`${t}.id`);await Le(e,f,l,t,n,o,i),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=G(l,n),p=await nr(e,t,n,o,i,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(rr(a)){let u=e(t).select(`${t}.id`);await Le(e,u,a,t,n,o,i),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=G(a,n),f=await nr(e,t,n,o,i,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function ii(r,e,t,n,o){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let i=e;Object.keys(i.fieldFilters).length===0&&i.subqueries.length===0||r.where(function(){Object.keys(i.fieldFilters).length>0&&ce(this,i.fieldFilters,t,o,n);for(let s of i.subqueries)this.whereRaw(s)})}function er(r,e,t,n,o){let i=!0;for(let s of e){let a=function(){for(let u of s)ii(this,u,t,n,o)};i?(r.where(a),i=!1):r.orWhere(a)}}function $n(r,e,t,n,o,i,s){let a=ri(e,o),u=ri(n,i),l=`${F(r,s)}.${F(e,s)}`,f=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Bt(r,e,t,n,o,i,s){let a=o.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw($n(u,a.foreignKeyColumn,e,"id",f,o,i));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw($n(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,i))).whereRaw($n(a.junctionTableName,a.junctionSourceColumn,e,"id",p,o,i));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw($n(u,"id",e,a.foreignKeyColumn,f,o,i));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await Le(r,c,n,u,f,i,s):c=ce(c,n,u,i,f||void 0):c=ce(c,n,u,i),c.toString()}async function Le(r,e,t,n,o,i,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Zn(l._or,r,n,o,i,s);e.where(function(){er(this,f,n,o,i)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await Le(r,e,f,n,o,i,s);else await Le(r,e,l,n,o,i,s);return}if(t._or&&Array.isArray(t._or)){let l=await Zn(t._or,r,n,o,i,s);e.where(function(){er(this,l,n,o,i)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(rr(d)){let g=r(n).select(`${n}.id`);await Le(r,g,d,n,o,i,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:m}=G(d,o),h=await nr(r,n,o,i,s,m);p.push({fieldFilters:g,subqueries:h})}e.whereNot(function(){for(let d of p)ii(this,d,n,o,i)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Zn(l._or,r,n,o,i,s);e.whereNot(function(){er(this,p,n,o,i)});return}let{fieldFilters:f,relationFilters:c}=G(l,o);e.whereNot(function(){Object.keys(f).length>0&&ce(this,f,n,i,o)});for(let[p,d]of Object.entries(c)){let g=await Bt(r,n,p,d,o,i,s);if(g===null){let m=o.relations.find(h=>h.propertyName===p);if(m&&m.foreignKeyColumn){let h=tr(n,m.foreignKeyColumn,i),b=d.id;if(b&&typeof b=="object"){let S=it(b._is_null),_=it(b._is_not_null);if(S===!0)e.whereRaw(`${h} IS NOT NULL`);else if(S===!1)e.whereRaw(`${h} IS NULL`);else if(_===!0)e.whereRaw(`${h} IS NULL`);else if(_===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let $=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${$.map(()=>"?").join(", ")})`,$)}else if(b._not_in!==void 0||b._nin!==void 0){let $=b._not_in??b._nin,k=Array.isArray($)?$:[$];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=G(t,o);Object.keys(a).length>0&&ce(e,a,n,i,o);for(let[l,f]of Object.entries(u)){let c=await Bt(r,n,l,f,o,i,s);if(c===null){let p=o.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=tr(n,p.foreignKeyColumn,i),m=f.id;if(m&&typeof m=="object"){let h=it(m._is_null),y=it(m._is_not_null);if(h===!0)e.whereRaw(`${d} IS NULL`);else if(h===!1)e.whereRaw(`${d} IS NOT NULL`);else if(y===!0)e.whereRaw(`${d} IS NOT NULL`);else if(y===!1)e.whereRaw(`${d} IS NULL`);else if(m._eq!==void 0)e.whereRaw(`${d} = ?`,[m._eq]);else if(m._neq!==void 0)e.whereRaw(`${d} != ?`,[m._neq]);else if(m._in!==void 0){let b=Array.isArray(m._in)?m._in:[m._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(m._not_in!==void 0||m._nin!==void 0){let b=m._not_in??m._nin,S=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${S.map(()=>"?").join(", ")})`,S)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Be(r,e,t,n,o,i,s){await Le(r,e,t,n,o,i,s)}le();or();Ve();le();function ot(r,e,t,n,o){for(let i of e){let s=i.field.split("."),a=t||s[0],u=s[s.length-1],l=Dt(n,a,u,i.value);switch(i.operator){case"=":r=r.where(i.field,"=",l);break;case"!=":r=r.where(i.field,"!=",l);break;case">":r=r.where(i.field,">",l);break;case"<":r=r.where(i.field,"<",l);break;case">=":r=r.where(i.field,">=",l);break;case"<=":r=r.where(i.field,"<=",l);break;case"like":r=r.where(i.field,"like",l);break;case"in":let f=Array.isArray(i.value)?i.value.map(m=>Dt(n,a,u,m)):[l];r=r.whereIn(i.field,f);break;case"not in":let c=Array.isArray(i.value)?i.value.map(m=>Dt(n,a,u,m)):[l];r=r.whereNotIn(i.field,c);break;case"is null":r=r.whereNull(i.field);break;case"is not null":r=r.whereNotNull(i.field);break;case"_contains":r=r.where(i.field,"like",`%${i.value}%`);break;case"_starts_with":r=r.where(i.field,"like",`${i.value}%`);break;case"_ends_with":r=r.where(i.field,"like",`%${i.value}`);break;case"_between":let p=i.value;if(typeof p=="string"&&(p=p.split(",").map(m=>m.trim())),Array.isArray(p)&&p.length===2){let m=Dt(n,a,u,p[0]),h=Dt(n,a,u,p[1]);r=r.whereBetween(i.field,[m,h])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(i.field):r.whereNotNull(i.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(i.field):r.whereNull(i.field);break}}return r}function Wt(r,e,t,n){let o=[],i=t;if(!r||typeof r!="object")return o;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let f=Wt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=Wt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Wt(a,e,t,n);u.length>0&&o.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let f=`${F(e,n)}.${F(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=i.columns?.find(m=>m.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")o.push(`${f} = ${c}`);else if(u==="_neq")o.push(`${f} != ${c}`);else if(u==="_gt")o.push(`${f} > ${c}`);else if(u==="_gte")o.push(`${f} >= ${c}`);else if(u==="_lt")o.push(`${f} < ${c}`);else if(u==="_lte")o.push(`${f} <= ${c}`);else if(u==="_is_null")o.push(`${f} IS NULL`);else if(u==="_is_not_null")o.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):o.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);o.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${F(e,n)}.${F(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),o.push(`${u} = ${l}`)}return o}function si(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Dt(r,e,t,n){if(n==null)return n;let o=r?.tables?.get(e);if(!o?.columns)return n;let i=o.columns.find(s=>s.name===t);if(!i)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}le();Kt();Qe();async function li(r,e,t,n,o,i,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(ar(),ai)),u=await a(e,t,n,o,i,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function lr(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function ci(r,e,t,n,o){let i=r.targetTableName||r.targetTable;if(!i)return null;let s=r.foreignKeyColumn||V(r.propertyName);if(!s)return null;let a=c=>F(c,o),u=n?.tables?.get(i),f=(u?Y(u):null)?.name||"id";return`(SELECT ${a(i)}.${a(e)} FROM ${a(i)} WHERE ${a(i)}.${a(f)} = ${a(t)}.${a(s)})`}Kt();var at=class r{constructor(e,t,n,o){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=o;this.logger=new _n(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let o=e.debugTrace;if(e.filter&&J(e.filter,e.tableName,e.metadata),!e.plan){let w=new q;e={...e,plan:w.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let i=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!u&&!a&&l){o&&o.setQueryPath("simple");let w=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),w}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(w=>w.trim())));let p=e.filter;if(e.filter&&!_e(e.filter)){c.where=[];for(let[w,C]of Object.entries(e.filter))if(typeof C=="object"&&C!==null)for(let[x,ue]of Object.entries(C)){let A;if(x==="_eq")A="=";else if(x==="_neq")A="!=";else if(x==="_in")A="in";else if(x==="_not_in"||x==="_nin")A="not in";else if(x==="_gt")A=">";else if(x==="_gte")A=">=";else if(x==="_lt")A="<";else if(x==="_lte")A="<=";else if(x==="_contains")A="_contains";else if(x==="_starts_with")A="_starts_with";else if(x==="_ends_with")A="_ends_with";else if(x==="_between")A="_between";else if(x==="_is_null")A="_is_null";else if(x==="_is_not_null")A="_is_not_null";else if(x==="_like")A="like";else if(x==="_ilike")A="ilike";else continue;c.where.push({field:w,operator:A,value:ue})}else c.where.push({field:w,operator:"=",value:C})}if(e.sort){let w=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(C=>C.trim());c.sort=w.map(C=>{let x=C.trim();return x.startsWith("-")?{field:x.substring(1),direction:"desc"}:{field:x,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,m=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=m===void 0||Number.isNaN(m)?void 0:m;h&&g!==void 0?(c.offset=(h-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let y=e.plan?.sortItems??(c.sort??[]).map(w=>({joinId:null,field:w.field,direction:w.direction,fullPath:w.field})),b=[],S=[];for(let w of y){if(w.function==="count"){let C={sql:this.buildRelationCountSortSubquery(c.table,w),direction:w.direction};S.push(C);continue}if(w.function==="max"||w.function==="min"){let C={sql:this.buildRelationAggregateSortSubquery(c.table,w),direction:w.direction};S.push(C);continue}if(w.joinId===null){if(w.field.includes(".")&&!e.plan){let x=w.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(z=>z.propertyName===x))continue}let C={field:w.field.includes(".")?w.field:`${c.table}.${w.field}`,direction:w.direction};b.push(C),S.push(C)}else{let C=e.plan?.joins.find(x=>x.id===w.joinId);if(C&&(C.relationType==="many-to-one"||C.relationType==="one-to-one")){let x=ci(C.relationMeta,w.field,c.table,this.metadata,this.dbType);if(x){let ue={sql:x,direction:w.direction};S.push(ue)}}}}let _=[];if(c.fields&&c.fields.length>0||u||a){let w=lr(this.metadata),C=c.fields&&c.fields.length>0?c.fields:["*"],x=await li(this.knex,c.table,C,w,this.dbType,this.maxQueryDepth,e.deep);x.select.length>0&&(c.select=[...c.select||[],...x.select]),_=x.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(w=>w.field.includes(".")?w:{...w,field:`${c.table}.${w.field}`})),c.sort=b;let $=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(w=>w.trim()).filter(Boolean),N=k.includes("filterCount")||k.includes("*"),R=k.includes("totalCount")||k.includes("*");if(c.select){let w=c.select.map(C=>typeof C=="string"&&C.trim().startsWith("(")?this.knex.raw(C):typeof C=="string"&&/ as /i.test(C)?this.knex.raw(C):C);$=$.select(w)}if(N&&$.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),R){let w=F(c.table,this.dbType);$.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) as __total_count__`))}let M=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(_e(p)||Object.keys(p).length>0)){let w=this.metadata?.tables?.get(c.table);(!M&&w&&w.relations&&w.relations.length>0?G(p,w).hasRelations:!1)?await Be(this.knex,$,p,c.table,w,this.dbType,x=>this.metadata?.tables?.get(x)):e.plan?.filterTree?te($,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),$=ce($,p,c.table,this.dbType,w))}else c.where&&c.where.length>0&&($=ot($,c.where,c.table,this.metadata,this.dbType));for(let w of S)if(w.field){let C=w.field.includes(".")?w.field:`${c.table}.${w.field}`;$=$.orderBy(C,w.direction)}else w.sql&&($=$.orderByRaw(`${w.sql} ${w.direction.toUpperCase()}`));c.groupBy&&($=$.groupBy(c.groupBy)),c.offset&&($=$.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&($=$.limit(c.limit));let T=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:$.toSQL().toNative()});let L;if(e.debugMode&&(L=$.toSQL().toNative().sql),e.debugMode&&o){let w=$.toSQL().toNative();o.setSql(w.sql);try{let C=w.sql.replace(/\$\d+/g,"?"),x=await this.knex.raw(`EXPLAIN ${C}`,w.bindings);o.setExplain(this.dbType==="postgres"?x.rows:x[0])}catch(C){o.setExplain({error:String(C)})}}let I,O=performance.now();I=await $,o&&o.dur("db_execute",O,{table:e.tableName});let B=0;if(N&&I.length>0&&(B=Number(I[0].__filter_count__||0),I.forEach(w=>{delete w.__filter_count__})),R&&I.length>0&&I[0].__total_count__!==void 0&&(T=Number(I[0].__total_count__||0),I.forEach(w=>{delete w.__total_count__})),_&&_.length>0&&I.length>0){let w=lr(this.metadata);if(w){let{executeBatchFetches:C}=await Promise.resolve().then(()=>(fr(),ui));await C(this.knex,I,_,w,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,o)}}if(this.knexService){let w=performance.now();I=await this.knexService.parseResult(I,c.table),o&&o.dur("db_parseResult",w,{table:e.tableName})}else{let w=(C,x)=>{if(!C||!this.metadata)return C;let ue=this.metadata.tables?.get(x);if(!ue)return C;if(Array.isArray(C))return C.map(z=>w(z,x));if(typeof C!="object"||Buffer.isBuffer(C))return C;let A={...C};for(let z of ue.columns)if(z.type==="simple-json"&&A[z.name]&&typeof A[z.name]=="string")try{A[z.name]=JSON.parse(A[z.name])}catch{}for(let[z,X]of Object.entries(A))if(X&&typeof X=="object"&&!Array.isArray(X)&&!Buffer.isBuffer(X)){let Rn=X;if(Rn.id!==void 0||Rn.createdAt!==void 0){let ct=ue.relations?.find(ut=>ut.propertyName===z);ct&&(A[z]=w(X,ct.targetTableName))}}else if(Array.isArray(X)&&X.length>0&&typeof X[0]=="object"&&X[0].id!==void 0){let ct=ue.relations?.find(ut=>ut.propertyName===z);ct&&(A[z]=X.map(ut=>w(ut,ct.targetTableName)))}return A};I=w(I,c.table)}o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName}));let P=await this.executeAggregate(c,p);return{data:I,...(k.length>0||P)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:T}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:B}:{},...P?{aggregate:P}:{}}},...L!==void 0&&{sql:L}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=Y(s)?.name||"id",u=F(e,this.dbType),l=F(a,this.dbType);if(!n||!i)throw new v(`Sort relation '${o}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new v(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let c=F(i,this.dbType),p=F(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=this.resolveManyToManyContract(n,o,e),c=F(f.tableName,this.dbType),p=F(f.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new v(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),l=Y(a)?.name||"id",f=Y(u)?.name||"id",c=F(e,this.dbType),p=F(l,this.dbType),d=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!d||!n||!s||!i)throw new v(`Sort function '${t.field}' is not supported on '${e}'.`);let g=F(s,this.dbType),m=F(i,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new v(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let y=F(h,this.dbType);return`(SELECT ${d}(${g}.${m}) FROM ${g} WHERE ${g}.${y} = ${c}.${p})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,o,e),y=F(h.tableName,this.dbType),b=F(h.sourceColumn,this.dbType),S=F(h.targetColumn,this.dbType),_=F(f,this.dbType);return`(SELECT ${d}(${g}.${m}) FROM ${y} JOIN ${g} ON ${g}.${_} = ${y}.${S} WHERE ${y}.${b} = ${c}.${p})`}throw new v(`Sort function '_${t.function}(${o}.${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new v(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(n).select(o);t.filterTree&&te(i,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let y=h.field.includes(".")?h.field:`${n}.${h.field}`;i=i.orderBy(y,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=F(n,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let h=i.toSQL().toNative();if(f=h.sql,l){l.setSql(h.sql);try{let y=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${y}`,h.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(y){l.setExplain({error:String(y)})}}}let c=performance.now(),p;p=await i,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(h=>delete h.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(h=>delete h.__total_count__));let m=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||m)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...m?{aggregate:m}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=et(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={};for(let i of n){let s=tt(t,i);J(s,e.table,e.metadata);let u=new q().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(i.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,i);ve(o,i,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Be(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&te(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${F(e.table,this.dbType)}.${F(i.field,this.dbType)}`,c=i.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${i.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();ve(o,i,p?.value??0)}return o}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table),i=o?.relations?.find(c=>c.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Be(this.knex,u,t,e.table,o,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&te(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){J(n.condition,s,e.metadata);let p=new q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Be(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&te(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(i.type==="one-to-many")l.whereIn(`${s}.${i.foreignKeyColumn}`,u);else if(i.type==="many-to-many"){let c=this.resolveManyToManyContract(i,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(i.type==="many-to-one"||i.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${i.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${i.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var Tn=require("mongodb"),lt=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),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&&(0,kn.mkdirSync)((0,fi.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!Tn.ObjectId)return e;if(typeof e=="string")try{return new Tn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),o=ze(n,e,t,this.dbType);return o._id!==void 0&&(o._id=this.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,n){let o=await this.getMetadataForQuery();return{query:ot(e,t,n??"",o,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.mongoService.insertOne(e.table,n);t.push(ae(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.knexService.insertWithCascade(e.table,n);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),o=performance.now(),s=new q().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",o,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb")return new nt(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new at(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(i).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);if(e.returning){let i=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(i,e.where,e.table),await i.select(e.returning)}return{affected:o.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(o).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let i=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,i)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n.count("* as count").first();return Number(o?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",i):t.id=this.normalizeWhereFilterValue("id",i):t[o]=this.normalizeWhereFilterValue(o,i);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Tn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,o]of Object.entries(e))t[n]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[n,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.entries(o)[0];if(i){let[s,a]=i,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return ae(a)}let o=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),s=o||t.id;return await i(e).where("id",s).first()})}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let o of n)this.batchInserts.items.push({table:e,data:o});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);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 n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...n.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}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(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.mongoService.insertOne(e,o.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.knexService.insertWithCascade(e,o.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let o=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,o)),this.runBatchInsertWithIsolation(e,t.slice(o))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let o=t.get(n.table);o?o.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,o=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let i=e[n++];await t(i)}});await Promise.all(o)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,kn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
54
- `)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return ae(i)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let o=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:o}=await this.applyWhereToKnex(o,s,e))}let i=await o.count("* as count").first();return Number(i?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let o=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:o})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[i,s]of Object.entries(t))i==="id"||i==="_id"?o._id=this.safeObjectId(s):o[i]=s;return this.mongoService.findOne(e,o)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?o._id=this.safeObjectId(u):o[a]=u;return await this.mongoService.collection(e).find(o).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=n||t.id;return await o(e).where("id",i).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let i=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await i.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await i.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};fr();cr();ar();le();Kt();Ye();pe();Ve();var di=new Set(["fields","filter","sort","limit","page","deep"]),Fn=3;function dr(r,e,t,n=0,o=3){if(!e||typeof e!="object")return;if(n>=o)throw new v(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(r),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let l=s.get(a);if(!l)throw new v(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!di.has(p))throw new v(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...di].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new v(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new v(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(J(u.filter,c,t),je(u.filter,c,t),Cn(u.filter,0,a,r)),u.sort){yn(u.sort,c,t);let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;Lo(g,c,t,a,r)}}u.deep&&dr(c,u.deep,t,n+1,o)}}}function Lo(r,e,t,n,o){if(r.includes("."))throw new v(`Sort field '${r}' is not supported for relation '${n}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new v(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${o}')`);let s=i.columns?.some(u=>u.name===r),a=r==="id"&&i.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new v(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${o}')`)}var Bo=new Set(["_and","_or","_not"]);function Cn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[o,i]of Object.entries(r)){if(Bo.has(o)){if(Array.isArray(i))for(let l of i)Cn(l,e,t,n);else i&&typeof i=="object"&&Cn(i,e,t,n);continue}if(o.startsWith("_")||!i||typeof i!="object"||Array.isArray(i)||!Object.keys(i).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>Fn)throw new v(`Filter path exceeds max dotted hops of ${Fn} at '${o}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(i))l.startsWith("_")||(u[l]=i[l]);Cn(u,a,t,n)}}function pi(r,e,t,n){return!r||typeof r!="object"?r:Ut(r,e,t,n)}function Ut(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let i=r.map(s=>Ut(s,e,t,n)).filter(s=>s!=null);return i.length>0?i:null}let o={};for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){let c=(Array.isArray(s)?s:[s]).map(p=>Ut(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(o[i]=c);continue}if(i==="_not"){let f=Ut(s,e,t,n);f!=null&&Object.keys(f).length>0&&(o[i]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===i);if(u){if(!n(e,i,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Ut(s,f,t,n);c!=null&&Object.keys(c).length>0&&(o[i]=c);continue}if(a?.columns?.find(f=>f.name===i)){if(!n(e,i,"column"))continue;o[i]=s;continue}o[i]=s}return o}function gi(r,e,t,n){if(!r)return r;let o=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,m=t?.tables?.get(c);if(!m){f=!1;break}if(g)m.columns?.find(y=>y.name===d)?n(c,d,"column")||(f=!1):m.relations?.find(b=>b.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let h=m.relations?.find(y=>y.propertyName===d);if(!h){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=h.targetTableName||h.targetTable||c}}f&&i.push(s)}if(i.length!==0)return Array.isArray(r)?i:i.join(",")}Ot();Ve();Et();gn();At();Qe();pe();function Do(r){let e=new lt({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,o=()=>(t||(t=new Ue({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),i=()=>(n||(n=new De({isolatedExecutorService:o()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return o()},get executorEngineService(){return i()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
52
+ }`}var xr="mongo-fold-text-search.body.txt",Qe=null;function Wi(){let r=[An.join(__dirname,xr),An.join(process.cwd(),"dist","kernel","query","utils",xr)];for(let e of r)try{if(Xt.existsSync(e))return Xt.readFileSync(e,"utf8")}catch{}return null}function Zt(){if(Qe!==null)return Qe;let r=Wi();return r?(Qe=r,Qe):(Qe=Yt(),Qe)}var Te=require("mongodb");function K(r,e,t,n){if(t==="_id"){if(n instanceof Te.ObjectId)return n;if(typeof n=="string")try{return new Te.ObjectId(n)}catch{return n}return n}let o=r?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new Te.ObjectId(n)}catch{return n}return n;default:return n}}var en="__mongoFoldTextTriples";function Ui(r){return r==="_id"?"$_id":`$${r}`}function Je(r,e,t,n){let o=Ui(e),i=r[en]??[];i.push({ref:o,needle:t,mode:n}),r[en]=i}function Qi(r){let e=r[en];if(delete r[en],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:Zt(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}function qe(r,e,t,n){let o={},i=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";i&&a==="id"&&(a="_id");let l=K(r,u,a,s.value);switch(s.operator){case"=":o[a]=l;break;case"!=":o[a]={$ne:l};break;case">":o[a]={$gt:l};break;case"<":o[a]={$lt:l};break;case">=":o[a]={$gte:l};break;case"<=":o[a]={$lte:l};break;case"like":o[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let c=f.map(m=>K(r,u,a,m));o[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(m=>m.trim()):[p]);let d=p.map(m=>K(r,u,a,m));o[a]={$nin:d};break;case"is null":o[a]=null;break;case"is not null":o[a]={$ne:null};break;case"_contains":Je(o,a,String(l),"contains");break;case"_starts_with":Je(o,a,String(l),"starts");break;case"_ends_with":Je(o,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(m=>m.trim())),Array.isArray(g)&&g.length===2){let m=K(r,u,a,g[0]),b=K(r,u,a,g[1]);o[a]={$gte:m,$lte:b}}break;case"_is_null":let y=l===!0||l==="true";o[a]=y?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=l===!0||l==="true";o[a]=h?{$ne:null}:{$eq:null};break}}return Qi(o),o}function vr(r,e,t){let o=r?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function tn(r,e,t,n,o,i){switch(o){case"_contains":Je(e,n,String(i),"contains");break;case"_starts_with":Je(e,n,String(i),"starts");break;case"_ends_with":Je(e,n,String(i),"ends");break;case"_eq":e[n]=K(r,t,n,i);break;case"_neq":{let c=K(r,t,n,i);vr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=i;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>K(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>K(r,t,n,c));vr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:K(r,t,n,i)};break;case"_gte":e[n]={$gte:K(r,t,n,i)};break;case"_lt":e[n]={$lt:K(r,t,n,i)};break;case"_lte":e[n]={$lte:K(r,t,n,i)};break;case"_is_null":let u=i===!0||i==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=i===!0||i==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=i;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=K(r,t,n,f[0]),p=K(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var Dn=require("mongodb");function re(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let o of n)if(re(o,e))return!0}}else if(t==="_not"){if(re(n,e))return!0}else if(e.has(t))return!0;return!1}function H(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let i=re(r,o);return{fieldFilters:t,relationFilters:n,hasRelations:i}}At();Ot();var sn="__mongoFoldTextTriples";function Ee(r,e){if(!r)return{};let t={};return Et(r,t,e),ke(t),t}function Xi(r,e){if(!r)return{};let t={};return Pn(r,t,e),ke(t),t}function ye(r,e,t){if(!e)return{};let n=new oe,{node:o}=ge(e,t,r,n);return Ee(o,{metadata:r,rootTable:t})}function an(r,e,t){if(!e)return{};let n=new oe,{node:o}=ge(e,t,r,n);return Xi(o,{metadata:r,rootTable:t})}function Et(r,e,t){switch(r.kind){case"true":return;case"false":he(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=r.children.map(i=>{let s={};return Et(i,s,t),ke(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}he(e,...o);return}case"or":{let o=r.children.map(s=>{let a={};return Et(s,a,t),ke(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;let i=e.$or;e.$or=i?[...i,...o]:o;return}case"not":{let n={};Et(r.child,n,t),ke(n);let o=e.$nor;e.$nor=o?[...o,n]:[n];return}case"compare":Or(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Or(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let o=i=>K(t.metadata,t.rootTable,n,i);switch(r.op){case"eq":Z(e,n,o(r.value));return;case"neq":{let i=o(r.value);jn(t,n)?he(e,{[n]:{$ne:null}},{[n]:{$ne:i}}):Z(e,n,{$ne:i});return}case"gt":Z(e,n,{$gt:o(r.value)});return;case"gte":Z(e,n,{$gte:o(r.value)});return;case"lt":Z(e,n,{$lt:o(r.value)});return;case"lte":Z(e,n,{$lte:o(r.value)});return;case"in":{let i=Ar(r.value).map(o);Z(e,n,{$in:i});return}case"not_in":{let i=Ar(r.value).map(o);jn(t,n)?he(e,{[n]:{$ne:null}},{[n]:{$nin:i}}):Z(e,n,{$nin:i});return}case"between":{let i=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&Z(e,n,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":Z(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":En(e,n,String(r.value),"contains");return;case"starts_with":En(e,n,String(r.value),"starts");return;case"ends_with":En(e,n,String(r.value),"ends");return}}function Pn(r,e,t){switch(r.kind){case"true":he(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let o=r.children.map(s=>{let a={};return Pn(s,a,t),ke(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}let i=e.$or;e.$or=i?[...i,...o]:o;return}case"or":{let o=r.children.map(i=>{let s={};return Pn(i,s,t),ke(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}he(e,...o);return}case"not":Et(r.child,e,t);return;case"compare":Zi(r,e,t);return;case"relation_exists":{Z(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function Zi(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){Z(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let o={};Or(r,o,t),ke(o);let i={$nor:[o]};jn(t,n)?he(e,i,{[n]:{$ne:null}}):he(e,i)}function Z(r,e,t){r[e]===void 0?r[e]=t:(he(r,{[e]:r[e]},{[e]:t}),delete r[e])}function he(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function jn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(o=>o.name===e);return n?n.isNullable!==!1:!0}function Ar(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function eo(r){return r==="_id"?"$_id":`$${r}`}function En(r,e,t,n){let o=eo(e),i=r[sn]??[];i.push({ref:o,needle:t,mode:n}),r[sn]=i}function ke(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:Zt(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}async function me(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return ye(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!re(r,i))return ye(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>me(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>me(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not)return await Bn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=H(r,o),u=[];if(s&&Object.keys(s).length>0){let l=ye(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await to(l,f,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Bn(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return an(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!re(r,i))return an(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>Bn(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$or:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>Bn(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._not)return me(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=H(r,o),u=[];if(s&&Object.keys(s).length>0){let l=an(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await ro(l,f,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function to(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?no(e,s,r,a,u,o,i):s.type==="one-to-many"?jr(e,s,t,a,u,o,i):s.type==="many-to-many"?Lr(e,s,t,a,u,o,i):{}}async function no(r,e,t,n,o,i,s){let a=V(e)||t,u=cn(r),l=un(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Kn(u);if(f!==null){let g=fn(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await ln(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{__impossible__:!0}:{[a]:{$in:d}}}async function ro(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return io(e,s,r,a,u,o,i);if(s.type==="one-to-many"){let l=await jr(e,s,t,a,u,o,i);return Pr(l)}if(s.type==="many-to-many"){let l=await Lr(e,s,t,a,u,o,i);return Pr(l)}return{}}async function io(r,e,t,n,o,i,s){let a=V(e)||t,u=cn(r),l=un(u);if(l!==null)return l?{[a]:{$ne:null}}:{[a]:null};let f=Kn(u);if(f!==null){let g=fn(f.value);if(f.op==="eq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(f.op==="neq")return{[a]:g};if(f.op==="in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]};if(f.op==="not_in")return{[a]:{$in:g}}}let c=await ln(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{[a]:null};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:d}},{[a]:{$ne:null}}]}}async function jr(r,e,t,n,o,i,s){let a=W(e)||t,u=cn(r),l=un(u);if(l!==null){let p=await Er(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await ln(u,n,o,i,s);if(!f||Object.keys(f).length===0)return{};let c=await Er(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Lr(r,e,t,n,o,i,s){let a=de(t,e);if(!a)return{};let u=cn(r),l=un(u);if(l!==null){let y=await Ln(s,a,n,null);return l?y.length===0?{}:{_id:{$nin:y}}:y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let f=Kn(u);if(f!==null){let y=fn(f.value),h=Array.isArray(y)?y:[y],m=await Ln(s,a,n,{_id:{$in:h}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let c=await ln(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await Ln(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function ln(r,e,t,n,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return re(r,i)?me(r,e,n,o):ye(n,r,e)}async function Er(r,e,t,n){let o=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let u=a[t];if(u==null)continue;let l=String(u);i.has(l)||(i.add(l),s.push(u))}return s}function Pr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function Ln(r,e,t,n){let o=null;n&&t&&(o=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(Boolean));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await r.collection(e.junctionName).find(i,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function cn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function un(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function fn(r){if(Array.isArray(r))return r.map(e=>fn(e));if(typeof r!="string")return r;try{return new Dn.ObjectId(r)}catch{return r}}function Kn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Dn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function Pt(r,e,t,n){let o=await It(r,e,t),i=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let y=Object.keys(g)[0];y&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(y)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,y]of Object.entries(s))if(typeof y=="object"&&y!==null)for(let[h,m]of Object.entries(y))tn(r,d,e,g,h,m);else d[g]=y;Object.keys(d).length>0&&i.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!o.relations.some(h=>h.propertyName===d)){let h=l.find(m=>m.propertyName===d);if(h){let m="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")m=V(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")m="_id",b=W(h)||h.propertyName;else if(h.type==="many-to-many")continue;let S=h.type==="one-to-many"||h.type==="many-to-many";f.push({propertyName:d,targetTable:h.targetTableName,localField:m,foreignField:b,type:S?"many":"one",nestedFields:[]})}}let c=[...o.relations,...f];for(let d of c){let g=a[d.propertyName],y=d.nestedFields&&d.nestedFields.length>0?await Pt(r,d.targetTable,d.nestedFields,g):g?await Pt(r,d.targetTable,["_id"],g):[];d.type==="one"&&y.length>0&&y.push({$limit:1}),i.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:y.length>0?y:void 0}}),d.type==="one"&&(i.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Ve(g)||i.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(o.scalarFields.length>0||o.relations.length>0||p.length>0){let d={_id:1};for(let y of o.scalarFields)d[y]=1;for(let y of c)d[y.propertyName]=1,y.type==="one"&&y.localField&&y.localField!==y.propertyName&&(d[y.localField]=1);if(t.includes("*"))for(let y of p){if(y.type==="one-to-many"||y.type==="many-to-many")continue;y.type==="many-to-many"?d[y.propertyName]={$map:{input:`$${y.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[y.propertyName]={$cond:{if:{$ne:[`$${y.propertyName}`,null]},then:{_id:`$${y.propertyName}`},else:null}}}i.push({$project:d})}return i}async function Br(r,e,t,n,o){let i=r?.tables?.get(t),s=i?.relations||[],a=i?.columns||[],u=s.filter(f=>!o.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&o.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of o)f[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(f[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function Ve(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ve(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ve(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ve(e));if("_not"in r)return Ve(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ve(t)))return!0}return!1}Ge();var jt=require("mongodb");Ge();dn();var Ye=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let o=n.field.split(".");if(o.length===1)t[o[0]]=n.order;else{let i=`__sort_${o.slice(0,-1).join("_")}`;t[`${i}.${o[o.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let o=n.startsWith("-");return{field:o?n.slice(1):n,order:o?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let o=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),i=[{$match:t}],s=new Set;for(let l of o){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],y=this.normalizeMetadata()?.tables?.get(p);if(!y)break;let h=y.relations?.find(S=>S.propertyName===g);if(!h)break;let m=h.targetTableName||h.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let S=V(h)||h.propertyName,_=d===0?null:`__sort_${c.slice(0,d).join("_")}`,$=_?`${_}.${S}`:S;i.push({$lookup:{from:m,localField:$,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=m}}let a=this.buildSortFromTokens(n);a&&i.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&i.push({$project:u}),i}toObjectId(e){try{return typeof e=="string"?new jt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof jt.ObjectId||t instanceof jt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(o=>!o.field.includes("."));n.length!==0&&e.sort((o,i)=>{for(let s of n){let a=this.compareSortValues(o[s.field],i[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(o._id,i._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},o=[];for(let i of this.parseSortTokens(t))i.field.includes(".")||n[i.field]===void 0&&(n[i.field]=1,o.push(i.field));return{projection:n,hiddenFields:o}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let o of t)delete n[o]}keyOf(e){return e==null?"":e instanceof jt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:o}=He(e),i={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])o.has(p.propertyName)||o.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?i[d.name]=1:t.relations?.find(y=>y.propertyName===p)&&!o.has(p)&&o.set(p,["_id"])}o.forEach((p,d)=>{let g=t.relations?.find(y=>y.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[V(g)||g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let y=g.targetTableName||g.targetTable;if(!y)return;let h,m;g.type==="many-to-one"||g.type==="one-to-one"?Ae(g)?(h="_id",m=W(g)||g.propertyName):(h=V(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(h="_id",m=W(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(h="_id",m=g.mappedBy):(h=g.propertyName,m="_id")),a.push({relationName:d,type:g.type,targetTable:y,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:h,foreignField:m})});let u=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)i[p.newName]===1&&i[p.oldName]!==1&&(i[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?ye(this.normalizeMetadata(),o.userFilter,e):null,s=this.buildSortFromTokens(o?.userSort),a=await ee(t,u=>{let l={_id:{$in:u}};i&&Object.keys(i).length>0&&Object.assign(l,i);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,o,i){let s=o.projection?{...o.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(h=>h!=null).map(h=>this.toObjectId(h)),u=i?.userFilter?ye(this.normalizeMetadata(),i.userFilter,e):null,l=i?.userLimit,f=i?.userPage,c=this.hasDottedSort(i?.userSort);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,m=await be(a,async S=>{let _={[t]:S};if(u&&Object.keys(u).length>0&&Object.assign(_,u),c){let R=this.buildSortAggregatePipeline(e,_,i.userSort);h>0&&R.push({$skip:h}),R.push({$limit:l}),s&&R.push({$project:s});let M=await this.db.collection(e).aggregate(R).toArray();return this.applyReadFallback(M,o)}let k={sort:this.buildSortFromTokens(i?.userSort)||{_id:1}};s&&(k.projection=s);let N=this.db.collection(e).find(_,k);return h>0&&N.skip(h),N.limit(l),this.applyReadFallback(await N.toArray(),o)},se),b=[];for(let[S,_]of m.entries()){let $=a.find(k=>this.keyOf(k)===S);for(let k of _)k[t]||(k[t]=$??S),b.push(k)}return{docs:b,groupKeyField:t}}if(s&&(s[t]=1),c){let h=[],m=await be(a,async b=>{let S={[t]:b};u&&Object.keys(u).length>0&&Object.assign(S,u);let _=this.buildSortAggregatePipeline(e,S,i.userSort);s&&_.push({$project:s});let $=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback($,o)},se);for(let b of m.values())for(let S of b)h.push(S);return{docs:h,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(i?.userSort)||{_id:1},g={projection:s,sort:d},y=await ee(a,h=>this.db.collection(e).find({[t]:{$in:h},...u||{}},g).toArray());return{docs:this.applyReadFallback(y,o),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,o,i){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=de(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(_=>_._id).filter(_=>_!=null),l=new Map;for(let _ of e)l.set(this.keyOf(_._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await ee(u,_=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:_}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?ye(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let _=d?(d-1)*p:0,$=await be(u,async N=>{let M=(await this.db.collection(a.junctionName).find({[a.selfColumn]:N},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(P=>P[a.otherColumn]).filter(P=>P!=null);if(M.length===0)return[];let T={_id:{$in:M}};if(c&&Object.keys(c).length>0&&Object.assign(T,c),this.hasDottedSort(t.userSort)){let P=this.buildSortAggregatePipeline(t.targetTable,T,t.userSort);_>0&&P.push({$skip:_}),P.push({$limit:p}),i.projection&&P.push({$project:i.projection});let w=await this.db.collection(t.targetTable).aggregate(P).toArray();return this.applyReadFallback(w,i)}let O={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};i.projection&&(O.projection=i.projection);let B=this.db.collection(t.targetTable).find(T,O);return _>0&&B.skip(_),B.limit(p),this.applyReadFallback(await B.toArray(),i)},se),k=[];for(let[N,R]of $.entries()){l.set(N,R);for(let M of R)k.push(M)}return{grouped:l,docs:k}}let g=new Set,y=[];for(let _ of f){let $=_[a.otherColumn];if($==null)continue;let k=this.keyOf($);g.has(k)||(g.add(k),y.push($))}let h=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1&&!c,m=[],b=new Map;if(h)m=y.map(_=>({_id:_})),this.sortDocsByPk(m);else{let _={_id:{$in:y}};c&&Object.keys(c).length>0&&Object.assign(_,c);let $=this.hasDottedSort(t.userSort),k;if($){let N=this.buildSortAggregatePipeline(t.targetTable,_,t.userSort);i.projection&&N.push({$project:i.projection}),k=await this.db.collection(t.targetTable).aggregate(N).toArray()}else{let N=this.buildSortFromTokens(t.userSort)||{_id:1},R=this.projectionWithSortFields(i.projection,t.userSort),M={sort:N};R.projection&&(M.projection=R.projection),k=await ee(y,T=>this.db.collection(t.targetTable).find({_id:{$in:T},...c||{}},M).toArray()),t.userSort?this.sortDocsInMemory(k,t.userSort):this.sortDocsByPk(k),this.removeHiddenFields(k,R.hiddenFields)}m=this.applyReadFallback(k,i)}for(let _ of m)b.set(this.keyOf(_._id),_);let S=new Map;for(let _ of f){let $=this.keyOf(_[a.selfColumn]),k=this.keyOf(_[a.otherColumn]);b.has(k)&&(S.has(k)||S.set(k,[]),S.get(k).push($))}for(let _ of m){let $=S.get(this.keyOf(_._id))||[];for(let k of $)l.get(k)?.push(_)}return{grouped:l,docs:m}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let o=new Set(t.hiddenFields??[]);for(let i of e)for(let s of n)i[s.newName]===void 0&&i[s.oldName]!==void 0&&(i[s.newName]=i[s.oldName]),(o.has(s.oldName)||i[s.newName]!==void 0)&&delete i[s.oldName];return e}};async function pn(r,e,t,n,o=3,i=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new Ye(r,a,f);await new Ce(c,n,u).execute(e,t,o,i,s)}async function Qn(r,e,t){let n=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,u=i?.tables?.get(e.table),l=new Set((u?.relations??[]).map(T=>T.propertyName)),f=!!e.mongoRawFilter&&!!i&&re(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&f){let T=await me(e.mongoRawFilter,e.table,i,o);T&&Object.keys(T).length>0&&n.push({$match:T})}else if(p){let T=Ee(c.filterTree,{metadata:i,rootTable:e.table});Object.keys(T).length>0&&n.push({$match:T})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let T=qe(i,e.where,e.table,s);n.push({$match:T})}let d=e.plan,y=d?d.hasRelationSort:e.sort?.some(T=>{if(!T.field.includes("."))return!1;let L=T.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(I=>I.propertyName===L)??!1})??!1,h=()=>d?.sortItems?fo(d.sortItems):e.sort?uo(e.sort):null,m=d?.sortItems?oo(d.sortItems):[],b=d?.sortItems?so(d.sortItems):[],S=()=>{!d||m.length===0||ao(n,e.table,d.sortItems,i)},_=()=>{!d||b.length===0||lo(n,e.table,d.sortItems,i)},$=()=>{let T=[...m,...b];T.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(T.map(L=>[L,0]))})};if(!e.mongoFieldsExpanded){S(),_();let T=h();if(T&&n.push({$sort:T}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),$(),e.select){let I={};for(let O of e.select)I[O]=1;n.push({$project:I})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let L=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:L,pipeline:n}:{results:Dr(L),pipeline:n}}let{scalarFields:k,relations:N}=e.mongoFieldsExpanded;if(!y){S(),_();let T=h();T&&n.push({$sort:T}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let R=[];for(let T of N)if(e.sort?.some(I=>I.field.startsWith(`${T.propertyName}.`))){let I=e.mongoRawFilter?.[T.propertyName];if(T.nestedFields&&T.nestedFields.length>0){let B=await Pt(i,T.targetTable,T.nestedFields??[],I);T.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName,pipeline:B.length>0?B:void 0}})}else if(I){let B=await Pt(i,T.targetTable,["_id"],I);T.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName,pipeline:B.length>0?B:void 0}})}else n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName}});T.type==="one"&&(n.push({$unwind:{path:`$${T.propertyName}`,preserveNullAndEmptyArrays:!0}}),I&&(Xe(I)||n.push({$match:{[T.propertyName]:{$ne:null}}})))}else R.push(T);if(y){S(),_();let T=h();T&&n.push({$sort:T}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}$(),await Br(i,n,e.table,k,[...N]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let M=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:M,pipeline:n};if(R.length>0&&M.length>0){let T=e.deep||{},L=R.map(O=>{let P=i?.tables?.get(e.table)?.relations?.find(x=>x.propertyName===O.propertyName),w=T[O.propertyName],F=w?.fields!=null?Array.isArray(w.fields)?w.fields:String(w.fields).split(",").map(x=>x.trim()).filter(Boolean):O.nestedFields&&O.nestedFields.length>0?O.nestedFields:["_id"];return{relationName:O.propertyName,type:P?.type,targetTable:O.targetTable,fields:F,isInverse:P?.isInverse,mappedBy:P?.mappedBy,junctionTableName:P?.junctionTableName,localField:O.localField,foreignField:O.foreignField,userFilter:w?.filter,userSort:w?.sort,userLimit:w?.limit!==void 0?Number(w.limit):void 0,userPage:w?.page!==void 0?Number(w.page):void 0,nestedDeep:w?.deep}}),I=co(i);I&&await pn(o,M,L,I,3,0,e.table,i,void 0,t.mongoPhysicalMigrationService)}return{results:Dr(M),pipeline:n}}function Jn(r){return`__sort_count_${r.relationName||r.field}`}function qn(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function oo(r){return r.filter(e=>e.function==="count").map(Jn)}function so(r){return r.filter(e=>e.function==="max"||e.function==="min").map(qn)}function ao(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=Jn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=W(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=de(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function lo(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=n?.tables?.get(l),c=f?.columns?.find(h=>h.isPrimary)?.name||(f?.columns?.some(h=>h.name==="_id")?"_id":"id"),p=s.aggregateField,d=p==="id"&&f?.columns?.some(h=>h.name==="_id")?"_id":p,g=qn(s),y=s.function==="min"?"$min":"$max";if(!(!a||!l||!p)){if(a.type==="one-to-many"){let h=W(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[y]:`$${d}`}}}],as:g}}),r.push({$addFields:{[g]:{$arrayElemAt:[`$${g}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=de(e,a);if(!h)continue;let m=`${g}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:m}}),r.push({$lookup:{from:l,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${c}`,"$$targetIds"]}}},{$group:{_id:null,value:{[y]:`$${d}`}}}],as:g}}),r.push({$addFields:{[g]:{$arrayElemAt:[`$${g}.value`,0]}}}),r.push({$project:{[m]:0}})}}}}function co(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function uo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function fo(r){let e={};for(let t of r){let n=t.function==="count"?Jn(t):t.function==="max"||t.function==="min"?qn(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Xe(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Xe(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Xe(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Xe(e));if("_not"in r)return Xe(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Xe(t)))return!0}return!1}function Dr(r){return r.map(ae)}function Kr(r,e){let t=[],n=[],o=e?.tables?.get(r.rootTable);if(!o)return{scalarFields:t,relations:n};for(let i of r.nodes)if(i.kind==="wildcard")for(let s of o.columns||[])t.includes(s.name)||t.push(s.name);else i.kind==="scalar"?o.columns?.some(a=>a.name===i.name)&&!t.includes(i.name)&&t.push(i.name):i.kind==="relation"&&n.push(po(i,o,e));return{scalarFields:t,relations:n}}function po(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),o,i,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ae(n)?(o="_id",i=W(n)||r.propertyName,s=!0):(o=n&&V(n)||r.propertyName,i="_id",s=!1):r.relationType==="one-to-many"?(o="_id",i=n&&W(n)||r.propertyName,s=!0):n?.mappedBy?(o="_id",i=n.mappedBy,s=!0):(o=r.propertyName,i="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Wr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:u}}function Wr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Wr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let o of n)e.push(`${t.propertyName}.${o}`)}return e}ze();Ot();At();function gn(r,e,t,n){let o={rootTable:e,nodes:[]};if(!r||r.length===0)return o;let i=t?.tables?.get(e);if(!i)return o;let s=i.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=i.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),y=p.substring(d+1);if(!i.relations?.some(m=>m.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(y)}else if(i.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!i.columns?.some(y=>y.name===p))continue;f.push(p)}}if(f.includes("*")){o.nodes.push({kind:"wildcard"});for(let c of i.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)o.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=i.relations?.find(h=>h.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,y={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Ur(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let h=n.registerWithParent(e,c,t,"left",null,"data");y.joinId=h}o.nodes.push(y)}return o}function Ur(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let o=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),i=n.columns?.some(f=>f.name==="id"),s=o&&!i?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Ur(c,d,t)})}return l}pe();pe();var go=new Set(["_and","_or","_not"]);function Qr(r,e){return r?.tables?.get(e)??null}function ho(r,e,t){return Qr(r,e)?.columns?.find(n=>n.name===t)}function zn(r,e,t){return Qr(r,e)?.relations?.find(n=>n.propertyName===t)}function yo(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let o=n.indexOf(".");return o<=0||o!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,o).trim(),fieldName:n.slice(o+1).trim()}}function Vn(r,e,t,n){if(ho(r,e,t)?.isEncrypted===!0)throw new v(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Pe(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Pe(n,e,t);return}for(let[n,o]of Object.entries(r)){if(go.has(n)){Pe(o,e,t);continue}if(n.startsWith("_"))continue;let i=zn(t,e,n);if(i){let s=i.targetTableName||i.targetTable;s&&Pe(o,s,t);continue}Vn(t,e,n,"filter")}}}function hn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(!i)continue;let s=yo(i);if(s){if(s.functionName==="count")continue;let l=zn(t,e,s.relationName),f=l?.targetTableName||l?.targetTable;f&&Vn(t,f,s.fieldName,"sort");continue}let a=i.split("."),u=e;for(let l=0;l<a.length;l++){let f=a[l];if(l===a.length-1){Vn(t,u,f,"sort");break}let p=zn(t,u,f);if(!p)break;u=p.targetTableName||p.targetTable||u}}}var J=class{plan(e){let{tableName:t,fields:n,filter:o,sort:i,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new oe,d=this.parseFields(n),g=null;d&&c&&(g=gn(d,t,l,p));let y=!1,h=null;if(o&&c){Pe(o,t,l);let L=ge(o,t,l,p);h=L.node,y=L.hasRelationFilters}let m=this.parseSort(i);c&&hn(m,t,l);let b=[],S=!1;for(let L of m){let I=L.startsWith("-"),O=I?L.substring(1):L,B=I?"desc":"asc";if(c){let P=this.parseRelationAggregateSort(t,c,O,l);if(P){b.push({joinId:null,field:O,direction:B,fullPath:O,function:P.functionName,relationName:P.relationName,aggregateField:P.aggregateField,relationMeta:P.relationMeta});continue}this.assertLocalSortField(t,c,O)}b.push({joinId:null,field:O,direction:B,fullPath:O})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let _=this.parseLimit(a),$=this.parsePage(s),k=$!==void 0&&_!==void 0?($-1)*_:void 0,N=this.parseMeta(u),R=N.includes("totalCount")||N.includes("*"),M=N.includes("filterCount")||N.includes("*"),T=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:o??null,joins:T,sortItems:b,limit:_,offset:k,needsTotalCount:R,needsFilterCount:M,hasRelationFilters:y,hasRelationSort:S,filterTree:h,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new v(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let o=t.columns?.some(s=>s.name===n),i=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!o&&!i)throw new v(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,o){let i=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!i){if(/^_(count|max|min)\(/.test(n))throw new v(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=i[1],a=i[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new v(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===h);if(!m)throw new v(`Sort relation '${h}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new v(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new v(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=a.slice(0,u).trim(),f=a.slice(u+1).trim();if(!l||!f)throw new v(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=t.relations?.find(h=>h.propertyName===l);if(!c)throw new v(`Sort relation '${l}' does not exist on '${e}'.`);if(c.type!=="one-to-many"&&c.type!=="many-to-many")throw new v(`Sort function '_${s}(${l}.${f})' is only supported for list relations on '${e}'.`);let p=c.targetTableName||c.targetTable,d=o?.tables?.get(p);if(!d)throw new v(`Sort function '${n}' references unknown target table '${p}' on '${e}'.`);let g=d.columns?.find(h=>h.name===f),y=f==="id"&&d.columns?.some(h=>h.name==="_id");if(!g&&!y)throw new v(`Sort field '${f}' does not exist on '${p}' for function '_${s}(${l}.${f})'.`);if(g?.isEncrypted===!0)throw new v(`Encrypted field '${f}' on '${p}' cannot be used for sort.`);return{functionName:s,relationName:l,aggregateField:f,relationMeta:c}}registerSortJoinChain(e,t,n,o,i){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=o.registerWithParent(t,a,n,"left",i,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,o,c)}};pe();Mt();var mo=new Set(["count","sum","avg","min","max","countRecords"]),bo=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),_o=new Set(["_and","_or","_not"]);function Re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function j(r,e){let t=r.replace(/^aggregate\./,"");throw new v(e,{path:r,aggregate:{[t]:e}})}function wo(r){return typeof r!="string"?!1:bo.has(r.toLowerCase())}function Jr(r){return Object.keys(r).length===0}function $o(r,e,t){return r===!0?{}:(r==null&&j(t,`aggregate.${e} condition must be true or an object`),Re(r)||j(t,`aggregate.${e} condition must be true or an object`),r)}function So(r,e,t){let n=r?.tables?.get(e);return n||j(t,`Table "${e}" metadata is not available`),n}function qr(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&j(e,"aggregate.countRecords relation target is not available"),t}function yn(r,e,t,n){let o=So(t,e,n);for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){Array.isArray(s)||j(n,`aggregate.countRecords ${i} condition must be an array`);for(let f of s)Re(f)||j(n,`aggregate.countRecords ${i} items must be objects`),yn(f,e,t,n);continue}if(i==="_not"){Re(s)||j(n,"aggregate.countRecords _not condition must be an object"),yn(s,e,t,n);continue}(i.startsWith("_")||_o.has(i))&&j(n,`Unsupported aggregate.countRecords condition key "${i}"`);let a=o.columns?.find(f=>f.name===i),u=o.relations?.find(f=>f.propertyName===i);if(!a&&!u&&j(n,`Unknown aggregate.countRecords field or relation "${i}" on table "${e}"`),Re(s)||j(n,`aggregate.countRecords condition for "${i}" must be an object`),a){for(let f of Object.keys(s))ie.has(f)||j(n,`aggregate.countRecords condition for "${i}" only supports field operators`);continue}let l=qr(u,n);yn(s,l,t,n)}}function Hn(r){return Re(r)&&Object.keys(r).length>0}function Ze(r,e,t){if(!Hn(r))return[];Re(r)||j("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||j("aggregate",`Table "${e}" metadata is not available`);let o=[];for(let[i,s]of Object.entries(r)){let a=`aggregate.${i}`;(!i||typeof i!="string")&&j("aggregate","aggregate field name must be a non-empty string"),Re(s)||j(a,"aggregate field config must be an object");let u=i,l=a,f=n.columns?.find(d=>d.name===i),c=n.relations?.find(d=>d.propertyName===i);!f&&!c&&j(l,`Unknown aggregate field or relation "${i}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&j(l,"aggregate field must define at least one operation");for(let[d,g]of p){mo.has(d)||j(l,`Unsupported aggregate operation "${d}"`);let y=$o(g,d,l);if(c&&d!=="countRecords"&&j(l,`aggregate.${d} is not supported on relation "${i}"; use countRecords`),f&&d==="countRecords"&&j(l,`aggregate.countRecords requires a relation, but "${i}" is a field`),f&&(d==="sum"||d==="avg")&&!wo(f.type)&&j(l,`aggregate.${d} requires a numeric field, but "${i}" is "${f.type}"`),f)for(let h of Object.keys(y))ie.has(h)||j(l,`aggregate.${d} condition for "${i}" only supports field operators`);if(c&&d==="countRecords"){let h=qr(c,l);yn(y,h,t,l)}o.push({field:i,outputKey:u,path:l,op:d,condition:y})}}return o}function et(r,e){let t=[];return Re(r)&&!Jr(r)&&t.push(r),Jr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function xe(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var tt=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new J;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(Q(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let o=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),i=0,s=0;(o.includes("totalCount")||o.includes("*"))&&(i=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&re(n.mongoRawFilter,u);if((o.includes("filterCount")||o.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?Ee(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(o.includes("filterCount")||o.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(o.length>0||c)&&{meta:{...o.includes("totalCount")||o.includes("*")?{totalCount:i}:{},...o.includes("filterCount")||o.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,o=this.metadata?.tables?.get(e.table),i=o?.relations&&o.relations.length>0;if(e.fields&&e.fields.length>0||n||i){let l=e.plan,f=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&l?.fieldTree){if(e.mongoFieldsExpanded=Kr(l.fieldTree,this.metadata),n){let c=await It(this.metadata,e.table,[],e.deep),p=new Set(e.mongoFieldsExpanded.relations.map(d=>d.propertyName));e.mongoFieldsExpanded.relations.push(...c.relations.filter(d=>!p.has(d.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await It(this.metadata,e.table,f,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let c=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:c.scalarFields},t=c.hiddenFields}}e.where&&(e.where=e.where.map(l=>l.field.includes(".")?l:{...l,field:`${e.table}.${l.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(ae);let{results:a,pipeline:u}=await Qn(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:o}=await Qn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,n}async executeAggregate(e,t){let n=Ze(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={},i=this.db.collection(e.table);for(let s of n){let a=et(t,s);Q(a,e.table,e.metadata);let l=new J().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);xe(o,s,p);continue}let f=l.hasRelationFilters?await me(a,e.table,e.metadata,this.db):l.filterTree?Ee(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await i.countDocuments(f);else{let[{value:p}={value:null}]=await i.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}xe(o,s,c)}return o}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(i.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[i.foreignKeyColumn]:{$in:c}}]})}if(i.type==="many-to-many"){let f=de(e.table,i);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(y=>y!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(y=>y[f.otherColumn]).filter(y=>y!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(i.type==="many-to-one"||i.type==="one-to-one"){let f=i.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};Q(t,e,n);let i=new J().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return i.hasRelationFilters?await me(t,e,n,this.db):i.filterTree?Ee(i.filterTree,{metadata:n,rootTable:e}):{}}};var mn=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&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};pe();le();var To=["_and","_or","_not"];function _e(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>_e(e));for(let e of Object.keys(r))if(To.includes(e)||typeof r[e]=="object"&&r[e]!==null&&_e(r[e]))return!0;return!1}var zr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function ko(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function bn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let o=t.columns.find(s=>s.name===n);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function Fo(r,e,t,n,o){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||bn(r,t,o),e}function Vr(r,e,t,n,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,u=ve(a,i??"postgres"),l=bn(e,o,s),f=Fo(e,n,o,i,s);switch(t){case"_eq":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",f);break;case"_neq":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",f);break;case"_gt":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",f);break;case"_gte":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",f);break;case"_lt":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",f);break;case"_lte":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",f);break;case"_in":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]),l&&i==="postgres"&&c.every(d=>typeof d=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[c]):r.whereIn(a,c);break;case"_not_in":case"_nin":let p=n;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(d=>d.trim()):[p]),l&&i==="postgres"&&p.every(d=>typeof d=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[p]):r.whereNotIn(a,p);break;case"_contains":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,ko(t),n)}}function Co(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.some(s=>s.name===n),i=t.relations?.some(s=>s.propertyName===n);return o||i}function nt(r,e,t,n="and",o,i){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){nt(this,s,t,"and",o,i)}):r.orWhere(function(){nt(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e))if(Co(s,t,i)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){nt(this,u,t,"and",o,i)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){nt(this,u,t,"and",o,i)})});continue}if(s==="_not"){r.whereNot(function(){nt(this,a,t,"and",o,i)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>zr.includes(l)))for(let[l,f]of Object.entries(a))zr.includes(l)&&(n==="and"?r.where(function(){Vr(this,s,l,f,t,o,i)}):r.orWhere(function(){Vr(this,s,l,f,t,o,i)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s,f=ve(l,o??"postgres");bn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${f} = ?::uuid`,[a]):r.orWhereRaw(`${f} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,l=ve(u,o??"postgres");bn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function ce(r,e,t,n,o){return!e||typeof e!="object"||nt(r,e,t,"and",n,o),r}le();function Xn(r,e,t){return`${C(r,t)}.${C(e,t)}`}function Ie(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Hr(r,e){if(!e)return!1;let t=e.columns.find(o=>o.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function rt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function Zn(r,e,t,n,o,i){let s=[];for(let[a,u]of Object.entries(i)){let l=await Lt(r,e,a,u,t,n,o);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Xn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=rt(d._is_null),y=rt(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(y===!0)s.push(`${c} IS NOT NULL`);else if(y===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let h=Ie(d._eq,n);s.push(`${c} = ${h}`)}else if(d._neq!==void 0){let h=Ie(d._neq,n);s.push(`${c} != ${h}`)}else if(d._in!==void 0){let m=(Array.isArray(d._in)?d._in:[d._in]).map(b=>Ie(b,n)).join(", ");s.push(`${c} IN (${m})`)}else if(d._not_in!==void 0||d._nin!==void 0){let h=d._not_in??d._nin,b=(Array.isArray(h)?h:[h]).map(S=>Ie(S,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let h=Ie(d._gt,n);s.push(`${c} > ${h}`)}else if(d._gte!==void 0){let h=Ie(d._gte,n);s.push(`${c} >= ${h}`)}else if(d._lt!==void 0){let h=Ie(d._lt,n);s.push(`${c} < ${h}`)}else if(d._lte!==void 0){let h=Ie(d._lte,n);s.push(`${c} <= ${h}`)}}}}}return s}function er(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function Gn(r,e,t,n,o,i){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(er(l)){let f=e(t).select(`${t}.id`);await je(e,f,l,t,n,o,i),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=H(l,n),p=await Zn(e,t,n,o,i,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(er(a)){let u=e(t).select(`${t}.id`);await je(e,u,a,t,n,o,i),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=H(a,n),f=await Zn(e,t,n,o,i,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Gr(r,e,t,n,o){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let i=e;Object.keys(i.fieldFilters).length===0&&i.subqueries.length===0||r.where(function(){Object.keys(i.fieldFilters).length>0&&ce(this,i.fieldFilters,t,o,n);for(let s of i.subqueries)this.whereRaw(s)})}function Yn(r,e,t,n,o){let i=!0;for(let s of e){let a=function(){for(let u of s)Gr(this,u,t,n,o)};i?(r.where(a),i=!1):r.orWhere(a)}}function _n(r,e,t,n,o,i,s){let a=Hr(e,o),u=Hr(n,i),l=`${C(r,s)}.${C(e,s)}`,f=`${C(t,s)}.${C(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Lt(r,e,t,n,o,i,s){let a=o.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(_n(u,a.foreignKeyColumn,e,"id",f,o,i));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(_n(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,i))).whereRaw(_n(a.junctionTableName,a.junctionSourceColumn,e,"id",p,o,i));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(_n(u,"id",e,a.foreignKeyColumn,f,o,i));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await je(r,c,n,u,f,i,s):c=ce(c,n,u,i,f||void 0):c=ce(c,n,u,i),c.toString()}async function je(r,e,t,n,o,i,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Gn(l._or,r,n,o,i,s);e.where(function(){Yn(this,f,n,o,i)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await je(r,e,f,n,o,i,s);else await je(r,e,l,n,o,i,s);return}if(t._or&&Array.isArray(t._or)){let l=await Gn(t._or,r,n,o,i,s);e.where(function(){Yn(this,l,n,o,i)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(er(d)){let g=r(n).select(`${n}.id`);await je(r,g,d,n,o,i,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:y}=H(d,o),h=await Zn(r,n,o,i,s,y);p.push({fieldFilters:g,subqueries:h})}e.whereNot(function(){for(let d of p)Gr(this,d,n,o,i)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Gn(l._or,r,n,o,i,s);e.whereNot(function(){Yn(this,p,n,o,i)});return}let{fieldFilters:f,relationFilters:c}=H(l,o);e.whereNot(function(){Object.keys(f).length>0&&ce(this,f,n,i,o)});for(let[p,d]of Object.entries(c)){let g=await Lt(r,n,p,d,o,i,s);if(g===null){let y=o.relations.find(h=>h.propertyName===p);if(y&&y.foreignKeyColumn){let h=Xn(n,y.foreignKeyColumn,i),b=d.id;if(b&&typeof b=="object"){let S=rt(b._is_null),_=rt(b._is_not_null);if(S===!0)e.whereRaw(`${h} IS NOT NULL`);else if(S===!1)e.whereRaw(`${h} IS NULL`);else if(_===!0)e.whereRaw(`${h} IS NULL`);else if(_===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let $=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${$.map(()=>"?").join(", ")})`,$)}else if(b._not_in!==void 0||b._nin!==void 0){let $=b._not_in??b._nin,k=Array.isArray($)?$:[$];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=H(t,o);Object.keys(a).length>0&&ce(e,a,n,i,o);for(let[l,f]of Object.entries(u)){let c=await Lt(r,n,l,f,o,i,s);if(c===null){let p=o.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Xn(n,p.foreignKeyColumn,i),y=f.id;if(y&&typeof y=="object"){let h=rt(y._is_null),m=rt(y._is_not_null);if(h===!0)e.whereRaw(`${d} IS NULL`);else if(h===!1)e.whereRaw(`${d} IS NOT NULL`);else if(m===!0)e.whereRaw(`${d} IS NOT NULL`);else if(m===!1)e.whereRaw(`${d} IS NULL`);else if(y._eq!==void 0)e.whereRaw(`${d} = ?`,[y._eq]);else if(y._neq!==void 0)e.whereRaw(`${d} != ?`,[y._neq]);else if(y._in!==void 0){let b=Array.isArray(y._in)?y._in:[y._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(y._not_in!==void 0||y._nin!==void 0){let b=y._not_in??y._nin,S=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${S.map(()=>"?").join(", ")})`,S)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Le(r,e,t,n,o,i,s){await je(r,e,t,n,o,i,s)}le();nr();ze();le();function it(r,e,t,n,o){for(let i of e){let s=i.field.split("."),a=t||s[0],u=s[s.length-1],l=Bt(n,a,u,i.value);switch(i.operator){case"=":r=r.where(i.field,"=",l);break;case"!=":r=r.where(i.field,"!=",l);break;case">":r=r.where(i.field,">",l);break;case"<":r=r.where(i.field,"<",l);break;case">=":r=r.where(i.field,">=",l);break;case"<=":r=r.where(i.field,"<=",l);break;case"like":r=r.where(i.field,"like",l);break;case"in":let f=Array.isArray(i.value)?i.value.map(y=>Bt(n,a,u,y)):[l];r=r.whereIn(i.field,f);break;case"not in":let c=Array.isArray(i.value)?i.value.map(y=>Bt(n,a,u,y)):[l];r=r.whereNotIn(i.field,c);break;case"is null":r=r.whereNull(i.field);break;case"is not null":r=r.whereNotNull(i.field);break;case"_contains":r=r.where(i.field,"like",`%${i.value}%`);break;case"_starts_with":r=r.where(i.field,"like",`${i.value}%`);break;case"_ends_with":r=r.where(i.field,"like",`%${i.value}`);break;case"_between":let p=i.value;if(typeof p=="string"&&(p=p.split(",").map(y=>y.trim())),Array.isArray(p)&&p.length===2){let y=Bt(n,a,u,p[0]),h=Bt(n,a,u,p[1]);r=r.whereBetween(i.field,[y,h])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(i.field):r.whereNotNull(i.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(i.field):r.whereNull(i.field);break}}return r}function Dt(r,e,t,n){let o=[],i=t;if(!r||typeof r!="object")return o;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let f=Dt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=Dt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Dt(a,e,t,n);u.length>0&&o.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let f=`${C(e,n)}.${C(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=i.columns?.find(y=>y.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")o.push(`${f} = ${c}`);else if(u==="_neq")o.push(`${f} != ${c}`);else if(u==="_gt")o.push(`${f} > ${c}`);else if(u==="_gte")o.push(`${f} >= ${c}`);else if(u==="_lt")o.push(`${f} < ${c}`);else if(u==="_lte")o.push(`${f} <= ${c}`);else if(u==="_is_null")o.push(`${f} IS NULL`);else if(u==="_is_not_null")o.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):o.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);o.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${C(e,n)}.${C(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),o.push(`${u} = ${l}`)}return o}function Xr(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Bt(r,e,t,n){if(n==null)return n;let o=r?.tables?.get(e);if(!o?.columns)return n;let i=o.columns.find(s=>s.name===t);if(!i)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}le();Kt();Ue();async function ei(r,e,t,n,o,i,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(ir(),Zr)),u=await a(e,t,n,o,i,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function or(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function ti(r,e,t,n,o){let i=r.targetTableName||r.targetTable;if(!i)return null;let s=r.foreignKeyColumn||z(r.propertyName);if(!s)return null;let a=c=>C(c,o),u=n?.tables?.get(i),f=(u?G(u):null)?.name||"id";return`(SELECT ${a(i)}.${a(e)} FROM ${a(i)} WHERE ${a(i)}.${a(f)} = ${a(t)}.${a(s)})`}Kt();var st=class r{constructor(e,t,n,o){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=o;this.logger=new mn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let o=e.debugTrace;if(e.filter&&Q(e.filter,e.tableName,e.metadata),!e.plan){let w=new J;e={...e,plan:w.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let i=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!u&&!a&&l){o&&o.setQueryPath("simple");let w=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),w}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(w=>w.trim())));let p=e.filter;if(e.filter&&!_e(e.filter)){c.where=[];for(let[w,F]of Object.entries(e.filter))if(typeof F=="object"&&F!==null)for(let[x,ue]of Object.entries(F)){let A;if(x==="_eq")A="=";else if(x==="_neq")A="!=";else if(x==="_in")A="in";else if(x==="_not_in"||x==="_nin")A="not in";else if(x==="_gt")A=">";else if(x==="_gte")A=">=";else if(x==="_lt")A="<";else if(x==="_lte")A="<=";else if(x==="_contains")A="_contains";else if(x==="_starts_with")A="_starts_with";else if(x==="_ends_with")A="_ends_with";else if(x==="_between")A="_between";else if(x==="_is_null")A="_is_null";else if(x==="_is_not_null")A="_is_not_null";else if(x==="_like")A="like";else if(x==="_ilike")A="ilike";else continue;c.where.push({field:w,operator:A,value:ue})}else c.where.push({field:w,operator:"=",value:F})}if(e.sort){let w=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(F=>F.trim());c.sort=w.map(F=>{let x=F.trim();return x.startsWith("-")?{field:x.substring(1),direction:"desc"}:{field:x,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,y=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=y===void 0||Number.isNaN(y)?void 0:y;h&&g!==void 0?(c.offset=(h-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let m=e.plan?.sortItems??(c.sort??[]).map(w=>({joinId:null,field:w.field,direction:w.direction,fullPath:w.field})),b=[],S=[];for(let w of m){if(w.function==="count"){let F={sql:this.buildRelationCountSortSubquery(c.table,w),direction:w.direction};S.push(F);continue}if(w.function==="max"||w.function==="min"){let F={sql:this.buildRelationAggregateSortSubquery(c.table,w),direction:w.direction};S.push(F);continue}if(w.joinId===null){if(w.field.includes(".")&&!e.plan){let x=w.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(q=>q.propertyName===x))continue}let F={field:w.field.includes(".")?w.field:`${c.table}.${w.field}`,direction:w.direction};b.push(F),S.push(F)}else{let F=e.plan?.joins.find(x=>x.id===w.joinId);if(F&&(F.relationType==="many-to-one"||F.relationType==="one-to-one")){let x=ti(F.relationMeta,w.field,c.table,this.metadata,this.dbType);if(x){let ue={sql:x,direction:w.direction};S.push(ue)}}}}let _=[];if(c.fields&&c.fields.length>0||u||a){let w=or(this.metadata),F=c.fields&&c.fields.length>0?c.fields:["*"],x=await ei(this.knex,c.table,F,w,this.dbType,this.maxQueryDepth,e.deep);x.select.length>0&&(c.select=[...c.select||[],...x.select]),_=x.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(w=>w.field.includes(".")?w:{...w,field:`${c.table}.${w.field}`})),c.sort=b;let $=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(w=>w.trim()).filter(Boolean),N=k.includes("filterCount")||k.includes("*"),R=k.includes("totalCount")||k.includes("*");if(c.select){let w=c.select.map(F=>typeof F=="string"&&F.trim().startsWith("(")?this.knex.raw(F):typeof F=="string"&&/ as /i.test(F)?this.knex.raw(F):F);$=$.select(w)}if(N&&$.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),R){let w=C(c.table,this.dbType);$.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) as __total_count__`))}let M=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(_e(p)||Object.keys(p).length>0)){let w=this.metadata?.tables?.get(c.table);(!M&&w&&w.relations&&w.relations.length>0?H(p,w).hasRelations:!1)?await Le(this.knex,$,p,c.table,w,this.dbType,x=>this.metadata?.tables?.get(x)):e.plan?.filterTree?te($,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),$=ce($,p,c.table,this.dbType,w))}else c.where&&c.where.length>0&&($=it($,c.where,c.table,this.metadata,this.dbType));for(let w of S)if(w.field){let F=w.field.includes(".")?w.field:`${c.table}.${w.field}`;$=$.orderBy(F,w.direction)}else w.sql&&($=$.orderByRaw(`${w.sql} ${w.direction.toUpperCase()}`));c.groupBy&&($=$.groupBy(c.groupBy)),c.offset&&($=$.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&($=$.limit(c.limit));let T=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:$.toSQL().toNative()});let L;if(e.debugMode&&(L=$.toSQL().toNative().sql),e.debugMode&&o){let w=$.toSQL().toNative();o.setSql(w.sql);try{let F=w.sql.replace(/\$\d+/g,"?"),x=await this.knex.raw(`EXPLAIN ${F}`,w.bindings);o.setExplain(this.dbType==="postgres"?x.rows:x[0])}catch(F){o.setExplain({error:String(F)})}}let I,O=performance.now();I=await $,o&&o.dur("db_execute",O,{table:e.tableName});let B=0;if(N&&I.length>0&&(B=Number(I[0].__filter_count__||0),I.forEach(w=>{delete w.__filter_count__})),R&&I.length>0&&I[0].__total_count__!==void 0&&(T=Number(I[0].__total_count__||0),I.forEach(w=>{delete w.__total_count__})),_&&_.length>0&&I.length>0){let w=or(this.metadata);if(w){let{executeBatchFetches:F}=await Promise.resolve().then(()=>(lr(),ni));await F(this.knex,I,_,w,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,o)}}if(this.knexService){let w=performance.now();I=await this.knexService.parseResult(I,c.table),o&&o.dur("db_parseResult",w,{table:e.tableName})}else{let w=(F,x)=>{if(!F||!this.metadata)return F;let ue=this.metadata.tables?.get(x);if(!ue)return F;if(Array.isArray(F))return F.map(q=>w(q,x));if(typeof F!="object"||Buffer.isBuffer(F))return F;let A={...F};for(let q of ue.columns)if(q.type==="simple-json"&&A[q.name]&&typeof A[q.name]=="string")try{A[q.name]=JSON.parse(A[q.name])}catch{}for(let[q,Y]of Object.entries(A))if(Y&&typeof Y=="object"&&!Array.isArray(Y)&&!Buffer.isBuffer(Y)){let Fn=Y;if(Fn.id!==void 0||Fn.createdAt!==void 0){let lt=ue.relations?.find(ct=>ct.propertyName===q);lt&&(A[q]=w(Y,lt.targetTableName))}}else if(Array.isArray(Y)&&Y.length>0&&typeof Y[0]=="object"&&Y[0].id!==void 0){let lt=ue.relations?.find(ct=>ct.propertyName===q);lt&&(A[q]=Y.map(ct=>w(ct,lt.targetTableName)))}return A};I=w(I,c.table)}o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName}));let P=await this.executeAggregate(c,p);return{data:I,...(k.length>0||P)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:T}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:B}:{},...P?{aggregate:P}:{}}},...L!==void 0&&{sql:L}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=G(s)?.name||"id",u=C(e,this.dbType),l=C(a,this.dbType);if(!n||!i)throw new v(`Sort relation '${o}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new v(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let c=C(i,this.dbType),p=C(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=this.resolveManyToManyContract(n,o,e),c=C(f.tableName,this.dbType),p=C(f.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new v(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),l=G(a)?.name||"id",f=G(u)?.name||"id",c=C(e,this.dbType),p=C(l,this.dbType),d=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!d||!n||!s||!i)throw new v(`Sort function '${t.field}' is not supported on '${e}'.`);let g=C(s,this.dbType),y=C(i,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new v(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let m=C(h,this.dbType);return`(SELECT ${d}(${g}.${y}) FROM ${g} WHERE ${g}.${m} = ${c}.${p})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,o,e),m=C(h.tableName,this.dbType),b=C(h.sourceColumn,this.dbType),S=C(h.targetColumn,this.dbType),_=C(f,this.dbType);return`(SELECT ${d}(${g}.${y}) FROM ${m} JOIN ${g} ON ${g}.${_} = ${m}.${S} WHERE ${m}.${b} = ${c}.${p})`}throw new v(`Sort function '_${t.function}(${o}.${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new v(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(n).select(o);t.filterTree&&te(i,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let m=h.field.includes(".")?h.field:`${n}.${h.field}`;i=i.orderBy(m,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=C(n,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let h=i.toSQL().toNative();if(f=h.sql,l){l.setSql(h.sql);try{let m=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,h.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){l.setExplain({error:String(m)})}}}let c=performance.now(),p;p=await i,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(h=>delete h.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(h=>delete h.__total_count__));let y=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||y)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...y?{aggregate:y}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=Ze(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={};for(let i of n){let s=et(t,i);Q(s,e.table,e.metadata);let u=new J().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(i.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,i);xe(o,i,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Le(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&te(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${C(e.table,this.dbType)}.${C(i.field,this.dbType)}`,c=i.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${i.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();xe(o,i,p?.value??0)}return o}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table),i=o?.relations?.find(c=>c.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new J().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Le(this.knex,u,t,e.table,o,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&te(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){Q(n.condition,s,e.metadata);let p=new J().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Le(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&te(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(i.type==="one-to-many")l.whereIn(`${s}.${i.foreignKeyColumn}`,u);else if(i.type==="many-to-many"){let c=this.resolveManyToManyContract(i,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(i.type==="many-to-one"||i.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${i.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${i.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var $n=require("mongodb"),at=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),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&&(0,Sn.mkdirSync)((0,ri.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!$n.ObjectId)return e;if(typeof e=="string")try{return new $n.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),o=qe(n,e,t,this.dbType);return o._id!==void 0&&(o._id=this.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,n){let o=await this.getMetadataForQuery();return{query:it(e,t,n??"",o,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.mongoService.insertOne(e.table,n);t.push(ae(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.knexService.insertWithCascade(e.table,n);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),o=performance.now(),s=new J().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",o,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb")return new tt(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new st(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(i).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);if(e.returning){let i=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(i,e.where,e.table),await i.select(e.returning)}return{affected:o.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(o).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let i=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,i)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n.count("* as count").first();return Number(o?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",i):t.id=this.normalizeWhereFilterValue("id",i):t[o]=this.normalizeWhereFilterValue(o,i);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof $n.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,o]of Object.entries(e))t[n]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[n,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.entries(o)[0];if(i){let[s,a]=i,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return ae(a)}let o=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),s=o||t.id;return await i(e).where("id",s).first()})}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let o of n)this.batchInserts.items.push({table:e,data:o});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);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 n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...n.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}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(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.mongoService.insertOne(e,o.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.knexService.insertWithCascade(e,o.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let o=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,o)),this.runBatchInsertWithIsolation(e,t.slice(o))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let o=t.get(n.table);o?o.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,o=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let i=e[n++];await t(i)}});await Promise.all(o)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,Sn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
53
+ `)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return ae(i)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let o=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:o}=await this.applyWhereToKnex(o,s,e))}let i=await o.count("* as count").first();return Number(i?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let o=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:o})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[i,s]of Object.entries(t))i==="id"||i==="_id"?o._id=this.safeObjectId(s):o[i]=s;return this.mongoService.findOne(e,o)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?o._id=this.safeObjectId(u):o[a]=u;return await this.mongoService.collection(e).find(o).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=n||t.id;return await o(e).where("id",i).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let i=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await i.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await i.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};lr();sr();ir();le();Kt();Ge();pe();ze();var ii=new Set(["fields","filter","sort","limit","page","deep"]),kn=3;function cr(r,e,t,n=0,o=3){if(!e||typeof e!="object")return;if(n>=o)throw new v(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(r),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let l=s.get(a);if(!l)throw new v(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!ii.has(p))throw new v(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...ii].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new v(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new v(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(Q(u.filter,c,t),Pe(u.filter,c,t),Tn(u.filter,0,a,r)),u.sort){hn(u.sort,c,t);let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;vo(g,c,t,a,r)}}u.deep&&cr(c,u.deep,t,n+1,o)}}}function vo(r,e,t,n,o){if(r.includes("."))throw new v(`Sort field '${r}' is not supported for relation '${n}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new v(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${o}')`);let s=i.columns?.some(u=>u.name===r),a=r==="id"&&i.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new v(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${o}')`)}var Io=new Set(["_and","_or","_not"]);function Tn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[o,i]of Object.entries(r)){if(Io.has(o)){if(Array.isArray(i))for(let l of i)Tn(l,e,t,n);else i&&typeof i=="object"&&Tn(i,e,t,n);continue}if(o.startsWith("_")||!i||typeof i!="object"||Array.isArray(i)||!Object.keys(i).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>kn)throw new v(`Filter path exceeds max dotted hops of ${kn} at '${o}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(i))l.startsWith("_")||(u[l]=i[l]);Tn(u,a,t,n)}}function oi(r,e,t,n){return!r||typeof r!="object"?r:Wt(r,e,t,n)}function Wt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let i=r.map(s=>Wt(s,e,t,n)).filter(s=>s!=null);return i.length>0?i:null}let o={};for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){let c=(Array.isArray(s)?s:[s]).map(p=>Wt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(o[i]=c);continue}if(i==="_not"){let f=Wt(s,e,t,n);f!=null&&Object.keys(f).length>0&&(o[i]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===i);if(u){if(!n(e,i,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Wt(s,f,t,n);c!=null&&Object.keys(c).length>0&&(o[i]=c);continue}if(a?.columns?.find(f=>f.name===i)){if(!n(e,i,"column"))continue;o[i]=s;continue}o[i]=s}return o}function si(r,e,t,n){if(!r)return r;let o=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,y=t?.tables?.get(c);if(!y){f=!1;break}if(g)y.columns?.find(m=>m.name===d)?n(c,d,"column")||(f=!1):y.relations?.find(b=>b.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let h=y.relations?.find(m=>m.propertyName===d);if(!h){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=h.targetTableName||h.targetTable||c}}f&&i.push(s)}if(i.length!==0)return Array.isArray(r)?i:i.join(",")}At();ze();Ot();dn();Mt();Ue();pe();function No(r){let e=new at({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,o=()=>(t||(t=new We({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),i=()=>(n||(n=new Be({isolatedExecutorService:o()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return o()},get executorEngineService(){return i()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.28",
3
+ "version": "1.1.30",
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.30",
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-error-metadata": "yarn build && node scripts/test-executor-error-metadata.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)\"",