@enfyra/kernel 1.1.38 → 1.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";var bi=Object.create;var Gt=Object.defineProperty;var _i=Object.getOwnPropertyDescriptor;var wi=Object.getOwnPropertyNames;var $i=Object.getPrototypeOf,Ti=Object.prototype.hasOwnProperty;var Q=(r,e)=>()=>(r&&(e=r(r=0)),e);var On=(r,e)=>{for(var t in e)Gt(r,t,{get:e[t],enumerable:!0})},wr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wi(e))!Ti.call(r,o)&&o!==t&&Gt(r,o,{get:()=>e[o],enumerable:!(n=_i(e,o))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?bi($i(r)):{},wr(e||!r||!r.__esModule?Gt(t,"default",{value:r,enumerable:!0}):t,r)),Si=r=>wr(Gt({},"__esModule",{value:!0}),r);function Ir(r){return Dn.createHash("md5").update(r).digest("hex").substring(0,8)}function Nr(r){return r.length<=vr-3?`${r}_pk`:`j_${Ir(r)}_pk`}function Mr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=vr?n:`j_${Ir(r)}_${t}_fk`}function Mt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Dn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function H(r){return`${r}Id`}function At(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Ar(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Er(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Or(r,e,t){return`${r}_${e}_${t}_fk`}function Pr(r,e,t){return`${r}_${e}_${t}_idx`}var Dn,vr,Je=Q(()=>{"use strict";Dn=fe(require("crypto")),vr=63});function un(r){return no[r]??null}var oe,Qn,Ot,no,Pt=Q(()=>{"use strict";oe=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Qn=new Set(["_and","_or","_not"]),Ot=[...Array.from(Qn),...Array.from(oe)],no={_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 x,ge=Q(()=>{"use strict";x=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 Dr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Wr=Q(()=>{"use strict"});function Oe(r,e,t){throw new x({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Ot.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Ot})}function dn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Dr();for(let o of Object.keys(e))if(o.startsWith("_")&&!oe.has(o)){if(n&&o==="_id")continue;Oe(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(ro.has(s)){if(Array.isArray(a))for(let c of a)J(c,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)){dn(s,a,e);let c=u.targetTableName||u.targetTable;if(c){let d=Object.keys(a).filter(l=>!l.startsWith("_"));if(d.length>0){let l={};for(let f of d)l[f]=a[f];J(l,c,t)}}}continue}s.startsWith("_")&&!o.has(s)&&s!=="_id"&&Oe(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&dn(s,a,e)}}var ro,He=Q(()=>{"use strict";ge();Pt();Wr();ro=new Set(["_and","_or","_not"])});function he(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:fn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function fn(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=io(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 io(r,e,t){if(r==="_and")return Kr("and",e,t);if(r==="_or")return Kr("or",e,t);if(r==="_not"){let c=fn(e,t);return c.node?{node:{kind:"not",child:c.node},hasRelationFilters:c.hasRelationFilters}:{node:null,hasRelationFilters:c.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),o=n?.columns?.some(c=>c.name==="_id"&&c.isPrimary),i=n?.columns?.some(c=>c.name==="id"),a=r==="id"?o&&!i?"_id":"id":r,u=n?.relations?.find(c=>c.propertyName===a);return u?oo(a,e,u,t):n&&!n.columns?.find(d=>d.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}):so(a,e,t)}function Kr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],o=!1;for(let i of e){let s=fn(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 oo(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},c=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),l=o.length>0&&o.every(p=>c.has(p))?{id:e}:e;return{node:fn(l,u).node,hasRelationFilters:!0}}function so(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:lo(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("_")&&!oe.has(s)&&Oe(s,r,t.tableName);let o=Object.entries(e).filter(([s])=>oe.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=ao(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 ao(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=un(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function lo(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 jt=Q(()=>{"use strict";Pt();He()});var se,Bt=Q(()=>{"use strict";se=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 f=this.map.get(a);return o==="inner"&&(f.joinType="inner"),f.purposes.includes(s)||f.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let c=u.relations?.find(f=>f.propertyName===t);if(!c)return null;let d=c.targetTableName||c.targetTable;if(!d)return null;let l={id:a,propertyName:t,parentTable:e,targetTable:d,relationType:c.type,parentJoinId:i,joinType:o,relationMeta:c,purposes:[s]};return this.map.set(a,l),a}}});async function K(r,e,t=ae){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(r.length<=t)return e(r);let n=[];for(let u=0;u<r.length;u+=t)n.push(r.slice(u,u+t));let o=[],i=0;async function s(){for(;i<n.length;){let u=i++;o[u]=await e(n[u])}}let a=Math.min(Xn,n.length);return await Promise.all(Array.from({length:a},s)),o.flat()}function Ye(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 je,ae,Xn,Zn,ke,Xe=Q(()=>{"use strict";ge();je=16,ae=5e3,Xn=4,Zn=10;ke=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(c=>c.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(d=>d.propertyName===s);if(!u)continue;let c=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];o.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:c,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:Zn}: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}uniqueValues(e){let t=new Set,n=[];for(let o of e){if(o==null)continue;let i=this.adapter.keyOf(o);t.has(i)||(t.add(i),n.push(o))}return n}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 x(`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 x(`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 b of e){let $=b[i];if($==null)continue;let S=this.adapter.keyOf($);s.has(S)||(s.add(S),a.push($))}if(a.length===0){for(let b of e)b[t.relationName]=null,i!==t.relationName&&delete b[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete b[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:c,nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),f=this.adapter.getTargetPkField(u);if(c){for(let b of e){let $=b[i];b[t.relationName]=$!=null?this.adapter.buildScalarRef($,f):null,i!==t.relationName&&delete b[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete b[t.fkColumn]}return}let p=performance.now(),h=await this.adapter.fetchOwner(t.targetTable,a,l,t),y=Array.isArray(h)?h:h.docs,g=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??"batch-in",roundtrips:g?.roundtrips??(Math.ceil(a.length/ae)||1),concurrencyWaves:g?.concurrencyWaves,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??y.length,rowsReturned:y.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(d,t.nestedDeep,u);m.length>0&&await this.execute(y,m,n,o+1,t.targetTable);let _=new Map;for(let b of y)_.set(this.adapter.keyOf(b[f]),b);for(let b of e){let $=b[i];b[t.relationName]=$!=null&&_.get(this.adapter.keyOf($))||null,i!==t.relationName&&delete b[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete b[t.fkColumn]}}async fetchInverseRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=this.uniqueValues(e.map(A=>A[s]));if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),c=await this.metadataGetter(t.targetTable);if(!c)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,c);let{nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),c),f=performance.now(),{docs:p,groupKeyField:h,stats:y}=await this.adapter.fetchInverse(t.targetTable,u,a,l,t),g=new Map,m=t.fields.includes(u)||t.fields.includes("*");for(let A of p){let L=A[h],T=this.adapter.keyOf(L);g.has(T)||g.set(T,[]),g.get(T).push(A)}let _=t.userLimit!==void 0&&t.userLimit>0,b=_?"per-parent-c16":"batch-in",$=_?a.length:Math.ceil(a.length/ae)||1,S=_?Math.ceil(a.length/je):void 0,k=Array.from(g.values()).reduce((A,L)=>A+L.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:y?.strategy??b,roundtrips:y?.roundtrips??$,concurrencyWaves:y?.concurrencyWaves??S,ioConcurrency:y?.ioConcurrency,rowsTransferred:y?.rowsTransferred??p.length,rowsReturned:k,rowsDiscarded:Math.max(0,(y?.rowsTransferred??p.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let A of p)this.adapter.postProcessInverseChild(A,u,m);let R=this.enrichNestedDescs(d,t.nestedDeep,c);R.length>0&&await this.execute(p,R,n,o+1,t.targetTable);let I=t.type==="one-to-one";for(let A of e){let L=this.adapter.keyOf(A[s]),T=g.get(L)||[];A[t.relationName]=I?T[0]||null:T}}async fetchM2MRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=this.uniqueValues(e.map(S=>S[s]));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:c,fetchSpec:d}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),l=performance.now(),{grouped:f,docs:p,stats:h}=await this.adapter.fetchM2M(e,t,i,u,d),y=t.userLimit!==void 0&&t.userLimit>0,g=y?"m2m-per-parent-c16":"m2m-batch",m=y?a.length:Math.ceil(a.length/ae)||1,_=y?Math.ceil(a.length/je):void 0,b=Array.from(f.values()).reduce((S,k)=>S+k.length,0);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,l,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??g,roundtrips:h?.roundtrips??m,concurrencyWaves:h?.concurrencyWaves??_,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??p.length,rowsReturned:b,rowsDiscarded:h?.rowsDiscarded??Math.max(0,(h?.rowsTransferred??p.length)-b),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let $=this.enrichNestedDescs(c,t.nestedDeep,u);$.length>0&&p.length>0&&await this.execute(p,$,n,o+1,t.targetTable);for(let S of e){let k=this.adapter.keyOf(S[s]);S[t.relationName]=f.get(k)||[]}}}});var Gr,Re,_n=Q(()=>{"use strict";Gr=2,Re=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});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 ue=Q(()=>{"use strict"});function ne(r,e,t){e&&xn(r,e,t,"and")}function xn(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(){xn(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(){xn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"not":{let o=function(){this.whereNot(function(){xn(this,e.child,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"compare":Bo(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 Bo(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=Lo(e.field,t),i=Ie(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",c=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",l=n==="or"?"orWhereNotIn":"whereNotIn",f=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",h=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[c](`${i} = ?::uuid`,[e.value]):r[u](o,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[c](`${i} != ?::uuid`,[e.value]):r[u](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[c](`${i} > ?::uuid`,[e.value]):r[u](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[c](`${i} >= ?::uuid`,[e.value]):r[u](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[c](`${i} < ?::uuid`,[e.value]):r[u](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[c](`${i} <= ?::uuid`,[e.value]):r[u](o,"<=",e.value);return;case"in":{let y=li(e.value);s&&a&&y.every(g=>typeof g=="string")?r[c](`${i} = ANY(?::uuid[])`,[y]):r[d](o,y);return}case"not_in":{let y=li(e.value);s&&a&&y.every(g=>typeof g=="string")?r[c](`${i} != ALL(?::uuid[])`,[y]):r[l](o,y);return}case"contains":dr(r,i,e.value,"contains",t,n);return;case"starts_with":dr(r,i,e.value,"starts_with",t,n);return;case"ends_with":dr(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[f](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](o):r[h](o);return}}function dr(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 Lo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function li(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var fr=Q(()=>{"use strict";ue()});function X(r){return r.columns.find(e=>e.isPrimary)||null}var qt=Q(()=>{"use strict"});var ui={};On(ui,{expandFieldsToJoinsAndSelect:()=>pr});async function pr(r,e,t,n,o,i){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let c=new Map;for(let l of e)if(l==="*"||!l.includes("."))c.has("")||c.set("",[]),c.get("").push(l);else{let f=l.split("."),p=f[0],h=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(h)}if(i&&typeof i=="object")for(let[l,f]of Object.entries(i)){if(c.has(l))continue;let p=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(h=>h.trim()).filter(Boolean):["*"];c.set(l,p)}let d=c.get("")||[];for(let l of d){if(l==="*"){let h=new Set;for(let g of u.relations||[])if(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse){let m=g.foreignKeyColumn||H(g.propertyName);m&&h.add(m)}let y=new Set;for(let g of u.columns)h.has(g.name)||(s.push(`${r}.${g.name}`),y.add(g.name));for(let g of u.relations||[])!c.has(g.propertyName)&&!y.has(g.propertyName)&&c.set(g.propertyName,["id"]);continue}if(l.includes(".")){s.push(`${r}.${l}`);continue}if(u.columns?.find(h=>h.name===l)){s.push(`${r}.${l}`);continue}if(u.relations?.find(h=>h.propertyName===l)){c.has(l)||c.set(l,["id"]);continue}}return c.forEach((l,f)=>{if(f==="")return;let p=u.relations?.find(_=>_.propertyName===f);if(!p)return;if(p.type==="many-to-one"||p.type==="one-to-one"&&!p.isInverse){let _=p.foreignKeyColumn||H(p.propertyName),b=F(r,n),$=F(_,n),S=F(f,n);s.push(`${b}.${$} as ${S}`)}let y=p.targetTableName||p.targetTable,g=i?.[f],m=g?.fields!=null?Array.isArray(g.fields)?g.fields:String(g.fields).split(",").map(_=>_.trim()).filter(Boolean):l;a.push({relationName:f,type:p.type,targetTable:y,fields:m,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter:g?.filter,userSort:g?.sort,userLimit:g?.limit!==void 0?Number(g.limit):void 0,userPage:g?.page!==void 0?Number(g.page):void 0,nestedDeep:g?.deep})}),{select:s,batchFetchDescriptors:a}}var gr=Q(()=>{"use strict";Je();ue()});var zt,Vt,vn,lt,Do,ct,yr=Q(()=>{"use strict";Je();ue();qt();Xe();_n();fr();Bt();jt();zt="__enfyra_row_number__",Vt="__sourceId__",vn="__targetId__",lt="__enfyra_partitioned__",Do=5e4,ct=class{constructor(e,t="postgres",n,o=new Re){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=o;this.pkField="id"}chunkCount(e,t=ae){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?Do:ae}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}buildPartitionRowNumber(e,t,n){let o=[...t];o.some(s=>s.column===n)||o.push({column:n,order:"asc"});let i=o.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${i}) as ??`,[e,...o.map(s=>s.column),zt])}buildPartitionSlice(e,t,n,o){return this.knex.from(e.as(lt)).select(`${lt}.*`).where(`${lt}.${zt}`,">",n).andWhere(`${lt}.${zt}`,"<=",n+o).orderBy(`${lt}.${t}`,"asc").orderBy(`${lt}.${zt}`,"asc")}removePartitionFields(e){for(let t of e)delete t[zt]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new se,o=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:i}=he(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 c=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${c}`,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 c=(a.startsWith("-")?a.slice(1):a).split(".");if(c.length<=1)continue;let d=n,l=o||n;for(let f=0;f<c.length-1;f++){let p=c[f],h=this.metadata?.tables?.get(d);if(!h)break;let y=h.relations?.find(_=>_.propertyName===p);if(!y)break;let g=y.targetTableName||y.targetTable,m=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(m)){s.add(m);let _=y.foreignKeyColumn||H(y.propertyName),b=this.metadata?.tables?.get(g),$=b&&X(b)?.name||"id";e.leftJoin(`${g} as ${m}`,`${m}.${$}`,`${l}.${_}`)}d=g,l=m}}}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 X(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=H(e.mappedBy)),t||(t=H(e.targetTable)),t}resolveParentPk(e){return e&&X(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:o}=Ye(e),i=[];if(n.includes("*")){let c=new Set;for(let d of t.relations||[])if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let l=d.foreignKeyColumn||H(d.propertyName);l&&c.add(l)}for(let d of t.columns)c.has(d.name)||i.push(d.name);for(let d of t.relations||[])o.has(d.propertyName)||o.set(d.propertyName,["id"])}else for(let c of n){let d=t.columns.find(l=>l.name===c);d?i.push(d.name):t.relations?.find(f=>f.propertyName===c)&&!o.has(c)&&o.set(c,["id"])}let s=X(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((c,d)=>{let l=t.relations?.find(f=>f.propertyName===d);if(l&&(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse)){let f=l.foreignKeyColumn||H(l.propertyName);f&&i.push(`${f} as ${d}`)}});let a=[];return o.forEach((c,d)=>{let l=t.relations?.find(p=>p.propertyName===d);if(!l)return;let f=l.targetTableName||l.targetTable;f&&a.push({relationName:d,type:l.type,targetTable:f,fields:c,isInverse:l.isInverse,fkColumn:l.foreignKeyColumn,mappedBy:l.mappedBy,junctionTableName:l.junctionTableName,junctionSourceColumn:l.junctionSourceColumn,junctionTargetColumn:l.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(c=>this.toKnexSelect(c)),u=await K(t,c=>{let d=this.knex(e).select(a).whereIn(n.pkCol,c);if(i&&ne(d,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,o.userSort,e);for(let l of s)d.orderBy(l.column,l.order)}return this.runQuery(d)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,o,i){let s=t,a=o.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let u=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,c=i?.userSort?this.parseSortTokens(i.userSort,e):[],d=i?.userLimit,l=i?.userPage;if(d!==void 0&&d>0){let h=l?(l-1)*d:0,y=o.selectCols.map(m=>this.toKnexSelect(m)),g=await K(n,async m=>{let _=this.knex(e).select(y).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${o.pkCol}`)).whereIn(`${e}.${t}`,m);u&&ne(_,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(_,i.userSort,e);let b=await this.runQuery(this.buildPartitionSlice(_,s,h,d));return this.removePartitionFields(b),b});return{docs:g,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}let f=o.selectCols.map(h=>this.toKnexSelect(h)),p=await K(n,h=>{let y=this.knex(e).select(f).whereIn(t,h);if(u&&ne(y,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(y,i?.userSort,e),c.length>0)for(let g of c)y.orderBy(g.column,g.order);else y.orderBy(o.pkCol,"asc");return this.runQuery(y)});return{docs:p,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}async selectM2MEdges(e,t,n,o,i,s,a,u){let c=`t.${s}`,d=!!a||u.some(y=>y.column!==c),l=d?u:u.map(y=>({...y,column:`${n}.${i}`})),f=t.userLimit,p=t.userPage;if(f!==void 0&&f>0){let y=p?(p-1)*f:0;return(await K(e,async m=>{let _=this.knex(n).select({[Vt]:`${n}.${o}`,[vn]:`${n}.${i}`}).whereIn(`${n}.${o}`,m);d&&(_=_.join(`${t.targetTable} as t`,`${n}.${i}`,`t.${s}`),a&&ne(_,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(_,t.userSort,t.targetTable,"t")),_.select(this.buildPartitionRowNumber(`${n}.${o}`,l,d?c:`${n}.${i}`));let b=await this.runQuery(this.buildPartitionSlice(_,Vt,y,f));return this.removePartitionFields(b),b})).map(m=>({sourceId:m[Vt],targetId:m[vn]}))}return(await K(e,y=>{let g=this.knex(n).select({[Vt]:`${n}.${o}`,[vn]:`${n}.${i}`}).whereIn(`${n}.${o}`,y);if(d&&(g=g.join(`${t.targetTable} as t`,`${n}.${i}`,`t.${s}`),a&&ne(g,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(g,t.userSort,t.targetTable,"t")),g.orderBy(`${n}.${o}`,"asc"),l.length>0){for(let m of l)g.orderBy(m.column,m.order);d&&!l.some(m=>m.column===c)&&g.orderBy(c,"asc")}else g.orderBy(`${n}.${i}`,"asc");return this.runQuery(g)})).map(y=>({sourceId:y[Vt],targetId:y[vn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let o=n.selectCols.map(i=>this.toKnexSelect(i));return K(t,i=>this.runQuery(this.knex(e).select(o).whereIn(n.pkCol,i)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,o,i){let s=this.resolveParentPk(n),a=this.uniqueValues(e.map(R=>R[s]));if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,c=t.junctionSourceColumn,d=t.junctionTargetColumn;if(!u||!c||!d)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let l=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,f=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,u,c,d,i.pkCol,l,f),h=new Map;for(let R of a)h.set(this.keyOf(R),[]);let y=i.selectCols.length===1&&i.selectCols[0]===i.pkCol,g=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),_=`t.${i.pkCol}`,b=!l&&f.every(R=>R.column===_);if(y){let R=new Map;for(let I of p){let A=this.keyOf(I.targetId);R.has(A)||R.set(A,{[i.pkCol]:I.targetId}),h.get(this.keyOf(I.sourceId))?.push(R.get(A))}return{grouped:h,docs:[],stats:{strategy:b?g?"m2m-junction-partitioned-top-k":"m2m-junction-batch":g?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let $=this.uniqueValues(p.map(R=>R.targetId)),S=await this.loadM2MTargets(t.targetTable,$,i),k=new Map(S.map(R=>[this.keyOf(R[i.pkCol]),R]));for(let R of p){let I=k.get(this.keyOf(R.targetId));I&&h.get(this.keyOf(R.sourceId))?.push(I)}return{grouped:h,docs:S,stats:{strategy:g?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+($.length>0?this.chunkCount($,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+S.length,rowsDiscarded:0}}}}});var pi={};On(pi,{executeBatchFetches:()=>mr});async function mr(r,e,t,n,o=3,i=0,s,a="postgres",u,c){let d=new ct(r,a,u);await new ke(d,n,c).execute(e,t,o,i,s)}var br=Q(()=>{"use strict";Xe();yr()});var Qo={};On(Qo,{ALL_SUPPORTED_OPERATORS:()=>Ot,AuthenticationException:()=>bt,AuthorizationException:()=>_t,BadRequestException:()=>x,BatchExecutionBudget:()=>Re,BatchFetchEngine:()=>ke,BusinessLogicException:()=>gt,CHUNKED_FETCH_CONCURRENCY:()=>Xn,ConfigurationException:()=>kt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Zn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Gr,DEFAULT_TIMEOUT_MS:()=>Yt,DOTTED_PATH_MAX_HOPS:()=>An,DatabaseException:()=>Ke,DuplicateResourceException:()=>mt,ErrorHandler:()=>Me,ExecutorEngineService:()=>We,ExternalServiceException:()=>Tt,FIELD_OPERATORS:()=>oe,FileNotFoundException:()=>Ft,FileSizeExceededException:()=>xt,FileUploadException:()=>Rt,HttpException:()=>O,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Zt,InvalidTokenException:()=>$t,IsolatedExecutorService:()=>Qe,JoinRegistry:()=>se,LOGICAL_OPERATORS:()=>Qn,MongoBatchAdapter:()=>et,MongoQueryExecutor:()=>it,PER_PARENT_CONCURRENCY:()=>je,QueryBuilderService:()=>dt,QueryPlanner:()=>q,ResourceNotFoundException:()=>yt,SchemaException:()=>Ct,ScriptContractService:()=>rn,ScriptExecutionException:()=>$e,ScriptTimeoutException:()=>we,ServiceUnavailableException:()=>St,SqlBatchAdapter:()=>ct,SqlQueryExecutor:()=>ut,TokenExpiredException:()=>wt,ValidationException:()=>ht,WHERE_IN_CHUNK_SIZE:()=>ae,WorkerPool:()=>It,appendIsolatedExecutorRuntimeLog:()=>ee,applyOperatorToMatch:()=>cn,applyRelationFilters:()=>De,applyWhereToKnex:()=>at,assertFieldOperatorValueIsClean:()=>dn,buildAggregateFilter:()=>rt,buildMongoCharFoldMapJson:()=>Kn,buildMongoFoldTextSearchJs:()=>on,buildRelationSubquery:()=>Ut,buildSqlWherePartsFromFieldAst:()=>Jt,buildWhereClause:()=>de,camelToSnake:()=>Er,chunkedFetch:()=>K,compileScriptSource:()=>Ji,computeEngineTuning:()=>jn,createEnfyraKernel:()=>Uo,dslOpToCompareOp:()=>un,encodeMainThreadToIsolate:()=>Ln,escapeSqlValue:()=>ci,executeBatchFetches:()=>mr,executeMongoBatchFetches:()=>$n,expandFieldsToJoinsAndSelect:()=>pr,getEffectiveCpuCount:()=>Pn,getEffectiveMemoryBytes:()=>vt,getEngineTuning:()=>nn,getExecutableScript:()=>Hi,getForeignKeyColumnName:()=>H,getIoAbortSignal:()=>Fr,getJunctionColumnNames:()=>At,getJunctionTableName:()=>Mt,getPrimaryKeyColumn:()=>X,getScriptLegacyField:()=>Ki,getShortFkConstraintName:()=>Mr,getShortFkName:()=>Or,getShortIndexName:()=>Pr,getShortPkName:()=>Nr,hasAggregateQuery:()=>or,hasLogicalOperators:()=>_e,isExecutableJavaScript:()=>qi,isScriptTable:()=>Ui,mergeAggregateValue:()=>ve,normalizeAggregateQuery:()=>nt,normalizeFlowStepScriptConfig:()=>Yi,normalizeScriptLanguage:()=>Qi,normalizeScriptPatch:()=>Vi,normalizeScriptRecord:()=>zi,parseBatchFields:()=>Ye,parseFields:()=>Tn,parseFilter:()=>he,perParentRun:()=>wn,quoteIdentifier:()=>F,quoteQualifiedIdentifier:()=>Ie,resolveExecutableScript:()=>Gi,rewriteFilterDenyingFields:()=>yi,rewriteSortDroppingDenied:()=>mi,runWithIoAbortSignal:()=>xr,scriptContractService:()=>re,separateFilters:()=>Y,snakeToCamel:()=>Ar,throwUnsupportedFieldOperator:()=>Oe,validateDeepOptions:()=>_r,validateFilterShape:()=>J,whereToMongoFilter:()=>Ve});module.exports=Si(Qo);var Yt=3e4,We=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,n={}){let o=e.routeData.__codeBlocks||[];return o.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(o,e.routeData.context,t??Yt,n)}async run(e,t,n=Yt,o={}){return this.isolatedExecutorService.run(e,t,n,o)}};var Xt=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 Sr=require("async_hooks"),Cr=fe(require("path")),kr=require("stream"),Rr=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}}},B=class extends Error{constructor(t,n,o,i){super(t);this.statusCode=n;this.errorCode=o;this.name=this.constructor.name,this.details=i}},O=class extends B{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},gt=class extends B{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},ht=class extends B{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},yt=class extends B{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},mt=class extends B{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},bt=class extends B{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},_t=class extends B{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},wt=class extends B{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},$t=class extends B{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Ke=class extends B{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},Tt=class extends B{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},St=class extends B{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},Ct=class extends B{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},kt=class extends B{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Rt=class extends B{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Ft=class extends B{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},xt=class extends B{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 O(n||"Error",t||500,i);case"$throw.businessLogic":return new gt(n||"Bad request",i);case"$throw.validation":return new ht(n||"Validation failed",i);case"$throw.notFound":return new yt(i?.resource||n||"Resource",i?.identifier);case"$throw.duplicate":return new mt(i?.resource||n||"Resource",i?.field||"field",i?.value||"value");case"$throw.unauthorized":return new bt(n||"Unauthorized");case"$throw.forbidden":return new _t(n||"Forbidden");case"$throw.tokenExpired":return new wt;case"$throw.invalidToken":return new $t;case"$throw.database":return new Ke(n||"Database error",i);case"$throw.dbQuery":return new Ke(n||"Query error",i);case"$throw.externalService":return new Tt(n||"Service",n||"Error",i);case"$throw.serviceUnavailable":return new St(n||"Service");case"$throw.rateLimit":return new O(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 Ct(n||"Schema error",i);case"$throw.config":return new kt(n||"Configuration error",i);case"$throw.fileUpload":return new Rt(n||"File upload error",i);case"$throw.fileNotFound":return new Ft(n||"File not found");case"$throw.fileSizeExceeded":return new xt(i?.maxSize||"unknown",i?.actualSize||"unknown");case"$throw.400":return new O(n||"Bad request",400,i);case"$throw.401":return new O(n||"Authentication required",401,i);case"$throw.403":return new O(n||"Insufficient permissions",403,i);case"$throw.404":return new O(n||"Not found",404,i);case"$throw.409":return new O(n||"Conflict",409,i);case"$throw.422":return new O(n||"Validation failed",422,i);case"$throw.429":return new O(n||"Rate limit exceeded",429,i);case"$throw.500":return new O(n||"Internal server error",500,i);case"$throw.503":return new O(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o)}if(t)switch(t){case 400:return new O(n||"Bad request",400,i);case 401:return new O(n||"Authentication required",401,i);case 403:return new O(n||"Insufficient permissions",403,i);case 404:return new O(n||"Not found",404,i);case 409:return new O(n||"Conflict",409,i);case 422:return new O(n||"Validation failed",422,i);case 429:return new O(n||"Rate limit exceeded",429,i);case 500:return new O(n||"Internal server error",500,i);case 503:return new O(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o,i)}return new $e(n||"Unknown error",o,i)}};var en=fe(require("fs")),tn=fe(require("path")),Zt=tn.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function Ci(){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 ki=Ci();function ee(r){if(ki)try{let e=tn.dirname(Zt);en.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
- `;en.appendFileSync(Zt,t)}catch{}}var Te=fe(require("os")),Ue=fe(require("fs"));function vt(){try{let r=Ue.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Te.totalmem())return e}}catch{}try{let r=Ue.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Te.totalmem())return e}catch{}return Te.totalmem()}function Pn(){let r=Te.availableParallelism?.()||Te.cpus()?.length||1;try{let e=Ue.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(Ue.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Ue.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 Ri=.25,Fi=2,xi=2048,vi=40,Ii=128,Ni=32;function jn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Ii,Math.max(vi,Math.round(t/Ni))),o=t*Ri,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<xi?1:Fi,c=Math.max(1,Math.min(u,Math.floor(o/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:c}}function nn(){return jn({logicalCpuCount:Pn(),totalMemoryBytes:vt()})}var Wi=Cr.join(__dirname,"execution/worker.js"),Bn=new Sr.AsyncLocalStorage;function Fr(){return Bn.getStore()}function xr(r,e){return Bn.run(r,e)}var It=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 c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Rr.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":t.lastError?`Worker crashed: ${t.lastError}`:"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()}),e.on("error",n=>{t.lastError=n.message}),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}},Tr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Ln(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 Qe=class r{constructor(e){this.logger=new Xt(r.name);this.effectiveMemory=vt();this.isolationTuning=nn();this.pool=new It(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Wi,()=>{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.taskCancellers=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(),c=t>.85||s>.7,d=t<.7&&s<.5,l=u>0,f=a;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,a-1))):d&&l?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==a&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${f} (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||Tr.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"||Tr.has(n)||n==="$env"||(e[n]=o));delete e.$pkgs}}spawnAndExecute(e,t,n,o,i){return(async()=>{let s=await this.pool.dispatch();if(i?.aborted){let c=new Error("Execution aborted after client disconnect");return c.code="ERR_EXECUTION_ABORTED",c.isAbort=!0,Promise.reject(c)}let a=`t_${++this.taskCounter}`,u=Date.now();return new Promise((c,d)=>{let l=!1,f=new AbortController,p=!1,h=()=>{let b=new Error("Execution aborted after client disconnect");return b.code="ERR_EXECUTION_ABORTED",b.isAbort=!0,b},y=()=>{if(!(l||p)){p=!0,f.abort(),this.cleanupResponseStream(a,h());try{s.worker.postMessage({type:"cancelTask",id:a})}catch{}}};this.taskCancellers.set(a,y);let g=()=>y(),m=()=>{i?.removeEventListener("abort",g)};i&&i.addEventListener("abort",g,{once:!0});let _=setTimeout(()=>{if(l)return;l=!0,f.abort();let b=new Error(`Script execution timed out after ${o}ms`);this.cleanupResponseStream(a,b),this.taskCancellers.delete(a),m(),this.pool.unregisterTask(s,a),this.taskTimeoutTotal++,ee({event:"task_timeout",id:a,timeoutMs:o}),this.pool.terminateEntry(s),b.code="ERR_SCRIPT_EXECUTION_TIMEOUT",b.isTimeout=!0,d(b)},o);this.pool.registerTask(s,a,{abortController:f,onResult:b=>{if(!l){if(l=!0,clearTimeout(_),this.taskCancellers.delete(a),m(),this.cleanupResponseStream(a),this.pool.unregisterTask(s,a),this.recordTaskDuration(Date.now()-u),p){f.abort(),this.taskErrorTotal++,d(h());return}if(b.success){this.taskDoneTotal++,ee({event:"task_done",id:a,ok:!0});let $={value:b.value,valueAbsent:b.valueAbsent===!0,ctxChanges:b.ctxChanges};b.shortCircuit&&($.shortCircuit=!0),c($)}else{this.taskErrorTotal++,ee({event:"task_done",id:a,ok:!1,message:b.error?.message});let $=new Error(b.error?.message||"Handler execution failed");$.statusCode=b.error?.statusCode,$.code=b.error?.code,$.details=b.error?.details,b.error?.stack&&($.stack=b.error.stack),b.ctxChanges&&($.ctxChanges=b.ctxChanges),this.cleanupResponseStream(a,$),d($)}}},onIoCall:b=>{if(l)return;let $=f.signal;b.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(b,n),s.worker,b.callId,$):b.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(b,n,s.worker),s.worker,b.callId,$):b.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(b,n),s.worker,b.callId,$):b.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(b,n),s.worker,b.callId,$):b.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(b,n),s.worker,b.callId,$):b.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(b,n,s.worker),s.worker,b.callId,$):b.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(b,n),s.worker,b.callId,$):b.type==="resCall"&&this.handleIoCall(()=>this.execResCall(b,n),s.worker,b.callId,$)}}),s.worker.postMessage({type:e,id:a,...t}),i?.aborted&&y()})})()}postAbortedCallError(e,t){try{e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})})}catch{}}async handleIoCall(e,t,n,o){if(o?.aborted){this.postAbortedCallError(t,n);return}try{let i=await(o?Bn.run(o,e):e());if(o?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:Ln(i)})}catch{}}catch(i){if(o?.aborted){this.postAbortedCallError(t,n);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=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!o||typeof o[e.method]!="function"){let i=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${i}${e.table}.${e.method}`)}return o[e.method](...n)}async execTransactionCall(e,t,n){let i=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof i!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,i)}async execHelpersCall(e,t){let 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(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),c=l=>{if(!(l?.type!=="runtimeCallbackResult"||l.callId!==i)){if(d(),l.error){a(new Error(l.error));return}s(l.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),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)}cancelTask(e){this.taskCancellers.get(e)?.()}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 kr.PassThrough,c={stream:u};this.responseStreams.set(e.id,c);let d=t?.$res;if(d&&typeof d.once=="function"){let f=()=>{d.writableEnded!==!0&&this.cancelTask(e.id)};d.once("close",f),c.closeCleanup=()=>{typeof d.off=="function"?d.off("close",f):typeof d.removeListener=="function"&&d.removeListener("close",f)}}let l=a.call(t.$res,u,s);return l&&typeof l.catch=="function"&&l.catch(()=>{}),!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 c=()=>{l(),a()},d=f=>{l(),u(f)},l=()=>{i.stream.off("drain",c),i.stream.off("error",d)};i.stream.once("drain",c),i.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let i=this.responseStreams.get(e.id);return i&&(i.closeCleanup?.(),i.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let i=this.responseStreams.get(e.id);if(i){i.closeCleanup?.();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),n.closeCleanup?.(),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);ee({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("execute",d,t,i)}catch(d){let l=d;if(ee({event:"isolated_run_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,e);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw Me.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),ee({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(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);ee({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let c;try{let l={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("executeBatch",l,t,i,o.signal)}catch(d){let l=d;if(ee({event:"isolated_batch_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.ctxChanges&&this.mergeCtxChanges(t,l.ctxChanges),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,"(batch execution)");let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw Me.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),ee({event:"isolated_batch_ok"}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.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 Ae=fe(require("typescript")),Nt={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 Ki(r){return re.getLegacyField(r)}function Ui(r){return re.isScriptTable(r)}function Qi(r){return re.normalizeLanguage(r)}var rn=class{getLegacyField(e){return Nt[e]}isScriptTable(e){return e in Nt}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,c={...t};return i&&(c.sourceCode=a??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(a,c.scriptLanguage),o&&o in c&&delete c[o],c}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(Nt).find(n=>Nt[n]in e);if(t){let n=e[Nt[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 bi=Object.create;var Gt=Object.defineProperty;var _i=Object.getOwnPropertyDescriptor;var wi=Object.getOwnPropertyNames;var $i=Object.getPrototypeOf,Ti=Object.prototype.hasOwnProperty;var Q=(r,e)=>()=>(r&&(e=r(r=0)),e);var On=(r,e)=>{for(var t in e)Gt(r,t,{get:e[t],enumerable:!0})},wr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wi(e))!Ti.call(r,o)&&o!==t&&Gt(r,o,{get:()=>e[o],enumerable:!(n=_i(e,o))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?bi($i(r)):{},wr(e||!r||!r.__esModule?Gt(t,"default",{value:r,enumerable:!0}):t,r)),Si=r=>wr(Gt({},"__esModule",{value:!0}),r);function Ir(r){return Dn.createHash("md5").update(r).digest("hex").substring(0,8)}function Nr(r){return r.length<=vr-3?`${r}_pk`:`j_${Ir(r)}_pk`}function Mr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=vr?n:`j_${Ir(r)}_${t}_fk`}function Mt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Dn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function G(r){return`${r}Id`}function Et(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Er(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Ar(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Or(r,e,t){return`${r}_${e}_${t}_fk`}function Pr(r,e,t){return`${r}_${e}_${t}_idx`}var Dn,vr,Je=Q(()=>{"use strict";Dn=fe(require("crypto")),vr=63});function un(r){return ro[r]??null}var oe,Qn,Ot,ro,Pt=Q(()=>{"use strict";oe=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Qn=new Set(["_and","_or","_not"]),Ot=[...Array.from(Qn),...Array.from(oe)],ro={_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 x,ge=Q(()=>{"use strict";x=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 Dr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Wr=Q(()=>{"use strict"});function Oe(r,e,t){throw new x({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Ot.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Ot})}function dn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Dr();for(let o of Object.keys(e))if(o.startsWith("_")&&!oe.has(o)){if(n&&o==="_id")continue;Oe(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(io.has(s)){if(Array.isArray(a))for(let c of a)J(c,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)){dn(s,a,e);let c=u.targetTableName||u.targetTable;if(c){let d=Object.keys(a).filter(l=>!l.startsWith("_"));if(d.length>0){let l={};for(let f of d)l[f]=a[f];J(l,c,t)}}}continue}s.startsWith("_")&&!o.has(s)&&s!=="_id"&&Oe(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&dn(s,a,e)}}var io,He=Q(()=>{"use strict";ge();Pt();Wr();io=new Set(["_and","_or","_not"])});function he(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:fn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function fn(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=oo(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 oo(r,e,t){if(r==="_and")return Kr("and",e,t);if(r==="_or")return Kr("or",e,t);if(r==="_not"){let c=fn(e,t);return c.node?{node:{kind:"not",child:c.node},hasRelationFilters:c.hasRelationFilters}:{node:null,hasRelationFilters:c.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),o=n?.columns?.some(c=>c.name==="_id"&&c.isPrimary),i=n?.columns?.some(c=>c.name==="id"),a=r==="id"?o&&!i?"_id":"id":r,u=n?.relations?.find(c=>c.propertyName===a);return u?so(a,e,u,t):n&&!n.columns?.find(d=>d.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}):ao(a,e,t)}function Kr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],o=!1;for(let i of e){let s=fn(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 so(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},c=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),l=o.length>0&&o.every(p=>c.has(p))?{id:e}:e;return{node:fn(l,u).node,hasRelationFilters:!0}}function ao(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:co(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("_")&&!oe.has(s)&&Oe(s,r,t.tableName);let o=Object.entries(e).filter(([s])=>oe.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=lo(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 lo(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=un(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function co(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 jt=Q(()=>{"use strict";Pt();He()});var se,Bt=Q(()=>{"use strict";se=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 f=this.map.get(a);return o==="inner"&&(f.joinType="inner"),f.purposes.includes(s)||f.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let c=u.relations?.find(f=>f.propertyName===t);if(!c)return null;let d=c.targetTableName||c.targetTable;if(!d)return null;let l={id:a,propertyName:t,parentTable:e,targetTable:d,relationType:c.type,parentJoinId:i,joinType:o,relationMeta:c,purposes:[s]};return this.map.set(a,l),a}}});async function K(r,e,t=ae){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(r.length<=t)return e(r);let n=[];for(let u=0;u<r.length;u+=t)n.push(r.slice(u,u+t));let o=[],i=0;async function s(){for(;i<n.length;){let u=i++;o[u]=await e(n[u])}}let a=Math.min(Xn,n.length);return await Promise.all(Array.from({length:a},s)),o.flat()}function Ye(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 je,ae,Xn,Zn,ke,Xe=Q(()=>{"use strict";ge();je=16,ae=5e3,Xn=4,Zn=10;ke=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(c=>c.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(d=>d.propertyName===s);if(!u)continue;let c=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];o.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:c,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:Zn}: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}uniqueValues(e){let t=new Set,n=[];for(let o of e){if(o==null)continue;let i=this.adapter.keyOf(o);t.has(i)||(t.add(i),n.push(o))}return n}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 x(`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 x(`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 w of e){let _=w[i];if(_==null)continue;let $=this.adapter.keyOf(_);s.has($)||(s.add($),a.push(_))}if(a.length===0){for(let w of e)w[t.relationName]=null,i!==t.relationName&&delete w[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[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:c,nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),f=this.adapter.getTargetPkField(u);if(c){for(let w of e){let _=w[i];w[t.relationName]=_!=null?this.adapter.buildScalarRef(_,f):null,i!==t.relationName&&delete w[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn]}return}let p=performance.now(),h=await this.adapter.fetchOwner(t.targetTable,a,l,t),y=Array.isArray(h)?h:h.docs,g=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??"batch-in",roundtrips:g?.roundtrips??(Math.ceil(a.length/ae)||1),concurrencyWaves:g?.concurrencyWaves,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??y.length,rowsReturned:y.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(d,t.nestedDeep,u);m.length>0&&await this.execute(y,m,n,o+1,t.targetTable);let b=new Map;for(let w of y)b.set(this.adapter.keyOf(w[f]),w);for(let w of e){let _=w[i];w[t.relationName]=_!=null&&b.get(this.adapter.keyOf(_))||null,i!==t.relationName&&delete w[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn]}}async fetchInverseRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=this.uniqueValues(e.map(E=>E[s]));if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),c=await this.metadataGetter(t.targetTable);if(!c)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,c);let{nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),c),f=performance.now(),{docs:p,groupKeyField:h,stats:y}=await this.adapter.fetchInverse(t.targetTable,u,a,l,t),g=new Map,m=t.fields.includes(u)||t.fields.includes("*");for(let E of p){let L=E[h],S=this.adapter.keyOf(L);g.has(S)||g.set(S,[]),g.get(S).push(E)}let b=t.userLimit!==void 0&&t.userLimit>0,w=b?"per-parent-c16":"batch-in",_=b?a.length:Math.ceil(a.length/ae)||1,$=b?Math.ceil(a.length/je):void 0,k=Array.from(g.values()).reduce((E,L)=>E+L.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:y?.strategy??w,roundtrips:y?.roundtrips??_,concurrencyWaves:y?.concurrencyWaves??$,ioConcurrency:y?.ioConcurrency,rowsTransferred:y?.rowsTransferred??p.length,rowsReturned:k,rowsDiscarded:Math.max(0,(y?.rowsTransferred??p.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let E of p)this.adapter.postProcessInverseChild(E,u,m);let R=this.enrichNestedDescs(d,t.nestedDeep,c);R.length>0&&await this.execute(p,R,n,o+1,t.targetTable);let I=t.type==="one-to-one";for(let E of e){let L=this.adapter.keyOf(E[s]),S=g.get(L)||[];E[t.relationName]=I?S[0]||null:S}}async fetchM2MRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=this.uniqueValues(e.map($=>$[s]));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:c,fetchSpec:d}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),l=performance.now(),{grouped:f,docs:p,stats:h}=await this.adapter.fetchM2M(e,t,i,u,d),y=t.userLimit!==void 0&&t.userLimit>0,g=y?"m2m-per-parent-c16":"m2m-batch",m=y?a.length:Math.ceil(a.length/ae)||1,b=y?Math.ceil(a.length/je):void 0,w=Array.from(f.values()).reduce(($,k)=>$+k.length,0);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,l,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??g,roundtrips:h?.roundtrips??m,concurrencyWaves:h?.concurrencyWaves??b,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??p.length,rowsReturned:w,rowsDiscarded:h?.rowsDiscarded??Math.max(0,(h?.rowsTransferred??p.length)-w),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let _=this.enrichNestedDescs(c,t.nestedDeep,u);_.length>0&&p.length>0&&await this.execute(p,_,n,o+1,t.targetTable);for(let $ of e){let k=this.adapter.keyOf($[s]);$[t.relationName]=f.get(k)||[]}}}});var Gr,Re,_n=Q(()=>{"use strict";Gr=2,Re=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});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 ue=Q(()=>{"use strict"});function ne(r,e,t){e&&xn(r,e,t,"and")}function xn(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(){xn(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(){xn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"not":{let o=function(){this.whereNot(function(){xn(this,e.child,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"compare":Lo(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 Lo(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=Do(e.field,t),i=Ie(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",c=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",l=n==="or"?"orWhereNotIn":"whereNotIn",f=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",h=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[c](`${i} = ?::uuid`,[e.value]):r[u](o,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[c](`${i} != ?::uuid`,[e.value]):r[u](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[c](`${i} > ?::uuid`,[e.value]):r[u](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[c](`${i} >= ?::uuid`,[e.value]):r[u](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[c](`${i} < ?::uuid`,[e.value]):r[u](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[c](`${i} <= ?::uuid`,[e.value]):r[u](o,"<=",e.value);return;case"in":{let y=li(e.value);s&&a&&y.every(g=>typeof g=="string")?r[c](`${i} = ANY(?::uuid[])`,[y]):r[d](o,y);return}case"not_in":{let y=li(e.value);s&&a&&y.every(g=>typeof g=="string")?r[c](`${i} != ALL(?::uuid[])`,[y]):r[l](o,y);return}case"contains":dr(r,i,e.value,"contains",t,n);return;case"starts_with":dr(r,i,e.value,"starts_with",t,n);return;case"ends_with":dr(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[f](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](o):r[h](o);return}}function dr(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 Do(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function li(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var fr=Q(()=>{"use strict";ue()});function Z(r){return r.columns.find(e=>e.isPrimary)||null}var qt=Q(()=>{"use strict"});var ui={};On(ui,{expandFieldsToJoinsAndSelect:()=>pr});async function pr(r,e,t,n,o,i){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let c=new Map;for(let l of e)if(l==="*"||!l.includes("."))c.has("")||c.set("",[]),c.get("").push(l);else{let f=l.split("."),p=f[0],h=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(h)}if(i&&typeof i=="object")for(let[l,f]of Object.entries(i)){if(c.has(l))continue;let p=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(h=>h.trim()).filter(Boolean):["*"];c.set(l,p)}let d=c.get("")||[];for(let l of d){if(l==="*"){let h=new Set;for(let g of u.relations||[])if(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse){let m=g.foreignKeyColumn||G(g.propertyName);m&&h.add(m)}let y=new Set;for(let g of u.columns)h.has(g.name)||(s.push(`${r}.${g.name}`),y.add(g.name));for(let g of u.relations||[])!c.has(g.propertyName)&&!y.has(g.propertyName)&&c.set(g.propertyName,["id"]);continue}if(l.includes(".")){s.push(`${r}.${l}`);continue}if(u.columns?.find(h=>h.name===l)){s.push(`${r}.${l}`);continue}if(u.relations?.find(h=>h.propertyName===l)){c.has(l)||c.set(l,["id"]);continue}}return c.forEach((l,f)=>{if(f==="")return;let p=u.relations?.find(b=>b.propertyName===f);if(!p)return;if(p.type==="many-to-one"||p.type==="one-to-one"&&!p.isInverse){let b=p.foreignKeyColumn||G(p.propertyName),w=F(r,n),_=F(b,n),$=F(f,n);s.push(`${w}.${_} as ${$}`)}let y=p.targetTableName||p.targetTable,g=i?.[f],m=g?.fields!=null?Array.isArray(g.fields)?g.fields:String(g.fields).split(",").map(b=>b.trim()).filter(Boolean):l;a.push({relationName:f,type:p.type,targetTable:y,fields:m,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter:g?.filter,userSort:g?.sort,userLimit:g?.limit!==void 0?Number(g.limit):void 0,userPage:g?.page!==void 0?Number(g.page):void 0,nestedDeep:g?.deep})}),{select:s,batchFetchDescriptors:a}}var gr=Q(()=>{"use strict";Je();ue()});var zt,Vt,vn,lt,Wo,ct,yr=Q(()=>{"use strict";Je();ue();qt();Xe();_n();fr();Bt();jt();zt="__enfyra_row_number__",Vt="__sourceId__",vn="__targetId__",lt="__enfyra_partitioned__",Wo=5e4,ct=class{constructor(e,t="postgres",n,o=new Re){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=o;this.pkField="id"}chunkCount(e,t=ae){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?Wo:ae}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}buildPartitionRowNumber(e,t,n){let o=[...t];o.some(s=>s.column===n)||o.push({column:n,order:"asc"});let i=o.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${i}) as ??`,[e,...o.map(s=>s.column),zt])}buildPartitionSlice(e,t,n,o){return this.knex.from(e.as(lt)).select(`${lt}.*`).where(`${lt}.${zt}`,">",n).andWhere(`${lt}.${zt}`,"<=",n+o).orderBy(`${lt}.${t}`,"asc").orderBy(`${lt}.${zt}`,"asc")}removePartitionFields(e){for(let t of e)delete t[zt]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new se,o=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:i}=he(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 c=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${c}`,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 c=(a.startsWith("-")?a.slice(1):a).split(".");if(c.length<=1)continue;let d=n,l=o||n;for(let f=0;f<c.length-1;f++){let p=c[f],h=this.metadata?.tables?.get(d);if(!h)break;let y=h.relations?.find(b=>b.propertyName===p);if(!y)break;let g=y.targetTableName||y.targetTable,m=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(m)){s.add(m);let b=y.foreignKeyColumn||G(y.propertyName),w=this.metadata?.tables?.get(g),_=w&&Z(w)?.name||"id";e.leftJoin(`${g} as ${m}`,`${m}.${_}`,`${l}.${b}`)}d=g,l=m}}}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 Z(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=G(e.mappedBy)),t||(t=G(e.targetTable)),t}resolveParentPk(e){return e&&Z(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:o}=Ye(e),i=[];if(n.includes("*")){let c=new Set;for(let d of t.relations||[])if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let l=d.foreignKeyColumn||G(d.propertyName);l&&c.add(l)}for(let d of t.columns)c.has(d.name)||i.push(d.name);for(let d of t.relations||[])o.has(d.propertyName)||o.set(d.propertyName,["id"])}else for(let c of n){let d=t.columns.find(l=>l.name===c);d?i.push(d.name):t.relations?.find(f=>f.propertyName===c)&&!o.has(c)&&o.set(c,["id"])}let s=Z(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((c,d)=>{let l=t.relations?.find(f=>f.propertyName===d);if(l&&(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse)){let f=l.foreignKeyColumn||G(l.propertyName);f&&i.push(`${f} as ${d}`)}});let a=[];return o.forEach((c,d)=>{let l=t.relations?.find(p=>p.propertyName===d);if(!l)return;let f=l.targetTableName||l.targetTable;f&&a.push({relationName:d,type:l.type,targetTable:f,fields:c,isInverse:l.isInverse,fkColumn:l.foreignKeyColumn,mappedBy:l.mappedBy,junctionTableName:l.junctionTableName,junctionSourceColumn:l.junctionSourceColumn,junctionTargetColumn:l.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(c=>this.toKnexSelect(c)),u=await K(t,c=>{let d=this.knex(e).select(a).whereIn(n.pkCol,c);if(i&&ne(d,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,o.userSort,e);for(let l of s)d.orderBy(l.column,l.order)}return this.runQuery(d)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,o,i){let s=t,a=o.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let u=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,c=i?.userSort?this.parseSortTokens(i.userSort,e):[],d=i?.userLimit,l=i?.userPage;if(d!==void 0&&d>0){let h=l?(l-1)*d:0,y=o.selectCols.map(m=>this.toKnexSelect(m)),g=await K(n,async m=>{let b=this.knex(e).select(y).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${o.pkCol}`)).whereIn(`${e}.${t}`,m);u&&ne(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,i.userSort,e);let w=await this.runQuery(this.buildPartitionSlice(b,s,h,d));return this.removePartitionFields(w),w});return{docs:g,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}let f=o.selectCols.map(h=>this.toKnexSelect(h)),p=await K(n,h=>{let y=this.knex(e).select(f).whereIn(t,h);if(u&&ne(y,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(y,i?.userSort,e),c.length>0)for(let g of c)y.orderBy(g.column,g.order);else y.orderBy(o.pkCol,"asc");return this.runQuery(y)});return{docs:p,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}async selectM2MEdges(e,t,n,o,i,s,a,u){let c=`t.${s}`,d=!!a||u.some(y=>y.column!==c),l=d?u:u.map(y=>({...y,column:`${n}.${i}`})),f=t.userLimit,p=t.userPage;if(f!==void 0&&f>0){let y=p?(p-1)*f:0;return(await K(e,async m=>{let b=this.knex(n).select({[Vt]:`${n}.${o}`,[vn]:`${n}.${i}`}).whereIn(`${n}.${o}`,m);d&&(b=b.join(`${t.targetTable} as t`,`${n}.${i}`,`t.${s}`),a&&ne(b,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.buildPartitionRowNumber(`${n}.${o}`,l,d?c:`${n}.${i}`));let w=await this.runQuery(this.buildPartitionSlice(b,Vt,y,f));return this.removePartitionFields(w),w})).map(m=>({sourceId:m[Vt],targetId:m[vn]}))}return(await K(e,y=>{let g=this.knex(n).select({[Vt]:`${n}.${o}`,[vn]:`${n}.${i}`}).whereIn(`${n}.${o}`,y);if(d&&(g=g.join(`${t.targetTable} as t`,`${n}.${i}`,`t.${s}`),a&&ne(g,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(g,t.userSort,t.targetTable,"t")),g.orderBy(`${n}.${o}`,"asc"),l.length>0){for(let m of l)g.orderBy(m.column,m.order);d&&!l.some(m=>m.column===c)&&g.orderBy(c,"asc")}else g.orderBy(`${n}.${i}`,"asc");return this.runQuery(g)})).map(y=>({sourceId:y[Vt],targetId:y[vn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let o=n.selectCols.map(i=>this.toKnexSelect(i));return K(t,i=>this.runQuery(this.knex(e).select(o).whereIn(n.pkCol,i)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,o,i){let s=this.resolveParentPk(n),a=this.uniqueValues(e.map(R=>R[s]));if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,c=t.junctionSourceColumn,d=t.junctionTargetColumn;if(!u||!c||!d)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let l=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,f=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,u,c,d,i.pkCol,l,f),h=new Map;for(let R of a)h.set(this.keyOf(R),[]);let y=i.selectCols.length===1&&i.selectCols[0]===i.pkCol,g=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),b=`t.${i.pkCol}`,w=!l&&f.every(R=>R.column===b);if(y){let R=new Map;for(let I of p){let E=this.keyOf(I.targetId);R.has(E)||R.set(E,{[i.pkCol]:I.targetId}),h.get(this.keyOf(I.sourceId))?.push(R.get(E))}return{grouped:h,docs:[],stats:{strategy:w?g?"m2m-junction-partitioned-top-k":"m2m-junction-batch":g?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let _=this.uniqueValues(p.map(R=>R.targetId)),$=await this.loadM2MTargets(t.targetTable,_,i),k=new Map($.map(R=>[this.keyOf(R[i.pkCol]),R]));for(let R of p){let I=k.get(this.keyOf(R.targetId));I&&h.get(this.keyOf(R.sourceId))?.push(I)}return{grouped:h,docs:$,stats:{strategy:g?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+(_.length>0?this.chunkCount(_,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+$.length,rowsDiscarded:0}}}}});var pi={};On(pi,{executeBatchFetches:()=>mr});async function mr(r,e,t,n,o=3,i=0,s,a="postgres",u,c){let d=new ct(r,a,u);await new ke(d,n,c).execute(e,t,o,i,s)}var br=Q(()=>{"use strict";Xe();yr()});var Jo={};On(Jo,{ALL_SUPPORTED_OPERATORS:()=>Ot,AuthenticationException:()=>bt,AuthorizationException:()=>_t,BadRequestException:()=>x,BatchExecutionBudget:()=>Re,BatchFetchEngine:()=>ke,BusinessLogicException:()=>gt,CHUNKED_FETCH_CONCURRENCY:()=>Xn,ConfigurationException:()=>kt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Zn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Gr,DEFAULT_TIMEOUT_MS:()=>Yt,DOTTED_PATH_MAX_HOPS:()=>En,DatabaseException:()=>Ke,DuplicateResourceException:()=>mt,ErrorHandler:()=>Me,ExecutorEngineService:()=>We,ExternalServiceException:()=>Tt,FIELD_OPERATORS:()=>oe,FileNotFoundException:()=>Ft,FileSizeExceededException:()=>xt,FileUploadException:()=>Rt,HttpException:()=>O,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Zt,InvalidTokenException:()=>$t,IsolatedExecutorService:()=>Qe,JoinRegistry:()=>se,LOGICAL_OPERATORS:()=>Qn,MongoBatchAdapter:()=>et,MongoQueryExecutor:()=>it,PER_PARENT_CONCURRENCY:()=>je,QueryBuilderService:()=>dt,QueryPlanner:()=>q,ResourceNotFoundException:()=>yt,SchemaException:()=>Ct,ScriptContractService:()=>rn,ScriptExecutionException:()=>$e,ScriptTimeoutException:()=>we,ServiceUnavailableException:()=>St,SqlBatchAdapter:()=>ct,SqlQueryExecutor:()=>ut,TokenExpiredException:()=>wt,ValidationException:()=>ht,WHERE_IN_CHUNK_SIZE:()=>ae,WorkerPool:()=>It,appendIsolatedExecutorRuntimeLog:()=>H,applyOperatorToMatch:()=>cn,applyRelationFilters:()=>De,applyWhereToKnex:()=>at,assertFieldOperatorValueIsClean:()=>dn,buildAggregateFilter:()=>rt,buildMongoCharFoldMapJson:()=>Kn,buildMongoFoldTextSearchJs:()=>on,buildRelationSubquery:()=>Ut,buildSqlWherePartsFromFieldAst:()=>Jt,buildWhereClause:()=>de,camelToSnake:()=>Ar,chunkedFetch:()=>K,compileScriptSource:()=>qi,computeEngineTuning:()=>jn,createEnfyraKernel:()=>Qo,dslOpToCompareOp:()=>un,encodeMainThreadToIsolate:()=>Ln,escapeSqlValue:()=>ci,executeBatchFetches:()=>mr,executeMongoBatchFetches:()=>$n,expandFieldsToJoinsAndSelect:()=>pr,getEffectiveCpuCount:()=>Pn,getEffectiveMemoryBytes:()=>vt,getEngineTuning:()=>nn,getExecutableScript:()=>Gi,getForeignKeyColumnName:()=>G,getIoAbortSignal:()=>Fr,getJunctionColumnNames:()=>Et,getJunctionTableName:()=>Mt,getPrimaryKeyColumn:()=>Z,getScriptLegacyField:()=>Ui,getShortFkConstraintName:()=>Mr,getShortFkName:()=>Or,getShortIndexName:()=>Pr,getShortPkName:()=>Nr,hasAggregateQuery:()=>or,hasLogicalOperators:()=>_e,isExecutableJavaScript:()=>zi,isScriptTable:()=>Qi,mergeAggregateValue:()=>ve,normalizeAggregateQuery:()=>nt,normalizeFlowStepScriptConfig:()=>Xi,normalizeScriptLanguage:()=>Ji,normalizeScriptPatch:()=>Hi,normalizeScriptRecord:()=>Vi,parseBatchFields:()=>Ye,parseFields:()=>Tn,parseFilter:()=>he,perParentRun:()=>wn,quoteIdentifier:()=>F,quoteQualifiedIdentifier:()=>Ie,resolveExecutableScript:()=>Yi,rewriteFilterDenyingFields:()=>yi,rewriteSortDroppingDenied:()=>mi,runWithIoAbortSignal:()=>xr,scriptContractService:()=>re,separateFilters:()=>X,snakeToCamel:()=>Er,throwUnsupportedFieldOperator:()=>Oe,validateDeepOptions:()=>_r,validateFilterShape:()=>J,whereToMongoFilter:()=>Ve});module.exports=Si(Jo);var Yt=3e4,We=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,n={}){let o=e.routeData.__codeBlocks||[];return o.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(o,e.routeData.context,t??Yt,n)}async run(e,t,n=Yt,o={}){return this.isolatedExecutorService.run(e,t,n,o)}};var Xt=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 Sr=require("async_hooks"),Cr=fe(require("path")),kr=require("stream"),Rr=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}}},B=class extends Error{constructor(t,n,o,i){super(t);this.statusCode=n;this.errorCode=o;this.name=this.constructor.name,this.details=i}},O=class extends B{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},gt=class extends B{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},ht=class extends B{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},yt=class extends B{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},mt=class extends B{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},bt=class extends B{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},_t=class extends B{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},wt=class extends B{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},$t=class extends B{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Ke=class extends B{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},Tt=class extends B{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},St=class extends B{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},Ct=class extends B{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},kt=class extends B{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Rt=class extends B{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Ft=class extends B{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},xt=class extends B{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 O(n||"Error",t||500,i);case"$throw.businessLogic":return new gt(n||"Bad request",i);case"$throw.validation":return new ht(n||"Validation failed",i);case"$throw.notFound":return new yt(i?.resource||n||"Resource",i?.identifier);case"$throw.duplicate":return new mt(i?.resource||n||"Resource",i?.field||"field",i?.value||"value");case"$throw.unauthorized":return new bt(n||"Unauthorized");case"$throw.forbidden":return new _t(n||"Forbidden");case"$throw.tokenExpired":return new wt;case"$throw.invalidToken":return new $t;case"$throw.database":return new Ke(n||"Database error",i);case"$throw.dbQuery":return new Ke(n||"Query error",i);case"$throw.externalService":return new Tt(n||"Service",n||"Error",i);case"$throw.serviceUnavailable":return new St(n||"Service");case"$throw.rateLimit":return new O(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 Ct(n||"Schema error",i);case"$throw.config":return new kt(n||"Configuration error",i);case"$throw.fileUpload":return new Rt(n||"File upload error",i);case"$throw.fileNotFound":return new Ft(n||"File not found");case"$throw.fileSizeExceeded":return new xt(i?.maxSize||"unknown",i?.actualSize||"unknown");case"$throw.400":return new O(n||"Bad request",400,i);case"$throw.401":return new O(n||"Authentication required",401,i);case"$throw.403":return new O(n||"Insufficient permissions",403,i);case"$throw.404":return new O(n||"Not found",404,i);case"$throw.409":return new O(n||"Conflict",409,i);case"$throw.422":return new O(n||"Validation failed",422,i);case"$throw.429":return new O(n||"Rate limit exceeded",429,i);case"$throw.500":return new O(n||"Internal server error",500,i);case"$throw.503":return new O(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o)}if(t)switch(t){case 400:return new O(n||"Bad request",400,i);case 401:return new O(n||"Authentication required",401,i);case 403:return new O(n||"Insufficient permissions",403,i);case 404:return new O(n||"Not found",404,i);case 409:return new O(n||"Conflict",409,i);case 422:return new O(n||"Validation failed",422,i);case 429:return new O(n||"Rate limit exceeded",429,i);case 500:return new O(n||"Internal server error",500,i);case 503:return new O(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o,i)}return new $e(n||"Unknown error",o,i)}};var en=fe(require("fs")),tn=fe(require("path")),Zt=tn.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function Ci(){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 ki=Ci();function H(r){if(ki)try{let e=tn.dirname(Zt);en.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
+ `;en.appendFileSync(Zt,t)}catch{}}var Te=fe(require("os")),Ue=fe(require("fs"));function vt(){try{let r=Ue.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Te.totalmem())return e}}catch{}try{let r=Ue.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Te.totalmem())return e}catch{}return Te.totalmem()}function Pn(){let r=Te.availableParallelism?.()||Te.cpus()?.length||1;try{let e=Ue.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(Ue.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Ue.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 Ri=.25,Fi=2,xi=2048,vi=40,Ii=128,Ni=32;function jn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Ii,Math.max(vi,Math.round(t/Ni))),o=t*Ri,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<xi?1:Fi,c=Math.max(1,Math.min(u,Math.floor(o/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:c}}function nn(){return jn({logicalCpuCount:Pn(),totalMemoryBytes:vt()})}var Wi=Cr.join(__dirname,"execution/worker.js"),Ki=1e4,Bn=new Sr.AsyncLocalStorage;function Fr(){return Bn.getStore()}function xr(r,e){return Bn.run(r,e)}var It=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 c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Rr.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":t.lastError?`Worker crashed: ${t.lastError}`:"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()}),e.on("error",n=>{t.lastError=n.message}),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}},Tr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Ln(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 Qe=class r{constructor(e){this.logger=new Xt(r.name);this.effectiveMemory=vt();this.isolationTuning=nn();this.pool=new It(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Wi,()=>{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.taskCancellers=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(),c=t>.85||s>.7,d=t<.7&&s<.5,l=u>0,f=a;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,a-1))):d&&l?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==a&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${f} (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||Tr.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"||Tr.has(n)||n==="$env"||(e[n]=o));delete e.$pkgs}}spawnAndExecute(e,t,n,o,i){return(async()=>{let s=await this.pool.dispatch();if(i?.aborted){let c=new Error("Execution aborted after client disconnect");return c.code="ERR_EXECUTION_ABORTED",c.isAbort=!0,Promise.reject(c)}let a=`t_${++this.taskCounter}`,u=Date.now();return new Promise((c,d)=>{let l=!1,f=new AbortController,p=!1,h=()=>{let _=new Error("Execution aborted after client disconnect");return _.code="ERR_EXECUTION_ABORTED",_.isAbort=!0,_},y,g=()=>{if(!(l||p)){p=!0,f.abort(),this.cleanupResponseStream(a,h());try{s.worker.postMessage({type:"cancelTask",id:a})}catch{}y=setTimeout(()=>{l||(l=!0,clearTimeout(w),b(),this.taskCancellers.delete(a),this.pool.unregisterTask(s,a),this.taskErrorTotal++,H({event:"task_cancel_grace_terminate",id:a}),this.pool.terminateEntry(s),d(h()))},Ki),y.unref?.()}};this.taskCancellers.set(a,g);let m=()=>g(),b=()=>{i?.removeEventListener("abort",m)};i&&i.addEventListener("abort",m,{once:!0});let w=setTimeout(()=>{if(l)return;l=!0,y&&clearTimeout(y),f.abort();let _=new Error(`Script execution timed out after ${o}ms`);this.cleanupResponseStream(a,_),this.taskCancellers.delete(a),b(),this.pool.unregisterTask(s,a),this.taskTimeoutTotal++,H({event:"task_timeout",id:a,timeoutMs:o}),this.pool.terminateEntry(s),_.code="ERR_SCRIPT_EXECUTION_TIMEOUT",_.isTimeout=!0,d(_)},o);this.pool.registerTask(s,a,{abortController:f,onResult:_=>{if(!l){if(l=!0,clearTimeout(w),y&&clearTimeout(y),this.taskCancellers.delete(a),b(),this.cleanupResponseStream(a),this.pool.unregisterTask(s,a),this.recordTaskDuration(Date.now()-u),p){f.abort(),this.taskErrorTotal++,d(h());return}if(_.success){this.taskDoneTotal++,H({event:"task_done",id:a,ok:!0});let $={value:_.value,valueAbsent:_.valueAbsent===!0,ctxChanges:_.ctxChanges};_.shortCircuit&&($.shortCircuit=!0),c($)}else{this.taskErrorTotal++,H({event:"task_done",id:a,ok:!1,message:_.error?.message});let $=new Error(_.error?.message||"Handler execution failed");$.statusCode=_.error?.statusCode,$.code=_.error?.code,$.details=_.error?.details,_.error?.stack&&($.stack=_.error.stack),_.ctxChanges&&($.ctxChanges=_.ctxChanges),this.cleanupResponseStream(a,$),d($)}}},onIoCall:_=>{if(l)return;let $=f.signal;_.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(_,n),s.worker,_.callId,$):_.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(_,n,s.worker),s.worker,_.callId,$):_.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(_,n),s.worker,_.callId,$):_.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(_,n),s.worker,_.callId,$):_.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(_,n),s.worker,_.callId,$):_.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(_,n,s.worker),s.worker,_.callId,$):_.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(_,n),s.worker,_.callId,$):_.type==="resCall"&&this.handleIoCall(()=>this.execResCall(_,n),s.worker,_.callId,$)}}),s.worker.postMessage({type:e,id:a,...t}),i?.aborted&&g()})})()}postAbortedCallError(e,t){try{e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})})}catch{}}async handleIoCall(e,t,n,o){if(o?.aborted){this.postAbortedCallError(t,n);return}try{let i=await(o?Bn.run(o,e):e());if(o?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:Ln(i)})}catch{}}catch(i){if(o?.aborted){this.postAbortedCallError(t,n);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=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!o||typeof o[e.method]!="function"){let i=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${i}${e.table}.${e.method}`)}return o[e.method](...n)}async execTransactionCall(e,t,n){let i=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof i!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,i)}async execHelpersCall(e,t){let 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(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),c=l=>{if(!(l?.type!=="runtimeCallbackResult"||l.callId!==i)){if(d(),l.error){a(new Error(l.error));return}s(l.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),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)}cancelTask(e){this.taskCancellers.get(e)?.()}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 kr.PassThrough,c={stream:u};this.responseStreams.set(e.id,c);let d=t?.$res;if(d&&typeof d.once=="function"){let f=()=>{d.writableEnded!==!0&&this.cancelTask(e.id)};d.once("close",f),c.closeCleanup=()=>{typeof d.off=="function"?d.off("close",f):typeof d.removeListener=="function"&&d.removeListener("close",f)}}let l=a.call(t.$res,u,s);return l&&typeof l.catch=="function"&&l.catch(()=>{}),!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 c=()=>{l(),a()},d=f=>{l(),u(f)},l=()=>{i.stream.off("drain",c),i.stream.off("error",d)};i.stream.once("drain",c),i.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let i=this.responseStreams.get(e.id);return i&&(i.closeCleanup?.(),i.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let i=this.responseStreams.get(e.id);if(i){i.closeCleanup?.();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),n.closeCleanup?.(),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);H({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("execute",d,t,i)}catch(d){let l=d;if(H({event:"isolated_run_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,e);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw Me.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),H({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(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);H({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let c;try{let l={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("executeBatch",l,t,i,o.signal)}catch(d){let l=d;if(H({event:"isolated_batch_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.ctxChanges&&this.mergeCtxChanges(t,l.ctxChanges),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,"(batch execution)");let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw Me.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),H({event:"isolated_batch_ok"}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.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 Ee=fe(require("typescript")),Nt={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 Ui(r){return re.getLegacyField(r)}function Qi(r){return re.isScriptTable(r)}function Ji(r){return re.normalizeLanguage(r)}var rn=class{getLegacyField(e){return Nt[e]}isScriptTable(e){return e in Nt}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,c={...t};return i&&(c.sourceCode=a??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(a,c.scriptLanguage),o&&o in c&&delete c[o],c}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(Nt).find(n=>Nt[n]in e);if(t){let n=e[Nt[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=Ee.default.transpileModule(e,{compilerOptions:{target:Ee.default.ScriptTarget.ES2022,module:Ee.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ee.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(o=>o.category===Ee.default.DiagnosticCategory.Error);if(n)throw new Error(Ee.default.flattenDiagnosticMessageText(n.messageText,`
3
3
  `));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
4
4
  "use strict";
5
5
  ${e}
6
- });`)}},re=new rn;function Ji(r,e){return re.compileSource(r,e)}function qi(r){return re.isExecutableJavaScript(r)}function zi(r,e){return re.normalizeRecord(r,e)}function Vi(r,e,t){return re.normalizePatch(r,e,t)}function Hi(r){return re.getExecutableScript(r)}function Gi(r){return re.resolveExecutableScript(r)}function Yi(r){return re.normalizeFlowStepScriptConfig(r)}var Nn=require("node:fs"),gi=require("node:path");var Wn=require("mongodb");Je();function Ee(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function G(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ee(r)&&(r.foreignKeyColumn||r.propertyName)||null}function U(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ce(r){if(!r||typeof r!="object")return r;if(r instanceof Wn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ce(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 Wn.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)?ce(n):n;return e}function pe(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,c=r,d=e.junctionTableName||Mt(a,u,c);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:c};let l=At(a,u,c);return{junctionName:d,selfColumn:l.targetColumn,otherColumn:l.sourceColumn,owningTable:a,inverseTable:c}}let n=r,o=t,i=e.junctionTableName||Mt(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=At(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function Et(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 c of t)if(c==="*")i.has("")||i.set("",[]),i.get("").push(c);else if(c.includes(".")){let d=c.split("."),l=d[0],f=d.slice(1).join(".");i.has(l)||i.set(l,[]),i.get(l).push(f)}else o.relations?.some(l=>l.propertyName===c)?i.has(c)||i.set(c,["_id"]):(i.has("")||i.set("",[]),i.get("").push(c));if(n&&typeof n=="object")for(let[c,d]of Object.entries(n)){if(i.has(c))continue;let l=d&&typeof d=="object"&&d.fields!=null?Array.isArray(d.fields)?d.fields:String(d.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];i.set(c,l)}let s=[],a=[],u=i.get("")||[];for(let c of u)if(c==="*"){if(o.columns)for(let d of o.columns)s.includes(d.name)||s.push(d.name);if(o.relations)for(let d of o.relations)i.has(d.propertyName)||i.set(d.propertyName,["_id"])}else o.columns?.some(l=>l.name===c)&&!s.includes(c)&&s.push(c);for(let[c,d]of i.entries()){if(c==="")continue;let l=o.relations?.find(g=>g.propertyName===c);if(!l)continue;let f="",p="",h=!1;l.type==="many-to-one"||l.type==="one-to-one"?Ee(l)?(f="_id",p=U(l)||l.propertyName,h=!0):(f=G(l)||l.propertyName,p="_id",h=!1):l.type==="one-to-many"?(f="_id",p=U(l)||l.propertyName,h=!0):l.type==="many-to-many"&&(l.mappedBy?(f="_id",p=l.mappedBy,h=!0):(f=l.propertyName,p="_id",h=!1));let y=l.type==="one-to-many"||l.type==="many-to-many";a.push({propertyName:c,targetTable:l.targetTableName,localField:f,foreignField:p,type:y?"many":"one",isInverse:h,nestedFields:d})}return{scalarFields:s,relations:a}}var sn=fe(require("fs")),Un=fe(require("path"));var Xi=new RegExp("\\p{Mark}","gu");function jr(r){return r==null?"":String(r).normalize("NFKD").replace(Xi,"").toLowerCase()}function Kn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=jr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function on(){return`function() {
6
+ });`)}},re=new rn;function qi(r,e){return re.compileSource(r,e)}function zi(r){return re.isExecutableJavaScript(r)}function Vi(r,e){return re.normalizeRecord(r,e)}function Hi(r,e,t){return re.normalizePatch(r,e,t)}function Gi(r){return re.getExecutableScript(r)}function Yi(r){return re.resolveExecutableScript(r)}function Xi(r){return re.normalizeFlowStepScriptConfig(r)}var Nn=require("node:fs"),gi=require("node:path");var Wn=require("mongodb");Je();function Ae(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function Y(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ae(r)&&(r.foreignKeyColumn||r.propertyName)||null}function U(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ce(r){if(!r||typeof r!="object")return r;if(r instanceof Wn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ce(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 Wn.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)?ce(n):n;return e}function pe(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,c=r,d=e.junctionTableName||Mt(a,u,c);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:c};let l=Et(a,u,c);return{junctionName:d,selfColumn:l.targetColumn,otherColumn:l.sourceColumn,owningTable:a,inverseTable:c}}let n=r,o=t,i=e.junctionTableName||Mt(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=Et(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function At(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 c of t)if(c==="*")i.has("")||i.set("",[]),i.get("").push(c);else if(c.includes(".")){let d=c.split("."),l=d[0],f=d.slice(1).join(".");i.has(l)||i.set(l,[]),i.get(l).push(f)}else o.relations?.some(l=>l.propertyName===c)?i.has(c)||i.set(c,["_id"]):(i.has("")||i.set("",[]),i.get("").push(c));if(n&&typeof n=="object")for(let[c,d]of Object.entries(n)){if(i.has(c))continue;let l=d&&typeof d=="object"&&d.fields!=null?Array.isArray(d.fields)?d.fields:String(d.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];i.set(c,l)}let s=[],a=[],u=i.get("")||[];for(let c of u)if(c==="*"){if(o.columns)for(let d of o.columns)s.includes(d.name)||s.push(d.name);if(o.relations)for(let d of o.relations)i.has(d.propertyName)||i.set(d.propertyName,["_id"])}else o.columns?.some(l=>l.name===c)&&!s.includes(c)&&s.push(c);for(let[c,d]of i.entries()){if(c==="")continue;let l=o.relations?.find(g=>g.propertyName===c);if(!l)continue;let f="",p="",h=!1;l.type==="many-to-one"||l.type==="one-to-one"?Ae(l)?(f="_id",p=U(l)||l.propertyName,h=!0):(f=Y(l)||l.propertyName,p="_id",h=!1):l.type==="one-to-many"?(f="_id",p=U(l)||l.propertyName,h=!0):l.type==="many-to-many"&&(l.mappedBy?(f="_id",p=l.mappedBy,h=!0):(f=l.propertyName,p="_id",h=!1));let y=l.type==="one-to-many"||l.type==="many-to-many";a.push({propertyName:c,targetTable:l.targetTableName,localField:f,foreignField:p,type:y?"many":"one",isInverse:h,nestedFields:d})}return{scalarFields:s,relations:a}}var sn=fe(require("fs")),Un=fe(require("path"));var Zi=new RegExp("\\p{Mark}","gu");function jr(r){return r==null?"":String(r).normalize("NFKD").replace(Zi,"").toLowerCase()}function Kn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=jr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function on(){return`function() {
7
7
  var M = ${Kn()};
8
8
  function foldStr(s) {
9
9
  if (s == null) return '';
@@ -49,5 +49,5 @@ ${e}
49
49
  }
50
50
  }
51
51
  return true;
52
- }`}var Br="mongo-fold-text-search.body.txt",qe=null;function Zi(){let r=[Un.join(__dirname,Br),Un.join(process.cwd(),"dist","kernel","query","utils",Br)];for(let e of r)try{if(sn.existsSync(e))return sn.readFileSync(e,"utf8")}catch{}return null}function an(){if(qe!==null)return qe;let r=Zi();return r?(qe=r,qe):(qe=on(),qe)}var Se=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof Se.ObjectId)return n;if(typeof n=="string")try{return new Se.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 Se.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 Se.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 Se.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.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 Se.ObjectId(n)}catch{return n}return n;default:return n}}var ln="__mongoFoldTextTriples";function eo(r){return r==="_id"?"$_id":`$${r}`}function ze(r,e,t,n){let o=eo(e),i=r[ln]??[];i.push({ref:o,needle:t,mode:n}),r[ln]=i}function to(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:an(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}function Ve(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 c=W(r,u,a,s.value);switch(s.operator){case"=":o[a]=c;break;case"!=":o[a]={$ne:c};break;case">":o[a]={$gt:c};break;case"<":o[a]={$lt:c};break;case">=":o[a]={$gte:c};break;case"<=":o[a]={$lte:c};break;case"like":o[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let l=d.map(m=>W(r,u,a,m));o[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let p=f.map(m=>W(r,u,a,m));o[a]={$nin:p};break;case"is null":o[a]=null;break;case"is not null":o[a]={$ne:null};break;case"_contains":ze(o,a,String(c),"contains");break;case"_starts_with":ze(o,a,String(c),"starts");break;case"_ends_with":ze(o,a,String(c),"ends");break;case"_between":let h=s.value;if(typeof h=="string"&&(h=h.split(",").map(m=>m.trim())),Array.isArray(h)&&h.length===2){let m=W(r,u,a,h[0]),_=W(r,u,a,h[1]);o[a]={$gte:m,$lte:_}}break;case"_is_null":let y=c===!0||c==="true";o[a]=y?{$eq:null}:{$ne:null};break;case"_is_not_null":let g=c===!0||c==="true";o[a]=g?{$ne:null}:{$eq:null};break}}return to(o),o}function Lr(r,e,t){let o=r?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function cn(r,e,t,n,o,i){switch(o){case"_contains":ze(e,n,String(i),"contains");break;case"_starts_with":ze(e,n,String(i),"starts");break;case"_ends_with":ze(e,n,String(i),"ends");break;case"_eq":e[n]=W(r,t,n,i);break;case"_neq":{let l=W(r,t,n,i);Lr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:l}})):e[n]={$ne:l};break}case"_in":{let l=i;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]);let f=l.map(p=>W(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>W(r,t,n,l));Lr(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 c=i===!0||i==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=i;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=W(r,t,n,d[0]),f=W(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Gn=require("mongodb");function ie(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(ie(o,e))return!0}}else if(t==="_not"){if(ie(n,e))return!0}else if(e.has(t))return!0;return!1}function Y(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(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let i=ie(r,o);return{fieldFilters:t,relationFilters:n,hasRelations:i}}jt();Bt();var pn="__mongoFoldTextTriples";function Pe(r,e){if(!r)return{};let t={};return Lt(r,t,e),Ce(t),t}function co(r,e){if(!r)return{};let t={};return qn(r,t,e),Ce(t),t}function me(r,e,t){if(!e)return{};let n=new se,{node:o}=he(e,t,r,n);return Pe(o,{metadata:r,rootTable:t})}function gn(r,e,t){if(!e)return{};let n=new se,{node:o}=he(e,t,r,n);return co(o,{metadata:r,rootTable:t})}function Lt(r,e,t){switch(r.kind){case"true":return;case"false":ye(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=r.children.map(i=>{let s={};return Lt(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}ye(e,...o);return}case"or":{let o=r.children.map(s=>{let a={};return Lt(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={};Lt(r.child,n,t),Ce(n);let o=e.$nor;e.$nor=o?[...o,n]:[n];return}case"compare":Qr(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 Qr(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":te(e,n,o(r.value));return;case"neq":{let i=o(r.value);zn(t,n)?ye(e,{[n]:{$ne:null}},{[n]:{$ne:i}}):te(e,n,{$ne:i});return}case"gt":te(e,n,{$gt:o(r.value)});return;case"gte":te(e,n,{$gte:o(r.value)});return;case"lt":te(e,n,{$lt:o(r.value)});return;case"lte":te(e,n,{$lte:o(r.value)});return;case"in":{let i=Ur(r.value).map(o);te(e,n,{$in:i});return}case"not_in":{let i=Ur(r.value).map(o);zn(t,n)?ye(e,{[n]:{$ne:null}},{[n]:{$nin:i}}):te(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&&te(e,n,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":te(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Jn(e,n,String(r.value),"contains");return;case"starts_with":Jn(e,n,String(r.value),"starts");return;case"ends_with":Jn(e,n,String(r.value),"ends");return}}function qn(r,e,t){switch(r.kind){case"true":ye(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let o=r.children.map(s=>{let a={};return qn(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 qn(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}ye(e,...o);return}case"not":Lt(r.child,e,t);return;case"compare":uo(r,e,t);return;case"relation_exists":{te(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function uo(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"){te(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let o={};Qr(r,o,t),Ce(o);let i={$nor:[o]};zn(t,n)?ye(e,i,{[n]:{$ne:null}}):ye(e,i)}function te(r,e,t){r[e]===void 0?r[e]=t:(ye(r,{[e]:r[e]},{[e]:t}),delete r[e])}function ye(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function zn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(o=>o.name===e);return n?n.isNullable!==!1:!0}function Ur(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function fo(r){return r==="_id"?"$_id":`$${r}`}function Jn(r,e,t,n){let o=fo(e),i=r[pn]??[];i.push({ref:o,needle:t,mode:n}),r[pn]=i}function Ce(r){let e=r[pn];if(delete r[pn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:an(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}async function be(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(c=>c.propertyName));if(!ie(r,i))return me(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>be(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>be(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Hn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=Y(r,o),u=[];if(s&&Object.keys(s).length>0){let c=me(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await po(c,d,e,o,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Hn(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return gn(t,r,e);let i=new Set((o.relations||[]).map(c=>c.propertyName));if(!ie(r,i))return gn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Hn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Hn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return be(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=Y(r,o),u=[];if(s&&Object.keys(s).length>0){let c=gn(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await ho(c,d,e,o,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function po(r,e,t,n,o,i){let s=(n.relations||[]).find(c=>c.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"?go(e,s,r,a,u,o,i):s.type==="one-to-many"?zr(e,s,t,a,u,o,i):s.type==="many-to-many"?Vr(e,s,t,a,u,o,i):{}}async function go(r,e,t,n,o,i,s){let a=G(e)||t,u=yn(r),c=mn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Yn(u);if(d!==null){let h=bn(d.value);if(d.op==="eq")return{[a]:h};if(d.op==="neq")return{[a]:{$ne:h}};if(d.op==="in")return{[a]:{$in:h}};if(d.op==="not_in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function ho(r,e,t,n,o,i){let s=(n.relations||[]).find(c=>c.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 yo(e,s,r,a,u,o,i);if(s.type==="one-to-many"){let c=await zr(e,s,t,a,u,o,i);return qr(c)}if(s.type==="many-to-many"){let c=await Vr(e,s,t,a,u,o,i);return qr(c)}return{}}async function yo(r,e,t,n,o,i,s){let a=G(e)||t,u=yn(r),c=mn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Yn(u);if(d!==null){let h=bn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:h}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:h};if(d.op==="in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:h}}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function zr(r,e,t,n,o,i,s){let a=U(e)||t,u=yn(r),c=mn(u);if(c!==null){let f=await Jr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await hn(u,n,o,i,s);if(!d||Object.keys(d).length===0)return{};let l=await Jr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Vr(r,e,t,n,o,i,s){let a=pe(t,e);if(!a)return{};let u=yn(r),c=mn(u);if(c!==null){let y=await Vn(s,a,n,null);return c?y.length===0?{}:{_id:{$nin:y}}:y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let d=Yn(u);if(d!==null){let y=bn(d.value),g=Array.isArray(y)?y:[y],m=await Vn(s,a,n,{_id:{$in:g}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let h=await Vn(s,a,n,{_id:{$in:p}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}async function hn(r,e,t,n,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return ie(r,i)?be(r,e,n,o):me(n,r,e)}async function Jr(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 c=String(u);i.has(c)||(i.add(c),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 Vn(r,e,t,n){let o=null;n&&t&&(o=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._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 c of s){let d=c[e.selfColumn];if(d==null)continue;let l=String(d);a.has(l)||(a.add(l),u.push(d))}return u}function yn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function mn(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 bn(r){if(Array.isArray(r))return r.map(e=>bn(e));if(typeof r!="string")return r;try{return new Gn.ObjectId(r)}catch{return r}}function Yn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Gn.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 Dt(r,e,t,n){let o=await Et(r,e,t),i=[],s={},a={};if(n&&typeof n=="object")for(let[p,h]of Object.entries(n))if(typeof h=="object"&&h!==null){let y=Object.keys(h)[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[p]=h:a[p]=h}else s[p]=h;if(Object.keys(s).length>0){let p={};for(let[h,y]of Object.entries(s))if(typeof y=="object"&&y!==null)for(let[g,m]of Object.entries(y))cn(r,p,e,h,g,m);else p[h]=y;Object.keys(p).length>0&&i.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,h]of Object.entries(a))if(!o.relations.some(g=>g.propertyName===p)){let g=c.find(m=>m.propertyName===p);if(g){let m="",_="";if(g.type==="many-to-one"||g.type==="one-to-one")m=G(g)||g.propertyName,_="_id";else if(g.type==="one-to-many")m="_id",_=U(g)||g.propertyName;else if(g.type==="many-to-many")continue;let b=g.type==="one-to-many"||g.type==="many-to-many";d.push({propertyName:p,targetTable:g.targetTableName,localField:m,foreignField:_,type:b?"many":"one",nestedFields:[]})}}let l=[...o.relations,...d];for(let p of l){let h=a[p.propertyName],y=p.nestedFields&&p.nestedFields.length>0?await Dt(r,p.targetTable,p.nestedFields,h):h?await Dt(r,p.targetTable,["_id"],h):[];p.type==="one"&&y.length>0&&y.push({$limit:1}),i.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:y.length>0?y:void 0}}),p.type==="one"&&(i.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),h&&(Ge(h)||i.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(h=>h.propertyName===p.propertyName));if(o.scalarFields.length>0||o.relations.length>0||f.length>0){let p={_id:1};for(let y of o.scalarFields)p[y]=1;for(let y of l)p[y.propertyName]=1,y.type==="one"&&y.localField&&y.localField!==y.propertyName&&(p[y.localField]=1);if(t.includes("*"))for(let y of f){if(y.type==="one-to-many"||y.type==="many-to-many")continue;y.type==="many-to-many"?p[y.propertyName]={$map:{input:`$${y.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[y.propertyName]={$cond:{if:{$ne:[`$${y.propertyName}`,null]},then:{_id:`$${y.propertyName}`},else:null}}}i.push({$project:p})}return i}async function Hr(r,e,t,n,o){let i=r?.tables?.get(t),s=i?.relations||[],a=i?.columns||[],u=s.filter(d=>!o.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&o.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of o)d[l.propertyName]=1,l.type==="one"&&l.localField&&l.localField!==l.propertyName&&(d[l.localField]=1);for(let l of u){if(l.type==="one-to-many"||l.type==="many-to-many")continue;l.type==="many-to-many"?d[l.propertyName]={$map:{input:`$${l.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[l.propertyName]={$cond:{if:{$ne:[`$${l.propertyName}`,null]},then:{_id:`$${l.propertyName}`},else:null}}}e.push({$project:d})}}function Ge(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ge(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ge(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ge(e));if("_not"in r)return Ge(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||Ge(t)))return!0}return!1}Xe();var Kt=require("mongodb");Xe();_n();async function wn(r,e,t){let n=new Map,o=0;async function i(){for(;o<r.length;){let u=o++,c=r[u];n.set(String(c),await e(c))}}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 le="__sourceId__",Fe="__targetId__",Ze="__enfyra_target__",Wt="__enfyra_top_n_documents__",et=class{constructor(e,t,n,o=new Re){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=o;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/ae)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let o={...t};for(let i of n)o[i]=1;e.push({$project:o})}}appendTopNStages(e,t,n,o,i){e.push({$group:{_id:`$${t}`,[Wt]:{$topN:{sortBy:n,output:"$$ROOT",n:o+i}}}},{$project:{[Wt]:{$slice:[`$${Wt}`,o,i]}}},{$unwind:`$${Wt}`},{$replaceRoot:{newRoot:`$${Wt}`}})}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("-"),i=o?n.slice(1):n;return{field:i==="id"?"_id":i,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(c=>c.trim()).filter(Boolean),i=[{$match:t}],s=new Set;for(let c of o){let l=(c.startsWith("-")?c.slice(1):c).split(".");if(l.length<=1)continue;let f=e;for(let p=0;p<l.length-1;p++){let h=l[p],y=this.normalizeMetadata()?.tables?.get(f);if(!y)break;let g=y.relations?.find(b=>b.propertyName===h);if(!g)break;let m=g.targetTableName||g.targetTable,_=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(_)){s.add(_);let b=G(g)||g.propertyName,$=p===0?null:`__sort_${l.slice(0,p).join("_")}`,S=$?`${$}.${b}`:b;i.push({$lookup:{from:m,localField:S,foreignField:"_id",as:_}},{$unwind:{path:`$${_}`,preserveNullAndEmptyArrays:!0}})}f=m}}let a=this.buildSortFromTokens(n);a&&i.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&i.push({$project:u}),i}toObjectId(e){try{return typeof e=="string"?new Kt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Kt.ObjectId||t instanceof Kt.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 Kt.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}=Ye(e),i={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])o.has(f.propertyName)||o.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(h=>h.name===f);p?i[p.name]=1:t.relations?.find(y=>y.propertyName===f)&&!o.has(f)&&o.set(f,["_id"])}o.forEach((f,p)=>{let h=t.relations?.find(y=>y.propertyName===p);h&&(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse)&&(s||(i[G(h)||h.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((f,p)=>{let h=t.relations?.find(_=>_.propertyName===p);if(!h)return;let y=h.targetTableName||h.targetTable;if(!y)return;let g,m;h.type==="many-to-one"||h.type==="one-to-one"?Ee(h)?(g="_id",m=U(h)||h.propertyName):(g=G(h)||h.propertyName,m="_id"):h.type==="one-to-many"?(g="_id",m=U(h)||h.propertyName):h.type==="many-to-many"&&(h.isInverse?(g="_id",m=h.mappedBy):(g=h.propertyName,m="_id")),a.push({relationName:p,type:h.type,targetTable:y,fields:f,isInverse:h.isInverse,fkColumn:h.foreignKeyColumn,mappedBy:h.mappedBy,junctionTableName:h.junctionTableName,junctionSourceColumn:h.junctionSourceColumn,junctionTargetColumn:h.junctionTargetColumn,localField:g,foreignField:m})});let u=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)i[f.newName]===1&&i[f.oldName]!==1&&(i[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?me(this.normalizeMetadata(),o.userFilter,e):null,s=this.buildSortFromTokens(o?.userSort),a=await K(t,c=>{let d={_id:{$in:c}};i&&Object.keys(i).length>0&&Object.assign(d,i);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}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=this.uniqueValues(n.map(m=>this.toObjectId(m))),u=i?.userFilter?me(this.normalizeMetadata(),i.userFilter,e):null,c=i?.userLimit,d=i?.userPage,l=this.hasDottedSort(i?.userSort);if(c!==void 0&&c>0){let m=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${i?.relationName}'`);let _=this.buildStableSort(i?.userSort),b=await K(a,async $=>{let S={[t]:{$in:$}};u&&Object.keys(u).length>0&&Object.assign(S,u);let k=[{$match:S}];this.appendTopNStages(k,t,_,m,c),k.push({$sort:{[t]:1,..._}}),this.appendPartitionProjection(k,s,[t]);let R=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(R,o)});return{docs:b,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:b.length}}}if(s&&(s[t]=1),l){let m=[],_=await wn(a,async b=>{let $={[t]:b};u&&Object.keys(u).length>0&&Object.assign($,u);let S=this.buildSortAggregatePipeline(e,$,i.userSort);s&&S.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(S).toArray());return this.applyReadFallback(k,o)},je);for(let b of _.values())for(let $ of b)m.push($);return{docs:m,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/je),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(i?.userSort)||{_id:1},h={projection:s,sort:p},y=await K(a,m=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:m},...u||{}},h).toArray())),g=this.applyReadFallback(y,o);return{docs:g,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let o=n.projection?{projection:n.projection}:void 0,i=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},o).toArray()));return this.applyReadFallback(i,n)}async fetchM2MTopK(e,t,n,o,i,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let m of e)u.set(this.keyOf(m),[]);let c=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,d=!i&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(m=>m.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await K(e,async m=>{if(d){let $=[{$match:{[n.selfColumn]:{$in:m}}}];return this.appendTopNStages($,n.selfColumn,{[n.otherColumn]:l},s,a),$.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate($).toArray())).map(k=>({sourceId:k[le],targetId:k[Fe]}))}let _=[{$match:{[n.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ze}},{$unwind:`$${Ze}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ze}`,{[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&_.push({$match:i}),this.appendTopNStages(_,le,f,s,a),_.push({$sort:{[le]:1,...f}}),_.push({$project:{_id:0,[le]:1,[Fe]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(_).toArray())).map($=>({sourceId:$[le],targetId:$[Fe]}))});if(c){let m=new Map;for(let _ of p){let b=this.keyOf(_.targetId);m.has(b)||m.set(b,{_id:_.targetId}),u.get(this.keyOf(_.sourceId))?.push(m.get(b))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let h=this.uniqueValues(p.map(m=>m.targetId)),y=await this.loadM2MTargets(t.targetTable,h,o),g=new Map(y.map(m=>[this.keyOf(m._id),m]));for(let m of p){let _=g.get(this.keyOf(m.targetId));_&&u.get(this.keyOf(m.sourceId))?.push(_)}return{grouped:u,docs:y,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(h.length>0?this.chunkCount(h):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+y.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,o,i){let s=new Map;for(let y of e)s.set(this.keyOf(y),[]);let a=!i&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await K(e,async y=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:y}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(b=>({sourceId:b[n.selfColumn],targetId:b[n.otherColumn]}));let g=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ze}},{$unwind:`$${Ze}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ze}`,{[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&g.push({$match:i}),g.push({$sort:{[le]:1,...c}},{$project:{_id:0,[le]:1,[Fe]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(g).toArray())).map(_=>({sourceId:_[le],targetId:_[Fe]}))});if(o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1){let y=new Map;for(let g of d){let m=this.keyOf(g.targetId);y.has(m)||y.set(m,{_id:g.targetId}),s.get(this.keyOf(g.sourceId))?.push(y.get(m))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(y=>y.targetId)),p=await this.loadM2MTargets(t.targetTable,f,o),h=new Map(p.map(y=>[this.keyOf(y._id),y]));for(let y of d){let g=h.get(this.keyOf(y.targetId));g&&s.get(this.keyOf(y.sourceId))?.push(g)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}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=pe(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=this.uniqueValues(e.map(k=>k._id)),c=new Map;for(let k of e)c.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?me(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,i,d,k,l)}let p=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1&&!d,h=this.hasDottedSort(t.userSort);if(!h)return this.fetchM2MEdgeBatch(u,t,a,i,d);let y=await K(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(y.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let g=new Set,m=[];for(let k of y){let R=k[a.otherColumn];if(R==null)continue;let I=this.keyOf(R);g.has(I)||(g.add(I),m.push(R))}let _=[],b=new Map;if(p)_=m.map(k=>({_id:k})),this.sortDocsByPk(_);else{let k={_id:{$in:m}};d&&Object.keys(d).length>0&&Object.assign(k,d);let R;if(h){let I=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);i.projection&&I.push({$project:i.projection}),R=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(I).toArray())}else{let I=this.buildSortFromTokens(t.userSort)||{_id:1},A=this.projectionWithSortFields(i.projection,t.userSort),L={sort:I};A.projection&&(L.projection=A.projection),R=await K(m,T=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:T},...d||{}},L).toArray())),t.userSort?this.sortDocsInMemory(R,t.userSort):this.sortDocsByPk(R),this.removeHiddenFields(R,A.hiddenFields)}_=this.applyReadFallback(R,i)}for(let k of _)b.set(this.keyOf(k._id),k);let $=new Map;for(let k of y){let R=this.keyOf(k[a.selfColumn]),I=this.keyOf(k[a.otherColumn]);b.has(I)&&($.has(I)||$.set(I,[]),$.get(I).push(R))}for(let k of _){let R=$.get(this.keyOf(k._id))||[];for(let I of R)c.get(I)?.push(k)}let S=p||m.length===0?0:this.chunkCount(m);return{grouped:c,docs:_,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+S,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length+_.length}}}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 $n(r,e,t,n,o=3,i=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new et(r,a,d);await new ke(l,n,u).execute(e,t,o,i,s)}async function er(r,e,t){let n=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,u=i?.tables?.get(e.table),c=new Set((u?.relations??[]).map(T=>T.propertyName)),d=!!e.mongoRawFilter&&!!i&&ie(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&d){let T=await be(e.mongoRawFilter,e.table,i,o);T&&Object.keys(T).length>0&&n.push({$match:T})}else if(f){let T=Pe(l.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=Ve(i,e.where,e.table,s);n.push({$match:T})}let p=e.plan,y=p?p.hasRelationSort:e.sort?.some(T=>{if(!T.field.includes("."))return!1;let N=T.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(E=>E.propertyName===N)??!1})??!1,g=()=>p?.sortItems?So(p.sortItems):e.sort?To(e.sort):null,m=p?.sortItems?mo(p.sortItems):[],_=p?.sortItems?bo(p.sortItems):[],b=()=>{!p||m.length===0||_o(n,e.table,p.sortItems,i)},$=()=>{!p||_.length===0||wo(n,e.table,p.sortItems,i)},S=()=>{let T=[...m,..._];T.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(T.map(N=>[N,0]))})};if(!e.mongoFieldsExpanded){b(),$();let T=g();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})),S(),e.select){let E={};for(let D of e.select)E[D]=1;n.push({$project:E})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let N=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:N,pipeline:n}:{results:Yr(N),pipeline:n}}let{scalarFields:k,relations:R}=e.mongoFieldsExpanded;if(!y){b(),$();let T=g();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 I=[];for(let T of R)if(e.sort?.some(E=>E.field.startsWith(`${T.propertyName}.`))){let E=e.mongoRawFilter?.[T.propertyName];if(T.nestedFields&&T.nestedFields.length>0){let j=await Dt(i,T.targetTable,T.nestedFields??[],E);T.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName,pipeline:j.length>0?j:void 0}})}else if(E){let j=await Dt(i,T.targetTable,["_id"],E);T.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName,pipeline:j.length>0?j: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}}),E&&(tt(E)||n.push({$match:{[T.propertyName]:{$ne:null}}})))}else I.push(T);if(y){b(),$();let T=g();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}))}S(),await Hr(i,n,e.table,k,[...R]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let A=performance.now(),L=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",A,{table:e.table}),e.mongoCountOnly)return{results:L,pipeline:n};if(I.length>0&&L.length>0){let T=e.deep||{},N=I.map(D=>{let w=i?.tables?.get(e.table)?.relations?.find(V=>V.propertyName===D.propertyName),C=T[D.propertyName],v=C?.fields!=null?Array.isArray(C.fields)?C.fields:String(C.fields).split(",").map(V=>V.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:w?.type,targetTable:D.targetTable,fields:v,isInverse:w?.isInverse,mappedBy:w?.mappedBy,junctionTableName:w?.junctionTableName,localField:D.localField,foreignField:D.foreignField,userFilter:C?.filter,userSort:C?.sort,userLimit:C?.limit!==void 0?Number(C.limit):void 0,userPage:C?.page!==void 0?Number(C.page):void 0,nestedDeep:C?.deep}}),E=$o(i);E&&await $n(o,L,N,E,3,0,e.table,i,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Yr(L),pipeline:n}}function tr(r){return`__sort_count_${r.relationName||r.field}`}function nr(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function mo(r){return r.filter(e=>e.function==="count").map(tr)}function bo(r){return r.filter(e=>e.function==="max"||e.function==="min").map(nr)}function _o(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,c=a?.targetTableName||a?.targetTable,d=tr(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=U(a)||u;r.push({$lookup:{from:c,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=pe(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function wo(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,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(g=>g.isPrimary)?.name||(d?.columns?.some(g=>g.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(g=>g.name==="_id")?"_id":f,h=nr(s),y=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let g=U(a)||u;r.push({$lookup:{from:c,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${g}`,"$$localId"]}}},{$group:{_id:null,value:{[y]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}});continue}if(a.type==="many-to-many"){let g=pe(e,a);if(!g)continue;let m=`${h}_junction`;r.push({$lookup:{from:g.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${g.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${g.otherColumn}`}}],as:m}}),r.push({$lookup:{from:c,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[y]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}}),r.push({$project:{[m]: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 To(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 So(r){let e={};for(let t of r){let n=t.function==="count"?tr(t):t.function==="max"||t.function==="min"?nr(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function tt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>tt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>tt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>tt(e));if("_not"in r)return tt(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||tt(t)))return!0}return!1}function Yr(r){return r.map(ce)}function Xr(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(Co(i,o,e));return{scalarFields:t,relations:n}}function Co(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),o,i,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ee(n)?(o="_id",i=U(n)||r.propertyName,s=!0):(o=n&&G(n)||r.propertyName,i="_id",s=!1):r.relationType==="one-to-many"?(o="_id",i=n&&U(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=Zr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:u}}function Zr(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=Zr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let o of n)e.push(`${t.propertyName}.${o}`)}return e}He();Bt();jt();function Tn(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(l=>l.name==="_id"&&l.isPrimary),a=i.columns?.some(l=>l.name==="id"),u=s&&!a?"_id":"id",c=new Map,d=[];for(let l of r){let f=l==="id"?u:l;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),h=f.substring(0,p),y=f.substring(p+1);if(!i.relations?.some(m=>m.propertyName===h))continue;c.has(h)||c.set(h,[]),c.get(h).push(y)}else if(i.relations?.some(h=>h.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!i.columns?.some(y=>y.name===f))continue;d.push(f)}}if(d.includes("*")){o.nodes.push({kind:"wildcard"});for(let l of i.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)o.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=i.relations?.find(g=>g.propertyName===l);if(!p)continue;let h=p.targetTableName||p.targetTable,y={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:h,children:ei(f,h,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let g=n.registerWithParent(e,l,t,"left",null,"data");y.joinId=g}o.nodes.push(y)}return o}function ei(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let o=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),i=n.columns?.some(d=>d.name==="id"),s=o&&!i?"_id":"id",a=new Map,u=[];for(let d of r){let l=d==="id"?s:d;if(l==="*")u.push("*");else if(l.includes(".")){let f=l.indexOf("."),p=l.substring(0,f),h=l.substring(f+1);if(!n.relations?.some(g=>g.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(h)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(h=>h.name===l))continue;u.push(l)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,l]of a.entries()){let f=n.relations?.find(h=>h.propertyName===d);if(!f)continue;let p=f.targetTableName||f.targetTable;c.push({kind:"relation",propertyName:d,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:p,children:ei(l,p,t)})}return c}ge();ge();var ko=new Set(["_and","_or","_not"]);function ti(r,e){return r?.tables?.get(e)??null}function Ro(r,e,t){return ti(r,e)?.columns?.find(n=>n.name===t)}function rr(r,e,t){return ti(r,e)?.relations?.find(n=>n.propertyName===t)}function Fo(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 ir(r,e,t,n){if(Ro(r,e,t)?.isEncrypted===!0)throw new x(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Be(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Be(n,e,t);return}for(let[n,o]of Object.entries(r)){if(ko.has(n)){Be(o,e,t);continue}if(n.startsWith("_"))continue;let i=rr(t,e,n);if(i){let s=i.targetTableName||i.targetTable;s&&Be(o,s,t);continue}ir(t,e,n,"filter")}}}function Sn(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=Fo(i);if(s){if(s.functionName==="count")continue;let c=rr(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&ir(t,d,s.fieldName,"sort");continue}let a=i.split("."),u=e;for(let c=0;c<a.length;c++){let d=a[c];if(c===a.length-1){ir(t,u,d,"sort");break}let f=rr(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var q=class{plan(e){let{tableName:t,fields:n,filter:o,sort:i,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new se,p=this.parseFields(n),h=null;p&&l&&(h=Tn(p,t,c,f));let y=!1,g=null;if(o&&l){Be(o,t,c);let T=he(o,t,c,f);g=T.node,y=T.hasRelationFilters}let m=this.parseSort(i);l&&Sn(m,t,c);let _=[],b=!1;for(let T of m){let N=T.startsWith("-"),E=N?T.substring(1):T,D=N?"desc":"asc";if(l){let j=this.parseRelationAggregateSort(t,l,E,c);if(j){_.push({joinId:null,field:E,direction:D,fullPath:E,function:j.functionName,relationName:j.relationName,aggregateField:j.aggregateField,relationMeta:j.relationMeta});continue}this.assertLocalSortField(t,l,E)}_.push({joinId:null,field:E,direction:D,fullPath:E})}_.length===0&&_.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let $=this.parseLimit(a),S=this.parsePage(s),k=S!==void 0&&$!==void 0?(S-1)*$:void 0,R=this.parseMeta(u),I=R.includes("totalCount")||R.includes("*"),A=R.includes("filterCount")||R.includes("*"),L=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:o??null,joins:L,sortItems:_,limit:$,offset:k,needsTotalCount:I,needsFilterCount:A,hasRelationFilters:y,hasRelationSort:b,filterTree:g,fieldTree:h}}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 x(`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 x(`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 x(`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 g=a;if(!g||g.includes("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(_=>_.propertyName===g);if(!m)throw new x(`Sort relation '${g}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new x(`Sort function '_count(${g})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:g,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new x(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(g=>g.propertyName===c);if(!l)throw new x(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new x(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=o?.tables?.get(f);if(!p)throw new x(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let h=p.columns?.find(g=>g.name===d),y=d==="id"&&p.columns?.some(g=>g.name==="_id");if(!h&&!y)throw new x(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(h?.isEncrypted===!0)throw new x(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}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),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=o.registerWithParent(t,a,n,"left",i,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,o,l)}};ge();Pt();var xo=new Set(["count","sum","avg","min","max","countRecords"]),vo=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),Io=new Set(["_and","_or","_not"]);function xe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function P(r,e){let t=r.replace(/^aggregate\./,"");throw new x(e,{path:r,aggregate:{[t]:e}})}function No(r){return typeof r!="string"?!1:vo.has(r.toLowerCase())}function ni(r){return Object.keys(r).length===0}function Mo(r,e,t){return r===!0?{}:(r==null&&P(t,`aggregate.${e} condition must be true or an object`),xe(r)||P(t,`aggregate.${e} condition must be true or an object`),r)}function Ao(r,e,t){let n=r?.tables?.get(e);return n||P(t,`Table "${e}" metadata is not available`),n}function ri(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&P(e,"aggregate.countRecords relation target is not available"),t}function Cn(r,e,t,n){let o=Ao(t,e,n);for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){Array.isArray(s)||P(n,`aggregate.countRecords ${i} condition must be an array`);for(let d of s)xe(d)||P(n,`aggregate.countRecords ${i} items must be objects`),Cn(d,e,t,n);continue}if(i==="_not"){xe(s)||P(n,"aggregate.countRecords _not condition must be an object"),Cn(s,e,t,n);continue}(i.startsWith("_")||Io.has(i))&&P(n,`Unsupported aggregate.countRecords condition key "${i}"`);let a=o.columns?.find(d=>d.name===i),u=o.relations?.find(d=>d.propertyName===i);if(!a&&!u&&P(n,`Unknown aggregate.countRecords field or relation "${i}" on table "${e}"`),xe(s)||P(n,`aggregate.countRecords condition for "${i}" must be an object`),a){for(let d of Object.keys(s))oe.has(d)||P(n,`aggregate.countRecords condition for "${i}" only supports field operators`);continue}let c=ri(u,n);Cn(s,c,t,n)}}function or(r){return xe(r)&&Object.keys(r).length>0}function nt(r,e,t){if(!or(r))return[];xe(r)||P("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||P("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")&&P("aggregate","aggregate field name must be a non-empty string"),xe(s)||P(a,"aggregate field config must be an object");let u=i,c=a,d=n.columns?.find(p=>p.name===i),l=n.relations?.find(p=>p.propertyName===i);!d&&!l&&P(c,`Unknown aggregate field or relation "${i}" on table "${e}"`);let f=Object.entries(s).filter(([p])=>p!=="as");f.length===0&&P(c,"aggregate field must define at least one operation");for(let[p,h]of f){xo.has(p)||P(c,`Unsupported aggregate operation "${p}"`);let y=Mo(h,p,c);if(l&&p!=="countRecords"&&P(c,`aggregate.${p} is not supported on relation "${i}"; use countRecords`),d&&p==="countRecords"&&P(c,`aggregate.countRecords requires a relation, but "${i}" is a field`),d&&(p==="sum"||p==="avg")&&!No(d.type)&&P(c,`aggregate.${p} requires a numeric field, but "${i}" is "${d.type}"`),d)for(let g of Object.keys(y))oe.has(g)||P(c,`aggregate.${p} condition for "${i}" only supports field operators`);if(l&&p==="countRecords"){let g=ri(l,c);Cn(y,g,t,c)}o.push({field:i,outputKey:u,path:c,op:p,condition:y})}}return o}function rt(r,e){let t=[];return xe(r)&&!ni(r)&&t.push(r),ni(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 it=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 f=new q;e={...e,plan:f.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,debugTrace:e.debugTrace};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(f=>f.trim()))),e.filter&&(J(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let f=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(p=>p.trim());n.sort=f.map(p=>{let h=p.trim();return h.startsWith("-")?{field:h.substring(1),direction:"desc"}:{field:h,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let f=typeof e.page=="string"?parseInt(e.page,10):e.page,p=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(f-1)*p,n.limit=p}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(f=>f.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(f=>f.propertyName)),c=!!n.mongoRawFilter&&ie(n.mongoRawFilter,u);if((o.includes("filterCount")||o.includes("*"))&&!c){let f=this.mongoService.collection(e.tableName),p=e.plan?.filterTree?Pe(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await f.countDocuments(p)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let f=this.lastBuiltPipeline??[],p;try{p=await this.db.collection(e.tableName).aggregate(f).explain()}catch(h){p={error:String(h)}}return{pipeline:f,explain:p}}if(c&&(o.includes("filterCount")||o.includes("*"))){let f={...n,mongoCountOnly:!0},p=await this.selectLegacy(f);s=p.length>0?p[0].count:0}let l=await this.executeAggregate(n,e.filter);return{data:d,...(o.length>0||l)&&{meta:{...o.includes("totalCount")||o.includes("*")?{totalCount:i}:{},...o.includes("filterCount")||o.includes("*")?{filterCount:s}:{},...l?{aggregate:l}:{}}}}}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 c=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&c?.fieldTree){if(e.mongoFieldsExpanded=Xr(c.fieldTree,this.metadata),n){let l=await Et(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...l.relations.filter(p=>!f.has(p.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await Et(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let l=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:l.scalarFields},t=l.hiddenFields}}e.where&&(e.where=e.where.map(c=>c.field.includes(".")?c:{...c,field:`${e.table}.${c.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(ce);let{results:a,pipeline:u}=await er(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 er(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=nt(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=rt(t,s);J(a,e.table,e.metadata);let c=new q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let f=await this.executeRelationCountRecords(e,t,s);ve(o,s,f);continue}let d=c.hasRelationFilters?await be(a,e.table,e.metadata,this.db):c.filterTree?Pe(c.filterTree,{metadata:e.metadata,rootTable:e.table}):{},l;if(s.op==="count")l=await i.countDocuments(d);else{let[{value:f}={value:null}]=await i.aggregate([{$match:d},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();l=f??0}ve(o,s,l)}return o}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table)?.relations?.find(d=>d.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),c=await this.resolveMatchFilter(s,n.condition,e.metadata);if(i.type==="one-to-many"){let l=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(f=>f!=null);return l.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{[i.foreignKeyColumn]:{$in:l}}]})}if(i.type==="many-to-many"){let d=pe(e.table,i);if(!d)return 0;let f=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(y=>y!=null);if(f.length===0)return 0;let h=(await this.db.collection(d.junctionName).find({[d.selfColumn]:{$in:f}},{projection:{[d.otherColumn]:1}}).toArray()).map(y=>y[d.otherColumn]).filter(y=>y!=null);return h.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{_id:{$in:h}}]})}if(i.type==="many-to-one"||i.type==="one-to-one"){let d=i.foreignKeyColumn||`${n.field}Id`,f=(await this.db.collection(e.table).find(u,{projection:{[d]:1}}).toArray()).map(p=>p[d]).filter(p=>p!=null);return f.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{_id:{$in:f}}]})}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 be(t,e,n,this.db):i.filterTree?Pe(i.filterTree,{metadata:n,rootTable:e}):{}}};var kn=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}};ge();ue();var Eo=["_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(Eo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&_e(r[e]))return!0;return!1}var ii=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Oo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Rn(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 Po(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)||Rn(r,t,o),e}function oi(r,e,t,n,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,u=Ie(a,i??"postgres"),c=Rn(e,o,s),d=Po(e,n,o,i,s);switch(t){case"_eq":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let l=n;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]),c&&i==="postgres"&&l.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[l]):r.whereIn(a,l);break;case"_not_in":case"_nin":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),c&&i==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);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,Oo(t),n)}}function jo(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 ot(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(){ot(this,s,t,"and",o,i)}):r.orWhere(function(){ot(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e))if(jo(s,t,i)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){ot(this,u,t,"and",o,i)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){ot(this,u,t,"and",o,i)})});continue}if(s==="_not"){r.whereNot(function(){ot(this,a,t,"and",o,i)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>ii.includes(c)))for(let[c,d]of Object.entries(a))ii.includes(c)&&(n==="and"?r.where(function(){oi(this,s,c,d,t,o,i)}):r.orWhere(function(){oi(this,s,c,d,t,o,i)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Ie(c,o??"postgres");Rn(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(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(c,"=",a):r.orWhere(c,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=Ie(u,o??"postgres");Rn(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(`${c} = ?::uuid`,[a]):r.orWhereRaw(`${c} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function de(r,e,t,n,o){return!e||typeof e!="object"||ot(r,e,t,"and",n,o),r}ue();function lr(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 si(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 st(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function cr(r,e,t,n,o,i){let s=[];for(let[a,u]of Object.entries(i)){let c=await Ut(r,e,a,u,t,n,o);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=lr(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let h=st(p._is_null),y=st(p._is_not_null);if(h===!0)s.push(`${l} IS NULL`);else if(h===!1)s.push(`${l} IS NOT NULL`);else if(y===!0)s.push(`${l} IS NOT NULL`);else if(y===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let g=Ne(p._eq,n);s.push(`${l} = ${g}`)}else if(p._neq!==void 0){let g=Ne(p._neq,n);s.push(`${l} != ${g}`)}else if(p._in!==void 0){let m=(Array.isArray(p._in)?p._in:[p._in]).map(_=>Ne(_,n)).join(", ");s.push(`${l} IN (${m})`)}else if(p._not_in!==void 0||p._nin!==void 0){let g=p._not_in??p._nin,_=(Array.isArray(g)?g:[g]).map(b=>Ne(b,n)).join(", ");s.push(`${l} NOT IN (${_})`)}else if(p._gt!==void 0){let g=Ne(p._gt,n);s.push(`${l} > ${g}`)}else if(p._gte!==void 0){let g=Ne(p._gte,n);s.push(`${l} >= ${g}`)}else if(p._lt!==void 0){let g=Ne(p._lt,n);s.push(`${l} < ${g}`)}else if(p._lte!==void 0){let g=Ne(p._lte,n);s.push(`${l} <= ${g}`)}}}}}return s}function ur(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 sr(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 c of a._and)if(ur(c)){let d=e(t).select(`${t}.id`);await Le(e,d,c,t,n,o,i),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=Y(c,n),f=await cr(e,t,n,o,i,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(ur(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:c}=Y(a,n),d=await cr(e,t,n,o,i,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ai(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&&de(this,i.fieldFilters,t,o,n);for(let s of i.subqueries)this.whereRaw(s)})}function ar(r,e,t,n,o){let i=!0;for(let s of e){let a=function(){for(let u of s)ai(this,u,t,n,o)};i?(r.where(a),i=!1):r.orWhere(a)}}function Fn(r,e,t,n,o,i,s){let a=si(e,o),u=si(n,i),c=`${F(r,s)}.${F(e,s)}`,d=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Ut(r,e,t,n,o,i,s){let a=o.relations.find(f=>f.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 c=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 f=Object.keys(n||{});if(f.length===1&&f[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(h=>c.has(h)))return null}let d=s?await s(u):null,l;switch(a.type){case"one-to-many":l=r(u).select(r.raw("1")).whereRaw(Fn(u,a.foreignKeyColumn,e,"id",d,o,i));break;case"many-to-many":let f=s?await s(a.junctionTableName):null;l=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(Fn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,i))).whereRaw(Fn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,o,i));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(Fn(u,"id",e,a.foreignKeyColumn,d,o,i));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Le(r,l,n,u,d,i,s):l=de(l,n,u,i,d||void 0):l=de(l,n,u,i),l.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 c of t._and)if(c._or&&Array.isArray(c._or)&&c._or.length>0){let d=await sr(c._or,r,n,o,i,s);e.where(function(){ar(this,d,n,o,i)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Le(r,e,d,n,o,i,s);else await Le(r,e,c,n,o,i,s);return}if(t._or&&Array.isArray(t._or)){let c=await sr(t._or,r,n,o,i,s);e.where(function(){ar(this,c,n,o,i)});return}if(t._not){let c=t._not;if(c._and&&Array.isArray(c._and)&&c._and.length>0){let f=[];for(let p of c._and)if(ur(p)){let h=r(n).select(`${n}.id`);await Le(r,h,p,n,o,i,s),f.push({idSubquery:h})}else{let{fieldFilters:h,relationFilters:y}=Y(p,o),g=await cr(r,n,o,i,s,y);f.push({fieldFilters:h,subqueries:g})}e.whereNot(function(){for(let p of f)ai(this,p,n,o,i)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await sr(c._or,r,n,o,i,s);e.whereNot(function(){ar(this,f,n,o,i)});return}let{fieldFilters:d,relationFilters:l}=Y(c,o);e.whereNot(function(){Object.keys(d).length>0&&de(this,d,n,i,o)});for(let[f,p]of Object.entries(l)){let h=await Ut(r,n,f,p,o,i,s);if(h===null){let y=o.relations.find(g=>g.propertyName===f);if(y&&y.foreignKeyColumn){let g=lr(n,y.foreignKeyColumn,i),_=p.id;if(_&&typeof _=="object"){let b=st(_._is_null),$=st(_._is_not_null);if(b===!0)e.whereRaw(`${g} IS NOT NULL`);else if(b===!1)e.whereRaw(`${g} IS NULL`);else if($===!0)e.whereRaw(`${g} IS NULL`);else if($===!1)e.whereRaw(`${g} IS NOT NULL`);else if(_._eq!==void 0)e.whereRaw(`${g} != ?`,[_._eq]);else if(_._neq!==void 0)e.whereRaw(`${g} = ?`,[_._neq]);else if(_._in!==void 0){let S=Array.isArray(_._in)?_._in:[_._in];e.whereRaw(`${g} NOT IN (${S.map(()=>"?").join(", ")})`,S)}else if(_._not_in!==void 0||_._nin!==void 0){let S=_._not_in??_._nin,k=Array.isArray(S)?S:[S];e.whereRaw(`${g} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${h})`)}return}let{fieldFilters:a,relationFilters:u}=Y(t,o);Object.keys(a).length>0&&de(e,a,n,i,o);for(let[c,d]of Object.entries(u)){let l=await Ut(r,n,c,d,o,i,s);if(l===null){let f=o.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=lr(n,f.foreignKeyColumn,i),y=d.id;if(y&&typeof y=="object"){let g=st(y._is_null),m=st(y._is_not_null);if(g===!0)e.whereRaw(`${p} IS NULL`);else if(g===!1)e.whereRaw(`${p} IS NOT NULL`);else if(m===!0)e.whereRaw(`${p} IS NOT NULL`);else if(m===!1)e.whereRaw(`${p} IS NULL`);else if(y._eq!==void 0)e.whereRaw(`${p} = ?`,[y._eq]);else if(y._neq!==void 0)e.whereRaw(`${p} != ?`,[y._neq]);else if(y._in!==void 0){let _=Array.isArray(y._in)?y._in:[y._in];e.whereRaw(`${p} IN (${_.map(()=>"?").join(", ")})`,_)}else if(y._not_in!==void 0||y._nin!==void 0){let _=y._not_in??y._nin,b=Array.isArray(_)?_:[_];e.whereRaw(`${p} NOT IN (${b.map(()=>"?").join(", ")})`,b)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function De(r,e,t,n,o,i,s){await Le(r,e,t,n,o,i,s)}ue();fr();He();ue();function at(r,e,t,n,o){for(let i of e){let s=i.field.split("."),a=t||s[0],u=s[s.length-1],c=Qt(n,a,u,i.value);switch(i.operator){case"=":r=r.where(i.field,"=",c);break;case"!=":r=r.where(i.field,"!=",c);break;case">":r=r.where(i.field,">",c);break;case"<":r=r.where(i.field,"<",c);break;case">=":r=r.where(i.field,">=",c);break;case"<=":r=r.where(i.field,"<=",c);break;case"like":r=r.where(i.field,"like",c);break;case"in":let d=Array.isArray(i.value)?i.value.map(y=>Qt(n,a,u,y)):[c];r=r.whereIn(i.field,d);break;case"not in":let l=Array.isArray(i.value)?i.value.map(y=>Qt(n,a,u,y)):[c];r=r.whereNotIn(i.field,l);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 f=i.value;if(typeof f=="string"&&(f=f.split(",").map(y=>y.trim())),Array.isArray(f)&&f.length===2){let y=Qt(n,a,u,f[0]),g=Qt(n,a,u,f[1]);r=r.whereBetween(i.field,[y,g])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(i.field):r.whereNotNull(i.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(i.field):r.whereNull(i.field);break}}return r}function Jt(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(c=>{let d=Jt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&o.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Jt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&o.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Jt(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,c]of Object.entries(a)){let d=`${F(e,n)}.${F(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=i.columns?.find(y=>y.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")o.push(`${d} = ${l}`);else if(u==="_neq")o.push(`${d} != ${l}`);else if(u==="_gt")o.push(`${d} > ${l}`);else if(u==="_gte")o.push(`${d} >= ${l}`);else if(u==="_lt")o.push(`${d} < ${l}`);else if(u==="_lte")o.push(`${d} <= ${l}`);else if(u==="_is_null")o.push(`${d} IS NULL`);else if(u==="_is_not_null")o.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");o.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");o.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):o.push(`lower(${d}) LIKE '%${f.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(c)&&c.length===2){let f=typeof c[0]=="string"?`'${c[0].replace(/'/g,"''")}'`:String(c[0]),p=typeof c[1]=="string"?`'${c[1].replace(/'/g,"''")}'`:String(c[1]);o.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${F(e,n)}.${F(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),o.push(`${u} = ${c}`)}return o}function ci(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 Qt(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}}ue();qt();Je();async function di(r,e,t,n,o,i,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(gr(),ui)),u=await a(e,t,n,o,i,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function hr(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 fi(r,e,t,n,o){let i=r.targetTableName||r.targetTable;if(!i)return null;let s=r.foreignKeyColumn||H(r.propertyName);if(!s)return null;let a=l=>F(l,o),u=n?.tables?.get(i),d=(u?X(u):null)?.name||"id";return`(SELECT ${a(i)}.${a(e)} FROM ${a(i)} WHERE ${a(i)}.${a(d)} = ${a(t)}.${a(s)})`}qt();var ut=class r{constructor(e,t,n,o){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=o;this.logger=new kn(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,c=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!u&&!a&&c){o&&o.setQueryPath("simple");let w=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),w}let l={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map(w=>w.trim())));let f=e.filter;if(e.filter&&!_e(e.filter)){l.where=[];for(let[w,C]of Object.entries(e.filter))if(typeof C=="object"&&C!==null)for(let[v,V]of Object.entries(C)){let M;if(v==="_eq")M="=";else if(v==="_neq")M="!=";else if(v==="_in")M="in";else if(v==="_not_in"||v==="_nin")M="not in";else if(v==="_gt")M=">";else if(v==="_gte")M=">=";else if(v==="_lt")M="<";else if(v==="_lte")M="<=";else if(v==="_contains")M="_contains";else if(v==="_starts_with")M="_starts_with";else if(v==="_ends_with")M="_ends_with";else if(v==="_between")M="_between";else if(v==="_is_null")M="_is_null";else if(v==="_is_not_null")M="_is_not_null";else if(v==="_like")M="like";else if(v==="_ilike")M="ilike";else continue;l.where.push({field:w,operator:M,value:V})}else l.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());l.sort=w.map(C=>{let v=C.trim();return v.startsWith("-")?{field:v.substring(1),direction:"desc"}:{field:v,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,h=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,y=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,g=y===void 0||Number.isNaN(y)?void 0:y;g&&h!==void 0?(l.offset=(g-1)*h,l.limit=h):h!==void 0&&(l.limit=h);let m=e.plan?.sortItems??(l.sort??[]).map(w=>({joinId:null,field:w.field,direction:w.direction,fullPath:w.field})),_=[],b=[];for(let w of m){if(w.function==="count"){let C={sql:this.buildRelationCountSortSubquery(l.table,w),direction:w.direction};b.push(C);continue}if(w.function==="max"||w.function==="min"){let C={sql:this.buildRelationAggregateSortSubquery(l.table,w),direction:w.direction};b.push(C);continue}if(w.joinId===null){if(w.field.includes(".")&&!e.plan){let v=w.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(z=>z.propertyName===v))continue}let C={field:w.field.includes(".")?w.field:`${l.table}.${w.field}`,direction:w.direction};_.push(C),b.push(C)}else{let C=e.plan?.joins.find(v=>v.id===w.joinId);if(C&&(C.relationType==="many-to-one"||C.relationType==="one-to-one")){let v=fi(C.relationMeta,w.field,l.table,this.metadata,this.dbType);if(v){let V={sql:v,direction:w.direction};b.push(V)}}}}let $=[];if(l.fields&&l.fields.length>0||u||a){let w=hr(this.metadata),C=l.fields&&l.fields.length>0?l.fields:["*"],v=await di(this.knex,l.table,C,w,this.dbType,this.maxQueryDepth,e.deep);v.select.length>0&&(l.select=[...l.select||[],...v.select]),$=v.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map(w=>w.field.includes(".")?w:{...w,field:`${l.table}.${w.field}`})),l.sort=_;let S=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(w=>w.trim()).filter(Boolean),R=k.includes("filterCount")||k.includes("*"),I=k.includes("totalCount")||k.includes("*");if(l.select){let w=l.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);S=S.select(w)}if(R&&S.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),I){let w=F(l.table,this.dbType);S.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) as __total_count__`))}let A=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(_e(f)||Object.keys(f).length>0)){let w=this.metadata?.tables?.get(l.table);(!A&&w&&w.relations&&w.relations.length>0?Y(f,w).hasRelations:!1)?await De(this.knex,S,f,l.table,w,this.dbType,v=>this.metadata?.tables?.get(v)):e.plan?.filterTree?ne(S,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),S=de(S,f,l.table,this.dbType,w))}else l.where&&l.where.length>0&&(S=at(S,l.where,l.table,this.metadata,this.dbType));for(let w of b)if(w.field){let C=w.field.includes(".")?w.field:`${l.table}.${w.field}`;S=S.orderBy(C,w.direction)}else w.sql&&(S=S.orderByRaw(`${w.sql} ${w.direction.toUpperCase()}`));l.groupBy&&(S=S.groupBy(l.groupBy)),l.offset&&(S=S.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(S=S.limit(l.limit));let L=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:S.toSQL().toNative()});let T;if(e.debugMode&&(T=S.toSQL().toNative().sql),e.debugMode&&o){let w=S.toSQL().toNative();o.setSql(w.sql);try{let C=w.sql.replace(/\$\d+/g,"?"),v=await this.knex.raw(`EXPLAIN ${C}`,w.bindings);o.setExplain(this.dbType==="postgres"?v.rows:v[0])}catch(C){o.setExplain({error:String(C)})}}let N,E=performance.now();N=await S,o&&o.dur("db_execute",E,{table:e.tableName});let D=0;if(R&&N.length>0&&(D=Number(N[0].__filter_count__||0),N.forEach(w=>{delete w.__filter_count__})),I&&N.length>0&&N[0].__total_count__!==void 0&&(L=Number(N[0].__total_count__||0),N.forEach(w=>{delete w.__total_count__})),$&&$.length>0&&N.length>0){let w=hr(this.metadata);if(w){let{executeBatchFetches:C}=await Promise.resolve().then(()=>(br(),pi));await C(this.knex,N,$,w,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,o)}}if(this.knexService){let w=performance.now();N=await this.knexService.parseResult(N,l.table),o&&o.dur("db_parseResult",w,{table:e.tableName})}else{let w=(C,v)=>{if(!C||!this.metadata)return C;let V=this.metadata.tables?.get(v);if(!V)return C;if(Array.isArray(C))return C.map(z=>w(z,v));if(typeof C!="object"||Buffer.isBuffer(C))return C;let M={...C};for(let z of V.columns)if(z.type==="simple-json"&&M[z.name]&&typeof M[z.name]=="string")try{M[z.name]=JSON.parse(M[z.name])}catch{}for(let[z,Z]of Object.entries(M))if(Z&&typeof Z=="object"&&!Array.isArray(Z)&&!Buffer.isBuffer(Z)){let En=Z;if(En.id!==void 0||En.createdAt!==void 0){let ft=V.relations?.find(pt=>pt.propertyName===z);ft&&(M[z]=w(Z,ft.targetTableName))}}else if(Array.isArray(Z)&&Z.length>0&&typeof Z[0]=="object"&&Z[0].id!==void 0){let ft=V.relations?.find(pt=>pt.propertyName===z);ft&&(M[z]=Z.map(pt=>w(pt,ft.targetTableName)))}return M};N=w(N,l.table)}o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName}));let j=await this.executeAggregate(l,f);return{data:N,...(k.length>0||j)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:L}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:D}:{},...j?{aggregate:j}:{}}},...T!==void 0&&{sql:T}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=X(s)?.name||"id",u=F(e,this.dbType),c=F(a,this.dbType);if(!n||!i)throw new x(`Sort relation '${o}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new x(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let l=F(i,this.dbType),f=F(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,o,e),l=F(d.tableName,this.dbType),f=F(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new x(`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),c=X(a)?.name||"id",d=X(u)?.name||"id",l=F(e,this.dbType),f=F(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!i)throw new x(`Sort function '${t.field}' is not supported on '${e}'.`);let h=F(s,this.dbType),y=F(i,this.dbType);if(n.type==="one-to-many"){let g=n.foreignKeyColumn||n.mappedBy;if(!g)throw new x(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let m=F(g,this.dbType);return`(SELECT ${p}(${h}.${y}) FROM ${h} WHERE ${h}.${m} = ${l}.${f})`}if(n.type==="many-to-many"){let g=this.resolveManyToManyContract(n,o,e),m=F(g.tableName,this.dbType),_=F(g.sourceColumn,this.dbType),b=F(g.targetColumn,this.dbType),$=F(d,this.dbType);return`(SELECT ${p}(${h}.${y}) FROM ${m} JOIN ${h} ON ${h}.${$} = ${m}.${b} WHERE ${m}.${_} = ${l}.${f})`}throw new x(`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 x(`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&&ne(i,t.filterTree,{dbType:this.dbType,rootTable:n});for(let g of t.sortItems){let m=g.field.includes(".")?g.field:`${n}.${g.field}`;i=i.orderBy(m,g.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(g=>g.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 g=F(n,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${g}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let g=i.toSQL().toNative();if(d=g.sql,c){c.setSql(g.sql);try{let m=g.sql.replace(/\$\d+/g,"?"),_=await this.knex.raw(`EXPLAIN ${m}`,g.bindings);c.setExplain(this.dbType==="postgres"?_.rows:_[0])}catch(m){c.setExplain({error:String(m)})}}}let l=performance.now(),f;f=await i,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=0,h=0;a&&f.length>0&&(p=Number(f[0].__filter_count__||0),f.forEach(g=>delete g.__filter_count__)),u&&f.length>0&&(h=Number(f[0].__total_count__||0),f.forEach(g=>delete g.__total_count__));let y=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:f,...(s.length>0||y)&&{meta:{...u?{totalCount:h}:{},...a?{filterCount:p}:{},...y?{aggregate:y}:{}}},...d!==void 0&&{sql:d}}}async executeAggregate(e,t){let n=nt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={};for(let i of n){let s=rt(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 p=await this.executeRelationCountRecords(e,t,i);ve(o,i,p);continue}let c=this.knex(e.table);if(u.hasRelationFilters){let p=e.metadata?.tables?.get(e.table);await De(this.knex,c,s,e.table,p,this.dbType,h=>e.metadata?.tables?.get(h))}else u.filterTree&&ne(c,u.filterTree,{dbType:this.dbType,rootTable:e.table});let d=`${F(e.table,this.dbType)}.${F(i.field,this.dbType)}`,l=i.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${i.op.toUpperCase()}(${d}) as value`),f=await c.clearSelect().select(l).first();ve(o,i,f?.value??0)}return o}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table),i=o?.relations?.find(l=>l.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 f=new q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});f.hasRelationFilters?await De(this.knex,u,t,e.table,o,this.dbType,p=>e.metadata?.tables?.get(p)):f.filterTree&&ne(u,f.filterTree,{dbType:this.dbType,rootTable:e.table})}let c=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){J(n.condition,s,e.metadata);let f=new q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});f.hasRelationFilters?await De(this.knex,c,n.condition,s,a,this.dbType,p=>e.metadata?.tables?.get(p)):f.filterTree&&ne(c,f.filterTree,{dbType:this.dbType,rootTable:s})}if(i.type==="one-to-many")c.whereIn(`${s}.${i.foreignKeyColumn}`,u);else if(i.type==="many-to-many"){let l=this.resolveManyToManyContract(i,n.field,e.table);c.whereIn(`${s}.id`,this.knex(l.tableName).select(`${l.tableName}.${l.targetColumn}`).whereIn(`${l.tableName}.${l.sourceColumn}`,u))}else(i.type==="many-to-one"||i.type==="one-to-one")&&c.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 d=await c.first();return Number(d?.value??0)}};var In=require("mongodb"),dt=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,Nn.mkdirSync)((0,gi.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(!In.ObjectId)return e;if(typeof e=="string")try{return new In.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=Ve(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:at(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(ce(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"){let l=await new it(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new ut(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}),c}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),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(i,a).toArray(),c=[];for(let d of u){let l=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(l)}return c});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),i=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await i.find(o,s).toArray(),u=0;for(let c of a)await this.mongoService.deleteOne(e.table,c._id)&&u++;return u});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 In.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 ce(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,Nn.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 ce(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[u,c]of Object.entries(t))u==="id"||u==="_id"?o._id=this.safeObjectId(c):o[u]=c;let i=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await i.find(o,s).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}};br();yr();gr();ue();qt();Xe();_n();ge();He();var hi=new Set(["fields","filter","sort","limit","page","deep"]),An=3;function _r(r,e,t,n=0,o=3){if(!e||typeof e!="object")return;if(n>=o)throw new x(`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 c=s.get(a);if(!c)throw new x(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!hi.has(f))throw new x(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...hi].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new x(`'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 x(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(J(u.filter,l,t),Be(u.filter,l,t),Mn(u.filter,0,a,r)),u.sort){Sn(u.sort,l,t);let f=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(p=>p.trim()).filter(Boolean);for(let p of f){let h=p.startsWith("-")?p.slice(1):p;Wo(h,l,t,a,r)}}u.deep&&_r(l,u.deep,t,n+1,o)}}}function Wo(r,e,t,n,o){if(r.includes("."))throw new x(`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 x(`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 x(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${o}')`)}var Ko=new Set(["_and","_or","_not"]);function Mn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[o,i]of Object.entries(r)){if(Ko.has(o)){if(Array.isArray(i))for(let c of i)Mn(c,e,t,n);else i&&typeof i=="object"&&Mn(i,e,t,n);continue}if(o.startsWith("_")||!i||typeof i!="object"||Array.isArray(i)||!Object.keys(i).some(c=>!c.startsWith("_")))continue;let a=e+1;if(a>An)throw new x(`Filter path exceeds max dotted hops of ${An} at '${o}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(i))c.startsWith("_")||(u[c]=i[c]);Mn(u,a,t,n)}}function yi(r,e,t,n){return!r||typeof r!="object"?r:Ht(r,e,t,n)}function Ht(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let i=r.map(s=>Ht(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 l=(Array.isArray(s)?s:[s]).map(f=>Ht(f,e,t,n)).filter(f=>f!=null&&Object.keys(f).length>0);l.length>0&&(o[i]=l);continue}if(i==="_not"){let d=Ht(s,e,t,n);d!=null&&Object.keys(d).length>0&&(o[i]=d);continue}let a=t?.tables?.get(e),u=a?.relations?.find(d=>d.propertyName===i);if(u){if(!n(e,i,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let l=Ht(s,d,t,n);l!=null&&Object.keys(l).length>0&&(o[i]=l);continue}if(a?.columns?.find(d=>d.name===i)){if(!n(e,i,"column"))continue;o[i]=s;continue}o[i]=s}return o}function mi(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 c=(s.startsWith("-")?s.slice(1):s).split("."),d=!0,l=e;for(let f=0;f<c.length;f++){let p=c[f],h=f===c.length-1,y=t?.tables?.get(l);if(!y){d=!1;break}if(h)y.columns?.find(m=>m.name===p)?n(l,p,"column")||(d=!1):y.relations?.find(_=>_.propertyName===p)&&(n(l,p,"relation")||(d=!1));else{let g=y.relations?.find(m=>m.propertyName===p);if(!g){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=g.targetTableName||g.targetTable||l}}d&&i.push(s)}if(i.length!==0)return Array.isArray(r)?i:i.join(",")}jt();He();Bt();Pt();Je();ge();function Uo(r){let e=new dt({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,o=()=>(t||(t=new Qe({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),i=()=>(n||(n=new We({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,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,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,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
52
+ }`}var Br="mongo-fold-text-search.body.txt",qe=null;function eo(){let r=[Un.join(__dirname,Br),Un.join(process.cwd(),"dist","kernel","query","utils",Br)];for(let e of r)try{if(sn.existsSync(e))return sn.readFileSync(e,"utf8")}catch{}return null}function an(){if(qe!==null)return qe;let r=eo();return r?(qe=r,qe):(qe=on(),qe)}var Se=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof Se.ObjectId)return n;if(typeof n=="string")try{return new Se.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 Se.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 Se.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 Se.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.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 Se.ObjectId(n)}catch{return n}return n;default:return n}}var ln="__mongoFoldTextTriples";function to(r){return r==="_id"?"$_id":`$${r}`}function ze(r,e,t,n){let o=to(e),i=r[ln]??[];i.push({ref:o,needle:t,mode:n}),r[ln]=i}function no(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:an(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}function Ve(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 c=W(r,u,a,s.value);switch(s.operator){case"=":o[a]=c;break;case"!=":o[a]={$ne:c};break;case">":o[a]={$gt:c};break;case"<":o[a]={$lt:c};break;case">=":o[a]={$gte:c};break;case"<=":o[a]={$lte:c};break;case"like":o[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let l=d.map(m=>W(r,u,a,m));o[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let p=f.map(m=>W(r,u,a,m));o[a]={$nin:p};break;case"is null":o[a]=null;break;case"is not null":o[a]={$ne:null};break;case"_contains":ze(o,a,String(c),"contains");break;case"_starts_with":ze(o,a,String(c),"starts");break;case"_ends_with":ze(o,a,String(c),"ends");break;case"_between":let h=s.value;if(typeof h=="string"&&(h=h.split(",").map(m=>m.trim())),Array.isArray(h)&&h.length===2){let m=W(r,u,a,h[0]),b=W(r,u,a,h[1]);o[a]={$gte:m,$lte:b}}break;case"_is_null":let y=c===!0||c==="true";o[a]=y?{$eq:null}:{$ne:null};break;case"_is_not_null":let g=c===!0||c==="true";o[a]=g?{$ne:null}:{$eq:null};break}}return no(o),o}function Lr(r,e,t){let o=r?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function cn(r,e,t,n,o,i){switch(o){case"_contains":ze(e,n,String(i),"contains");break;case"_starts_with":ze(e,n,String(i),"starts");break;case"_ends_with":ze(e,n,String(i),"ends");break;case"_eq":e[n]=W(r,t,n,i);break;case"_neq":{let l=W(r,t,n,i);Lr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:l}})):e[n]={$ne:l};break}case"_in":{let l=i;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]);let f=l.map(p=>W(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>W(r,t,n,l));Lr(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 c=i===!0||i==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=i;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=W(r,t,n,d[0]),f=W(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Gn=require("mongodb");function ie(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(ie(o,e))return!0}}else if(t==="_not"){if(ie(n,e))return!0}else if(e.has(t))return!0;return!1}function X(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(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let i=ie(r,o);return{fieldFilters:t,relationFilters:n,hasRelations:i}}jt();Bt();var pn="__mongoFoldTextTriples";function Pe(r,e){if(!r)return{};let t={};return Lt(r,t,e),Ce(t),t}function uo(r,e){if(!r)return{};let t={};return qn(r,t,e),Ce(t),t}function me(r,e,t){if(!e)return{};let n=new se,{node:o}=he(e,t,r,n);return Pe(o,{metadata:r,rootTable:t})}function gn(r,e,t){if(!e)return{};let n=new se,{node:o}=he(e,t,r,n);return uo(o,{metadata:r,rootTable:t})}function Lt(r,e,t){switch(r.kind){case"true":return;case"false":ye(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=r.children.map(i=>{let s={};return Lt(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}ye(e,...o);return}case"or":{let o=r.children.map(s=>{let a={};return Lt(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={};Lt(r.child,n,t),Ce(n);let o=e.$nor;e.$nor=o?[...o,n]:[n];return}case"compare":Qr(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 Qr(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":te(e,n,o(r.value));return;case"neq":{let i=o(r.value);zn(t,n)?ye(e,{[n]:{$ne:null}},{[n]:{$ne:i}}):te(e,n,{$ne:i});return}case"gt":te(e,n,{$gt:o(r.value)});return;case"gte":te(e,n,{$gte:o(r.value)});return;case"lt":te(e,n,{$lt:o(r.value)});return;case"lte":te(e,n,{$lte:o(r.value)});return;case"in":{let i=Ur(r.value).map(o);te(e,n,{$in:i});return}case"not_in":{let i=Ur(r.value).map(o);zn(t,n)?ye(e,{[n]:{$ne:null}},{[n]:{$nin:i}}):te(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&&te(e,n,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":te(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Jn(e,n,String(r.value),"contains");return;case"starts_with":Jn(e,n,String(r.value),"starts");return;case"ends_with":Jn(e,n,String(r.value),"ends");return}}function qn(r,e,t){switch(r.kind){case"true":ye(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let o=r.children.map(s=>{let a={};return qn(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 qn(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}ye(e,...o);return}case"not":Lt(r.child,e,t);return;case"compare":fo(r,e,t);return;case"relation_exists":{te(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function fo(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"){te(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let o={};Qr(r,o,t),Ce(o);let i={$nor:[o]};zn(t,n)?ye(e,i,{[n]:{$ne:null}}):ye(e,i)}function te(r,e,t){r[e]===void 0?r[e]=t:(ye(r,{[e]:r[e]},{[e]:t}),delete r[e])}function ye(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function zn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(o=>o.name===e);return n?n.isNullable!==!1:!0}function Ur(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function po(r){return r==="_id"?"$_id":`$${r}`}function Jn(r,e,t,n){let o=po(e),i=r[pn]??[];i.push({ref:o,needle:t,mode:n}),r[pn]=i}function Ce(r){let e=r[pn];if(delete r[pn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:an(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}async function be(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(c=>c.propertyName));if(!ie(r,i))return me(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>be(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>be(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Hn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=X(r,o),u=[];if(s&&Object.keys(s).length>0){let c=me(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await go(c,d,e,o,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Hn(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return gn(t,r,e);let i=new Set((o.relations||[]).map(c=>c.propertyName));if(!ie(r,i))return gn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Hn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Hn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return be(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=X(r,o),u=[];if(s&&Object.keys(s).length>0){let c=gn(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await yo(c,d,e,o,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function go(r,e,t,n,o,i){let s=(n.relations||[]).find(c=>c.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"?ho(e,s,r,a,u,o,i):s.type==="one-to-many"?zr(e,s,t,a,u,o,i):s.type==="many-to-many"?Vr(e,s,t,a,u,o,i):{}}async function ho(r,e,t,n,o,i,s){let a=Y(e)||t,u=yn(r),c=mn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Yn(u);if(d!==null){let h=bn(d.value);if(d.op==="eq")return{[a]:h};if(d.op==="neq")return{[a]:{$ne:h}};if(d.op==="in")return{[a]:{$in:h}};if(d.op==="not_in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function yo(r,e,t,n,o,i){let s=(n.relations||[]).find(c=>c.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 mo(e,s,r,a,u,o,i);if(s.type==="one-to-many"){let c=await zr(e,s,t,a,u,o,i);return qr(c)}if(s.type==="many-to-many"){let c=await Vr(e,s,t,a,u,o,i);return qr(c)}return{}}async function mo(r,e,t,n,o,i,s){let a=Y(e)||t,u=yn(r),c=mn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Yn(u);if(d!==null){let h=bn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:h}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:h};if(d.op==="in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:h}}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function zr(r,e,t,n,o,i,s){let a=U(e)||t,u=yn(r),c=mn(u);if(c!==null){let f=await Jr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await hn(u,n,o,i,s);if(!d||Object.keys(d).length===0)return{};let l=await Jr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Vr(r,e,t,n,o,i,s){let a=pe(t,e);if(!a)return{};let u=yn(r),c=mn(u);if(c!==null){let y=await Vn(s,a,n,null);return c?y.length===0?{}:{_id:{$nin:y}}:y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let d=Yn(u);if(d!==null){let y=bn(d.value),g=Array.isArray(y)?y:[y],m=await Vn(s,a,n,{_id:{$in:g}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let h=await Vn(s,a,n,{_id:{$in:p}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}async function hn(r,e,t,n,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return ie(r,i)?be(r,e,n,o):me(n,r,e)}async function Jr(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 c=String(u);i.has(c)||(i.add(c),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 Vn(r,e,t,n){let o=null;n&&t&&(o=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._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 c of s){let d=c[e.selfColumn];if(d==null)continue;let l=String(d);a.has(l)||(a.add(l),u.push(d))}return u}function yn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function mn(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 bn(r){if(Array.isArray(r))return r.map(e=>bn(e));if(typeof r!="string")return r;try{return new Gn.ObjectId(r)}catch{return r}}function Yn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Gn.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 Dt(r,e,t,n){let o=await At(r,e,t),i=[],s={},a={};if(n&&typeof n=="object")for(let[p,h]of Object.entries(n))if(typeof h=="object"&&h!==null){let y=Object.keys(h)[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[p]=h:a[p]=h}else s[p]=h;if(Object.keys(s).length>0){let p={};for(let[h,y]of Object.entries(s))if(typeof y=="object"&&y!==null)for(let[g,m]of Object.entries(y))cn(r,p,e,h,g,m);else p[h]=y;Object.keys(p).length>0&&i.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,h]of Object.entries(a))if(!o.relations.some(g=>g.propertyName===p)){let g=c.find(m=>m.propertyName===p);if(g){let m="",b="";if(g.type==="many-to-one"||g.type==="one-to-one")m=Y(g)||g.propertyName,b="_id";else if(g.type==="one-to-many")m="_id",b=U(g)||g.propertyName;else if(g.type==="many-to-many")continue;let w=g.type==="one-to-many"||g.type==="many-to-many";d.push({propertyName:p,targetTable:g.targetTableName,localField:m,foreignField:b,type:w?"many":"one",nestedFields:[]})}}let l=[...o.relations,...d];for(let p of l){let h=a[p.propertyName],y=p.nestedFields&&p.nestedFields.length>0?await Dt(r,p.targetTable,p.nestedFields,h):h?await Dt(r,p.targetTable,["_id"],h):[];p.type==="one"&&y.length>0&&y.push({$limit:1}),i.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:y.length>0?y:void 0}}),p.type==="one"&&(i.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),h&&(Ge(h)||i.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(h=>h.propertyName===p.propertyName));if(o.scalarFields.length>0||o.relations.length>0||f.length>0){let p={_id:1};for(let y of o.scalarFields)p[y]=1;for(let y of l)p[y.propertyName]=1,y.type==="one"&&y.localField&&y.localField!==y.propertyName&&(p[y.localField]=1);if(t.includes("*"))for(let y of f){if(y.type==="one-to-many"||y.type==="many-to-many")continue;y.type==="many-to-many"?p[y.propertyName]={$map:{input:`$${y.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[y.propertyName]={$cond:{if:{$ne:[`$${y.propertyName}`,null]},then:{_id:`$${y.propertyName}`},else:null}}}i.push({$project:p})}return i}async function Hr(r,e,t,n,o){let i=r?.tables?.get(t),s=i?.relations||[],a=i?.columns||[],u=s.filter(d=>!o.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&o.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of o)d[l.propertyName]=1,l.type==="one"&&l.localField&&l.localField!==l.propertyName&&(d[l.localField]=1);for(let l of u){if(l.type==="one-to-many"||l.type==="many-to-many")continue;l.type==="many-to-many"?d[l.propertyName]={$map:{input:`$${l.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[l.propertyName]={$cond:{if:{$ne:[`$${l.propertyName}`,null]},then:{_id:`$${l.propertyName}`},else:null}}}e.push({$project:d})}}function Ge(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ge(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ge(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ge(e));if("_not"in r)return Ge(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||Ge(t)))return!0}return!1}Xe();var Kt=require("mongodb");Xe();_n();async function wn(r,e,t){let n=new Map,o=0;async function i(){for(;o<r.length;){let u=o++,c=r[u];n.set(String(c),await e(c))}}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 le="__sourceId__",Fe="__targetId__",Ze="__enfyra_target__",Wt="__enfyra_top_n_documents__",et=class{constructor(e,t,n,o=new Re){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=o;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/ae)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let o={...t};for(let i of n)o[i]=1;e.push({$project:o})}}appendTopNStages(e,t,n,o,i){e.push({$group:{_id:`$${t}`,[Wt]:{$topN:{sortBy:n,output:"$$ROOT",n:o+i}}}},{$project:{[Wt]:{$slice:[`$${Wt}`,o,i]}}},{$unwind:`$${Wt}`},{$replaceRoot:{newRoot:`$${Wt}`}})}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("-"),i=o?n.slice(1):n;return{field:i==="id"?"_id":i,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(c=>c.trim()).filter(Boolean),i=[{$match:t}],s=new Set;for(let c of o){let l=(c.startsWith("-")?c.slice(1):c).split(".");if(l.length<=1)continue;let f=e;for(let p=0;p<l.length-1;p++){let h=l[p],y=this.normalizeMetadata()?.tables?.get(f);if(!y)break;let g=y.relations?.find(w=>w.propertyName===h);if(!g)break;let m=g.targetTableName||g.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let w=Y(g)||g.propertyName,_=p===0?null:`__sort_${l.slice(0,p).join("_")}`,$=_?`${_}.${w}`:w;i.push({$lookup:{from:m,localField:$,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=m}}let a=this.buildSortFromTokens(n);a&&i.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&i.push({$project:u}),i}toObjectId(e){try{return typeof e=="string"?new Kt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Kt.ObjectId||t instanceof Kt.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 Kt.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}=Ye(e),i={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])o.has(f.propertyName)||o.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(h=>h.name===f);p?i[p.name]=1:t.relations?.find(y=>y.propertyName===f)&&!o.has(f)&&o.set(f,["_id"])}o.forEach((f,p)=>{let h=t.relations?.find(y=>y.propertyName===p);h&&(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse)&&(s||(i[Y(h)||h.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((f,p)=>{let h=t.relations?.find(b=>b.propertyName===p);if(!h)return;let y=h.targetTableName||h.targetTable;if(!y)return;let g,m;h.type==="many-to-one"||h.type==="one-to-one"?Ae(h)?(g="_id",m=U(h)||h.propertyName):(g=Y(h)||h.propertyName,m="_id"):h.type==="one-to-many"?(g="_id",m=U(h)||h.propertyName):h.type==="many-to-many"&&(h.isInverse?(g="_id",m=h.mappedBy):(g=h.propertyName,m="_id")),a.push({relationName:p,type:h.type,targetTable:y,fields:f,isInverse:h.isInverse,fkColumn:h.foreignKeyColumn,mappedBy:h.mappedBy,junctionTableName:h.junctionTableName,junctionSourceColumn:h.junctionSourceColumn,junctionTargetColumn:h.junctionTargetColumn,localField:g,foreignField:m})});let u=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)i[f.newName]===1&&i[f.oldName]!==1&&(i[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?me(this.normalizeMetadata(),o.userFilter,e):null,s=this.buildSortFromTokens(o?.userSort),a=await K(t,c=>{let d={_id:{$in:c}};i&&Object.keys(i).length>0&&Object.assign(d,i);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}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=this.uniqueValues(n.map(m=>this.toObjectId(m))),u=i?.userFilter?me(this.normalizeMetadata(),i.userFilter,e):null,c=i?.userLimit,d=i?.userPage,l=this.hasDottedSort(i?.userSort);if(c!==void 0&&c>0){let m=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${i?.relationName}'`);let b=this.buildStableSort(i?.userSort),w=await K(a,async _=>{let $={[t]:{$in:_}};u&&Object.keys(u).length>0&&Object.assign($,u);let k=[{$match:$}];this.appendTopNStages(k,t,b,m,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let R=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(R,o)});return{docs:w,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:w.length}}}if(s&&(s[t]=1),l){let m=[],b=await wn(a,async w=>{let _={[t]:w};u&&Object.keys(u).length>0&&Object.assign(_,u);let $=this.buildSortAggregatePipeline(e,_,i.userSort);s&&$.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate($).toArray());return this.applyReadFallback(k,o)},je);for(let w of b.values())for(let _ of w)m.push(_);return{docs:m,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/je),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(i?.userSort)||{_id:1},h={projection:s,sort:p},y=await K(a,m=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:m},...u||{}},h).toArray())),g=this.applyReadFallback(y,o);return{docs:g,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let o=n.projection?{projection:n.projection}:void 0,i=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},o).toArray()));return this.applyReadFallback(i,n)}async fetchM2MTopK(e,t,n,o,i,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let m of e)u.set(this.keyOf(m),[]);let c=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,d=!i&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(m=>m.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await K(e,async m=>{if(d){let _=[{$match:{[n.selfColumn]:{$in:m}}}];return this.appendTopNStages(_,n.selfColumn,{[n.otherColumn]:l},s,a),_.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(_).toArray())).map(k=>({sourceId:k[le],targetId:k[Fe]}))}let b=[{$match:{[n.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ze}},{$unwind:`$${Ze}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ze}`,{[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&b.push({$match:i}),this.appendTopNStages(b,le,f,s,a),b.push({$sort:{[le]:1,...f}}),b.push({$project:{_id:0,[le]:1,[Fe]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(_=>({sourceId:_[le],targetId:_[Fe]}))});if(c){let m=new Map;for(let b of p){let w=this.keyOf(b.targetId);m.has(w)||m.set(w,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(m.get(w))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let h=this.uniqueValues(p.map(m=>m.targetId)),y=await this.loadM2MTargets(t.targetTable,h,o),g=new Map(y.map(m=>[this.keyOf(m._id),m]));for(let m of p){let b=g.get(this.keyOf(m.targetId));b&&u.get(this.keyOf(m.sourceId))?.push(b)}return{grouped:u,docs:y,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(h.length>0?this.chunkCount(h):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+y.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,o,i){let s=new Map;for(let y of e)s.set(this.keyOf(y),[]);let a=!i&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await K(e,async y=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:y}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(w=>({sourceId:w[n.selfColumn],targetId:w[n.otherColumn]}));let g=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ze}},{$unwind:`$${Ze}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ze}`,{[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&g.push({$match:i}),g.push({$sort:{[le]:1,...c}},{$project:{_id:0,[le]:1,[Fe]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(g).toArray())).map(b=>({sourceId:b[le],targetId:b[Fe]}))});if(o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1){let y=new Map;for(let g of d){let m=this.keyOf(g.targetId);y.has(m)||y.set(m,{_id:g.targetId}),s.get(this.keyOf(g.sourceId))?.push(y.get(m))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(y=>y.targetId)),p=await this.loadM2MTargets(t.targetTable,f,o),h=new Map(p.map(y=>[this.keyOf(y._id),y]));for(let y of d){let g=h.get(this.keyOf(y.targetId));g&&s.get(this.keyOf(y.sourceId))?.push(g)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}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=pe(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=this.uniqueValues(e.map(k=>k._id)),c=new Map;for(let k of e)c.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?me(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,i,d,k,l)}let p=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1&&!d,h=this.hasDottedSort(t.userSort);if(!h)return this.fetchM2MEdgeBatch(u,t,a,i,d);let y=await K(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(y.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let g=new Set,m=[];for(let k of y){let R=k[a.otherColumn];if(R==null)continue;let I=this.keyOf(R);g.has(I)||(g.add(I),m.push(R))}let b=[],w=new Map;if(p)b=m.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:m}};d&&Object.keys(d).length>0&&Object.assign(k,d);let R;if(h){let I=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);i.projection&&I.push({$project:i.projection}),R=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(I).toArray())}else{let I=this.buildSortFromTokens(t.userSort)||{_id:1},E=this.projectionWithSortFields(i.projection,t.userSort),L={sort:I};E.projection&&(L.projection=E.projection),R=await K(m,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},L).toArray())),t.userSort?this.sortDocsInMemory(R,t.userSort):this.sortDocsByPk(R),this.removeHiddenFields(R,E.hiddenFields)}b=this.applyReadFallback(R,i)}for(let k of b)w.set(this.keyOf(k._id),k);let _=new Map;for(let k of y){let R=this.keyOf(k[a.selfColumn]),I=this.keyOf(k[a.otherColumn]);w.has(I)&&(_.has(I)||_.set(I,[]),_.get(I).push(R))}for(let k of b){let R=_.get(this.keyOf(k._id))||[];for(let I of R)c.get(I)?.push(k)}let $=p||m.length===0?0:this.chunkCount(m);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+$,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length+b.length}}}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 $n(r,e,t,n,o=3,i=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new et(r,a,d);await new ke(l,n,u).execute(e,t,o,i,s)}async function er(r,e,t){let n=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,u=i?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!i&&ie(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&d){let S=await be(e.mongoRawFilter,e.table,i,o);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=Pe(l.filterTree,{metadata:i,rootTable:e.table});Object.keys(S).length>0&&n.push({$match:S})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let S=Ve(i,e.where,e.table,s);n.push({$match:S})}let p=e.plan,y=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let N=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===N)??!1})??!1,g=()=>p?.sortItems?Co(p.sortItems):e.sort?So(e.sort):null,m=p?.sortItems?bo(p.sortItems):[],b=p?.sortItems?_o(p.sortItems):[],w=()=>{!p||m.length===0||wo(n,e.table,p.sortItems,i)},_=()=>{!p||b.length===0||$o(n,e.table,p.sortItems,i)},$=()=>{let S=[...m,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(N=>[N,0]))})};if(!e.mongoFieldsExpanded){w(),_();let S=g();if(S&&n.push({$sort:S}),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 A={};for(let D of e.select)A[D]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let N=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:N,pipeline:n}:{results:Yr(N),pipeline:n}}let{scalarFields:k,relations:R}=e.mongoFieldsExpanded;if(!y){w(),_();let S=g();S&&n.push({$sort:S}),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 I=[];for(let S of R)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let j=await Dt(i,S.targetTable,S.nestedFields??[],A);S.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:j.length>0?j:void 0}})}else if(A){let j=await Dt(i,S.targetTable,["_id"],A);S.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:j.length>0?j:void 0}})}else n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName}});S.type==="one"&&(n.push({$unwind:{path:`$${S.propertyName}`,preserveNullAndEmptyArrays:!0}}),A&&(tt(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else I.push(S);if(y){w(),_();let S=g();S&&n.push({$sort:S}),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 Hr(i,n,e.table,k,[...R]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let E=performance.now(),L=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",E,{table:e.table}),e.mongoCountOnly)return{results:L,pipeline:n};if(I.length>0&&L.length>0){let S=e.deep||{},N=I.map(D=>{let T=i?.tables?.get(e.table)?.relations?.find(V=>V.propertyName===D.propertyName),C=S[D.propertyName],v=C?.fields!=null?Array.isArray(C.fields)?C.fields:String(C.fields).split(",").map(V=>V.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:T?.type,targetTable:D.targetTable,fields:v,isInverse:T?.isInverse,mappedBy:T?.mappedBy,junctionTableName:T?.junctionTableName,localField:D.localField,foreignField:D.foreignField,userFilter:C?.filter,userSort:C?.sort,userLimit:C?.limit!==void 0?Number(C.limit):void 0,userPage:C?.page!==void 0?Number(C.page):void 0,nestedDeep:C?.deep}}),A=To(i);A&&await $n(o,L,N,A,3,0,e.table,i,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Yr(L),pipeline:n}}function tr(r){return`__sort_count_${r.relationName||r.field}`}function nr(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function bo(r){return r.filter(e=>e.function==="count").map(tr)}function _o(r){return r.filter(e=>e.function==="max"||e.function==="min").map(nr)}function wo(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,c=a?.targetTableName||a?.targetTable,d=tr(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=U(a)||u;r.push({$lookup:{from:c,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=pe(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function $o(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,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(g=>g.isPrimary)?.name||(d?.columns?.some(g=>g.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(g=>g.name==="_id")?"_id":f,h=nr(s),y=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let g=U(a)||u;r.push({$lookup:{from:c,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${g}`,"$$localId"]}}},{$group:{_id:null,value:{[y]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}});continue}if(a.type==="many-to-many"){let g=pe(e,a);if(!g)continue;let m=`${h}_junction`;r.push({$lookup:{from:g.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${g.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${g.otherColumn}`}}],as:m}}),r.push({$lookup:{from:c,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[y]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}}),r.push({$project:{[m]:0}})}}}}function To(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 So(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 Co(r){let e={};for(let t of r){let n=t.function==="count"?tr(t):t.function==="max"||t.function==="min"?nr(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function tt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>tt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>tt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>tt(e));if("_not"in r)return tt(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||tt(t)))return!0}return!1}function Yr(r){return r.map(ce)}function Xr(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(ko(i,o,e));return{scalarFields:t,relations:n}}function ko(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),o,i,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ae(n)?(o="_id",i=U(n)||r.propertyName,s=!0):(o=n&&Y(n)||r.propertyName,i="_id",s=!1):r.relationType==="one-to-many"?(o="_id",i=n&&U(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=Zr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:u}}function Zr(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=Zr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let o of n)e.push(`${t.propertyName}.${o}`)}return e}He();Bt();jt();function Tn(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(l=>l.name==="_id"&&l.isPrimary),a=i.columns?.some(l=>l.name==="id"),u=s&&!a?"_id":"id",c=new Map,d=[];for(let l of r){let f=l==="id"?u:l;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),h=f.substring(0,p),y=f.substring(p+1);if(!i.relations?.some(m=>m.propertyName===h))continue;c.has(h)||c.set(h,[]),c.get(h).push(y)}else if(i.relations?.some(h=>h.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!i.columns?.some(y=>y.name===f))continue;d.push(f)}}if(d.includes("*")){o.nodes.push({kind:"wildcard"});for(let l of i.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)o.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=i.relations?.find(g=>g.propertyName===l);if(!p)continue;let h=p.targetTableName||p.targetTable,y={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:h,children:ei(f,h,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let g=n.registerWithParent(e,l,t,"left",null,"data");y.joinId=g}o.nodes.push(y)}return o}function ei(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let o=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),i=n.columns?.some(d=>d.name==="id"),s=o&&!i?"_id":"id",a=new Map,u=[];for(let d of r){let l=d==="id"?s:d;if(l==="*")u.push("*");else if(l.includes(".")){let f=l.indexOf("."),p=l.substring(0,f),h=l.substring(f+1);if(!n.relations?.some(g=>g.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(h)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(h=>h.name===l))continue;u.push(l)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,l]of a.entries()){let f=n.relations?.find(h=>h.propertyName===d);if(!f)continue;let p=f.targetTableName||f.targetTable;c.push({kind:"relation",propertyName:d,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:p,children:ei(l,p,t)})}return c}ge();ge();var Ro=new Set(["_and","_or","_not"]);function ti(r,e){return r?.tables?.get(e)??null}function Fo(r,e,t){return ti(r,e)?.columns?.find(n=>n.name===t)}function rr(r,e,t){return ti(r,e)?.relations?.find(n=>n.propertyName===t)}function xo(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 ir(r,e,t,n){if(Fo(r,e,t)?.isEncrypted===!0)throw new x(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Be(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Be(n,e,t);return}for(let[n,o]of Object.entries(r)){if(Ro.has(n)){Be(o,e,t);continue}if(n.startsWith("_"))continue;let i=rr(t,e,n);if(i){let s=i.targetTableName||i.targetTable;s&&Be(o,s,t);continue}ir(t,e,n,"filter")}}}function Sn(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=xo(i);if(s){if(s.functionName==="count")continue;let c=rr(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&ir(t,d,s.fieldName,"sort");continue}let a=i.split("."),u=e;for(let c=0;c<a.length;c++){let d=a[c];if(c===a.length-1){ir(t,u,d,"sort");break}let f=rr(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var q=class{plan(e){let{tableName:t,fields:n,filter:o,sort:i,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new se,p=this.parseFields(n),h=null;p&&l&&(h=Tn(p,t,c,f));let y=!1,g=null;if(o&&l){Be(o,t,c);let S=he(o,t,c,f);g=S.node,y=S.hasRelationFilters}let m=this.parseSort(i);l&&Sn(m,t,c);let b=[],w=!1;for(let S of m){let N=S.startsWith("-"),A=N?S.substring(1):S,D=N?"desc":"asc";if(l){let j=this.parseRelationAggregateSort(t,l,A,c);if(j){b.push({joinId:null,field:A,direction:D,fullPath:A,function:j.functionName,relationName:j.relationName,aggregateField:j.aggregateField,relationMeta:j.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:D,fullPath:A})}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,R=this.parseMeta(u),I=R.includes("totalCount")||R.includes("*"),E=R.includes("filterCount")||R.includes("*"),L=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:o??null,joins:L,sortItems:b,limit:_,offset:k,needsTotalCount:I,needsFilterCount:E,hasRelationFilters:y,hasRelationSort:w,filterTree:g,fieldTree:h}}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 x(`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 x(`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 x(`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 g=a;if(!g||g.includes("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===g);if(!m)throw new x(`Sort relation '${g}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new x(`Sort function '_count(${g})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:g,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new x(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(g=>g.propertyName===c);if(!l)throw new x(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new x(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=o?.tables?.get(f);if(!p)throw new x(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let h=p.columns?.find(g=>g.name===d),y=d==="id"&&p.columns?.some(g=>g.name==="_id");if(!h&&!y)throw new x(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(h?.isEncrypted===!0)throw new x(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}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),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=o.registerWithParent(t,a,n,"left",i,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,o,l)}};ge();Pt();var vo=new Set(["count","sum","avg","min","max","countRecords"]),Io=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),No=new Set(["_and","_or","_not"]);function xe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function P(r,e){let t=r.replace(/^aggregate\./,"");throw new x(e,{path:r,aggregate:{[t]:e}})}function Mo(r){return typeof r!="string"?!1:Io.has(r.toLowerCase())}function ni(r){return Object.keys(r).length===0}function Eo(r,e,t){return r===!0?{}:(r==null&&P(t,`aggregate.${e} condition must be true or an object`),xe(r)||P(t,`aggregate.${e} condition must be true or an object`),r)}function Ao(r,e,t){let n=r?.tables?.get(e);return n||P(t,`Table "${e}" metadata is not available`),n}function ri(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&P(e,"aggregate.countRecords relation target is not available"),t}function Cn(r,e,t,n){let o=Ao(t,e,n);for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){Array.isArray(s)||P(n,`aggregate.countRecords ${i} condition must be an array`);for(let d of s)xe(d)||P(n,`aggregate.countRecords ${i} items must be objects`),Cn(d,e,t,n);continue}if(i==="_not"){xe(s)||P(n,"aggregate.countRecords _not condition must be an object"),Cn(s,e,t,n);continue}(i.startsWith("_")||No.has(i))&&P(n,`Unsupported aggregate.countRecords condition key "${i}"`);let a=o.columns?.find(d=>d.name===i),u=o.relations?.find(d=>d.propertyName===i);if(!a&&!u&&P(n,`Unknown aggregate.countRecords field or relation "${i}" on table "${e}"`),xe(s)||P(n,`aggregate.countRecords condition for "${i}" must be an object`),a){for(let d of Object.keys(s))oe.has(d)||P(n,`aggregate.countRecords condition for "${i}" only supports field operators`);continue}let c=ri(u,n);Cn(s,c,t,n)}}function or(r){return xe(r)&&Object.keys(r).length>0}function nt(r,e,t){if(!or(r))return[];xe(r)||P("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||P("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")&&P("aggregate","aggregate field name must be a non-empty string"),xe(s)||P(a,"aggregate field config must be an object");let u=i,c=a,d=n.columns?.find(p=>p.name===i),l=n.relations?.find(p=>p.propertyName===i);!d&&!l&&P(c,`Unknown aggregate field or relation "${i}" on table "${e}"`);let f=Object.entries(s).filter(([p])=>p!=="as");f.length===0&&P(c,"aggregate field must define at least one operation");for(let[p,h]of f){vo.has(p)||P(c,`Unsupported aggregate operation "${p}"`);let y=Eo(h,p,c);if(l&&p!=="countRecords"&&P(c,`aggregate.${p} is not supported on relation "${i}"; use countRecords`),d&&p==="countRecords"&&P(c,`aggregate.countRecords requires a relation, but "${i}" is a field`),d&&(p==="sum"||p==="avg")&&!Mo(d.type)&&P(c,`aggregate.${p} requires a numeric field, but "${i}" is "${d.type}"`),d)for(let g of Object.keys(y))oe.has(g)||P(c,`aggregate.${p} condition for "${i}" only supports field operators`);if(l&&p==="countRecords"){let g=ri(l,c);Cn(y,g,t,c)}o.push({field:i,outputKey:u,path:c,op:p,condition:y})}}return o}function rt(r,e){let t=[];return xe(r)&&!ni(r)&&t.push(r),ni(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 it=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 f=new q;e={...e,plan:f.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,debugTrace:e.debugTrace};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(f=>f.trim()))),e.filter&&(J(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let f=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(p=>p.trim());n.sort=f.map(p=>{let h=p.trim();return h.startsWith("-")?{field:h.substring(1),direction:"desc"}:{field:h,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let f=typeof e.page=="string"?parseInt(e.page,10):e.page,p=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(f-1)*p,n.limit=p}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(f=>f.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(f=>f.propertyName)),c=!!n.mongoRawFilter&&ie(n.mongoRawFilter,u);if((o.includes("filterCount")||o.includes("*"))&&!c){let f=this.mongoService.collection(e.tableName),p=e.plan?.filterTree?Pe(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await f.countDocuments(p)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let f=this.lastBuiltPipeline??[],p;try{p=await this.db.collection(e.tableName).aggregate(f).explain()}catch(h){p={error:String(h)}}return{pipeline:f,explain:p}}if(c&&(o.includes("filterCount")||o.includes("*"))){let f={...n,mongoCountOnly:!0},p=await this.selectLegacy(f);s=p.length>0?p[0].count:0}let l=await this.executeAggregate(n,e.filter);return{data:d,...(o.length>0||l)&&{meta:{...o.includes("totalCount")||o.includes("*")?{totalCount:i}:{},...o.includes("filterCount")||o.includes("*")?{filterCount:s}:{},...l?{aggregate:l}:{}}}}}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 c=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&c?.fieldTree){if(e.mongoFieldsExpanded=Xr(c.fieldTree,this.metadata),n){let l=await At(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...l.relations.filter(p=>!f.has(p.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await At(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let l=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:l.scalarFields},t=l.hiddenFields}}e.where&&(e.where=e.where.map(c=>c.field.includes(".")?c:{...c,field:`${e.table}.${c.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(ce);let{results:a,pipeline:u}=await er(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 er(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=nt(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=rt(t,s);J(a,e.table,e.metadata);let c=new q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let f=await this.executeRelationCountRecords(e,t,s);ve(o,s,f);continue}let d=c.hasRelationFilters?await be(a,e.table,e.metadata,this.db):c.filterTree?Pe(c.filterTree,{metadata:e.metadata,rootTable:e.table}):{},l;if(s.op==="count")l=await i.countDocuments(d);else{let[{value:f}={value:null}]=await i.aggregate([{$match:d},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();l=f??0}ve(o,s,l)}return o}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table)?.relations?.find(d=>d.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),c=await this.resolveMatchFilter(s,n.condition,e.metadata);if(i.type==="one-to-many"){let l=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(f=>f!=null);return l.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{[i.foreignKeyColumn]:{$in:l}}]})}if(i.type==="many-to-many"){let d=pe(e.table,i);if(!d)return 0;let f=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(y=>y!=null);if(f.length===0)return 0;let h=(await this.db.collection(d.junctionName).find({[d.selfColumn]:{$in:f}},{projection:{[d.otherColumn]:1}}).toArray()).map(y=>y[d.otherColumn]).filter(y=>y!=null);return h.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{_id:{$in:h}}]})}if(i.type==="many-to-one"||i.type==="one-to-one"){let d=i.foreignKeyColumn||`${n.field}Id`,f=(await this.db.collection(e.table).find(u,{projection:{[d]:1}}).toArray()).map(p=>p[d]).filter(p=>p!=null);return f.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{_id:{$in:f}}]})}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 be(t,e,n,this.db):i.filterTree?Pe(i.filterTree,{metadata:n,rootTable:e}):{}}};var kn=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}};ge();ue();var Oo=["_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(Oo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&_e(r[e]))return!0;return!1}var ii=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Po(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Rn(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 jo(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)||Rn(r,t,o),e}function oi(r,e,t,n,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,u=Ie(a,i??"postgres"),c=Rn(e,o,s),d=jo(e,n,o,i,s);switch(t){case"_eq":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let l=n;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]),c&&i==="postgres"&&l.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[l]):r.whereIn(a,l);break;case"_not_in":case"_nin":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),c&&i==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);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,Po(t),n)}}function Bo(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 ot(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(){ot(this,s,t,"and",o,i)}):r.orWhere(function(){ot(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e))if(Bo(s,t,i)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){ot(this,u,t,"and",o,i)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){ot(this,u,t,"and",o,i)})});continue}if(s==="_not"){r.whereNot(function(){ot(this,a,t,"and",o,i)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>ii.includes(c)))for(let[c,d]of Object.entries(a))ii.includes(c)&&(n==="and"?r.where(function(){oi(this,s,c,d,t,o,i)}):r.orWhere(function(){oi(this,s,c,d,t,o,i)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Ie(c,o??"postgres");Rn(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(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(c,"=",a):r.orWhere(c,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=Ie(u,o??"postgres");Rn(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(`${c} = ?::uuid`,[a]):r.orWhereRaw(`${c} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function de(r,e,t,n,o){return!e||typeof e!="object"||ot(r,e,t,"and",n,o),r}ue();function lr(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 si(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 st(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function cr(r,e,t,n,o,i){let s=[];for(let[a,u]of Object.entries(i)){let c=await Ut(r,e,a,u,t,n,o);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=lr(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let h=st(p._is_null),y=st(p._is_not_null);if(h===!0)s.push(`${l} IS NULL`);else if(h===!1)s.push(`${l} IS NOT NULL`);else if(y===!0)s.push(`${l} IS NOT NULL`);else if(y===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let g=Ne(p._eq,n);s.push(`${l} = ${g}`)}else if(p._neq!==void 0){let g=Ne(p._neq,n);s.push(`${l} != ${g}`)}else if(p._in!==void 0){let m=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Ne(b,n)).join(", ");s.push(`${l} IN (${m})`)}else if(p._not_in!==void 0||p._nin!==void 0){let g=p._not_in??p._nin,b=(Array.isArray(g)?g:[g]).map(w=>Ne(w,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let g=Ne(p._gt,n);s.push(`${l} > ${g}`)}else if(p._gte!==void 0){let g=Ne(p._gte,n);s.push(`${l} >= ${g}`)}else if(p._lt!==void 0){let g=Ne(p._lt,n);s.push(`${l} < ${g}`)}else if(p._lte!==void 0){let g=Ne(p._lte,n);s.push(`${l} <= ${g}`)}}}}}return s}function ur(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 sr(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 c of a._and)if(ur(c)){let d=e(t).select(`${t}.id`);await Le(e,d,c,t,n,o,i),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=X(c,n),f=await cr(e,t,n,o,i,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(ur(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:c}=X(a,n),d=await cr(e,t,n,o,i,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ai(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&&de(this,i.fieldFilters,t,o,n);for(let s of i.subqueries)this.whereRaw(s)})}function ar(r,e,t,n,o){let i=!0;for(let s of e){let a=function(){for(let u of s)ai(this,u,t,n,o)};i?(r.where(a),i=!1):r.orWhere(a)}}function Fn(r,e,t,n,o,i,s){let a=si(e,o),u=si(n,i),c=`${F(r,s)}.${F(e,s)}`,d=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Ut(r,e,t,n,o,i,s){let a=o.relations.find(f=>f.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 c=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 f=Object.keys(n||{});if(f.length===1&&f[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(h=>c.has(h)))return null}let d=s?await s(u):null,l;switch(a.type){case"one-to-many":l=r(u).select(r.raw("1")).whereRaw(Fn(u,a.foreignKeyColumn,e,"id",d,o,i));break;case"many-to-many":let f=s?await s(a.junctionTableName):null;l=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(Fn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,i))).whereRaw(Fn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,o,i));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(Fn(u,"id",e,a.foreignKeyColumn,d,o,i));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Le(r,l,n,u,d,i,s):l=de(l,n,u,i,d||void 0):l=de(l,n,u,i),l.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 c of t._and)if(c._or&&Array.isArray(c._or)&&c._or.length>0){let d=await sr(c._or,r,n,o,i,s);e.where(function(){ar(this,d,n,o,i)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Le(r,e,d,n,o,i,s);else await Le(r,e,c,n,o,i,s);return}if(t._or&&Array.isArray(t._or)){let c=await sr(t._or,r,n,o,i,s);e.where(function(){ar(this,c,n,o,i)});return}if(t._not){let c=t._not;if(c._and&&Array.isArray(c._and)&&c._and.length>0){let f=[];for(let p of c._and)if(ur(p)){let h=r(n).select(`${n}.id`);await Le(r,h,p,n,o,i,s),f.push({idSubquery:h})}else{let{fieldFilters:h,relationFilters:y}=X(p,o),g=await cr(r,n,o,i,s,y);f.push({fieldFilters:h,subqueries:g})}e.whereNot(function(){for(let p of f)ai(this,p,n,o,i)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await sr(c._or,r,n,o,i,s);e.whereNot(function(){ar(this,f,n,o,i)});return}let{fieldFilters:d,relationFilters:l}=X(c,o);e.whereNot(function(){Object.keys(d).length>0&&de(this,d,n,i,o)});for(let[f,p]of Object.entries(l)){let h=await Ut(r,n,f,p,o,i,s);if(h===null){let y=o.relations.find(g=>g.propertyName===f);if(y&&y.foreignKeyColumn){let g=lr(n,y.foreignKeyColumn,i),b=p.id;if(b&&typeof b=="object"){let w=st(b._is_null),_=st(b._is_not_null);if(w===!0)e.whereRaw(`${g} IS NOT NULL`);else if(w===!1)e.whereRaw(`${g} IS NULL`);else if(_===!0)e.whereRaw(`${g} IS NULL`);else if(_===!1)e.whereRaw(`${g} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${g} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${g} = ?`,[b._neq]);else if(b._in!==void 0){let $=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${g} 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(`${g} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${h})`)}return}let{fieldFilters:a,relationFilters:u}=X(t,o);Object.keys(a).length>0&&de(e,a,n,i,o);for(let[c,d]of Object.entries(u)){let l=await Ut(r,n,c,d,o,i,s);if(l===null){let f=o.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=lr(n,f.foreignKeyColumn,i),y=d.id;if(y&&typeof y=="object"){let g=st(y._is_null),m=st(y._is_not_null);if(g===!0)e.whereRaw(`${p} IS NULL`);else if(g===!1)e.whereRaw(`${p} IS NOT NULL`);else if(m===!0)e.whereRaw(`${p} IS NOT NULL`);else if(m===!1)e.whereRaw(`${p} IS NULL`);else if(y._eq!==void 0)e.whereRaw(`${p} = ?`,[y._eq]);else if(y._neq!==void 0)e.whereRaw(`${p} != ?`,[y._neq]);else if(y._in!==void 0){let b=Array.isArray(y._in)?y._in:[y._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(y._not_in!==void 0||y._nin!==void 0){let b=y._not_in??y._nin,w=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${w.map(()=>"?").join(", ")})`,w)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function De(r,e,t,n,o,i,s){await Le(r,e,t,n,o,i,s)}ue();fr();He();ue();function at(r,e,t,n,o){for(let i of e){let s=i.field.split("."),a=t||s[0],u=s[s.length-1],c=Qt(n,a,u,i.value);switch(i.operator){case"=":r=r.where(i.field,"=",c);break;case"!=":r=r.where(i.field,"!=",c);break;case">":r=r.where(i.field,">",c);break;case"<":r=r.where(i.field,"<",c);break;case">=":r=r.where(i.field,">=",c);break;case"<=":r=r.where(i.field,"<=",c);break;case"like":r=r.where(i.field,"like",c);break;case"in":let d=Array.isArray(i.value)?i.value.map(y=>Qt(n,a,u,y)):[c];r=r.whereIn(i.field,d);break;case"not in":let l=Array.isArray(i.value)?i.value.map(y=>Qt(n,a,u,y)):[c];r=r.whereNotIn(i.field,l);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 f=i.value;if(typeof f=="string"&&(f=f.split(",").map(y=>y.trim())),Array.isArray(f)&&f.length===2){let y=Qt(n,a,u,f[0]),g=Qt(n,a,u,f[1]);r=r.whereBetween(i.field,[y,g])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(i.field):r.whereNotNull(i.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(i.field):r.whereNull(i.field);break}}return r}function Jt(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(c=>{let d=Jt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&o.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Jt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&o.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Jt(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,c]of Object.entries(a)){let d=`${F(e,n)}.${F(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=i.columns?.find(y=>y.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")o.push(`${d} = ${l}`);else if(u==="_neq")o.push(`${d} != ${l}`);else if(u==="_gt")o.push(`${d} > ${l}`);else if(u==="_gte")o.push(`${d} >= ${l}`);else if(u==="_lt")o.push(`${d} < ${l}`);else if(u==="_lte")o.push(`${d} <= ${l}`);else if(u==="_is_null")o.push(`${d} IS NULL`);else if(u==="_is_not_null")o.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");o.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");o.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):o.push(`lower(${d}) LIKE '%${f.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(c)&&c.length===2){let f=typeof c[0]=="string"?`'${c[0].replace(/'/g,"''")}'`:String(c[0]),p=typeof c[1]=="string"?`'${c[1].replace(/'/g,"''")}'`:String(c[1]);o.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${F(e,n)}.${F(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),o.push(`${u} = ${c}`)}return o}function ci(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 Qt(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}}ue();qt();Je();async function di(r,e,t,n,o,i,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(gr(),ui)),u=await a(e,t,n,o,i,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function hr(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 fi(r,e,t,n,o){let i=r.targetTableName||r.targetTable;if(!i)return null;let s=r.foreignKeyColumn||G(r.propertyName);if(!s)return null;let a=l=>F(l,o),u=n?.tables?.get(i),d=(u?Z(u):null)?.name||"id";return`(SELECT ${a(i)}.${a(e)} FROM ${a(i)} WHERE ${a(i)}.${a(d)} = ${a(t)}.${a(s)})`}qt();var ut=class r{constructor(e,t,n,o){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=o;this.logger=new kn(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 T=new q;e={...e,plan:T.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,c=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!u&&!a&&c){o&&o.setQueryPath("simple");let T=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),T}let l={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map(T=>T.trim())));let f=e.filter;if(e.filter&&!_e(e.filter)){l.where=[];for(let[T,C]of Object.entries(e.filter))if(typeof C=="object"&&C!==null)for(let[v,V]of Object.entries(C)){let M;if(v==="_eq")M="=";else if(v==="_neq")M="!=";else if(v==="_in")M="in";else if(v==="_not_in"||v==="_nin")M="not in";else if(v==="_gt")M=">";else if(v==="_gte")M=">=";else if(v==="_lt")M="<";else if(v==="_lte")M="<=";else if(v==="_contains")M="_contains";else if(v==="_starts_with")M="_starts_with";else if(v==="_ends_with")M="_ends_with";else if(v==="_between")M="_between";else if(v==="_is_null")M="_is_null";else if(v==="_is_not_null")M="_is_not_null";else if(v==="_like")M="like";else if(v==="_ilike")M="ilike";else continue;l.where.push({field:T,operator:M,value:V})}else l.where.push({field:T,operator:"=",value:C})}if(e.sort){let T=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(C=>C.trim());l.sort=T.map(C=>{let v=C.trim();return v.startsWith("-")?{field:v.substring(1),direction:"desc"}:{field:v,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,h=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,y=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,g=y===void 0||Number.isNaN(y)?void 0:y;g&&h!==void 0?(l.offset=(g-1)*h,l.limit=h):h!==void 0&&(l.limit=h);let m=e.plan?.sortItems??(l.sort??[]).map(T=>({joinId:null,field:T.field,direction:T.direction,fullPath:T.field})),b=[],w=[];for(let T of m){if(T.function==="count"){let C={sql:this.buildRelationCountSortSubquery(l.table,T),direction:T.direction};w.push(C);continue}if(T.function==="max"||T.function==="min"){let C={sql:this.buildRelationAggregateSortSubquery(l.table,T),direction:T.direction};w.push(C);continue}if(T.joinId===null){if(T.field.includes(".")&&!e.plan){let v=T.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(z=>z.propertyName===v))continue}let C={field:T.field.includes(".")?T.field:`${l.table}.${T.field}`,direction:T.direction};b.push(C),w.push(C)}else{let C=e.plan?.joins.find(v=>v.id===T.joinId);if(C&&(C.relationType==="many-to-one"||C.relationType==="one-to-one")){let v=fi(C.relationMeta,T.field,l.table,this.metadata,this.dbType);if(v){let V={sql:v,direction:T.direction};w.push(V)}}}}let _=[];if(l.fields&&l.fields.length>0||u||a){let T=hr(this.metadata),C=l.fields&&l.fields.length>0?l.fields:["*"],v=await di(this.knex,l.table,C,T,this.dbType,this.maxQueryDepth,e.deep);v.select.length>0&&(l.select=[...l.select||[],...v.select]),_=v.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map(T=>T.field.includes(".")?T:{...T,field:`${l.table}.${T.field}`})),l.sort=b;let $=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(T=>T.trim()).filter(Boolean),R=k.includes("filterCount")||k.includes("*"),I=k.includes("totalCount")||k.includes("*");if(l.select){let T=l.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(T)}if(R&&$.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),I){let T=F(l.table,this.dbType);$.select(this.knex.raw(`(SELECT COUNT(*) FROM ${T}) as __total_count__`))}let E=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(_e(f)||Object.keys(f).length>0)){let T=this.metadata?.tables?.get(l.table);(!E&&T&&T.relations&&T.relations.length>0?X(f,T).hasRelations:!1)?await De(this.knex,$,f,l.table,T,this.dbType,v=>this.metadata?.tables?.get(v)):e.plan?.filterTree?ne($,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),$=de($,f,l.table,this.dbType,T))}else l.where&&l.where.length>0&&($=at($,l.where,l.table,this.metadata,this.dbType));for(let T of w)if(T.field){let C=T.field.includes(".")?T.field:`${l.table}.${T.field}`;$=$.orderBy(C,T.direction)}else T.sql&&($=$.orderByRaw(`${T.sql} ${T.direction.toUpperCase()}`));l.groupBy&&($=$.groupBy(l.groupBy)),l.offset&&($=$.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&($=$.limit(l.limit));let L=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:$.toSQL().toNative()});let S;if(e.debugMode&&(S=$.toSQL().toNative().sql),e.debugMode&&o){let T=$.toSQL().toNative();o.setSql(T.sql);try{let C=T.sql.replace(/\$\d+/g,"?"),v=await this.knex.raw(`EXPLAIN ${C}`,T.bindings);o.setExplain(this.dbType==="postgres"?v.rows:v[0])}catch(C){o.setExplain({error:String(C)})}}let N,A=performance.now();N=await $,o&&o.dur("db_execute",A,{table:e.tableName});let D=0;if(R&&N.length>0&&(D=Number(N[0].__filter_count__||0),N.forEach(T=>{delete T.__filter_count__})),I&&N.length>0&&N[0].__total_count__!==void 0&&(L=Number(N[0].__total_count__||0),N.forEach(T=>{delete T.__total_count__})),_&&_.length>0&&N.length>0){let T=hr(this.metadata);if(T){let{executeBatchFetches:C}=await Promise.resolve().then(()=>(br(),pi));await C(this.knex,N,_,T,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,o)}}if(this.knexService){let T=performance.now();N=await this.knexService.parseResult(N,l.table),o&&o.dur("db_parseResult",T,{table:e.tableName})}else{let T=(C,v)=>{if(!C||!this.metadata)return C;let V=this.metadata.tables?.get(v);if(!V)return C;if(Array.isArray(C))return C.map(z=>T(z,v));if(typeof C!="object"||Buffer.isBuffer(C))return C;let M={...C};for(let z of V.columns)if(z.type==="simple-json"&&M[z.name]&&typeof M[z.name]=="string")try{M[z.name]=JSON.parse(M[z.name])}catch{}for(let[z,ee]of Object.entries(M))if(ee&&typeof ee=="object"&&!Array.isArray(ee)&&!Buffer.isBuffer(ee)){let An=ee;if(An.id!==void 0||An.createdAt!==void 0){let ft=V.relations?.find(pt=>pt.propertyName===z);ft&&(M[z]=T(ee,ft.targetTableName))}}else if(Array.isArray(ee)&&ee.length>0&&typeof ee[0]=="object"&&ee[0].id!==void 0){let ft=V.relations?.find(pt=>pt.propertyName===z);ft&&(M[z]=ee.map(pt=>T(pt,ft.targetTableName)))}return M};N=T(N,l.table)}o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName}));let j=await this.executeAggregate(l,f);return{data:N,...(k.length>0||j)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:L}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:D}:{},...j?{aggregate:j}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=Z(s)?.name||"id",u=F(e,this.dbType),c=F(a,this.dbType);if(!n||!i)throw new x(`Sort relation '${o}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new x(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let l=F(i,this.dbType),f=F(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,o,e),l=F(d.tableName,this.dbType),f=F(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new x(`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),c=Z(a)?.name||"id",d=Z(u)?.name||"id",l=F(e,this.dbType),f=F(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!i)throw new x(`Sort function '${t.field}' is not supported on '${e}'.`);let h=F(s,this.dbType),y=F(i,this.dbType);if(n.type==="one-to-many"){let g=n.foreignKeyColumn||n.mappedBy;if(!g)throw new x(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let m=F(g,this.dbType);return`(SELECT ${p}(${h}.${y}) FROM ${h} WHERE ${h}.${m} = ${l}.${f})`}if(n.type==="many-to-many"){let g=this.resolveManyToManyContract(n,o,e),m=F(g.tableName,this.dbType),b=F(g.sourceColumn,this.dbType),w=F(g.targetColumn,this.dbType),_=F(d,this.dbType);return`(SELECT ${p}(${h}.${y}) FROM ${m} JOIN ${h} ON ${h}.${_} = ${m}.${w} WHERE ${m}.${b} = ${l}.${f})`}throw new x(`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 x(`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&&ne(i,t.filterTree,{dbType:this.dbType,rootTable:n});for(let g of t.sortItems){let m=g.field.includes(".")?g.field:`${n}.${g.field}`;i=i.orderBy(m,g.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(g=>g.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 g=F(n,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${g}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let g=i.toSQL().toNative();if(d=g.sql,c){c.setSql(g.sql);try{let m=g.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,g.bindings);c.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){c.setExplain({error:String(m)})}}}let l=performance.now(),f;f=await i,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=0,h=0;a&&f.length>0&&(p=Number(f[0].__filter_count__||0),f.forEach(g=>delete g.__filter_count__)),u&&f.length>0&&(h=Number(f[0].__total_count__||0),f.forEach(g=>delete g.__total_count__));let y=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:f,...(s.length>0||y)&&{meta:{...u?{totalCount:h}:{},...a?{filterCount:p}:{},...y?{aggregate:y}:{}}},...d!==void 0&&{sql:d}}}async executeAggregate(e,t){let n=nt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={};for(let i of n){let s=rt(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 p=await this.executeRelationCountRecords(e,t,i);ve(o,i,p);continue}let c=this.knex(e.table);if(u.hasRelationFilters){let p=e.metadata?.tables?.get(e.table);await De(this.knex,c,s,e.table,p,this.dbType,h=>e.metadata?.tables?.get(h))}else u.filterTree&&ne(c,u.filterTree,{dbType:this.dbType,rootTable:e.table});let d=`${F(e.table,this.dbType)}.${F(i.field,this.dbType)}`,l=i.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${i.op.toUpperCase()}(${d}) as value`),f=await c.clearSelect().select(l).first();ve(o,i,f?.value??0)}return o}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table),i=o?.relations?.find(l=>l.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 f=new q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});f.hasRelationFilters?await De(this.knex,u,t,e.table,o,this.dbType,p=>e.metadata?.tables?.get(p)):f.filterTree&&ne(u,f.filterTree,{dbType:this.dbType,rootTable:e.table})}let c=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){J(n.condition,s,e.metadata);let f=new q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});f.hasRelationFilters?await De(this.knex,c,n.condition,s,a,this.dbType,p=>e.metadata?.tables?.get(p)):f.filterTree&&ne(c,f.filterTree,{dbType:this.dbType,rootTable:s})}if(i.type==="one-to-many")c.whereIn(`${s}.${i.foreignKeyColumn}`,u);else if(i.type==="many-to-many"){let l=this.resolveManyToManyContract(i,n.field,e.table);c.whereIn(`${s}.id`,this.knex(l.tableName).select(`${l.tableName}.${l.targetColumn}`).whereIn(`${l.tableName}.${l.sourceColumn}`,u))}else(i.type==="many-to-one"||i.type==="one-to-one")&&c.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 d=await c.first();return Number(d?.value??0)}};var In=require("mongodb"),dt=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,Nn.mkdirSync)((0,gi.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(!In.ObjectId)return e;if(typeof e=="string")try{return new In.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=Ve(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:at(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(ce(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"){let l=await new it(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new ut(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}),c}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),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(i,a).toArray(),c=[];for(let d of u){let l=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(l)}return c});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),i=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await i.find(o,s).toArray(),u=0;for(let c of a)await this.mongoService.deleteOne(e.table,c._id)&&u++;return u});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 In.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 ce(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,Nn.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 ce(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[u,c]of Object.entries(t))u==="id"||u==="_id"?o._id=this.safeObjectId(c):o[u]=c;let i=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await i.find(o,s).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}};br();yr();gr();ue();qt();Xe();_n();ge();He();var hi=new Set(["fields","filter","sort","limit","page","deep"]),En=3;function _r(r,e,t,n=0,o=3){if(!e||typeof e!="object")return;if(n>=o)throw new x(`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 c=s.get(a);if(!c)throw new x(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!hi.has(f))throw new x(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...hi].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new x(`'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 x(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(J(u.filter,l,t),Be(u.filter,l,t),Mn(u.filter,0,a,r)),u.sort){Sn(u.sort,l,t);let f=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(p=>p.trim()).filter(Boolean);for(let p of f){let h=p.startsWith("-")?p.slice(1):p;Ko(h,l,t,a,r)}}u.deep&&_r(l,u.deep,t,n+1,o)}}}function Ko(r,e,t,n,o){if(r.includes("."))throw new x(`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 x(`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 x(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${o}')`)}var Uo=new Set(["_and","_or","_not"]);function Mn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[o,i]of Object.entries(r)){if(Uo.has(o)){if(Array.isArray(i))for(let c of i)Mn(c,e,t,n);else i&&typeof i=="object"&&Mn(i,e,t,n);continue}if(o.startsWith("_")||!i||typeof i!="object"||Array.isArray(i)||!Object.keys(i).some(c=>!c.startsWith("_")))continue;let a=e+1;if(a>En)throw new x(`Filter path exceeds max dotted hops of ${En} at '${o}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(i))c.startsWith("_")||(u[c]=i[c]);Mn(u,a,t,n)}}function yi(r,e,t,n){return!r||typeof r!="object"?r:Ht(r,e,t,n)}function Ht(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let i=r.map(s=>Ht(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 l=(Array.isArray(s)?s:[s]).map(f=>Ht(f,e,t,n)).filter(f=>f!=null&&Object.keys(f).length>0);l.length>0&&(o[i]=l);continue}if(i==="_not"){let d=Ht(s,e,t,n);d!=null&&Object.keys(d).length>0&&(o[i]=d);continue}let a=t?.tables?.get(e),u=a?.relations?.find(d=>d.propertyName===i);if(u){if(!n(e,i,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let l=Ht(s,d,t,n);l!=null&&Object.keys(l).length>0&&(o[i]=l);continue}if(a?.columns?.find(d=>d.name===i)){if(!n(e,i,"column"))continue;o[i]=s;continue}o[i]=s}return o}function mi(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 c=(s.startsWith("-")?s.slice(1):s).split("."),d=!0,l=e;for(let f=0;f<c.length;f++){let p=c[f],h=f===c.length-1,y=t?.tables?.get(l);if(!y){d=!1;break}if(h)y.columns?.find(m=>m.name===p)?n(l,p,"column")||(d=!1):y.relations?.find(b=>b.propertyName===p)&&(n(l,p,"relation")||(d=!1));else{let g=y.relations?.find(m=>m.propertyName===p);if(!g){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=g.targetTableName||g.targetTable||l}}d&&i.push(s)}if(i.length!==0)return Array.isArray(r)?i:i.join(",")}jt();He();Bt();Pt();Je();ge();function Qo(r){let e=new dt({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,o=()=>(t||(t=new Qe({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),i=()=>(n||(n=new We({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,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,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,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});