@enfyra/kernel 1.1.48 → 1.1.50

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,10 +1,10 @@
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 $ of e){let _=$[i];if(_==null)continue;let T=this.adapter.keyOf(_);s.has(T)||(s.add(T),a.push(_))}if(a.length===0){for(let $ of e)$[t.relationName]=null,i!==t.relationName&&delete $[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[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 $ of e){let _=$[i];$[t.relationName]=_!=null?this.adapter.buildScalarRef(_,f):null,i!==t.relationName&&delete $[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[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 $ of y)b.set(this.adapter.keyOf($[f]),$);for(let $ of e){let _=$[i];$[t.relationName]=_!=null&&b.get(this.adapter.keyOf(_))||null,i!==t.relationName&&delete $[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[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,$=b?"per-parent-c16":"batch-in",_=b?a.length:Math.ceil(a.length/ae)||1,T=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??$,roundtrips:y?.roundtrips??_,concurrencyWaves:y?.concurrencyWaves??T,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(T=>T[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,$=Array.from(f.values()).reduce((T,k)=>T+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:$,rowsDiscarded:h?.rowsDiscarded??Math.max(0,(h?.rowsTransferred??p.length)-$),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 T of e){let k=this.adapter.keyOf(T[s]);T[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),$=F(r,n),_=F(b,n),T=F(f,n);s.push(`${$}.${_} as ${T}`)}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),$=this.metadata?.tables?.get(g),_=$&&Z($)?.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 $=await this.runQuery(this.buildPartitionSlice(b,s,h,d));return this.removePartitionFields($),$});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 $=await this.runQuery(this.buildPartitionSlice(b,Vt,y,f));return this.removePartitionFields($),$})).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}`,$=!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:$?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)),T=await this.loadM2MTargets(t.targetTable,_,i),k=new Map(T.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:T,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+T.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($),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 $=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($),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 T={value:_.value,valueAbsent:_.valueAbsent===!0,ctxChanges:_.ctxChanges};_.shortCircuit&&(T.shortCircuit=!0),c(T)}else{this.taskErrorTotal++,H({event:"task_done",id:a,ok:!1,message:_.error?.message});let T=new Error(_.error?.message||"Handler execution failed");T.statusCode=_.error?.statusCode,T.code=_.error?.code,T.details=_.error?.details,_.error?.stack&&(T.stack=_.error.stack),_.ctxChanges&&(T.ctxChanges=_.ctxChanges),this.cleanupResponseStream(a,T),d(T)}}},onIoCall:_=>{if(l)return;let T=f.signal;_.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(_,n),s.worker,_.callId,T):_.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(_,n,s.worker),s.worker,_.callId,T):_.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(_,n),s.worker,_.callId,T):_.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(_,n),s.worker,_.callId,T):_.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(_,n),s.worker,_.callId,T):_.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(_,n,s.worker),s.worker,_.callId,T):_.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(_,n),s.worker,_.callId,T):_.type==="resCall"&&this.handleIoCall(()=>this.execResCall(_,n),s.worker,_.callId,T)}}),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,`
1
+ "use strict";var pi=Object.create;var zt=Object.defineProperty;var gi=Object.getOwnPropertyDescriptor;var hi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var q=(r,e)=>()=>(r&&(e=r(r=0)),e);var On=(r,e)=>{for(var t in e)zt(r,t,{get:e[t],enumerable:!0})},yr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hi(e))!yi.call(r,i)&&i!==t&&zt(r,i,{get:()=>e[i],enumerable:!(n=gi(e,i))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?pi(mi(r)):{},yr(e||!r||!r.__esModule?zt(t,"default",{value:r,enumerable:!0}):t,r)),bi=r=>yr(zt({},"__esModule",{value:!0}),r);function Fr(r){return Bn.createHash("md5").update(r).digest("hex").substring(0,8)}function xr(r){return r.length<=Rr-3?`${r}_pk`:`j_${Fr(r)}_pk`}function vr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=Rr?n:`j_${Fr(r)}_${t}_fk`}function xt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Bn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function J(r){return`${r}Id`}function vt(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Ir(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Nr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Er(r,e,t){return`${r}_${e}_${t}_fk`}function Or(r,e,t){return`${r}_${e}_${t}_idx`}var Bn,Rr,Ke=q(()=>{"use strict";Bn=ue(require("crypto")),Rr=63});function ln(r){return eo[r]??null}var we,Kn,Nt,eo,cn=q(()=>{"use strict";we=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Kn=new Set(["_and","_or","_not"]),Nt=[...Array.from(Kn),...Array.from(we)],eo={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var I,de=q(()=>{"use strict";I=class extends Error{constructor(t="Bad Request",n){let i=Array.isArray(t),o=i?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(o);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,i&&(this.messages=t)}}});function jr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Br=q(()=>{"use strict"});function Ee(r,e,t){throw new I({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Nt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Nt})}function un(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=jr();for(let i of Object.keys(e))if(i.startsWith("_")&&!we.has(i)){if(n&&i==="_id")continue;Ee(i,r,t)}}function re(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),i=new Set((n?.columns??[]).map(s=>s.name)),o=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,l]of Object.entries(r)){if(to.has(s)){if(Array.isArray(l))for(let c of l)re(c,e,t);else l&&typeof l=="object"&&re(l,e,t);continue}let u=o.get(s);if(u){if(l&&typeof l=="object"&&!Array.isArray(l)){un(s,l,e);let c=u.targetTableName||u.targetTable;if(c){let d=Object.keys(l).filter(a=>!a.startsWith("_"));if(d.length>0){let a={};for(let f of d)a[f]=l[f];re(a,c,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Ee(s,s,e),l&&typeof l=="object"&&!Array.isArray(l)&&un(s,l,e)}}var to,Je=q(()=>{"use strict";de();cn();Br();to=new Set(["_and","_or","_not"])});function fe(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:dn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function dn(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[i,o]of Object.entries(r)){let s=no(i,o,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function no(r,e,t){if(r==="_and")return Lr("and",e,t);if(r==="_or")return Lr("or",e,t);if(r==="_not"){let c=dn(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),i=n?.columns?.some(c=>c.name==="_id"&&c.isPrimary),o=n?.columns?.some(c=>c.name==="id"),l=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(c=>c.propertyName===l);return u?ro(l,e,u,t):n&&!n.columns?.find(d=>d.name===l)?(r.startsWith("_")&&r!=="_id"&&Ee(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):io(l,e,t)}function Lr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=dn(o,t);s.hasRelationFilters&&(i=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:i}:n.length===1?{node:n[0],hasRelationFilters:i}:{node:{kind:r,children:n},hasRelationFilters:i}}function ro(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let i=Object.keys(e),o=i.length===1&&(i[0]==="_is_null"||i[0]==="_is_not_null"||i[0]==="_eq"||i[0]==="_neq"||i[0]==="_in"||i[0]==="_not_in"||i[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(o&&i[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&i[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(o&&(i[0]==="_eq"||i[0]==="_neq")&&e[i[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:i[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let l=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:l},c=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),a=i.length>0&&i.every(p=>c.has(p))?{id:e}:e;return{node:dn(a,u).node,hasRelationFilters:!0}}function io(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:so(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!we.has(s)&&Ee(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>we.has(s));if(i.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let o=[];for(let[s,l]of i){let u=oo(n,s,l);u&&o.push(u)}return o.length===0?{node:null,hasRelationFilters:!1}:o.length===1?{node:o[0],hasRelationFilters:!1}:{node:{kind:"and",children:o},hasRelationFilters:!1}}function oo(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=ln(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function so(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.find(s=>s.name===n);if(!i)return!1;let o=(i.type||"").toLowerCase();return o==="uuid"||o==="uuidv4"||o.includes("uuid")}var Et=q(()=>{"use strict";cn();Je()});var ie,Ot=q(()=>{"use strict";ie=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,i="left",o=null,s="data"){let l=o?`${o}.${t}`:t;if(this.map.has(l)){let f=this.map.get(l);return i==="inner"&&(f.joinType="inner"),f.purposes.includes(s)||f.purposes.push(s),l}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 a={id:l,propertyName:t,parentTable:e,targetTable:d,relationType:c.type,parentJoinId:o,joinType:i,relationMeta:c,purposes:[s]};return this.map.set(l,a),l}}});async function W(r,e,t=oe){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 i=[],o=0;async function s(){for(;o<n.length;){let u=o++;i[u]=await e(n[u])}}let l=Math.min(Gn,n.length);return await Promise.all(Array.from({length:l},s)),i.flat()}function He(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let i=n.split("."),o=i[0],s=i.slice(1).join(".");t.has(o)||t.set(o,[]),t.get(o).push(s)}return{rootFields:e,subRelations:t}}var Oe,oe,Gn,Yn,Se,Ge=q(()=>{"use strict";de();Oe=16,oe=5e3,Gn=4,Yn=10;Se=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 i=e.map(s=>{let l=t[s.relationName];if(!l)return s;let u=l.fields!=null?Array.isArray(l.fields)?l.fields:String(l.fields).split(",").map(c=>c.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:l.filter??s.userFilter,userSort:l.sort??s.userSort,userLimit:l.limit!==void 0?Number(l.limit):s.userLimit,userPage:l.page!==void 0?Number(l.page):s.userPage,nestedDeep:l.deep??s.nestedDeep}}),o=new Set(i.map(s=>s.relationName));for(let[s,l]of Object.entries(t)){if(o.has(s))continue;let u=n?.relations?.find(d=>d.propertyName===s);if(!u)continue;let c=l.fields!=null?Array.isArray(l.fields)?l.fields:String(l.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.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:l.filter,userSort:l.sort,userLimit:l.limit!==void 0?Number(l.limit):void 0,userPage:l.page!==void 0?Number(l.page):void 0,nestedDeep:l.deep})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Yn}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(o=>o!=="*").map(o=>o.split(".")[0])),i=[...e];for(let o of Object.keys(t))n.has(o)||i.push(o);return i}uniqueValues(e){let t=new Set,n=[];for(let i of e){if(i==null)continue;let o=this.adapter.keyOf(i);t.has(o)||(t.add(o),n.push(i))}return n}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(o.includes("."))throw new I(`Sort field '${o}' 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===o),l=o==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!l)throw new I(`Sort field '${o}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,i=0,o){if(e.length===0||t.length===0||i>=n)return;let s;o&&(s=await this.metadataGetter(o)??void 0),await Promise.all(t.map(l=>{let u=this.withDefaultToManyLimit(l);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,i):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,i,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,i,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,i){let o=this.adapter.resolveOwnerFkKey(t),s=new Set,l=[];for(let $ of e){let C=$[o];if(C==null)continue;let T=this.adapter.keyOf(C);s.has(T)||(s.add(T),l.push(C))}if(l.length===0){for(let $ of e)$[t.relationName]=null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[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:a}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),f=this.adapter.getTargetPkField(u);if(c){for(let $ of e){let C=$[o];$[t.relationName]=C!=null?this.adapter.buildScalarRef(C,f):null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn]}return}let p=performance.now(),h=await this.adapter.fetchOwner(t.targetTable,l,a,t),g=Array.isArray(h)?h:h.docs,m=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:m?.strategy??"batch-in",roundtrips:m?.roundtrips??(Math.ceil(l.length/oe)||1),concurrencyWaves:m?.concurrencyWaves,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(d,t.nestedDeep,u);y.length>0&&await this.execute(g,y,n,i+1,t.targetTable);let b=new Map;for(let $ of g)b.set(this.adapter.keyOf($[f]),$);for(let $ of e){let C=$[o];$[t.relationName]=C!=null&&b.get(this.adapter.keyOf(C))||null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),l=this.uniqueValues(e.map(O=>O[s]));if(l.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:a}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),c),f=performance.now(),{docs:p,groupKeyField:h,stats:g}=await this.adapter.fetchInverse(t.targetTable,u,l,a,t),m=new Map,y=t.fields.includes(u)||t.fields.includes("*");for(let O of p){let B=O[h],S=this.adapter.keyOf(B);m.has(S)||m.set(S,[]),m.get(S).push(O)}let b=t.userLimit!==void 0&&t.userLimit>0,$=b?"per-parent-c16":"batch-in",C=b?l.length:Math.ceil(l.length/oe)||1,T=b?Math.ceil(l.length/Oe):void 0,k=Array.from(m.values()).reduce((O,B)=>O+B.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??$,roundtrips:g?.roundtrips??C,concurrencyWaves:g?.concurrencyWaves??T,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??p.length,rowsReturned:k,rowsDiscarded:Math.max(0,(g?.rowsTransferred??p.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let O of p)this.adapter.postProcessInverseChild(O,u,y);let _=this.enrichNestedDescs(d,t.nestedDeep,c);_.length>0&&await this.execute(p,_,n,i+1,t.targetTable);let F=t.type==="one-to-one";for(let O of e){let B=this.adapter.keyOf(O[s]),S=m.get(B)||[];O[t.relationName]=F?S[0]||null:S}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),l=this.uniqueValues(e.map(T=>T[s]));if(l.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),a=performance.now(),{grouped:f,docs:p,stats:h}=await this.adapter.fetchM2M(e,t,o,u,d),g=t.userLimit!==void 0&&t.userLimit>0,m=g?"m2m-per-parent-c16":"m2m-batch",y=g?l.length:Math.ceil(l.length/oe)||1,b=g?Math.ceil(l.length/Oe):void 0,$=Array.from(f.values()).reduce((T,k)=>T+k.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,a,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??m,roundtrips:h?.roundtrips??y,concurrencyWaves:h?.concurrencyWaves??b,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??p.length,rowsReturned:$,rowsDiscarded:h?.rowsDiscarded??Math.max(0,(h?.rowsTransferred??p.length)-$),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let C=this.enrichNestedDescs(c,t.nestedDeep,u);C.length>0&&p.length>0&&await this.execute(p,C,n,i+1,t.targetTable);for(let T of e){let k=this.adapter.keyOf(T[s]);T[t.relationName]=f.get(k)||[]}}}});var zr,Ce,bn=q(()=>{"use strict";zr=2,Ce=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 v(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 Re(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:v(t,e)).join(".")}var ae=q(()=>{"use strict"});function ce(r,e,t){e&&Rn(r,e,t,"and")}function Rn(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 i=function(){for(let o of e.children)this.where(function(){Rn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"or":{let i=function(){for(let o of e.children)this.orWhere(function(){Rn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){Rn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":jo(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 jo(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 i=Bo(e.field,t),o=Re(i,t.dbType),s=!!e.field.isUuid,l=t.dbType==="postgres",u=n==="or"?"orWhere":"where",c=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",a=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&&l&&typeof e.value=="string"?r[c](`${o} = ?::uuid`,[e.value]):r[u](i,"=",e.value);return;case"neq":s&&l&&typeof e.value=="string"?r[c](`${o} != ?::uuid`,[e.value]):r[u](i,"!=",e.value);return;case"gt":s&&l&&typeof e.value=="string"?r[c](`${o} > ?::uuid`,[e.value]):r[u](i,">",e.value);return;case"gte":s&&l&&typeof e.value=="string"?r[c](`${o} >= ?::uuid`,[e.value]):r[u](i,">=",e.value);return;case"lt":s&&l&&typeof e.value=="string"?r[c](`${o} < ?::uuid`,[e.value]):r[u](i,"<",e.value);return;case"lte":s&&l&&typeof e.value=="string"?r[c](`${o} <= ?::uuid`,[e.value]):r[u](i,"<=",e.value);return;case"in":{let g=ii(e.value);s&&l&&g.every(m=>typeof m=="string")?r[c](`${o} = ANY(?::uuid[])`,[g]):r[d](i,g);return}case"not_in":{let g=ii(e.value);s&&l&&g.every(m=>typeof m=="string")?r[c](`${o} != ALL(?::uuid[])`,[g]):r[a](i,g);return}case"contains":lr(r,o,e.value,"contains",t,n);return;case"starts_with":lr(r,o,e.value,"starts_with",t,n);return;case"ends_with":lr(r,o,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[f](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[h](i);return}}function lr(r,e,t,n,i,o){let s=o==="or"?"orWhereRaw":"whereRaw";if(i.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(i.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 l=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](l,[t])}function Bo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function ii(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var cr=q(()=>{"use strict";ae()});function H(r){return r.columns.find(e=>e.isPrimary)||null}var qt=q(()=>{"use strict"});var oi={};On(oi,{expandFieldsToJoinsAndSelect:()=>ur});async function ur(r,e,t,n,i,o){let s=[],l=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let c=new Map;for(let a of e)if(a==="*"||!a.includes("."))c.has("")||c.set("",[]),c.get("").push(a);else{let f=a.split("."),p=f[0],h=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(h)}if(o&&typeof o=="object")for(let[a,f]of Object.entries(o)){if(c.has(a))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(a,p)}let d=c.get("")||[];for(let a of d){if(a==="*"){let h=new Set;for(let m of u.relations||[])if(m.type==="many-to-one"||m.type==="one-to-one"&&!m.isInverse){let y=m.foreignKeyColumn||J(m.propertyName);y&&h.add(y)}let g=new Set;for(let m of u.columns)h.has(m.name)||(s.push(`${r}.${m.name}`),g.add(m.name));for(let m of u.relations||[])!c.has(m.propertyName)&&!g.has(m.propertyName)&&c.set(m.propertyName,["id"]);continue}if(a.includes(".")){s.push(`${r}.${a}`);continue}if(u.columns?.find(h=>h.name===a)){s.push(`${r}.${a}`);continue}if(u.relations?.find(h=>h.propertyName===a)){c.has(a)||c.set(a,["id"]);continue}}return c.forEach((a,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||J(p.propertyName),$=v(r,n),C=v(b,n),T=v(f,n);s.push(`${$}.${C} as ${T}`)}let g=p.targetTableName||p.targetTable,m=o?.[f],y=m?.fields!=null?Array.isArray(m.fields)?m.fields:String(m.fields).split(",").map(b=>b.trim()).filter(Boolean):a;l.push({relationName:f,type:p.type,targetTable:g,fields:y,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter:m?.filter,userSort:m?.sort,userLimit:m?.limit!==void 0?Number(m.limit):void 0,userPage:m?.page!==void 0?Number(m.page):void 0,nestedDeep:m?.deep})}),{select:s,batchFetchDescriptors:l}}var dr=q(()=>{"use strict";Ke();ae()});var Ut,Qt,Fn,ot,Lo,st,pr=q(()=>{"use strict";Ke();ae();qt();Ge();bn();cr();Ot();Et();Ut="__enfyra_row_number__",Qt="__sourceId__",Fn="__targetId__",ot="__enfyra_partitioned__",Lo=5e4,st=class{constructor(e,t="postgres",n,i=new Ce){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=i;this.pkField="id"}chunkCount(e,t=oe){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?Lo:oe}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 i=[...t];i.some(s=>s.column===n)||i.push({column:n,order:"asc"});let o=i.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${o}) as ??`,[e,...i.map(s=>s.column),Ut])}buildPartitionSlice(e,t,n,i){return this.knex.from(e.as(ot)).select(`${ot}.*`).where(`${ot}.${Ut}`,">",n).andWhere(`${ot}.${Ut}`,"<=",n+i).orderBy(`${ot}.${t}`,"asc").orderBy(`${ot}.${Ut}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Ut]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new ie,i=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:o}=fe(e,t,i,n);return o}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean)).map(o=>{let s=o.startsWith("-"),u=(s?o.slice(1):o).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,i){if(!t||!this.metadata)return;let o=Array.isArray(t)?t:t.split(",").map(l=>l.trim()).filter(Boolean),s=new Set;for(let l of o){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let d=n,a=i||n;for(let f=0;f<c.length-1;f++){let p=c[f],h=this.metadata?.tables?.get(d);if(!h)break;let g=h.relations?.find(b=>b.propertyName===p);if(!g)break;let m=g.targetTableName||g.targetTable,y=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(y)){s.add(y);let b=g.foreignKeyColumn||J(g.propertyName),$=this.metadata?.tables?.get(m),C=$&&H($)?.name||"id";e.leftJoin(`${m} as ${y}`,`${y}.${C}`,`${a}.${b}`)}d=m,a=y}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=v(o,this.dbType),l=t?`${t}.${v(i,this.dbType)}`:v(i,this.dbType);return this.knex.raw(`${l} as ${s}`)}return t?this.knex.raw(`${t}.${v(e,this.dbType)} as ${v(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return H(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=J(e.mappedBy)),t||(t=J(e.targetTable)),t}resolveParentPk(e){return e&&H(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o=[];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 a=d.foreignKeyColumn||J(d.propertyName);a&&c.add(a)}for(let d of t.columns)c.has(d.name)||o.push(d.name);for(let d of t.relations||[])i.has(d.propertyName)||i.set(d.propertyName,["id"])}else for(let c of n){let d=t.columns.find(a=>a.name===c);d?o.push(d.name):t.relations?.find(f=>f.propertyName===c)&&!i.has(c)&&i.set(c,["id"])}let s=H(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((c,d)=>{let a=t.relations?.find(f=>f.propertyName===d);if(a&&(a.type==="many-to-one"||a.type==="one-to-one"&&!a.isInverse)){let f=a.foreignKeyColumn||J(a.propertyName);f&&o.push(`${f} as ${d}`)}});let l=[];return i.forEach((c,d)=>{let a=t.relations?.find(p=>p.propertyName===d);if(!a)return;let f=a.targetTableName||a.targetTable;f&&l.push({relationName:d,type:a.type,targetTable:f,fields:c,isInverse:a.isInverse,fkColumn:a.foreignKeyColumn,mappedBy:a.mappedBy,junctionTableName:a.junctionTableName,junctionSourceColumn:a.junctionSourceColumn,junctionTargetColumn:a.junctionTargetColumn})}),{isPkOnly:o.length===1&&o[0]===s&&l.length===0,nestedDescs:l,fetchSpec:{selectCols:o,pkCol:s}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,s=i?.userSort?this.parseSortTokens(i.userSort,e):[],l=n.selectCols.map(c=>this.toKnexSelect(c)),u=await W(t,c=>{let d=this.knex(e).select(l).whereIn(n.pkCol,c);if(o&&ce(d,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,i.userSort,e);for(let a of s)d.orderBy(a.column,a.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,i,o){let s=t,l=i.selectCols.find(h=>h.startsWith(`${t} as `));l?s=l.split(" as ")[1].trim():i.selectCols.includes(t)||i.selectCols.push(t);let u=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,c=o?.userSort?this.parseSortTokens(o.userSort,e):[],d=o?.userLimit,a=o?.userPage;if(d!==void 0&&d>0){let h=a?(a-1)*d:0,g=i.selectCols.map(y=>this.toKnexSelect(y)),m=await W(n,async y=>{let b=this.knex(e).select(g).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${i.pkCol}`)).whereIn(`${e}.${t}`,y);u&&ce(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,o.userSort,e);let $=await this.runQuery(this.buildPartitionSlice(b,s,h,d));return this.removePartitionFields($),$});return{docs:m,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f=i.selectCols.map(h=>this.toKnexSelect(h)),p=await W(n,h=>{let g=this.knex(e).select(f).whereIn(t,h);if(u&&ce(g,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(g,o?.userSort,e),c.length>0)for(let m of c)g.orderBy(m.column,m.order);else g.orderBy(i.pkCol,"asc");return this.runQuery(g)});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,i,o,s,l,u){let c=`t.${s}`,d=!!l||u.some(g=>g.column!==c),a=d?u:u.map(g=>({...g,column:`${n}.${o}`})),f=t.userLimit,p=t.userPage;if(f!==void 0&&f>0){let g=p?(p-1)*f:0;return(await W(e,async y=>{let b=this.knex(n).select({[Qt]:`${n}.${i}`,[Fn]:`${n}.${o}`}).whereIn(`${n}.${i}`,y);d&&(b=b.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),l&&ce(b,l,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.buildPartitionRowNumber(`${n}.${i}`,a,d?c:`${n}.${o}`));let $=await this.runQuery(this.buildPartitionSlice(b,Qt,g,f));return this.removePartitionFields($),$})).map(y=>({sourceId:y[Qt],targetId:y[Fn]}))}return(await W(e,g=>{let m=this.knex(n).select({[Qt]:`${n}.${i}`,[Fn]:`${n}.${o}`}).whereIn(`${n}.${i}`,g);if(d&&(m=m.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),l&&ce(m,l,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(m,t.userSort,t.targetTable,"t")),m.orderBy(`${n}.${i}`,"asc"),a.length>0){for(let y of a)m.orderBy(y.column,y.order);d&&!a.some(y=>y.column===c)&&m.orderBy(c,"asc")}else m.orderBy(`${n}.${o}`,"asc");return this.runQuery(m)})).map(g=>({sourceId:g[Qt],targetId:g[Fn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.selectCols.map(o=>this.toKnexSelect(o));return W(t,o=>this.runQuery(this.knex(e).select(i).whereIn(n.pkCol,o)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),l=this.uniqueValues(e.map(_=>_[s]));if(l.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 a=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,f=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(l,t,u,c,d,o.pkCol,a,f),h=new Map;for(let _ of l)h.set(this.keyOf(_),[]);let g=o.selectCols.length===1&&o.selectCols[0]===o.pkCol,m=t.userLimit!==void 0&&t.userLimit>0,y=this.chunkCount(l),b=`t.${o.pkCol}`,$=!a&&f.every(_=>_.column===b);if(g){let _=new Map;for(let F of p){let O=this.keyOf(F.targetId);_.has(O)||_.set(O,{[o.pkCol]:F.targetId}),h.get(this.keyOf(F.sourceId))?.push(_.get(O))}return{grouped:h,docs:[],stats:{strategy:$?m?"m2m-junction-partitioned-top-k":"m2m-junction-batch":m?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:y,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let C=this.uniqueValues(p.map(_=>_.targetId)),T=await this.loadM2MTargets(t.targetTable,C,o),k=new Map(T.map(_=>[this.keyOf(_[o.pkCol]),_]));for(let _ of p){let F=k.get(this.keyOf(_.targetId));F&&h.get(this.keyOf(_.sourceId))?.push(F)}return{grouped:h,docs:T,stats:{strategy:m?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:y+(C.length>0?this.chunkCount(C,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+T.length,rowsDiscarded:0}}}}});var li={};On(li,{executeBatchFetches:()=>gr});async function gr(r,e,t,n,i=3,o=0,s,l="postgres",u,c){let d=new st(r,l,u);await new Se(d,n,c).execute(e,t,i,o,s)}var hr=q(()=>{"use strict";Ge();pr()});var qo={};On(qo,{ALL_SUPPORTED_OPERATORS:()=>Nt,AuthenticationException:()=>gt,AuthorizationException:()=>ht,BadRequestException:()=>I,BatchExecutionBudget:()=>Ce,BatchFetchEngine:()=>Se,BusinessLogicException:()=>ut,CHUNKED_FETCH_CONCURRENCY:()=>Gn,ConfigurationException:()=>$t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Yn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>zr,DEFAULT_TIMEOUT_MS:()=>Vt,DOTTED_PATH_MAX_HOPS:()=>Nn,DatabaseException:()=>Le,DuplicateResourceException:()=>pt,ErrorHandler:()=>xe,ExecutorEngineService:()=>Be,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>we,FileNotFoundException:()=>St,FileSizeExceededException:()=>Ct,FileUploadException:()=>Tt,HttpException:()=>P,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Yt,InvalidTokenException:()=>yt,IsolatedExecutorService:()=>We,JoinRegistry:()=>ie,LOGICAL_OPERATORS:()=>Kn,MongoBatchAdapter:()=>Xe,MongoQueryExecutor:()=>Ae,PER_PARENT_CONCURRENCY:()=>Oe,QueryBuilderService:()=>at,QueryPlanner:()=>X,ResourceNotFoundException:()=>ft,SchemaException:()=>wt,ScriptContractService:()=>tn,ScriptExecutionException:()=>ye,ScriptTimeoutException:()=>me,ServiceUnavailableException:()=>_t,SqlBatchAdapter:()=>st,SqlQueryExecutor:()=>je,TokenExpiredException:()=>mt,ValidationException:()=>dt,WHERE_IN_CHUNK_SIZE:()=>oe,WorkerPool:()=>Rt,appendIsolatedExecutorRuntimeLog:()=>Q,applyOperatorToMatch:()=>an,applyRelationFilters:()=>Lt,applyWhereToKnex:()=>it,assertFieldOperatorValueIsClean:()=>un,buildMongoCharFoldMapJson:()=>Dn,buildMongoFoldTextSearchJs:()=>nn,buildRelationSubquery:()=>Bt,buildSqlWherePartsFromFieldAst:()=>Wt,buildWhereClause:()=>le,camelToSnake:()=>Nr,chunkedFetch:()=>W,compileScriptSource:()=>qi,computeEngineTuning:()=>An,createEnfyraKernel:()=>Ko,dslOpToCompareOp:()=>ln,encodeMainThreadToIsolate:()=>jn,escapeSqlValue:()=>Kt,executeBatchFetches:()=>gr,executeMongoBatchFetches:()=>wn,expandFieldsToJoinsAndSelect:()=>ur,getEffectiveCpuCount:()=>Mn,getEffectiveMemoryBytes:()=>kt,getEngineTuning:()=>en,getExecutableScript:()=>zi,getForeignKeyColumnName:()=>J,getIoAbortSignal:()=>Cr,getJunctionColumnNames:()=>vt,getJunctionTableName:()=>xt,getPrimaryKeyColumn:()=>H,getScriptLegacyField:()=>Di,getShortFkConstraintName:()=>vr,getShortFkName:()=>Er,getShortIndexName:()=>Or,getShortPkName:()=>xr,hasLogicalOperators:()=>he,isExecutableJavaScript:()=>Ui,isScriptTable:()=>Wi,normalizeAggregateQuery:()=>tt,normalizeFlowStepScriptConfig:()=>Hi,normalizeScriptLanguage:()=>Ki,normalizeScriptPatch:()=>Ji,normalizeScriptRecord:()=>Qi,parseBatchFields:()=>He,parseFields:()=>$n,parseFilter:()=>fe,perParentRun:()=>_n,quoteIdentifier:()=>v,quoteQualifiedIdentifier:()=>Re,resolveExecutableScript:()=>Vi,rewriteFilterDenyingFields:()=>di,rewriteSortDroppingDenied:()=>fi,runWithIoAbortSignal:()=>kr,scriptContractService:()=>ee,separateFilters:()=>V,snakeToCamel:()=>Ir,throwUnsupportedFieldOperator:()=>Ee,validateDeepOptions:()=>mr,validateFilterShape:()=>re,whereToMongoFilter:()=>Qe});module.exports=bi(qo);var Vt=3e4,Be=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t,n={}){let i=e.routeData.__codeBlocks||[];return i.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(i,e.routeData.context,t??Vt,n)}async run(e,t,n=Vt,i={}){return this.isolatedExecutorService.run(e,t,n,i)}};var Ht=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var $r=require("async_hooks"),Tr=ue(require("path")),Sr=require("stream");var br=require("child_process"),_i=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function wi(){let r={};for(let e of _i){let t=process.env[e];t!==void 0&&(r[e]=t)}return r}var Gt=class{constructor(e){this.terminated=!1;this.child=(0,br.fork)(e,[],{stdio:["ignore","ignore","ignore","ipc"],env:wi(),serialization:"advanced"})}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){if(!this.child.connected)throw new Error("Executor runner IPC is closed");this.child.send(e)}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var me=class extends Error{constructor(t=0,n,i){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,...i}}},ye=class extends Error{constructor(t,n,i){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...i}}},j=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},P=class extends j{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ut=class extends j{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},dt=class extends j{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},ft=class extends j{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},pt=class extends j{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},gt=class extends j{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},ht=class extends j{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},mt=class extends j{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},yt=class extends j{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Le=class extends j{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},bt=class extends j{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},_t=class extends j{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},wt=class extends j{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},$t=class extends j{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Tt=class extends j{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},St=class extends j{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},Ct=class extends j{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var xe=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.http":return new P(n||"Error",t||500,o);case"$throw.businessLogic":return new ut(n||"Bad request",o);case"$throw.validation":return new dt(n||"Validation failed",o);case"$throw.notFound":return new ft(o?.resource||n||"Resource",o?.identifier);case"$throw.duplicate":return new pt(o?.resource||n||"Resource",o?.field||"field",o?.value||"value");case"$throw.unauthorized":return new gt(n||"Unauthorized");case"$throw.forbidden":return new ht(n||"Forbidden");case"$throw.tokenExpired":return new mt;case"$throw.invalidToken":return new yt;case"$throw.database":return new Le(n||"Database error",o);case"$throw.dbQuery":return new Le(n||"Query error",o);case"$throw.externalService":return new bt(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new _t(n||"Service");case"$throw.rateLimit":return new P(n||"Rate limit exceeded",429);case"$throw.scriptError":return new ye(n||"Script error",i,o);case"$throw.scriptTimeout":return new me(o?.timeout||5e3,i);case"$throw.schema":return new wt(n||"Schema error",o);case"$throw.config":return new $t(n||"Configuration error",o);case"$throw.fileUpload":return new Tt(n||"File upload error",o);case"$throw.fileNotFound":return new St(n||"File not found");case"$throw.fileSizeExceeded":return new Ct(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new P(n||"Bad request",400,o);case"$throw.401":return new P(n||"Authentication required",401,o);case"$throw.403":return new P(n||"Insufficient permissions",403,o);case"$throw.404":return new P(n||"Not found",404,o);case"$throw.409":return new P(n||"Conflict",409,o);case"$throw.422":return new P(n||"Validation failed",422,o);case"$throw.429":return new P(n||"Rate limit exceeded",429,o);case"$throw.500":return new P(n||"Internal server error",500,o);case"$throw.503":return new P(n||"Service unavailable",503,o);default:return new ye(n||"Unknown error",i)}if(t)switch(t){case 400:return new P(n||"Bad request",400,o);case 401:return new P(n||"Authentication required",401,o);case 403:return new P(n||"Insufficient permissions",403,o);case 404:return new P(n||"Not found",404,o);case 409:return new P(n||"Conflict",409,o);case 422:return new P(n||"Validation failed",422,o);case 429:return new P(n||"Rate limit exceeded",429,o);case 500:return new P(n||"Internal server error",500,o);case 503:return new P(n||"Service unavailable",503,o);default:return new ye(n||"Unknown error",i,o)}return new ye(n||"Unknown error",i,o)}};var Xt=ue(require("fs")),Zt=ue(require("path")),Yt=Zt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function $i(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var Ti=$i();function Q(r){if(Ti)try{let e=Zt.dirname(Yt);Xt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
+ `;Xt.appendFileSync(Yt,t)}catch{}}var be=ue(require("os")),De=ue(require("fs"));function kt(){try{let r=De.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}}catch{}try{let r=De.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}catch{}return be.totalmem()}function Mn(){let r=be.availableParallelism?.()||be.cpus()?.length||1;try{let e=De.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let i=parseInt(t,10),o=parseInt(n,10);if(i>0&&o>0)return Math.max(1,Math.ceil(i/o))}}catch{}try{let e=parseInt(De.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(De.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 Si=.25,Ci=16,ki=2048,Ri=40,Fi=128,xi=32;function An(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Fi,Math.max(Ri,Math.round(t/xi))),i=t*Si,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),l=t<ki?1:Ci,u=Math.max(1,Math.min(l,Math.floor(i/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:u,isolatePoolSize:u}}function en(){return An({logicalCpuCount:Mn(),totalMemoryBytes:kt()})}var Bi=Tr.join(__dirname,"execution/worker.js"),Li=1e3,Pn=new $r.AsyncLocalStorage;function Cr(){return Pn.getStore()}function kr(r,e){return Pn.run(r,e)}var Rt=class{constructor(e,t,n,i,o,s,l,u=6e4){this.scriptPath=o;this.onCrash=s;this.onRotate=l;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=i,this.drainTimeoutMs=u;for(let c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Gt(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="taskReleased"?i.onRelease?.():n.type==="result"||n.type==="taskCancelled"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n.type==="taskCancelled"?{type:"result",id:n.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}}:n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":t.lastError?`Worker crashed: ${t.lastError}`:"Worker crashed",code:i?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:i?void 0:{outcome:"unknown_outcome",retryable:!1}}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),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){if(t.draining)continue;let n=t.tasks.size+t.reservations;n<this.tasksCap&&(!e||n<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable())?(e.reservations++,Promise.resolve(e)):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,n)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),this.drainWaiting()}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+e.reservations===0||this.isMemoryAvailable()))e.reservations++,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,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},wr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function jn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var We=class r{constructor(e){this.logger=new Ht(r.name);this.effectiveMemory=kt();this.isolationTuning=en();this.pool=new Rt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Bi,()=>{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(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let l=this.pool.getMax(),u=this.pool.getWaitingCount(),c=t>.85||s>.7,d=t<.7&&s<.5,a=u>0,f=l;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,l-1))):d&&a?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,l+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==l&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${l} -> ${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 i of Object.keys(e)){if(!i.startsWith("$")||i in t||wr.has(i))continue;let o=this.cloneSnapshotValue(e[i]);o!==void 0&&(t[i]=o)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,i]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||wr.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i,o){return(async()=>{let s=await this.pool.dispatch();if(o?.aborted){this.pool.releaseReservation(s);let c=new Error("Execution aborted after client disconnect");return c.code="ERR_EXECUTION_ABORTED",c.isAbort=!0,Promise.reject(c)}let l=`t_${++this.taskCounter}`,u=Date.now();return new Promise((c,d)=>{let a=!1,f=new AbortController,p=!1,h,g=()=>{let _=new Error("Execution aborted after client disconnect");return _.code="ERR_EXECUTION_ABORTED",_.isAbort=!0,_},m=()=>{let _=new Error(`Script execution timed out after ${i}ms`);return _.code="ERR_SCRIPT_EXECUTION_TIMEOUT",_.isTimeout=!0,_},y,b=_=>{if(!(a||p)){p=!0,h=_,f.abort(),this.cleanupResponseStream(l,_);try{s.worker.postMessage({type:"cancelTask",id:l})}catch{}y=setTimeout(()=>{a||(a=!0,clearTimeout(k),T(),this.taskCancellers.delete(l),this.pool.unregisterTask(s,l),this.taskErrorTotal++,Q({event:"task_cancel_grace_terminate",id:l}),this.pool.terminateEntry(s),_.details={..._.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},d(_))},Li),y.unref?.()}},$=()=>b(g());this.taskCancellers.set(l,$);let C=()=>$(),T=()=>{o?.removeEventListener("abort",C)};o&&o.addEventListener("abort",C,{once:!0});let k=setTimeout(()=>{a||(this.taskTimeoutTotal++,Q({event:"task_timeout",id:l,timeoutMs:i}),b(m()))},i);this.pool.registerTask(s,l,{abortController:f,onResult:_=>{if(!a){if(_.taskCancelled===!0&&this.pool.unregisterTask(s,l),a=!0,clearTimeout(k),y&&clearTimeout(y),this.taskCancellers.delete(l),T(),this.cleanupResponseStream(l),this.recordTaskDuration(Date.now()-u),p){f.abort(),this.taskErrorTotal++,d(h??g());return}if(_.success){this.taskDoneTotal++,Q({event:"task_done",id:l,ok:!0});let F={value:_.value,valueAbsent:_.valueAbsent===!0,ctxChanges:_.ctxChanges};_.shortCircuit&&(F.shortCircuit=!0),c(F)}else{this.taskErrorTotal++,Q({event:"task_done",id:l,ok:!1,message:_.error?.message});let F=new Error(_.error?.message||"Handler execution failed");F.statusCode=_.error?.statusCode,F.code=_.error?.code,F.details=_.error?.details,_.error?.stack&&(F.stack=_.error.stack),_.ctxChanges&&(F.ctxChanges=_.ctxChanges),this.cleanupResponseStream(l,F),d(F)}}},onRelease:()=>{this.pool.unregisterTask(s,l)},onIoCall:_=>{if(a)return;let F=f.signal;_.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(_,n),s.worker,_.callId,F):_.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(_,n,s.worker),s.worker,_.callId,F):_.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(_,n),s.worker,_.callId,F):_.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(_,n),s.worker,_.callId,F):_.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(_,n),s.worker,_.callId,F):_.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(_,n,s.worker),s.worker,_.callId,F):_.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(_,n),s.worker,_.callId,F):_.type==="resCall"&&this.handleIoCall(()=>this.execResCall(_,n),s.worker,_.callId,F)}}),s.worker.postMessage({type:e,id:l,...t}),o?.aborted&&$()})})()}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,i){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let o=await(i?Pn.run(i,e):e());if(i?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:jn(o)})}catch{}}catch(o){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function"){let o=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${o}${e.table}.${e.method}`)}return i[e.method](...n)}async execTransactionCall(e,t,n){let o=JSON.parse(e.argsJson||"[]").map(l=>l?.__fnRef&&typeof l.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,l.__fnRef,u):l)[0];if(typeof o!="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,o)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execStorageCall(e,t,n){let i=this.parseStorageArgs(e.argsJson,n,e.id),o=t?.$storage?.[e.method];if(typeof o!="function")throw new Error(`Storage method not found: ${e.method}`);return o(...i)}parseStorageArgs(e,t,n){return JSON.parse(e,(i,o)=>{if(o?.__fnRef&&typeof o.__fnRef=="string"){let s=o.__fnRef;return(...l)=>this.invokeRuntimeCallback(t,n,s,l)}return o})}invokeRuntimeCallback(e,t,n,i){let o=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,l)=>{let u=setTimeout(()=>{d(),l(new Error(`Runtime callback timed out: ${n}`))},3e4),c=a=>{if(!(a?.type!=="runtimeCallbackResult"||a.callId!==o)){if(d(),a.error){l(new Error(a.error));return}s(a.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:o,callbackId:n,argsJson:JSON.stringify(i)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}cancelTask(e){this.taskCancellers.get(e)?.()}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},l=t?.$res?.stream;if(typeof l!="function")throw new Error("Response method not found: stream");let u=new Sr.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 a=l.call(t.$res,u,s);return a&&typeof a.catch=="function"&&a.catch(()=>{}),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((l,u)=>{let c=()=>{a(),l()},d=f=>{a(),u(f)},a=()=>{o.stream.off("drain",c),o.stream.off("error",d)};o.stream.once("drain",c),o.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.closeCleanup?.(),o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){o.closeCleanup?.();let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),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,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),l=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_run_start",timeoutMs:o,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:i.sourceCode??e,pkgSources:l,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("execute",d,t,o)}catch(d){let a=d;if(Q({event:"isolated_run_error",message:a.message,code:a.code,isTimeout:!!a.isTimeout}),a.code==="ERR_EXECUTION_ABORTED"||a.isAbort)throw a;if(a.isTimeout||a.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new me(o,e,a.details);a.code&&a.details&&(a.details.executorCode=a.code);let f=a.statusCode??(typeof a.status=="number"?a.status:void 0);throw xe.createException(a.errorPath,f,a.message||"Unknown error",e,a.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),Q({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),l=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let c;try{let a={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:l,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("executeBatch",a,t,o,i.signal)}catch(d){let a=d;if(Q({event:"isolated_batch_error",message:a.message,code:a.code,isTimeout:!!a.isTimeout}),a.ctxChanges&&this.mergeCtxChanges(t,a.ctxChanges),a.code==="ERR_EXECUTION_ABORTED"||a.isAbort)throw a;if(a.isTimeout||a.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new me(o,"(batch execution)",a.details);a.code&&a.details&&(a.details.executorCode=a.code);let f=a.statusCode??(typeof a.status=="number"?a.status:void 0);throw xe.createException(a.errorPath,f,a.message||"Unknown error","(batch execution)",a.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),Q({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((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var ve=ue(require("typescript")),Ft={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 Di(r){return ee.getLegacyField(r)}function Wi(r){return ee.isScriptTable(r)}function Ki(r){return ee.normalizeLanguage(r)}var tn=class{getLegacyField(e){return Ft[e]}isScriptTable(e){return e in Ft}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),o=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(o),o}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},i=this.getLegacyField(e);return i&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[i]!==void 0&&(n.sourceCode=n[i]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),i&&i in n&&delete n[i],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let i=this.getLegacyField(e),o=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(i?Object.prototype.hasOwnProperty.call(t,i):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!o&&!s)return t;let l=o?t.sourceCode??(i?t[i]:void 0):n?.sourceCode??(i&&n?n[i]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,c={...t};return o&&(c.sourceCode=l??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(l,c.scriptLanguage),i&&i in c&&delete c[i],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(Ft).find(n=>Ft[n]in e);if(t){let n=e[Ft[t]];if(typeof n=="string"&&n!==""){let i=this.compileSource(n,e.scriptLanguage);return{code:i,compiledCode:i,shouldPersistCompiledCode:i!==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},i=e.config;if(typeof i=="string")try{i=JSON.parse(i)}catch{return e}let o=i&&typeof i=="object"?i:{};n.sourceCode=n.sourceCode??o.sourceCode??o.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??o.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...o};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,i=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:i,compiledCode:i,shouldPersistCompiledCode:i!==e?.compiledCode}}transpileTypeScript(e){let t=ve.default.transpileModule(e,{compilerOptions:{target:ve.default.ScriptTarget.ES2022,module:ve.default.ModuleKind.CommonJS,importsNotUsedAsValues:ve.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(i=>i.category===ve.default.DiagnosticCategory.Error);if(n)throw new Error(ve.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 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
- var M = ${Kn()};
6
+ });`)}},ee=new tn;function qi(r,e){return ee.compileSource(r,e)}function Ui(r){return ee.isExecutableJavaScript(r)}function Qi(r,e){return ee.normalizeRecord(r,e)}function Ji(r,e,t){return ee.normalizePatch(r,e,t)}function zi(r){return ee.getExecutableScript(r)}function Vi(r){return ee.resolveExecutableScript(r)}function Hi(r){return ee.normalizeFlowStepScriptConfig(r)}var vn=require("node:fs"),ci=require("node:path");var Ln=require("mongodb");Ke();function Ie(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function z(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ie(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function te(r){if(!r||typeof r!="object")return r;if(r instanceof Ln.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>te(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((i,o)=>parseInt(i)-parseInt(o)).map(i=>t[i]);return new Ln.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)?te(n):n;return e}function Ne(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let l=t,u=e.mappedBy,c=r,d=e.junctionTableName||xt(l,u,c);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:l,inverseTable:c};let a=vt(l,u,c);return{junctionName:d,selfColumn:a.targetColumn,otherColumn:a.sourceColumn,owningTable:l,inverseTable:c}}let n=r,i=t,o=e.junctionTableName||xt(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=vt(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function It(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let i=r.tables?.get(e);if(!i)return{scalarFields:[],relations:[]};let o=new Map;for(let c of t)if(c==="*")o.has("")||o.set("",[]),o.get("").push(c);else if(c.includes(".")){let d=c.split("."),a=d[0],f=d.slice(1).join(".");o.has(a)||o.set(a,[]),o.get(a).push(f)}else i.relations?.some(a=>a.propertyName===c)?o.has(c)||o.set(c,["_id"]):(o.has("")||o.set("",[]),o.get("").push(c));if(n&&typeof n=="object")for(let[c,d]of Object.entries(n)){if(o.has(c))continue;let a=d&&typeof d=="object"&&d.fields!=null?Array.isArray(d.fields)?d.fields:String(d.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];o.set(c,a)}let s=[],l=[],u=o.get("")||[];for(let c of u)if(c==="*"){if(i.columns)for(let d of i.columns)s.includes(d.name)||s.push(d.name);if(i.relations)for(let d of i.relations)o.has(d.propertyName)||o.set(d.propertyName,["_id"])}else i.columns?.some(a=>a.name===c)&&!s.includes(c)&&s.push(c);for(let[c,d]of o.entries()){if(c==="")continue;let a=i.relations?.find(m=>m.propertyName===c);if(!a)continue;let f="",p="",h=!1;a.type==="many-to-one"||a.type==="one-to-one"?Ie(a)?(f="_id",p=K(a)||a.propertyName,h=!0):(f=z(a)||a.propertyName,p="_id",h=!1):a.type==="one-to-many"?(f="_id",p=K(a)||a.propertyName,h=!0):a.type==="many-to-many"&&(a.mappedBy?(f="_id",p=a.mappedBy,h=!0):(f=a.propertyName,p="_id",h=!1));let g=a.type==="one-to-many"||a.type==="many-to-many";l.push({propertyName:c,targetTable:a.targetTableName,localField:f,foreignField:p,type:g?"many":"one",isInverse:h,nestedFields:d})}return{scalarFields:s,relations:l}}var rn=ue(require("fs")),Wn=ue(require("path"));var Gi=new RegExp("\\p{Mark}","gu");function Mr(r){return r==null?"":String(r).normalize("NFKD").replace(Gi,"").toLowerCase()}function Dn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Mr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function nn(){return`function() {
7
+ var M = ${Dn()};
8
8
  function foldStr(s) {
9
9
  if (s == null) return '';
10
10
  s = String(s);
@@ -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 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 $=g.type==="one-to-many"||g.type==="many-to-many";d.push({propertyName:p,targetTable:g.targetTableName,localField:m,foreignField:b,type:$?"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($=>$.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 $=Y(g)||g.propertyName,_=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=_?`${_}.${$}`:$;i.push({$lookup:{from:m,localField:T,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),$=await K(a,async _=>{let T={[t]:{$in:_}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];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:$,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:$.length}}}if(s&&(s[t]=1),l){let m=[],b=await wn(a,async $=>{let _={[t]:$};u&&Object.keys(u).length>0&&Object.assign(_,u);let T=this.buildSortAggregatePipeline(e,_,i.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,o)},je);for(let $ of b.values())for(let _ of $)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 $=this.keyOf(b.targetId);m.has($)||m.set($,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(m.get($))}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($=>({sourceId:$[n.selfColumn],targetId:$[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=[],$=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)$.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]);$.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 T=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)+T,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):[],$=()=>{!p||m.length===0||wo(n,e.table,p.sortItems,i)},_=()=>{!p||b.length===0||$o(n,e.table,p.sortItems,i)},T=()=>{let S=[...m,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(N=>[N,0]))})};if(!e.mongoFieldsExpanded){$(),_();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})),T(),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){$(),_();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){$(),_();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}))}T(),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 w=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:w?.type,targetTable:D.targetTable,fields:v,isInverse:w?.isInverse,mappedBy:w?.mappedBy,junctionTableName:w?.junctionTableName,junctionSourceColumn:w?.junctionSourceColumn,junctionTargetColumn:w?.junctionTargetColumn,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=[],$=!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),T=this.parsePage(s),k=T!==void 0&&_!==void 0?(T-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:$,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($=>Ne($,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 $=st(b._is_null),_=st(b._is_not_null);if($===!0)e.whereRaw(`${g} IS NOT NULL`);else if($===!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 T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${g} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];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,$=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${$.map(()=>"?").join(", ")})`,$)}}}}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 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};$.push(C);continue}if(w.function==="max"||w.function==="min"){let C={sql:this.buildRelationAggregateSortSubquery(l.table,w),direction:w.direction};$.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};b.push(C),$.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};$.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=b;let T=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);T=T.select(w)}if(R&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),I){let w=F(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) 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 w=this.metadata?.tables?.get(l.table);(!E&&w&&w.relations&&w.relations.length>0?X(f,w).hasRelations:!1)?await De(this.knex,T,f,l.table,w,this.dbType,v=>this.metadata?.tables?.get(v)):e.plan?.filterTree?ne(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=de(T,f,l.table,this.dbType,w))}else l.where&&l.where.length>0&&(T=at(T,l.where,l.table,this.metadata,this.dbType));for(let w of $)if(w.field){let C=w.field.includes(".")?w.field:`${l.table}.${w.field}`;T=T.orderBy(C,w.direction)}else w.sql&&(T=T.orderByRaw(`${w.sql} ${w.direction.toUpperCase()}`));l.groupBy&&(T=T.groupBy(l.groupBy)),l.offset&&(T=T.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(T=T.limit(l.limit));let L=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&o){let w=T.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,A=performance.now();N=await T,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(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,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]=w(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=>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}:{}}},...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),$=F(g.targetColumn,this.dbType),_=F(d,this.dbType);return`(SELECT ${p}(${h}.${y}) FROM ${m} JOIN ${h} ON ${h}.${_} = ${m}.${$} 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});
52
+ }`}var Ar="mongo-fold-text-search.body.txt",qe=null;function Yi(){let r=[Wn.join(__dirname,Ar),Wn.join(process.cwd(),"dist","kernel","query","utils",Ar)];for(let e of r)try{if(rn.existsSync(e))return rn.readFileSync(e,"utf8")}catch{}return null}function on(){if(qe!==null)return qe;let r=Yi();return r?(qe=r,qe):(qe=nn(),qe)}var _e=require("mongodb");function D(r,e,t,n){if(t==="_id"){if(n instanceof _e.ObjectId)return n;if(typeof n=="string")try{return new _e.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(l=>l.propertyName===t||l.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.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 _e.ObjectId(n)}catch{return n}return n;default:return n}}var sn="__mongoFoldTextTriples";function Xi(r){return r==="_id"?"$_id":`$${r}`}function Ue(r,e,t,n){let i=Xi(e),o=r[sn]??[];o.push({ref:i,needle:t,mode:n}),r[sn]=o}function Zi(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:on(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Qe(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let l=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&l==="id"&&(l="_id");let c=D(r,u,l,s.value);switch(s.operator){case"=":i[l]=c;break;case"!=":i[l]={$ne:c};break;case">":i[l]={$gt:c};break;case"<":i[l]={$lt:c};break;case">=":i[l]={$gte:c};break;case"<=":i[l]={$lte:c};break;case"like":i[l]={$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(y=>y.trim()):[d]);let a=d.map(y=>D(r,u,l,y));i[l]={$in:a};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(y=>y.trim()):[f]);let p=f.map(y=>D(r,u,l,y));i[l]={$nin:p};break;case"is null":i[l]=null;break;case"is not null":i[l]={$ne:null};break;case"_contains":Ue(i,l,String(c),"contains");break;case"_starts_with":Ue(i,l,String(c),"starts");break;case"_ends_with":Ue(i,l,String(c),"ends");break;case"_between":let h=s.value;if(typeof h=="string"&&(h=h.split(",").map(y=>y.trim())),Array.isArray(h)&&h.length===2){let y=D(r,u,l,h[0]),b=D(r,u,l,h[1]);i[l]={$gte:y,$lte:b}}break;case"_is_null":let g=c===!0||c==="true";i[l]=g?{$eq:null}:{$ne:null};break;case"_is_not_null":let m=c===!0||c==="true";i[l]=m?{$ne:null}:{$eq:null};break}}return Zi(i),i}function Pr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function an(r,e,t,n,i,o){switch(i){case"_contains":Ue(e,n,String(o),"contains");break;case"_starts_with":Ue(e,n,String(o),"starts");break;case"_ends_with":Ue(e,n,String(o),"ends");break;case"_eq":e[n]=D(r,t,n,o);break;case"_neq":{let a=D(r,t,n,o);Pr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:a}})):e[n]={$ne:a};break}case"_in":{let a=o;Array.isArray(a)||(a=typeof a=="string"&&a.includes(",")?a.split(",").map(p=>p.trim()):[a]);let f=a.map(p=>D(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(a=>a.trim()):[s]);let l=s.map(a=>D(r,t,n,a));Pr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:l}})):e[n]={$nin:l};break;case"_gt":e[n]={$gt:D(r,t,n,o)};break;case"_gte":e[n]={$gte:D(r,t,n,o)};break;case"_lt":e[n]={$lt:D(r,t,n,o)};break;case"_lte":e[n]={$lte:D(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=o===!0||o==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=o;if(typeof d=="string"&&(d=d.split(",").map(a=>a.trim())),Array.isArray(d)&&d.length===2){let a=D(r,t,n,d[0]),f=D(r,t,n,d[1]);e[n]={$gte:a,$lte:f}}break}}var Vn=require("mongodb");function ne(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 i of n)if(ne(i,e))return!0}}else if(t==="_not"){if(ne(n,e))return!0}else if(e.has(t))return!0;return!1}function V(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,l]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=l;continue}if(i.has(s))if(typeof l=="object"&&l!==null){let u=Object.keys(l);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:l}:n[s]=l}else n[s]=l}else n[s]=l;else t[s]=l}let o=ne(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Et();Ot();var fn="__mongoFoldTextTriples";function ze(r,e){if(!r)return{};let t={};return Mt(r,t,e),$e(t),t}function ao(r,e){if(!r)return{};let t={};return Un(r,t,e),$e(t),t}function ge(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return ze(i,{metadata:r,rootTable:t})}function pn(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return ao(i,{metadata:r,rootTable:t})}function Mt(r,e,t){switch(r.kind){case"true":return;case"false":pe(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return Mt(o,s,t),$e(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}pe(e,...i);return}case"or":{let i=r.children.map(s=>{let l={};return Mt(s,l,t),$e(l),l}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};Mt(r.child,n,t),$e(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Wr(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 Wr(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 i=o=>D(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":Y(e,n,i(r.value));return;case"neq":{let o=i(r.value);Qn(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):Y(e,n,{$ne:o});return}case"gt":Y(e,n,{$gt:i(r.value)});return;case"gte":Y(e,n,{$gte:i(r.value)});return;case"lt":Y(e,n,{$lt:i(r.value)});return;case"lte":Y(e,n,{$lte:i(r.value)});return;case"in":{let o=Dr(r.value).map(i);Y(e,n,{$in:o});return}case"not_in":{let o=Dr(r.value).map(i);Qn(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):Y(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&Y(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":Y(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":qn(e,n,String(r.value),"contains");return;case"starts_with":qn(e,n,String(r.value),"starts");return;case"ends_with":qn(e,n,String(r.value),"ends");return}}function Un(r,e,t){switch(r.kind){case"true":pe(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let l={};return Un(s,l,t),$e(l),l}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}let o=e.$or;e.$or=o?[...o,...i]:i;return}case"or":{let i=r.children.map(o=>{let s={};return Un(o,s,t),$e(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}pe(e,...i);return}case"not":Mt(r.child,e,t);return;case"compare":lo(r,e,t);return;case"relation_exists":{Y(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function lo(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){Y(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Wr(r,i,t),$e(i);let o={$nor:[i]};Qn(t,n)?pe(e,o,{[n]:{$ne:null}}):pe(e,o)}function Y(r,e,t){r[e]===void 0?r[e]=t:(pe(r,{[e]:r[e]},{[e]:t}),delete r[e])}function pe(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Qn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Dr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function co(r){return r==="_id"?"$_id":`$${r}`}function qn(r,e,t,n){let i=co(e),o=r[fn]??[];o.push({ref:i,needle:t,mode:n}),r[fn]=o}function $e(r){let e=r[fn];if(delete r[fn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:on(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function Te(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return ge(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return ge(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(a=>Te(a,e,t,n)))).filter(a=>a&&Object.keys(a).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(a=>Te(a,e,t,n)))).filter(a=>a&&Object.keys(a).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await zn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:l}=V(r,i),u=[];if(s&&Object.keys(s).length>0){let c=ge(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(l&&Object.keys(l).length>0)for(let[c,d]of Object.entries(l)){let a=await uo(c,d,e,i,t,n);a&&Object.keys(a).length>0&&u.push(a)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function zn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return pn(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return pn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(a=>zn(a,e,t,n)))).filter(a=>a&&Object.keys(a).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(a=>zn(a,e,t,n)))).filter(a=>a&&Object.keys(a).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return Te(r._not,e,t,n);let{fieldFilters:s,relationFilters:l}=V(r,i),u=[];if(s&&Object.keys(s).length>0){let c=pn(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(l&&Object.keys(l).length>0)for(let[c,d]of Object.entries(l)){let a=await po(c,d,e,i,t,n);a&&Object.keys(a).length>0&&u.push(a)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function uo(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let l=s.targetTableName||s.targetTable,u=i?.tables?.get(l);return!l||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?fo(e,s,r,l,u,i,o):s.type==="one-to-many"?Ur(e,s,t,l,u,i,o):s.type==="many-to-many"?Qr(e,s,t,l,u,i,o):{}}async function fo(r,e,t,n,i,o,s){let l=z(e)||t,u=hn(r),c=mn(u);if(c!==null)return c?{[l]:null}:{[l]:{$ne:null}};let d=Hn(u);if(d!==null){let h=yn(d.value);if(d.op==="eq")return{[l]:h};if(d.op==="neq")return{[l]:{$ne:h}};if(d.op==="in")return{[l]:{$in:h}};if(d.op==="not_in")return{$and:[{[l]:{$nin:h}},{[l]:{$ne:null}}]}}let a=await gn(u,n,i,o,s);if(!a||Object.keys(a).length===0)return{};let p=(await s.collection(n).find(a,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[l]:{$in:p}}}async function po(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let l=s.targetTableName||s.targetTable,u=i?.tables?.get(l);if(!l||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return go(e,s,r,l,u,i,o);if(s.type==="one-to-many"){let c=await Ur(e,s,t,l,u,i,o);return qr(c)}if(s.type==="many-to-many"){let c=await Qr(e,s,t,l,u,i,o);return qr(c)}return{}}async function go(r,e,t,n,i,o,s){let l=z(e)||t,u=hn(r),c=mn(u);if(c!==null)return c?{[l]:{$ne:null}}:{[l]:null};let d=Hn(u);if(d!==null){let h=yn(d.value);if(d.op==="eq")return{$and:[{[l]:{$ne:h}},{[l]:{$ne:null}}]};if(d.op==="neq")return{[l]:h};if(d.op==="in")return{$and:[{[l]:{$nin:h}},{[l]:{$ne:null}}]};if(d.op==="not_in")return{[l]:{$in:h}}}let a=await gn(u,n,i,o,s);if(!a||Object.keys(a).length===0)return{[l]:null};let p=(await s.collection(n).find(a,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{[l]:{$ne:null}}:{$and:[{[l]:{$nin:p}},{[l]:{$ne:null}}]}}async function Ur(r,e,t,n,i,o,s){let l=K(e)||t,u=hn(r),c=mn(u);if(c!==null){let f=await Kr(s,n,l,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await gn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let a=await Kr(s,n,l,d);return a.length===0?{__impossible__:!0}:{_id:{$in:a}}}async function Qr(r,e,t,n,i,o,s){let l=Ne(t,e);if(!l)return{};let u=hn(r),c=mn(u);if(c!==null){let g=await Jn(s,l,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=Hn(u);if(d!==null){let g=yn(d.value),m=Array.isArray(g)?g:[g],y=await Jn(s,l,n,{_id:{$in:m}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let a=await gn(u,n,i,o,s);if(!a||Object.keys(a).length===0)return{};let p=(await s.collection(n).find(a,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let h=await Jn(s,l,n,{_id:{$in:p}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}async function gn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ne(r,o)?Te(r,e,n,i):ge(n,r,e)}async function Kr(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let l of i){let u=l[t];if(u==null)continue;let c=String(u);o.has(c)||(o.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 Jn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),l=new Set,u=[];for(let c of s){let d=c[e.selfColumn];if(d==null)continue;let a=String(d);l.has(a)||(l.add(a),u.push(d))}return u}function hn(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 yn(r){if(Array.isArray(r))return r.map(e=>yn(e));if(typeof r!="string")return r;try{return new Vn.ObjectId(r)}catch{return r}}function Hn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Vn.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 At(r,e,t,n){let i=await It(r,e,t),o=[],s={},l={};if(n&&typeof n=="object")for(let[p,h]of Object.entries(n))if(typeof h=="object"&&h!==null){let g=Object.keys(h)[0];g&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(g)?s[p]=h:l[p]=h}else s[p]=h;if(Object.keys(s).length>0){let p={};for(let[h,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[m,y]of Object.entries(g))an(r,p,e,h,m,y);else p[h]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,h]of Object.entries(l))if(!i.relations.some(m=>m.propertyName===p)){let m=c.find(y=>y.propertyName===p);if(m){let y="",b="";if(m.type==="many-to-one"||m.type==="one-to-one")y=z(m)||m.propertyName,b="_id";else if(m.type==="one-to-many")y="_id",b=K(m)||m.propertyName;else if(m.type==="many-to-many")continue;let $=m.type==="one-to-many"||m.type==="many-to-many";d.push({propertyName:p,targetTable:m.targetTableName,localField:y,foreignField:b,type:$?"many":"one",nestedFields:[]})}}let a=[...i.relations,...d];for(let p of a){let h=l[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await At(r,p.targetTable,p.nestedFields,h):h?await At(r,p.targetTable,["_id"],h):[];p.type==="one"&&g.length>0&&g.push({$limit:1}),o.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:g.length>0?g:void 0}}),p.type==="one"&&(o.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),h&&(Ve(h)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!a.some(h=>h.propertyName===p.propertyName));if(i.scalarFields.length>0||i.relations.length>0||f.length>0){let p={_id:1};for(let g of i.scalarFields)p[g]=1;for(let g of a)p[g.propertyName]=1,g.type==="one"&&g.localField&&g.localField!==g.propertyName&&(p[g.localField]=1);if(t.includes("*"))for(let g of f){if(g.type==="one-to-many"||g.type==="many-to-many")continue;g.type==="many-to-many"?p[g.propertyName]={$map:{input:`$${g.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[g.propertyName]={$cond:{if:{$ne:[`$${g.propertyName}`,null]},then:{_id:`$${g.propertyName}`},else:null}}}o.push({$project:p})}return o}async function Jr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],l=o?.columns||[],u=s.filter(d=>!i.some(a=>a.propertyName===d.propertyName)),c=n.length===l.length||n.length===0&&i.length===0;if(u.length>0||!c){let d={_id:1};for(let a of n)d[a]=1;for(let a of i)d[a.propertyName]=1,a.type==="one"&&a.localField&&a.localField!==a.propertyName&&(d[a.localField]=1);for(let a of u){if(a.type==="one-to-many"||a.type==="many-to-many")continue;a.type==="many-to-many"?d[a.propertyName]={$map:{input:`$${a.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[a.propertyName]={$cond:{if:{$ne:[`$${a.propertyName}`,null]},then:{_id:`$${a.propertyName}`},else:null}}}e.push({$project:d})}}function Ve(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ve(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ve(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ve(e));if("_not"in r)return Ve(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ve(t)))return!0}return!1}Ge();var jt=require("mongodb");Ge();bn();async function _n(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,c=r[u];n.set(String(c),await e(c))}}let s=Math.min(t,r.length);if(s===0)return n;let l=Array.from({length:s},o);return await Promise.all(l),n}var se="__sourceId__",ke="__targetId__",Ye="__enfyra_target__",Pt="__enfyra_top_n_documents__",Xe=class{constructor(e,t,n,i=new Ce){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=i;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/oe)||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 i={...t};for(let o of n)i[o]=1;e.push({$project:i})}}appendTopNStages(e,t,n,i,o){e.push({$group:{_id:`$${t}`,[Pt]:{$topN:{sortBy:n,output:"$$ROOT",n:i+o}}}},{$project:{[Pt]:{$slice:[`$${Pt}`,i,o]}}},{$unwind:`$${Pt}`},{$replaceRoot:{newRoot:`$${Pt}`}})}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 i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.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 i=n.startsWith("-"),o=i?n.slice(1):n;return{field:o==="id"?"_id":o,order:i?-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 i=Array.isArray(n)?n:n.split(",").map(c=>c.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let c of i){let a=(c.startsWith("-")?c.slice(1):c).split(".");if(a.length<=1)continue;let f=e;for(let p=0;p<a.length-1;p++){let h=a[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let m=g.relations?.find($=>$.propertyName===h);if(!m)break;let y=m.targetTableName||m.targetTable,b=`__sort_${a.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let $=z(m)||m.propertyName,C=p===0?null:`__sort_${a.slice(0,p).join("_")}`,T=C?`${C}.${$}`:$;o.push({$lookup:{from:y,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=y}}let l=this.buildSortFromTokens(n);l&&o.push({$sort:l});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new jt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof jt.ObjectId||t instanceof jt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let l=this.compareSortValues(i[s.field],o[s.field]);if(l!==0)return l*s.order}return this.compareSortValues(i._id,o._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},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof jt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(h=>h.name===f);p?o[p.name]=1:t.relations?.find(g=>g.propertyName===f)&&!i.has(f)&&i.set(f,["_id"])}i.forEach((f,p)=>{let h=t.relations?.find(g=>g.propertyName===p);h&&(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse)&&(s||(o[z(h)||h.propertyName]=1))}),s||(o._id=1);let l=[];i.forEach((f,p)=>{let h=t.relations?.find(b=>b.propertyName===p);if(!h)return;let g=h.targetTableName||h.targetTable;if(!g)return;let m,y;h.type==="many-to-one"||h.type==="one-to-one"?Ie(h)?(m="_id",y=K(h)||h.propertyName):(m=z(h)||h.propertyName,y="_id"):h.type==="one-to-many"?(m="_id",y=K(h)||h.propertyName):h.type==="many-to-many"&&(h.isInverse?(m="_id",y=h.mappedBy):(m=h.propertyName,y="_id")),l.push({relationName:p,type:h.type,targetTable:g,fields:f,isInverse:h.isInverse,fkColumn:h.foreignKeyColumn,mappedBy:h.mappedBy,junctionTableName:h.junctionTableName,junctionSourceColumn:h.junctionSourceColumn,junctionTargetColumn:h.junctionTargetColumn,localField:m,foreignField:y})});let u=!s&&Object.keys(o).length===1&&o._id===1&&l.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)o[f.newName]===1&&o[f.oldName]!==1&&(o[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:l,fetchSpec:{projection:s?void 0:o,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?ge(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),l=await W(t,c=>{let d={_id:{$in:c}};o&&Object.keys(o).length>0&&Object.assign(d,o);let a={projection:n.projection};return s&&(a.sort=s),this.runQuery(()=>this.db.collection(e).find(d,a).toArray())}),u=this.applyReadFallback(l,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let l=this.uniqueValues(n.map(y=>this.toObjectId(y))),u=o?.userFilter?ge(this.normalizeMetadata(),o.userFilter,e):null,c=o?.userLimit,d=o?.userPage,a=this.hasDottedSort(o?.userSort);if(c!==void 0&&c>0){let y=d?(d-1)*c:0;if(a)throw new Error(`Dotted sort is not supported for batch relation '${o?.relationName}'`);let b=this.buildStableSort(o?.userSort),$=await W(l,async C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,y,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let _=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(_,i)});return{docs:$,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(l),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:$.length}}}if(s&&(s[t]=1),a){let y=[],b=await _n(l,async $=>{let C={[t]:$};u&&Object.keys(u).length>0&&Object.assign(C,u);let T=this.buildSortAggregatePipeline(e,C,o.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,i)},Oe);for(let $ of b.values())for(let C of $)y.push(C);return{docs:y,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:l.length,concurrencyWaves:Math.ceil(l.length/Oe),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length}}}let f={[t]:{$in:l}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(o?.userSort)||{_id:1},h={projection:s,sort:p},g=await W(l,y=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:y},...u||{}},h).toArray())),m=this.applyReadFallback(g,i);return{docs:m,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(l),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.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 i=n.projection?{projection:n.projection}:void 0,o=await W(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},i).toArray()));return this.applyReadFallback(o,n)}async fetchM2MTopK(e,t,n,i,o,s,l){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let y of e)u.set(this.keyOf(y),[]);let c=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1,d=!o&&this.m2mSortCanUseJunction(t.userSort),a=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await W(e,async y=>{if(d){let C=[{$match:{[n.selfColumn]:{$in:y}}}];return this.appendTopNStages(C,n.selfColumn,{[n.otherColumn]:a},s,l),C.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:a}},{$project:{_id:0,[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[se],targetId:k[ke]}))}let b=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&b.push({$match:o}),this.appendTopNStages(b,se,f,s,l),b.push({$sort:{[se]:1,...f}}),b.push({$project:{_id:0,[se]:1,[ke]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(C=>({sourceId:C[se],targetId:C[ke]}))});if(c){let y=new Map;for(let b of p){let $=this.keyOf(b.targetId);y.has($)||y.set($,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(y.get($))}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(y=>y.targetId)),g=await this.loadM2MTargets(t.targetTable,h,i),m=new Map(g.map(y=>[this.keyOf(y._id),y]));for(let y of p){let b=m.get(this.keyOf(y.targetId));b&&u.get(this.keyOf(y.sourceId))?.push(b)}return{grouped:u,docs:g,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(h.length>0?this.chunkCount(h):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+g.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,i,o){let s=new Map;for(let g of e)s.set(this.keyOf(g),[]);let l=!o&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(g=>g.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await W(e,async g=>{if(l)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:g}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map($=>({sourceId:$[n.selfColumn],targetId:$[n.otherColumn]}));let m=[{$match:{[n.selfColumn]:{$in:g}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&m.push({$match:o}),m.push({$sort:{[se]:1,...c}},{$project:{_id:0,[se]:1,[ke]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(m).toArray())).map(b=>({sourceId:b[se],targetId:b[ke]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let m of d){let y=this.keyOf(m.targetId);g.has(y)||g.set(y,{_id:m.targetId}),s.get(this.keyOf(m.sourceId))?.push(g.get(y))}return{grouped:s,docs:[],stats:{strategy:l?"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(g=>g.targetId)),p=await this.loadM2MTargets(t.targetTable,f,i),h=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let m=h.get(this.keyOf(g.targetId));m&&s.get(this.keyOf(g.sourceId))?.push(m)}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,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let l=Ne(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(!l)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?ge(this.normalizeMetadata(),t.userFilter,t.targetTable):null,a=t.userLimit,f=t.userPage;if(a!==void 0&&a>0){let k=f?(f-1)*a:0;return this.fetchM2MTopK(u,t,l,o,d,k,a)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,h=this.hasDottedSort(t.userSort);if(!h)return this.fetchM2MEdgeBatch(u,t,l,o,d);let g=await W(u,k=>this.runQuery(()=>this.db.collection(l.junctionName).find({[l.selfColumn]:{$in:k}},{projection:{_id:0,[l.selfColumn]:1,[l.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let m=new Set,y=[];for(let k of g){let _=k[l.otherColumn];if(_==null)continue;let F=this.keyOf(_);m.has(F)||(m.add(F),y.push(_))}let b=[],$=new Map;if(p)b=y.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:y}};d&&Object.keys(d).length>0&&Object.assign(k,d);let _;if(h){let F=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&F.push({$project:o.projection}),_=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(F).toArray())}else{let F=this.buildSortFromTokens(t.userSort)||{_id:1},O=this.projectionWithSortFields(o.projection,t.userSort),B={sort:F};O.projection&&(B.projection=O.projection),_=await W(y,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},B).toArray())),t.userSort?this.sortDocsInMemory(_,t.userSort):this.sortDocsByPk(_),this.removeHiddenFields(_,O.hiddenFields)}b=this.applyReadFallback(_,o)}for(let k of b)$.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let _=this.keyOf(k[l.selfColumn]),F=this.keyOf(k[l.otherColumn]);$.has(F)&&(C.has(F)||C.set(F,[]),C.get(F).push(_))}for(let k of b){let _=C.get(this.keyOf(k._id))||[];for(let F of _)c.get(F)?.push(k)}let T=p||y.length===0?0:this.chunkCount(y);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function wn(r,e,t,n,i=3,o=0,s,l,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),a=new Xe(r,l,d);await new Se(a,n,u).execute(e,t,i,o,s)}async function Xn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:l}=t,u=o?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!o&&ne(e.mongoRawFilter,c),a=e.plan,f=a?.filterTree&&!a.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&d){let S=await Te(e.mongoRawFilter,e.table,o,i);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=ze(a.filterTree,{metadata:o,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=Qe(o,e.where,e.table,s);n.push({$match:S})}let p=e.plan,g=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let E=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===E)??!1})??!1,m=()=>p?.sortItems?$o(p.sortItems):e.sort?wo(e.sort):null,y=p?.sortItems?ho(p.sortItems):[],b=p?.sortItems?mo(p.sortItems):[],$=()=>{!p||y.length===0||yo(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||bo(n,e.table,p.sortItems,o)},T=()=>{let S=[...y,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(E=>[E,0]))})};if(!e.mongoFieldsExpanded){$(),C();let S=m();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})),T(),e.select){let A={};for(let L of e.select)A[L]=1;n.push({$project:A})}l&&l.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let E=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:E,pipeline:n}:{results:Vr(E),pipeline:n}}let{scalarFields:k,relations:_}=e.mongoFieldsExpanded;if(!g){$(),C();let S=m();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 F=[];for(let S of _)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let w=await At(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&w.length>0&&w.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:w.length>0?w:void 0}})}else if(A){let w=await At(o,S.targetTable,["_id"],A);S.type==="one"&&w.length>0&&w.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:w.length>0?w: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&&(Ze(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else F.push(S);if(g){$(),C();let S=m();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}))}T(),await Jr(o,n,e.table,k,[..._]),e.mongoCountOnly&&n.push({$count:"count"}),l&&l.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let O=performance.now(),B=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",O,{table:e.table}),e.mongoCountOnly)return{results:B,pipeline:n};if(F.length>0&&B.length>0){let S=e.deep||{},E=F.map(L=>{let R=o?.tables?.get(e.table)?.relations?.find(N=>N.propertyName===L.propertyName),x=S[L.propertyName],Z=x?.fields!=null?Array.isArray(x.fields)?x.fields:String(x.fields).split(",").map(N=>N.trim()).filter(Boolean):L.nestedFields&&L.nestedFields.length>0?L.nestedFields:["_id"];return{relationName:L.propertyName,type:R?.type,targetTable:L.targetTable,fields:Z,isInverse:R?.isInverse,mappedBy:R?.mappedBy,junctionTableName:R?.junctionTableName,junctionSourceColumn:R?.junctionSourceColumn,junctionTargetColumn:R?.junctionTargetColumn,localField:L.localField,foreignField:L.foreignField,userFilter:x?.filter,userSort:x?.sort,userLimit:x?.limit!==void 0?Number(x.limit):void 0,userPage:x?.page!==void 0?Number(x.page):void 0,nestedDeep:x?.deep}}),A=_o(o);A&&await wn(i,B,E,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Vr(B),pipeline:n}}function Zn(r){return`__sort_count_${r.relationName||r.field}`}function er(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function ho(r){return r.filter(e=>e.function==="count").map(Zn)}function mo(r){return r.filter(e=>e.function==="max"||e.function==="min").map(er)}function yo(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let l=s.relationMeta,u=s.relationName||s.field,c=l?.targetTableName||l?.targetTable,d=Zn(s);if(!(!l||!c)){if(l.type==="one-to-many"){let a=K(l)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${a}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(l.type==="many-to-many"){let a=Ne(e,l);if(!a)continue;r.push({$lookup:{from:a.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${a.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function bo(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let l=s.relationMeta,u=s.relationName||s.field,c=l?.targetTableName||l?.targetTable,d=n?.tables?.get(c),a=d?.columns?.find(m=>m.isPrimary)?.name||(d?.columns?.some(m=>m.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(m=>m.name==="_id")?"_id":f,h=er(s),g=s.function==="min"?"$min":"$max";if(!(!l||!c||!f)){if(l.type==="one-to-many"){let m=K(l)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${m}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}});continue}if(l.type==="many-to-many"){let m=Ne(e,l);if(!m)continue;let y=`${h}_junction`;r.push({$lookup:{from:m.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${m.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${m.otherColumn}`}}],as:y}}),r.push({$lookup:{from:c,let:{targetIds:`$${y}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${a}`,"$$targetIds"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}}),r.push({$project:{[y]:0}})}}}}function _o(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function wo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function $o(r){let e={};for(let t of r){let n=t.function==="count"?Zn(t):t.function==="max"||t.function==="min"?er(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Ze(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ze(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ze(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ze(e));if("_not"in r)return Ze(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ze(t)))return!0}return!1}function Vr(r){return r.map(te)}function Hr(r,e){let t=[],n=[],i=e?.tables?.get(r.rootTable);if(!i)return{scalarFields:t,relations:n};for(let o of r.nodes)if(o.kind==="wildcard")for(let s of i.columns||[])t.includes(s.name)||t.push(s.name);else o.kind==="scalar"?i.columns?.some(l=>l.name===o.name)&&!t.includes(o.name)&&t.push(o.name):o.kind==="relation"&&n.push(To(o,i,e));return{scalarFields:t,relations:n}}function To(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ie(n)?(i="_id",o=K(n)||r.propertyName,s=!0):(i=n&&z(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&K(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let l=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Gr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:l?"many":"one",isInverse:s,nestedFields:u}}function Gr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Gr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Je();Ot();Et();function $n(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(a=>a.name==="_id"&&a.isPrimary),l=o.columns?.some(a=>a.name==="id"),u=s&&!l?"_id":"id",c=new Map,d=[];for(let a of r){let f=a==="id"?u:a;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),h=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(y=>y.propertyName===h))continue;c.has(h)||c.set(h,[]),c.get(h).push(g)}else if(o.relations?.some(h=>h.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!o.columns?.some(g=>g.name===f))continue;d.push(f)}}if(d.includes("*")){i.nodes.push({kind:"wildcard"});for(let a of o.relations||[])c.has(a.propertyName)||c.set(a.propertyName,[u])}else for(let a of d)i.nodes.push({kind:"scalar",name:a});for(let[a,f]of c.entries()){let p=o.relations?.find(m=>m.propertyName===a);if(!p)continue;let h=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:a,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:h,children:Yr(f,h,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let m=n.registerWithParent(e,a,t,"left",null,"data");g.joinId=m}i.nodes.push(g)}return i}function Yr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),o=n.columns?.some(d=>d.name==="id"),s=i&&!o?"_id":"id",l=new Map,u=[];for(let d of r){let a=d==="id"?s:d;if(a==="*")u.push("*");else if(a.includes(".")){let f=a.indexOf("."),p=a.substring(0,f),h=a.substring(f+1);if(!n.relations?.some(m=>m.propertyName===p))continue;l.has(p)||l.set(p,[]),l.get(p).push(h)}else if(n.relations?.some(p=>p.propertyName===a))l.has(a)||l.set(a,[s]);else{if(!n.columns?.some(h=>h.name===a))continue;u.push(a)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])l.has(d.propertyName)||l.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,a]of l.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:Yr(a,p,t)})}return c}de();de();var So=new Set(["_and","_or","_not"]);function Xr(r,e){return r?.tables?.get(e)??null}function Co(r,e,t){return Xr(r,e)?.columns?.find(n=>n.name===t)}function tr(r,e,t){return Xr(r,e)?.relations?.find(n=>n.propertyName===t)}function ko(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 i=n.indexOf(".");return i<=0||i!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,i).trim(),fieldName:n.slice(i+1).trim()}}function nr(r,e,t,n){if(Co(r,e,t)?.isEncrypted===!0)throw new I(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Me(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Me(n,e,t);return}for(let[n,i]of Object.entries(r)){if(So.has(n)){Me(i,e,t);continue}if(n.startsWith("_"))continue;let o=tr(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Me(i,s,t);continue}nr(t,e,n,"filter")}}}function Tn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(!o)continue;let s=ko(o);if(s){if(s.functionName==="count")continue;let c=tr(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&nr(t,d,s.fieldName,"sort");continue}let l=o.split("."),u=e;for(let c=0;c<l.length;c++){let d=l[c];if(c===l.length-1){nr(t,u,d,"sort");break}let f=tr(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var X=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:l,meta:u,metadata:c,dbType:d}=e,a=c?.tables?.get(t),f=new ie,p=this.parseFields(n),h=null;p&&a&&(h=$n(p,t,c,f));let g=!1,m=null;if(i&&a){Me(i,t,c);let S=fe(i,t,c,f);m=S.node,g=S.hasRelationFilters}let y=this.parseSort(o);a&&Tn(y,t,c);let b=[],$=!1;for(let S of y){let E=S.startsWith("-"),A=E?S.substring(1):S,L=E?"desc":"asc";if(a){let w=this.parseRelationAggregateSort(t,a,A,c);if(w){b.push({joinId:null,field:A,direction:L,fullPath:A,function:w.functionName,relationName:w.relationName,aggregateField:w.aggregateField,relationMeta:w.relationMeta});continue}this.assertLocalSortField(t,a,A)}b.push({joinId:null,field:A,direction:L,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let C=this.parseLimit(l),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,_=this.parseMeta(u),F=_.includes("totalCount")||_.includes("*"),O=_.includes("filterCount")||_.includes("*"),B=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:B,sortItems:b,limit:C,offset:k,needsTotalCount:F,needsFilterCount:O,hasRelationFilters:g,hasRelationSort:$,filterTree:m,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 I(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new I(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],l=o[2].trim();if(s==="count"){let m=l;if(!m||m.includes("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let y=t.relations?.find(b=>b.propertyName===m);if(!y)throw new I(`Sort relation '${m}' does not exist on '${e}'.`);if(y.type!=="one-to-many"&&y.type!=="many-to-many")throw new I(`Sort function '_count(${m})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:m,relationMeta:y}}let u=l.indexOf(".");if(u<=0||u!==l.lastIndexOf("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=l.slice(0,u).trim(),d=l.slice(u+1).trim();if(!c||!d)throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let a=t.relations?.find(m=>m.propertyName===c);if(!a)throw new I(`Sort relation '${c}' does not exist on '${e}'.`);if(a.type!=="one-to-many"&&a.type!=="many-to-many")throw new I(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=a.targetTableName||a.targetTable,p=i?.tables?.get(f);if(!p)throw new I(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let h=p.columns?.find(m=>m.name===d),g=d==="id"&&p.columns?.some(m=>m.name==="_id");if(!h&&!g)throw new I(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(h?.isEncrypted===!0)throw new I(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:a}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let l=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===l);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let a=i.registerWithParent(t,l,n,"left",o,"sort");if(!a)return null;if(!u.includes("."))return{lastJoinId:a,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,i,a)}};de();var Ro=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Fo=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),xo=new Set(["hour","day","week","month","year"]),vo=new Set(["count","countDistinct","sum","avg","min","max"]);function M(r,e){throw new I(e,{path:r})}function et(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Io(r,e){let t=r?.tables?.get(e);return t||M("aggregate",`Table "${e}" metadata is not available`),t}function Zr(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||M(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&M(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function No(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&M(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{M(e,`Invalid aggregate timezone "${t}"`)}return t}function Eo(r,e){return r==null?{}:(et(r)||M(e,"Aggregate filter must be an object"),r)}function tt(r,e,t){et(r)||M("aggregate","Aggregate options must be an object");let n=Io(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||M("aggregate.dimensions","Aggregate dimensions must be an array"),(!et(o)||Object.keys(o).length===0)&&M("aggregate.measures","Aggregate requires at least one measure");let s=new Set,l=i.map((g,m)=>{let y=`aggregate.dimensions[${m}]`;(!et(g)||typeof g.field!="string"||g.field.length===0)&&M(y,"Aggregate dimension requires a field");let b=Zr(n,g.field,`${y}.field`);return s.has(g.field)&&M(`${y}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&M(`${y}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!xo.has(g.bucket))&&M(`${y}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Fo.has(String(b.type).toLowerCase())||M(`${y}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:No(g.timezone,`${y}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,m])=>{let y=`aggregate.measures.${g}`;(!g||!et(m))&&M(y,"Aggregate measure must be an object");let b=Object.entries(m).filter(([k])=>k!=="as");b.length!==1&&M(y,"Aggregate measure must define exactly one operation");let[$,C]=b[0];vo.has($)||M(y,`Unsupported aggregate measure "${$}"`),(typeof C!="string"||C.length===0)&&M(y,"Aggregate measure field must be a non-empty string");let T=Zr(n,C,`${y}.${$}`);return(u.has(g)||s.has(g))&&M(y,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes($)&&!Ro.has(String(T.type).toLowerCase())&&M(y,`Aggregate ${$} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:$,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||M("aggregate.sort","Aggregate sort must be an array");let a=new Set([...s,...u]),f=d.map((g,m)=>{let y=`aggregate.sort[${m}]`;return(!et(g)||typeof g.field!="string"||!a.has(g.field))&&M(y,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&M(`${y}.direction`,"Aggregate sort direction must be asc or desc"),{field:g.field,direction:g.direction}}),p=r.limit===void 0?void 0:Number(r.limit),h=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&M("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(h)||h<=0)&&M("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Eo(r.filter,"aggregate.filter"),dimensions:l,measures:c,sort:f,page:h,limit:p}}var Ae=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 a=new X;e={...e,plan:a.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,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(a=>a.trim()))),e.filter&&(re(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let a=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(f=>f.trim());n.sort=a.map(f=>{let p=f.trim();return p.startsWith("-")?{field:p.substring(1),direction:"desc"}:{field:p,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let a=typeof e.page=="string"?parseInt(e.page,10):e.page,f=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(a-1)*f,n.limit=f}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(a=>a.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let l=this.metadata?.tables?.get(e.tableName),u=new Set((l?.relations??[]).map(a=>a.propertyName)),c=!!n.mongoRawFilter&&ne(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!c){let a=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?ze(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await a.countDocuments(f)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let a=this.lastBuiltPipeline??[],f;try{f=await this.db.collection(e.tableName).aggregate(a).explain()}catch(p){f={error:String(p)}}return{pipeline:a,explain:f}}if(c&&(i.includes("filterCount")||i.includes("*"))){let a={...n,mongoCountOnly:!0},f=await this.selectLegacy(a);s=f.length>0?f[0].count:0}return{data:d,...i.length>0&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{}}}}}async aggregate(e){this.metadata=e.metadata,this.dbType=e.dbType||"mongodb";let t=tt(e.aggregate,e.tableName,e.metadata),n=this.db.collection(e.tableName),i=new X().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await Te(t.filter,e.tableName,e.metadata,this.db):i.filterTree?ze(i.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(o).length>0&&s.push({$match:o});let l={_id:{}},u={};for(let d of t.dimensions){let a=`$${d.field}`,f=d.bucket?{$dateTrunc:{date:a,unit:d.bucket,timezone:d.timezone}}:a;l._id[d.outputKey]=f,u[d.outputKey]=`$_id.${d.outputKey}`}for(let d of t.measures){let a=`$${d.field}`;l[d.outputKey]=d.operation==="count"?{$sum:{$cond:[{$ne:[a,null]},1,0]}}:d.operation==="countDistinct"?{$addToSet:a}:{[`$${d.operation}`]:a},u[d.outputKey]=d.operation==="countDistinct"?{$size:{$setDifference:[`$${d.outputKey}`,[null]]}}:`$${d.outputKey}`}return s.push({$group:l},{$project:{_id:0,...u}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(d=>[d.field,d.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),this.lastBuiltPipeline=s,e.debugMode?{pipeline:s,explain:await n.aggregate(s).explain()}:{data:(await n.aggregate(s).toArray()).map(te)}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=this.metadata?.tables?.get(e.table),o=i?.relations&&i.relations.length>0;if(e.fields&&e.fields.length>0||n||o){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=Hr(c.fieldTree,this.metadata),n){let a=await It(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...a.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 It(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.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(te);let{results:l,pipeline:u}=await Xn(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,l,t):l}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Xn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var Sn=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}};de();ae();var Oo=["_and","_or","_not"];function he(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>he(e));for(let e of Object.keys(r))if(Oo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&he(r[e]))return!0;return!1}var ei=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Mo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Cn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function Ao(r,e,t,n,i){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)||Cn(r,t,i),e}function ti(r,e,t,n,i,o,s){let l=i&&!e.includes(".")?`${i}.${e}`:e,u=Re(l,o??"postgres"),c=Cn(e,i,s),d=Ao(e,n,i,o,s);switch(t){case"_eq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(l,"=",d);break;case"_neq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(l,"!=",d);break;case"_gt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(l,">",d);break;case"_gte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(l,">=",d);break;case"_lt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(l,"<",d);break;case"_lte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(l,"<=",d);break;case"_in":let a=n;Array.isArray(a)||(a=typeof a=="string"&&a.includes(",")?a.split(",").map(p=>p.trim()):[a]),c&&o==="postgres"&&a.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[a]):r.whereIn(l,a);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&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(l,f);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="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":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="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":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="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(l,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(l):r.whereNotNull(l);break;case"_is_not_null":n===!0?r.whereNotNull(l):r.whereNull(l);break;default:r.where(l,Mo(t),n)}}function Po(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function nt(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){nt(this,s,t,"and",i,o)}):r.orWhere(function(){nt(this,s,t,"and",i,o)});return}for(let[s,l]of Object.entries(e))if(Po(s,t,o)){if(s==="_and"){Array.isArray(l)&&r.where(function(){for(let u of l)this.where(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(l)&&r.where(function(){for(let u of l)this.orWhere(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){nt(this,l,t,"and",i,o)});continue}if(typeof l=="object"&&l!==null)if(Object.keys(l).some(c=>ei.includes(c)))for(let[c,d]of Object.entries(l))ei.includes(c)&&(n==="and"?r.where(function(){ti(this,s,c,d,t,i,o)}):r.orWhere(function(){ti(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Re(c,i??"postgres");Cn(s,t,o)&&i==="postgres"&&typeof l=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l)?n==="and"?r.whereRaw(`${d} = ?::uuid`,[l]):r.orWhereRaw(`${d} = ?::uuid`,[l]):n==="and"?r.where(c,"=",l):r.orWhere(c,"=",l)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=Re(u,i??"postgres");Cn(s,t,o)&&i==="postgres"&&typeof l=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l)?n==="and"?r.whereRaw(`${c} = ?::uuid`,[l]):r.orWhereRaw(`${c} = ?::uuid`,[l]):n==="and"?r.where(u,"=",l):r.orWhere(u,"=",l)}}}}function le(r,e,t,n,i){return!e||typeof e!="object"||nt(r,e,t,"and",n,i),r}ae();function or(r,e,t){return`${v(r,t)}.${v(e,t)}`}function Fe(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 ni(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function rt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function sr(r,e,t,n,i,o){let s=[];for(let[l,u]of Object.entries(o)){let c=await Bt(r,e,l,u,t,n,i);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(a=>a.propertyName===l);if(d&&d.foreignKeyColumn){let a=or(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let h=rt(p._is_null),g=rt(p._is_not_null);if(h===!0)s.push(`${a} IS NULL`);else if(h===!1)s.push(`${a} IS NOT NULL`);else if(g===!0)s.push(`${a} IS NOT NULL`);else if(g===!1)s.push(`${a} IS NULL`);else if(p._eq!==void 0){let m=Fe(p._eq,n);s.push(`${a} = ${m}`)}else if(p._neq!==void 0){let m=Fe(p._neq,n);s.push(`${a} != ${m}`)}else if(p._in!==void 0){let y=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Fe(b,n)).join(", ");s.push(`${a} IN (${y})`)}else if(p._not_in!==void 0||p._nin!==void 0){let m=p._not_in??p._nin,b=(Array.isArray(m)?m:[m]).map($=>Fe($,n)).join(", ");s.push(`${a} NOT IN (${b})`)}else if(p._gt!==void 0){let m=Fe(p._gt,n);s.push(`${a} > ${m}`)}else if(p._gte!==void 0){let m=Fe(p._gte,n);s.push(`${a} >= ${m}`)}else if(p._lt!==void 0){let m=Fe(p._lt,n);s.push(`${a} < ${m}`)}else if(p._lte!==void 0){let m=Fe(p._lte,n);s.push(`${a} <= ${m}`)}}}}}return s}function ar(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 rr(r,e,t,n,i,o){let s=[];for(let l of r)if(l._and&&Array.isArray(l._and)&&l._and.length>0){let u=[];for(let c of l._and)if(ar(c)){let d=e(t).select(`${t}.id`);await Pe(e,d,c,t,n,i,o),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:a}=V(c,n),f=await sr(e,t,n,i,o,a);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(ar(l)){let u=e(t).select(`${t}.id`);await Pe(e,u,l,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=V(l,n),d=await sr(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ri(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&le(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function ir(r,e,t,n,i){let o=!0;for(let s of e){let l=function(){for(let u of s)ri(this,u,t,n,i)};o?(r.where(l),o=!1):r.orWhere(l)}}function kn(r,e,t,n,i,o,s){let l=ni(e,i),u=ni(n,o),c=`${v(r,s)}.${v(e,s)}`,d=`${v(t,s)}.${v(n,s)}`;if(s==="postgres"){if(l&&!u)return`${c} = ${d}::uuid`;if(!l&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Bt(r,e,t,n,i,o,s){let l=i.relations.find(f=>f.propertyName===t);if(!l)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=l.targetTableName||l.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(l,null,2)}`);let c=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((l.type==="many-to-one"||l.type==="one-to-one")&&l.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,a;switch(l.type){case"one-to-many":a=r(u).select(r.raw("1")).whereRaw(kn(u,l.foreignKeyColumn,e,"id",d,i,o));break;case"many-to-many":let f=s?await s(l.junctionTableName):null;a=r(l.junctionTableName).select(r.raw("1")).join(u,r.raw(kn(l.junctionTableName,l.junctionTargetColumn,u,"id",f,d,o))).whereRaw(kn(l.junctionTableName,l.junctionSourceColumn,e,"id",f,i,o));break;case"many-to-one":case"one-to-one":a=r(u).select(r.raw("1")).whereRaw(kn(u,"id",e,l.foreignKeyColumn,d,i,o));break;default:throw new Error(`Unsupported relation type: ${l.type}`)}return s?d?await Pe(r,a,n,u,d,o,s):a=le(a,n,u,o,d||void 0):a=le(a,n,u,o),a.toString()}async function Pe(r,e,t,n,i,o,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 rr(c._or,r,n,i,o,s);e.where(function(){ir(this,d,n,i,o)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Pe(r,e,d,n,i,o,s);else await Pe(r,e,c,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let c=await rr(t._or,r,n,i,o,s);e.where(function(){ir(this,c,n,i,o)});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(ar(p)){let h=r(n).select(`${n}.id`);await Pe(r,h,p,n,i,o,s),f.push({idSubquery:h})}else{let{fieldFilters:h,relationFilters:g}=V(p,i),m=await sr(r,n,i,o,s,g);f.push({fieldFilters:h,subqueries:m})}e.whereNot(function(){for(let p of f)ri(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await rr(c._or,r,n,i,o,s);e.whereNot(function(){ir(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:a}=V(c,i);e.whereNot(function(){Object.keys(d).length>0&&le(this,d,n,o,i)});for(let[f,p]of Object.entries(a)){let h=await Bt(r,n,f,p,i,o,s);if(h===null){let g=i.relations.find(m=>m.propertyName===f);if(g&&g.foreignKeyColumn){let m=or(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let $=rt(b._is_null),C=rt(b._is_not_null);if($===!0)e.whereRaw(`${m} IS NOT NULL`);else if($===!1)e.whereRaw(`${m} IS NULL`);else if(C===!0)e.whereRaw(`${m} IS NULL`);else if(C===!1)e.whereRaw(`${m} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${m} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${m} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${m} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${m} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${h})`)}return}let{fieldFilters:l,relationFilters:u}=V(t,i);Object.keys(l).length>0&&le(e,l,n,o,i);for(let[c,d]of Object.entries(u)){let a=await Bt(r,n,c,d,i,o,s);if(a===null){let f=i.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=or(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let m=rt(g._is_null),y=rt(g._is_not_null);if(m===!0)e.whereRaw(`${p} IS NULL`);else if(m===!1)e.whereRaw(`${p} IS NOT NULL`);else if(y===!0)e.whereRaw(`${p} IS NOT NULL`);else if(y===!1)e.whereRaw(`${p} IS NULL`);else if(g._eq!==void 0)e.whereRaw(`${p} = ?`,[g._eq]);else if(g._neq!==void 0)e.whereRaw(`${p} != ?`,[g._neq]);else if(g._in!==void 0){let b=Array.isArray(g._in)?g._in:[g._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(g._not_in!==void 0||g._nin!==void 0){let b=g._not_in??g._nin,$=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${$.map(()=>"?").join(", ")})`,$)}}}}else e.whereRaw(`EXISTS (${a})`)}}async function Lt(r,e,t,n,i,o,s){await Pe(r,e,t,n,i,o,s)}ae();ae();function it(r,e,t,n,i){for(let o of e){let s=o.field.split("."),l=t||s[0],u=s[s.length-1],c=Dt(n,l,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",c);break;case"!=":r=r.where(o.field,"!=",c);break;case">":r=r.where(o.field,">",c);break;case"<":r=r.where(o.field,"<",c);break;case">=":r=r.where(o.field,">=",c);break;case"<=":r=r.where(o.field,"<=",c);break;case"like":r=r.where(o.field,"like",c);break;case"in":let d=Array.isArray(o.value)?o.value.map(g=>Dt(n,l,u,g)):[c];r=r.whereIn(o.field,d);break;case"not in":let a=Array.isArray(o.value)?o.value.map(g=>Dt(n,l,u,g)):[c];r=r.whereNotIn(o.field,a);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let f=o.value;if(typeof f=="string"&&(f=f.split(",").map(g=>g.trim())),Array.isArray(f)&&f.length===2){let g=Dt(n,l,u,f[0]),m=Dt(n,l,u,f[1]);r=r.whereBetween(o.field,[g,m])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Wt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,l]of Object.entries(r))if(s==="_and"&&Array.isArray(l)){let u=l.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(l)){let u=l.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof l=="object"&&l!==null){let u=Wt(l,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof l=="object"&&l!==null&&!Array.isArray(l))for(let[u,c]of Object.entries(l)){let d=`${v(e,n)}.${v(s,n)}`,a;if(c===null)a="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=o.columns?.find(g=>g.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?a=`'${c}'::uuid`:a=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?a=c?"true":"false":typeof c=="number"?a=String(c):a=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${d} = ${a}`);else if(u==="_neq")i.push(`${d} != ${a}`);else if(u==="_gt")i.push(`${d} > ${a}`);else if(u==="_gte")i.push(`${d} >= ${a}`);else if(u==="_lt")i.push(`${d} < ${a}`);else if(u==="_lte")i.push(`${d} <= ${a}`);else if(u==="_is_null")i.push(`${d} IS NULL`);else if(u==="_is_not_null")i.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(", ");i.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(", ");i.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):i.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]);i.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${v(e,n)}.${v(s,n)}`,c;l===null?c="NULL":typeof l=="string"?c=`'${l.replace(/'/g,"''")}'`:typeof l=="boolean"?c=l?"true":"false":c=String(l),i.push(`${u} = ${c}`)}return i}function Kt(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Dt(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.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}}cr();Je();ae();qt();Ke();async function si(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:l}=await Promise.resolve().then(()=>(dr(),oi)),u=await l(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function fr(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function ai(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||J(r.propertyName);if(!s)return null;let l=a=>v(a,i),u=n?.tables?.get(o),d=(u?H(u):null)?.name||"id";return`(SELECT ${l(o)}.${l(e)} FROM ${l(o)} WHERE ${l(o)}.${l(d)} = ${l(t)}.${l(s)})`}qt();var je=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new Sn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&re(e.filter,e.tableName,e.metadata),!e.plan){let w=new X;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 o=e.plan,s=e.metadata?.tables?.get(e.tableName),l=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,c=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!l&&c){i&&i.setQueryPath("simple");let w=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),w}let a={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?a.fields=e.fields:typeof e.fields=="string"&&(a.fields=e.fields.split(",").map(w=>w.trim())));let f=e.filter;if(e.filter&&!he(e.filter)){a.where=[];for(let[w,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[x,Z]of Object.entries(R)){let N;if(x==="_eq")N="=";else if(x==="_neq")N="!=";else if(x==="_in")N="in";else if(x==="_not_in"||x==="_nin")N="not in";else if(x==="_gt")N=">";else if(x==="_gte")N=">=";else if(x==="_lt")N="<";else if(x==="_lte")N="<=";else if(x==="_contains")N="_contains";else if(x==="_starts_with")N="_starts_with";else if(x==="_ends_with")N="_ends_with";else if(x==="_between")N="_between";else if(x==="_is_null")N="_is_null";else if(x==="_is_not_null")N="_is_not_null";else if(x==="_like")N="like";else if(x==="_ilike")N="ilike";else continue;a.where.push({field:w,operator:N,value:Z})}else a.where.push({field:w,operator:"=",value:R})}if(e.sort){let w=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());a.sort=w.map(R=>{let x=R.trim();return x.startsWith("-")?{field:x.substring(1),direction:"desc"}:{field:x,direction:"asc"}})}else a.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,g=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,m=g===void 0||Number.isNaN(g)?void 0:g;m&&h!==void 0?(a.offset=(m-1)*h,a.limit=h):h!==void 0&&(a.limit=h);let y=e.plan?.sortItems??(a.sort??[]).map(w=>({joinId:null,field:w.field,direction:w.direction,fullPath:w.field})),b=[],$=[];for(let w of y){if(w.function==="count"){let R={sql:this.buildRelationCountSortSubquery(a.table,w),direction:w.direction};$.push(R);continue}if(w.function==="max"||w.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(a.table,w),direction:w.direction};$.push(R);continue}if(w.joinId===null){if(w.field.includes(".")&&!e.plan){let x=w.field.split(".")[0];if(this.metadata?.tables?.get(a.table)?.relations?.some(U=>U.propertyName===x))continue}let R={field:w.field.includes(".")?w.field:`${a.table}.${w.field}`,direction:w.direction};b.push(R),$.push(R)}else{let R=e.plan?.joins.find(x=>x.id===w.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let x=ai(R.relationMeta,w.field,a.table,this.metadata,this.dbType);if(x){let Z={sql:x,direction:w.direction};$.push(Z)}}}}let C=[];if(a.fields&&a.fields.length>0||u||l){let w=fr(this.metadata),R=a.fields&&a.fields.length>0?a.fields:["*"],x=await si(this.knex,a.table,R,w,this.dbType,this.maxQueryDepth,e.deep);x.select.length>0&&(a.select=[...a.select||[],...x.select]),C=x.batchFetchDescriptors||[]}a.where&&(a.where=a.where.map(w=>w.field.includes(".")?w:{...w,field:`${a.table}.${w.field}`})),a.sort=b;let T=this.knex(a.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(w=>w.trim()).filter(Boolean),_=k.includes("filterCount")||k.includes("*"),F=k.includes("totalCount")||k.includes("*");if(a.select){let w=a.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select(w)}if(_&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),F){let w=v(a.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) as __total_count__`))}let O=["table_definition","column_definition","relation_definition","method_definition"].includes(a.table);if(f&&(he(f)||Object.keys(f).length>0)){let w=this.metadata?.tables?.get(a.table);(!O&&w&&w.relations&&w.relations.length>0?V(f,w).hasRelations:!1)?await Lt(this.knex,T,f,a.table,w,this.dbType,x=>this.metadata?.tables?.get(x)):e.plan?.filterTree?ce(T,e.plan.filterTree,{dbType:this.dbType,rootTable:a.table}):(this.logger.debug(`buildWhereClause fallback for table=${a.table}`),T=le(T,f,a.table,this.dbType,w))}else a.where&&a.where.length>0&&(T=it(T,a.where,a.table,this.metadata,this.dbType));for(let w of $)if(w.field){let R=w.field.includes(".")?w.field:`${a.table}.${w.field}`;T=T.orderBy(R,w.direction)}else w.sql&&(T=T.orderByRaw(`${w.sql} ${w.direction.toUpperCase()}`));a.groupBy&&(T=T.groupBy(a.groupBy)),a.offset&&(T=T.offset(a.offset)),a.limit!==void 0&&a.limit!==null&&a.limit>0&&(T=T.limit(a.limit));let B=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:a.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&i){let w=T.toSQL().toNative();i.setSql(w.sql);try{let R=w.sql.replace(/\$\d+/g,"?"),x=await this.knex.raw(`EXPLAIN ${R}`,w.bindings);i.setExplain(this.dbType==="postgres"?x.rows:x[0])}catch(R){i.setExplain({error:String(R)})}}let E,A=performance.now();E=await T,i&&i.dur("db_execute",A,{table:e.tableName});let L=0;if(_&&E.length>0&&(L=Number(E[0].__filter_count__||0),E.forEach(w=>{delete w.__filter_count__})),F&&E.length>0&&E[0].__total_count__!==void 0&&(B=Number(E[0].__total_count__||0),E.forEach(w=>{delete w.__total_count__})),C&&C.length>0&&E.length>0){let w=fr(this.metadata);if(w){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(hr(),li));await R(this.knex,E,C,w,this.maxQueryDepth??3,0,a.table,this.dbType,this.metadata,i)}}if(this.knexService){let w=performance.now();E=await this.knexService.parseResult(E,a.table),i&&i.dur("db_parseResult",w,{table:e.tableName})}else{let w=(R,x)=>{if(!R||!this.metadata)return R;let Z=this.metadata.tables?.get(x);if(!Z)return R;if(Array.isArray(R))return R.map(U=>w(U,x));if(typeof R!="object"||Buffer.isBuffer(R))return R;let N={...R};for(let U of Z.columns)if(U.type==="simple-json"&&N[U.name]&&typeof N[U.name]=="string")try{N[U.name]=JSON.parse(N[U.name])}catch{}for(let[U,G]of Object.entries(N))if(G&&typeof G=="object"&&!Array.isArray(G)&&!Buffer.isBuffer(G)){let En=G;if(En.id!==void 0||En.createdAt!==void 0){let lt=Z.relations?.find(ct=>ct.propertyName===U);lt&&(N[U]=w(G,lt.targetTableName))}}else if(Array.isArray(G)&&G.length>0&&typeof G[0]=="object"&&G[0].id!==void 0){let lt=Z.relations?.find(ct=>ct.propertyName===U);lt&&(N[U]=G.map(ct=>w(ct,lt.targetTableName)))}return N};E=w(E,a.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:E,...k.length>0&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:B}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:L}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),l=H(s)?.name||"id",u=v(e,this.dbType),c=v(l,this.dbType);if(!n||!o)throw new I(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new I(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let a=v(o,this.dbType),f=v(d,this.dbType);return`(SELECT COUNT(*) FROM ${a} WHERE ${a}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),a=v(d.tableName,this.dbType),f=v(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${a} WHERE ${a}.${f} = ${u}.${c})`}throw new I(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=t.aggregateField,s=n?.targetTableName||n?.targetTable,l=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=H(l)?.name||"id",d=H(u)?.name||"id",a=v(e,this.dbType),f=v(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new I(`Sort function '${t.field}' is not supported on '${e}'.`);let h=v(s,this.dbType),g=v(o,this.dbType);if(n.type==="one-to-many"){let m=n.foreignKeyColumn||n.mappedBy;if(!m)throw new I(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let y=v(m,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${h} WHERE ${h}.${y} = ${a}.${f})`}if(n.type==="many-to-many"){let m=this.resolveManyToManyContract(n,i,e),y=v(m.tableName,this.dbType),b=v(m.sourceColumn,this.dbType),$=v(m.targetColumn,this.dbType),C=v(d,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${y} JOIN ${h} ON ${h}.${C} = ${y}.${$} WHERE ${y}.${b} = ${a}.${f})`}throw new I(`Sort function '_${t.function}(${i}.${o})' 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 I(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&ce(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let g of t.sortItems){let m=g.field.includes(".")?g.field:`${n}.${g.field}`;o=o.orderBy(m,g.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(g=>g.trim()).filter(Boolean),l=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(l&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let g=v(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${g}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let g=o.toSQL().toNative();if(d=g.sql,c){c.setSql(g.sql);try{let m=g.sql.replace(/\$\d+/g,"?"),y=await this.knex.raw(`EXPLAIN ${m}`,g.bindings);c.setExplain(this.dbType==="postgres"?y.rows:y[0])}catch(m){c.setExplain({error:String(m)})}}}let a=performance.now(),f;f=await o,c&&c.dur("db_execute",a,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=0,h=0;return l&&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__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:h}:{},...l?{filterCount:p}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=tt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=v(e.tableName,this.dbType),o=[],s=[];for(let a of t.dimensions){let f=`${i}.${v(a.field,this.dbType)}`,p=a.bucket?this.buildSqlBucketExpression(f,a.bucket,a.timezone,a.column.type):f;s.push(this.knex.raw(`${p} as ${v(a.outputKey,this.dbType)}`)),o.push(p)}for(let a of t.measures){let f=`${i}.${v(a.field,this.dbType)}`,p=a.operation==="count"?`COUNT(${f})`:a.operation==="countDistinct"?`COUNT(DISTINCT ${f})`:`${a.operation.toUpperCase()}(${f})`;s.push(this.knex.raw(`${p} as ${v(a.outputKey,this.dbType)}`))}let u=new X().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});u.hasRelationFilters?await Lt(this.knex,n,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,a=>e.metadata?.tables?.get(a)):u.filterTree&&ce(n,u.filterTree,{dbType:this.dbType,rootTable:e.tableName}),n.select(s),o.length>0&&n.groupByRaw(o.join(", "));for(let a of t.sort)n.orderByRaw(`${v(a.field,this.dbType)} ${a.direction.toUpperCase()}`);return t.limit!==void 0&&n.limit(t.limit).offset((t.page-1)*t.limit),{data:(await n).map(a=>{let f={...a};for(let p of t.measures){let h=f[p.outputKey];h!=null&&typeof h=="string"&&/^-?\d+(\.\d+)?$/.test(h)&&(f[p.outputKey]=Number(h))}return f})}}buildSqlBucketExpression(e,t,n,i){let o=Kt(n);if(this.dbType==="postgres"){let s=`(${e} AT TIME ZONE ${o})`;return`DATE_TRUNC(${Kt(t)}, ${s})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${o})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%u-1'), '%Y-%u-%d')`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new I(`Aggregate time bucket is not supported on ${this.dbType}`)}};var xn=require("mongodb"),at=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,vn.mkdirSync)((0,ci.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(!xn.ObjectId)return e;if(typeof e=="string")try{return new xn.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(),i=Qe(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:it(e,t,n??"",i,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 i=await this.mongoService.insertOne(e.table,n);t.push(te(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new X().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}),l=e.debugTrace;if(l&&(l.dur("qb_planner",i,{table:e.tableName}),l.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let a=await new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s});return l&&l.dur("qb_total_select",t,{table:e.tableName}),a}let c=await new je(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return l&&l.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 o=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),l=this.mongoService.ioSignalPublic?.()??{},u=await s.find(o,l).toArray(),c=[];for(let d of u){let a=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(a)}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 i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),o=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},l=await o.find(i,s).toArray(),u=0;for(let c of l)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 o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);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 xn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,l]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:l})}}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,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new je(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}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 l=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return te(l)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(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 i of n)this.batchInserts.items.push({table:e,data:i});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(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count: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(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),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(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}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,vn.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 o=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return te(o)}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 i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.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 i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[u,c]of Object.entries(t))u==="id"||u==="_id"?i._id=this.safeObjectId(c):i[u]=c;let o=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await o.find(i,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),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).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 o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.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}};hr();pr();dr();ae();qt();Ge();bn();de();Je();var ui=new Set(["fields","filter","sort","limit","page","deep"]),Nn=3;function mr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new I(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(l=>[l.propertyName,l]));for(let[l,u]of Object.entries(e)){let c=s.get(l);if(!c)throw new I(`Unknown relation '${l}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!ui.has(f))throw new I(`Unknown deep option key '${f}' for relation '${l}'. Allowed: ${[...ui].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new I(`'limit' not supported on many-to-one/one-to-one relations (relation '${l}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new I(`'page' requires 'limit' to be present (relation '${l}' on '${r}')`);let a=c.targetTableName||c.targetTable;if(a){if(u.filter&&(re(u.filter,a,t),Me(u.filter,a,t),In(u.filter,0,l,r)),u.sort){Tn(u.sort,a,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;Do(h,a,t,l,r)}}u.deep&&mr(a,u.deep,t,n+1,i)}}}function Do(r,e,t,n,i){if(r.includes("."))throw new I(`Sort field '${r}' is not supported for relation '${n}' on '${i}'. Sort only by local fields defined on '${e}'.`);let o=t?.tables?.get(e);if(!o)throw new I(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${i}')`);let s=o.columns?.some(u=>u.name===r),l=r==="id"&&o.columns?.some(u=>u.name==="_id");if(!s&&!l)throw new I(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var Wo=new Set(["_and","_or","_not"]);function In(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(Wo.has(i)){if(Array.isArray(o))for(let c of o)In(c,e,t,n);else o&&typeof o=="object"&&In(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(c=>!c.startsWith("_")))continue;let l=e+1;if(l>Nn)throw new I(`Filter path exceeds max dotted hops of ${Nn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(o))c.startsWith("_")||(u[c]=o[c]);In(u,l,t,n)}}function di(r,e,t,n){return!r||typeof r!="object"?r:Jt(r,e,t,n)}function Jt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Jt(s,e,t,n)).filter(s=>s!=null);return o.length>0?o:null}let i={};for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){let a=(Array.isArray(s)?s:[s]).map(f=>Jt(f,e,t,n)).filter(f=>f!=null&&Object.keys(f).length>0);a.length>0&&(i[o]=a);continue}if(o==="_not"){let d=Jt(s,e,t,n);d!=null&&Object.keys(d).length>0&&(i[o]=d);continue}let l=t?.tables?.get(e),u=l?.relations?.find(d=>d.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let a=Jt(s,d,t,n);a!=null&&Object.keys(a).length>0&&(i[o]=a);continue}if(l?.columns?.find(d=>d.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function fi(r,e,t,n){if(!r)return r;let i=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let c=(s.startsWith("-")?s.slice(1):s).split("."),d=!0,a=e;for(let f=0;f<c.length;f++){let p=c[f],h=f===c.length-1,g=t?.tables?.get(a);if(!g){d=!1;break}if(h)g.columns?.find(y=>y.name===p)?n(a,p,"column")||(d=!1):g.relations?.find(b=>b.propertyName===p)&&(n(a,p,"relation")||(d=!1));else{let m=g.relations?.find(y=>y.propertyName===p);if(!m){d=!1;break}if(!n(a,p,"relation")){d=!1;break}a=m.targetTableName||m.targetTable||a}}d&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}Et();Je();Ot();cn();Ke();de();function Ko(r){let e=new at({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new We({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Be({isolatedExecutorService:i()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return i()},get executorEngineService(){return o()},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,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,hasLogicalOperators,isExecutableJavaScript,isScriptTable,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});