@enfyra/kernel 1.1.58 → 1.1.60

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