@enfyra/kernel 1.0.8 → 1.0.9
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.d.ts +1 -0
- package/dist/index.js +5 -5
- package/dist/package-metadata.json +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -307,6 +307,7 @@ export const buildWhereClause: any;
|
|
|
307
307
|
export const compileScriptSource: any;
|
|
308
308
|
export const computeEngineTuning: any;
|
|
309
309
|
export const CHUNKED_FETCH_CONCURRENCY: number;
|
|
310
|
+
export const DEEP_TO_MANY_DEFAULT_LIMIT: number;
|
|
310
311
|
export const PER_PARENT_CONCURRENCY: number;
|
|
311
312
|
export const WHERE_IN_CHUNK_SIZE: number;
|
|
312
313
|
export const encodeMainThreadToIsolate: any;
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var Xr=Object.create;var Dt=Object.defineProperty;var Zr=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ni=Object.prototype.hasOwnProperty;var D=(r,e)=>()=>(r&&(e=r(r=0)),e);var hn=(r,e)=>{for(var t in e)Dt(r,t,{get:e[t],enumerable:!0})},er=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ei(e))!ni.call(r,i)&&i!==t&&Dt(r,i,{get:()=>e[i],enumerable:!(n=Zr(e,i))||n.enumerable});return r};var ie=(r,e,t)=>(t=r!=null?Xr(ti(r)):{},er(e||!r||!r.__esModule?Dt(t,"default",{value:r,enumerable:!0}):t,r)),ri=r=>er(Dt({},"__esModule",{value:!0}),r);function xn(r){return pr.createHash("md5").update(r).digest("hex").substring(0,8)}function gr(r){return r.length<=Cn-3?`${r}_pk`:`j_${xn(r)}_pk`}function yr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=Cn?n:`j_${xn(r)}_${t}_fk`}function Pe(r,e,t){let n=`${r}_${e}_${t}`;if(n.length<=Cn)return n;let i=xn(n),o=r.replace(/_definition/g,"").substring(0,10),s=e.substring(0,10),a=t.replace(/_definition/g,"").substring(0,10);return`j_${i}_${o}_${s}_${a}`}function L(r){return`${r}Id`}function je(r,e,t){let n=L(r);if(r===t){let o=L(e);return{sourceColumn:n,targetColumn:o}}let i=L(t);return{sourceColumn:n,targetColumn:i}}function mr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function hr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function br(r,e,t){return`${r}_${e}_${t}_fk`}function _r(r,e,t){return`${r}_${e}_${t}_idx`}var pr,Cn,Le=D(()=>{"use strict";pr=ie(require("crypto")),Cn=63});function Xt(r){return Ai[r]??null}var Y,vn,Rt,Ai,Ft=D(()=>{"use strict";Y=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),vn=new Set(["_and","_or","_not"]),Rt=[...Array.from(vn),...Array.from(Y)],Ai={_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 E,Nt=D(()=>{"use strict";E=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 kr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Sr=D(()=>{"use strict"});function Be(r,e,t){throw new E({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Rt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Rt})}function Zt(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=kr();for(let i of Object.keys(e))if(i.startsWith("_")&&!Y.has(i)){if(n&&i==="_id")continue;Be(i,r,t)}}function B(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(Ii.has(s)){if(Array.isArray(a))for(let l of a)B(l,e,t);else a&&typeof a=="object"&&B(a,e,t);continue}let f=o.get(s);if(f){if(a&&typeof a=="object"&&!Array.isArray(a)){Zt(s,a,e);let l=f.targetTableName||f.targetTable;if(l){let u=Object.keys(a).filter(c=>!c.startsWith("_"));if(u.length>0){let c={};for(let p of u)c[p]=a[p];B(c,l,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Be(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&Zt(s,a,e)}}var Ii,Ye=D(()=>{"use strict";Nt();Ft();Sr();Ii=new Set(["_and","_or","_not"])});function be(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:en(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function en(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=Mi(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 Mi(r,e,t){if(r==="_and")return Cr("and",e,t);if(r==="_or")return Cr("or",e,t);if(r==="_not"){let l=en(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),o=n?.columns?.some(l=>l.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,f=n?.relations?.find(l=>l.propertyName===a);return f?Ei(a,e,f,t):n&&!n.columns?.find(u=>u.name===a)?(r.startsWith("_")&&r!=="_id"&&Be(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}):Pi(a,e,t)}function Cr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=en(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 Ei(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,f={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=i.length>0&&i.every(d=>l.has(d))?{id:e}:e;return{node:en(c,f).node,hasRelationFilters:!0}}function Pi(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:Li(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("_")&&!Y.has(s)&&Be(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>Y.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 f=ji(n,s,a);f&&o.push(f)}return o.length===0?{node:null,hasRelationFilters:!1}:o.length===1?{node:o[0],hasRelationFilters:!1}:{node:{kind:"and",children:o},hasRelationFilters:!1}}function ji(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=Xt(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function Li(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 vt=D(()=>{"use strict";Ft();Ye()});var te,Ot=D(()=>{"use strict";te=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 p=this.map.get(a);return i==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let f=n?.tables?.get(e);if(!f)return null;let l=f.relations?.find(p=>p.propertyName===t);if(!l)return null;let u=l.targetTableName||l.targetTable;if(!u)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:u,relationType:l.type,parentJoinId:o,joinType:i,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function H(r,e){if(r.length<=5e3)return e(r);let t=[];for(let a=0;a<r.length;a+=5e3)t.push(r.slice(a,a+5e3));let n=[],i=0;async function o(){for(;i<t.length;){let a=i++;n[a]=await e(t[a])}}let s=Math.min(4,t.length);return await Promise.all(Array.from({length:s},o)),n.flat()}function Ze(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 le,Or,Ar,_e,et=D(()=>{"use strict";le=16,Or=5e3,Ar=4;_e=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t){return!t||Object.keys(t).length===0?e:e.map(n=>{let i=t[n.relationName];if(!i)return n;let o=i.fields!=null?Array.isArray(i.fields)?i.fields:String(i.fields).split(",").map(s=>s.trim()).filter(Boolean):n.fields;return{...n,fields:o,userFilter:i.filter??n.userFilter,userSort:i.sort??n.userSort,userLimit:i.limit!==void 0?Number(i.limit):n.userLimit,userPage:i.page!==void 0?Number(i.page):n.userPage,nestedDeep:i.deep??n.nestedDeep}})}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=>a.type==="many-to-one"||a.type==="one-to-one"&&!a.isInverse?this.fetchOwnerRelation(e,a,n,i):a.type==="one-to-many"||a.type==="one-to-one"&&a.isInverse?this.fetchInverseRelation(e,a,n,i,s):a.type==="many-to-many"?this.fetchM2MRelation(e,a,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 w=_[o];if(w==null)continue;let b=this.adapter.keyOf(w);s.has(b)||(s.add(b),a.push(w))}if(a.length===0){for(let _ of e)_[o]=null,t.fkColumn&&t.fkColumn!==o&&delete _[t.fkColumn];return}let f=await this.metadataGetter(t.targetTable);if(!f)throw new Error(`Metadata not found for target table: ${t.targetTable}`);let{isPkOnly:l,nestedDescs:u,fetchSpec:c}=this.adapter.resolveFields(t.fields,f),p=this.adapter.getTargetPkField(f);if(l){for(let _ of e){let w=_[o];_[o]=w!=null?this.adapter.buildScalarRef(w,p):null,t.fkColumn&&t.fkColumn!==o&&delete _[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/5e3)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(u,t.nestedDeep);m.length>0&&await this.execute(g,m,n,i+1,t.targetTable);let y=new Map;for(let _ of g)y.set(this.adapter.keyOf(_[p]),_);for(let _ of e){let w=_[o];_[o]=w!=null&&y.get(this.adapter.keyOf(w))||null,t.fkColumn&&t.fkColumn!==o&&delete _[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(S=>S[s]).filter(S=>S!=null);if(a.length===0)return;let f=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);let{nestedDescs:u,fetchSpec:c}=this.adapter.resolveFields(t.fields,l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,f,a,c,t),m=new Map,y=t.fields.includes(f)||t.fields.includes("*");for(let S of d){let x=S[g],R=this.adapter.keyOf(x);m.has(R)||m.set(R,[]),m.get(R).push(S)}let _=t.userLimit!==void 0?"per-parent-c16":"batch-in",w=t.userLimit!==void 0?a.length:Math.ceil(a.length/5e3)||1,b=t.userLimit!==void 0?Math.ceil(a.length/16):void 0,T=Array.from(m.values()).reduce((S,x)=>S+x.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:_,roundtrips:w,concurrencyWaves:b,rowsTransferred:d.length,rowsReturned:T,rowsDiscarded:d.length-T,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let S of d)this.adapter.postProcessInverseChild(S,f,y);let h=this.enrichNestedDescs(u,t.nestedDeep);h.length>0&&await this.execute(d,h,n,i+1,t.targetTable);let k=t.type==="one-to-one";for(let S of e){let x=this.adapter.keyOf(S[s]),R=m.get(x)||[];S[t.relationName]=k?R[0]||null:R}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(b=>b[s]).filter(b=>b!=null);if(a.length===0)return;let f=await this.metadataGetter(t.targetTable);if(!f)throw new Error(`Metadata not found for target table: ${t.targetTable}`);let{nestedDescs:l,fetchSpec:u}=this.adapter.resolveFields(t.fields,f),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,o,f,u),g=t.userLimit!==void 0?"m2m-per-parent-c16":"m2m-batch",m=t.userLimit!==void 0?a.length:Math.ceil(a.length/5e3)||1,y=t.userLimit!==void 0?Math.ceil(a.length/16):void 0,_=Array.from(p.values()).reduce((b,T)=>b+T.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:g,roundtrips:m,concurrencyWaves:y,rowsTransferred:d.length,rowsReturned:_,rowsDiscarded:d.length-_,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let w=this.enrichNestedDescs(l,t.nestedDeep);w.length>0&&d.length>0&&await this.execute(d,w,n,i+1,t.targetTable);for(let b of e){let T=this.adapter.keyOf(b[s]);b[t.relationName]=p.get(T)||[]}}}});async function ce(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let f=i++,l=r[f];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var on=D(()=>{"use strict"});function N(r,e){switch(e){case"mysql":return`\`${r}\``;case"postgres":case"pg":case"sqlite":return`"${r}"`;case"mongodb":return r;default:return`\`${r}\``}}var $e=D(()=>{"use strict"});function q(r,e,t){e&&dn(r,e,t,"and")}function dn(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(){dn(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(){dn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){dn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":oo(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 oo(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=so(e.field,t),o=!!e.field.isUuid,s=t.dbType==="postgres",a=n==="or"?"orWhere":"where",f=n==="or"?"orWhereRaw":"whereRaw",l=n==="or"?"orWhereIn":"whereIn",u=n==="or"?"orWhereNotIn":"whereNotIn",c=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",d=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":o&&s&&typeof e.value=="string"?r[f](`${i} = ?::uuid`,[e.value]):r[a](i,"=",e.value);return;case"neq":o&&s&&typeof e.value=="string"?r[f](`${i} != ?::uuid`,[e.value]):r[a](i,"!=",e.value);return;case"gt":o&&s&&typeof e.value=="string"?r[f](`${i} > ?::uuid`,[e.value]):r[a](i,">",e.value);return;case"gte":o&&s&&typeof e.value=="string"?r[f](`${i} >= ?::uuid`,[e.value]):r[a](i,">=",e.value);return;case"lt":o&&s&&typeof e.value=="string"?r[f](`${i} < ?::uuid`,[e.value]):r[a](i,"<",e.value);return;case"lte":o&&s&&typeof e.value=="string"?r[f](`${i} <= ?::uuid`,[e.value]):r[a](i,"<=",e.value);return;case"in":{let g=Ur(e.value);o&&s&&g.every(m=>typeof m=="string")?r[f](`${i} = ANY(?::uuid[])`,[g]):r[l](i,g);return}case"not_in":{let g=Ur(e.value);o&&s&&g.every(m=>typeof m=="string")?r[f](`${i} != ALL(?::uuid[])`,[g]):r[u](i,g);return}case"contains":Jn(r,i,e.value,"contains",t,n);return;case"starts_with":Jn(r,i,e.value,"starts_with",t,n);return;case"ends_with":Jn(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[c](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[d](i);return}}function Jn(r,e,t,n,i,o){let s=o==="or"?"orWhereRaw":"whereRaw";if(i.dbType==="postgres"){let f=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](f,[t]);return}if(i.dbType==="sqlite"){let f=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](f,[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 so(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function Ur(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var Vn=D(()=>{"use strict"});function fe(r){return r.columns.find(e=>e.isPrimary)||null}var pn=D(()=>{"use strict"});var Jr={};hn(Jr,{expandFieldsToJoinsAndSelect:()=>zn});async function zn(r,e,t,n,i,o){let s=[],a=[],f=await t(r);if(!f)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}let u=l.get("")||[];for(let c of u){if(c==="*"){let g=new Set;for(let y of f.relations||[])if(y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse){let _=y.foreignKeyColumn||L(y.targetTableName);_&&g.add(_)}let m=new Set;for(let y of f.columns)g.has(y.name)||(s.push(`${r}.${y.name}`),m.add(y.name));for(let y of f.relations||[])!l.has(y.propertyName)&&!m.has(y.propertyName)&&l.set(y.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(f.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(f.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=f.relations?.find(w=>w.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let w=d.foreignKeyColumn||L(d.targetTableName||d.targetTable),b=N(r,n),T=N(w,n),h=N(p,n);s.push(`${b}.${T} as ${h}`)}let m=d.targetTableName||d.targetTable,y=o?.[p],_=y?.fields!=null?Array.isArray(y.fields)?y.fields:String(y.fields).split(",").map(w=>w.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:m,fields:_,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:y?.filter,userSort:y?.sort,userLimit:y?.limit!==void 0?Number(y.limit):void 0,userPage:y?.page!==void 0?Number(y.page):void 0,nestedDeep:y?.deep})}),{select:s,batchFetchDescriptors:a}}var Hn=D(()=>{"use strict";Le();$e()});var ct,Gn=D(()=>{"use strict";Le();$e();pn();et();Vn();Ot();vt();on();ct=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new te,i=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:o}=be(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("-"),f=(s?o.slice(1):o).split(".");if(f.length===1)return{column:n?`${n}.${f[0]}`:`${t}.${f[0]}`,order:s?"desc":"asc"};let l=f[f.length-1];return{column:`${`__sort_${f.slice(0,-1).join("_")}`}.${l}`,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 l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let u=n,c=i||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(u);if(!g)break;let m=g.relations?.find(w=>w.propertyName===d);if(!m)break;let y=m.targetTableName||m.targetTable,_=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(_)){s.add(_);let w=m.foreignKeyColumn||L(m.propertyName),b=this.metadata?.tables?.get(y),T=b&&fe(b)?.name||"id";e.leftJoin(`${y} as ${_}`,`${_}.${T}`,`${c}.${w}`)}u=y,c=_}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=N(o,this.dbType),a=t?`${t}.${N(i,this.dbType)}`:N(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${N(e,this.dbType)} as ${N(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return fe(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=L(e.mappedBy)),t||(t=L(e.targetTable)),t}resolveParentPk(e){return e&&fe(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ze(e),o=[];if(n.includes("*")){let l=new Set;for(let u of t.relations||[])if(u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse){let c=u.foreignKeyColumn||L(u.propertyName);c&&l.add(c)}for(let u of t.columns)l.has(u.name)||o.push(u.name);for(let u of t.relations||[])i.has(u.propertyName)||i.set(u.propertyName,["id"])}else for(let l of n){let u=t.columns.find(c=>c.name===l);u?o.push(u.name):t.relations?.find(p=>p.propertyName===l)&&!i.has(l)&&i.set(l,["id"])}let s=fe(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((l,u)=>{let c=t.relations?.find(p=>p.propertyName===u);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||L(c.propertyName);p&&o.push(`${p} as ${u}`)}});let a=[];return i.forEach((l,u)=>{let c=t.relations?.find(d=>d.propertyName===u);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:u,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly: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(f=>this.toKnexSelect(f));return H(t,f=>{let l=this.knex(e).select(a).whereIn(n.pkCol,f);if(o&&q(l,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,i.userSort,e);for(let u of s)l.orderBy(u.column,u.order)}return l})}async fetchInverse(e,t,n,i,o){let s=t,a=i.selectCols.find(g=>g.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():i.selectCols.includes(t)||i.selectCols.push(t);let f=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,l=o?.userSort?this.parseSortTokens(o.userSort,e):[],u=o?.userLimit,c=o?.userPage;if(u!==void 0){let g=c?(c-1)*u:0,m=i.selectCols.map(w=>this.toKnexSelect(w)),y=await ce(n,async w=>{let b=this.knex(e).select(m).where(t,w);if(f&&q(b,f,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,o.userSort,e),l.length>0)for(let T of l)b.orderBy(T.column,T.order);else b.orderBy(i.pkCol,"asc");return g>0&&b.offset(g),b.limit(u),b},16),_=[];for(let[w,b]of y.entries()){let T=n.find(h=>String(h)===w);for(let h of b)h[t]||(h[t]=T??w),_.push(h)}return{docs:_,groupKeyField:s}}let p=i.selectCols.map(g=>this.toKnexSelect(g));return{docs:await H(n,g=>{let m=this.knex(e).select(p).whereIn(t,g);if(f&&q(m,f,{dbType:this.dbType,rootTable:e}),this.applySortJoins(m,o?.userSort,e),l.length>0)for(let y of l)m.orderBy(y.column,y.order);else m.orderBy(i.pkCol,"asc");return m}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=e.map(b=>b[s]).filter(b=>b!=null);if(a.length===0)return{grouped:new Map,docs:[]};let f=t.junctionTableName,l=t.junctionSourceColumn,u=t.junctionTargetColumn;if(!f||!l||!u)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(o.selectCols.length===1&&o.selectCols[0]===o.pkCol&&!c&&!d){let b=await H(a,h=>this.knex(f).select([`${l} as __sourceId__`,`${u} as __targetId__`]).whereIn(l,h).orderBy(u,"asc")),T=new Map;for(let h of b){let k=this.keyOf(h.__sourceId__);T.has(k)||T.set(k,[]),T.get(k).push({[o.pkCol]:h.__targetId__})}return{grouped:T,docs:[]}}let y=o.selectCols.map(b=>this.toKnexSelect(b,"t"));if(d!==void 0){let b=g?(g-1)*d:0,T=new Map;for(let S of a)T.set(this.keyOf(S),[]);let h=await ce(a,async S=>{let x=this.knex(f).join(`${t.targetTable} as t`,`${f}.${u}`,`t.${o.pkCol}`).select(y).where(`${f}.${l}`,S);if(c&&q(x,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(x,t.userSort,t.targetTable,"t"),p.length>0)for(let R of p)x.orderBy(R.column,R.order);else x.orderBy(`t.${o.pkCol}`,"asc");return b>0&&x.offset(b),x.limit(d),x},16),k=[];for(let[S,x]of h.entries()){T.set(S,x);for(let R of x)k.push(R)}return{grouped:T,docs:k}}let _=await H(a,b=>{let T=this.knex(f).join(`${t.targetTable} as t`,`${f}.${u}`,`t.${o.pkCol}`).select([`${f}.${l} as __sourceId__`,...y]).whereIn(`${f}.${l}`,b);if(c&&q(T,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(T,t.userSort,t.targetTable,"t"),p.length>0)for(let h of p)T.orderBy(h.column,h.order);else T.orderBy(`t.${o.pkCol}`,"asc");return T}),w=new Map;for(let b of _){let T=b.__sourceId__;delete b.__sourceId__;let h=this.keyOf(T);w.has(h)||w.set(h,[]),w.get(h).push(b)}return{grouped:w,docs:_}}}});var Hr={};hn(Hr,{executeBatchFetches:()=>Yn});async function Yn(r,e,t,n,i=3,o=0,s,a="postgres",f,l){let u=new ct(r,a,f);await new _e(u,n,l).execute(e,t,i,o,s)}var Xn=D(()=>{"use strict";et();Gn()});var uo={};hn(uo,{ALL_SUPPORTED_OPERATORS:()=>Rt,AuthenticationException:()=>Oe,AuthorizationException:()=>Ae,BadRequestException:()=>E,BatchFetchEngine:()=>_e,BusinessLogicException:()=>Re,CHUNKED_FETCH_CONCURRENCY:()=>Ar,ConfigurationException:()=>_t,DEFAULT_TIMEOUT_MS:()=>Bt,DOTTED_PATH_MAX_HOPS:()=>dt,DatabaseException:()=>ye,DuplicateResourceException:()=>ve,ErrorHandler:()=>Me,ExecutorEngineService:()=>Qe,ExternalServiceException:()=>ht,FIELD_OPERATORS:()=>Y,FileNotFoundException:()=>Tt,FileSizeExceededException:()=>$t,FileUploadException:()=>wt,HttpException:()=>xe,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Wt,InvalidTokenException:()=>mt,IsolatedExecutorService:()=>Ve,JoinRegistry:()=>te,LOGICAL_OPERATORS:()=>vn,MongoBatchAdapter:()=>tt,MongoQueryExecutor:()=>ot,PER_PARENT_CONCURRENCY:()=>le,QueryBuilderService:()=>ft,QueryPlanner:()=>K,ResourceNotFoundException:()=>Ne,SchemaException:()=>bt,ScriptExecutionException:()=>ge,ScriptTimeoutException:()=>pe,ServiceUnavailableException:()=>Ie,SqlBatchAdapter:()=>ct,SqlQueryExecutor:()=>ut,TokenExpiredException:()=>yt,ValidationException:()=>Fe,WHERE_IN_CHUNK_SIZE:()=>Or,WorkerPool:()=>xt,appendIsolatedExecutorRuntimeLog:()=>U,applyOperatorToMatch:()=>Yt,applyRelationFilters:()=>Ue,applyWhereToKnex:()=>lt,assertFieldOperatorValueIsClean:()=>Zt,buildAggregateFilter:()=>it,buildMongoCharFoldMapJson:()=>Fn,buildMongoFoldTextSearchJs:()=>zt,buildRelationSubquery:()=>Et,buildSqlWherePartsFromFieldAst:()=>jt,buildWhereClause:()=>re,camelToSnake:()=>hr,chunkedFetch:()=>H,compileScriptSource:()=>oe,computeEngineTuning:()=>Tn,createEnfyraKernel:()=>co,dslOpToCompareOp:()=>Xt,encodeMainThreadToIsolate:()=>Sn,escapeSqlValue:()=>Qr,executeBatchFetches:()=>Yn,executeMongoBatchFetches:()=>sn,expandFieldsToJoinsAndSelect:()=>zn,getEffectiveCpuCount:()=>wn,getEffectiveMemoryBytes:()=>kt,getEngineTuning:()=>Jt,getExecutableScript:()=>yi,getForeignKeyColumnName:()=>L,getIoAbortSignal:()=>dr,getJunctionColumnNames:()=>je,getJunctionTableName:()=>Pe,getPrimaryKeyColumn:()=>fe,getScriptLegacyField:()=>$n,getShortFkConstraintName:()=>yr,getShortFkName:()=>br,getShortIndexName:()=>_r,getShortPkName:()=>gr,hasAggregateQuery:()=>Dn,hasLogicalOperators:()=>ue,isExecutableJavaScript:()=>or,isScriptTable:()=>kn,mergeAggregateValue:()=>Te,normalizeAggregateQuery:()=>rt,normalizeFlowStepScriptConfig:()=>mi,normalizeScriptLanguage:()=>Ct,normalizeScriptPatch:()=>gi,normalizeScriptRecord:()=>pi,parseBatchFields:()=>Ze,parseFields:()=>an,parseFilter:()=>be,perParentRun:()=>ce,quoteIdentifier:()=>N,resolveExecutableScript:()=>sr,rewriteFilterDenyingFields:()=>Gr,rewriteSortDroppingDenied:()=>Yr,separateFilters:()=>z,snakeToCamel:()=>mr,throwUnsupportedFieldOperator:()=>Be,transformCode:()=>_n,validateDeepOptions:()=>Zn,validateFilterShape:()=>B,whereToMongoFilter:()=>Ge});module.exports=ri(uo);var ii={"@CACHE":"$ctx.$cache","@REPOS":"$ctx.$repos","@HELPERS":"$ctx.$helpers","@FETCH":"$ctx.$helpers.$fetch","@LOGS":"$ctx.$logs","@BODY":"$ctx.$body","@DATA":"$ctx.$data","@PARAMS":"$ctx.$params","@QUERY":"$ctx.$query","@USER":"$ctx.$user","@REQ":"$ctx.$req","@RES":"$ctx.$res","@SHARE":"$ctx.$share","@API":"$ctx.$api","@UPLOADED_FILE":"$ctx.$uploadedFile","@PKGS":"$ctx.$pkgs","@SOCKET":"$ctx.$socket","@TRIGGER":"$ctx.$trigger","@FLOW":"$ctx.$flow","@FLOW_PAYLOAD":"$ctx.$flow.$payload","@FLOW_LAST":"$ctx.$flow.$last","@FLOW_META":"$ctx.$flow.$meta","@THROW400":"$ctx.$throw['400']","@THROW401":"$ctx.$throw['401']","@THROW403":"$ctx.$throw['403']","@THROW404":"$ctx.$throw['404']","@THROW409":"$ctx.$throw['409']","@THROW422":"$ctx.$throw['422']","@THROW429":"$ctx.$throw['429']","@THROW500":"$ctx.$throw['500']","@THROW503":"$ctx.$throw['503']","@THROW":"$ctx.$throw","@ERROR":"$ctx.$error","@STATUS":"$ctx.$statusCode"},de=0,tr=1,nr=2,bn=3,rr=4,ir=5;function _n(r){let e=r.length,t="",n=0,i=de,o=0,s=0;for(;n<e;){let a=r[n],f=r[n+1];switch(i){case de:if(a==='"')i=tr,t+=a,n++;else if(a==="'")i=nr,t+=a,n++;else if(a==="`")i=bn,t+=a,n++;else if(a==="/"&&f==="/")i=rr,t+=a+f,n+=2;else if(a==="/"&&f==="*")i=ir,t+=a+f,n+=2;else if(a==="@"||a==="#"||a==="%"){let l=n,u=a;for(n++;n<e;){let p=r[n];if(p>="A"&&p<="Z"||p>="0"&&p<="9"||p==="_")n++;else break}let c=r.substring(l,n);if(u==="@"){let p=ii[c];t+=p||c}else u==="#"?t+="$ctx.$repos."+c.substring(1):t+="$ctx.$pkgs."+c.substring(1)}else a==="{"?(o>0&&s++,t+=a,n++):a==="}"&&o>0?s>0?(s--,t+=a,n++):(o--,t+=a,n++,i=bn):(t+=a,n++);break;case tr:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==='"'&&(i=de),n++);break;case nr:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==="'"&&(i=de),n++);break;case bn:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):a==="`"?(i=de,n++):a==="$"&&n+1<e&&r[n+1]==="{"?(t+="{",n+=2,o++,i=de):n++;break;case rr:t+=a,a===`
|
|
2
|
-
`&&(i=
|
|
3
|
-
`;Ut.appendFileSync(Wt,t)}catch{}}var
|
|
1
|
+
"use strict";var Zr=Object.create;var Dt=Object.defineProperty;var ei=Object.getOwnPropertyDescriptor;var ti=Object.getOwnPropertyNames;var ni=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty;var B=(r,e)=>()=>(r&&(e=r(r=0)),e);var hn=(r,e)=>{for(var t in e)Dt(r,t,{get:e[t],enumerable:!0})},er=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ti(e))!ri.call(r,i)&&i!==t&&Dt(r,i,{get:()=>e[i],enumerable:!(n=ei(e,i))||n.enumerable});return r};var oe=(r,e,t)=>(t=r!=null?Zr(ni(r)):{},er(e||!r||!r.__esModule?Dt(t,"default",{value:r,enumerable:!0}):t,r)),ii=r=>er(Dt({},"__esModule",{value:!0}),r);function xn(r){return pr.createHash("md5").update(r).digest("hex").substring(0,8)}function gr(r){return r.length<=Cn-3?`${r}_pk`:`j_${xn(r)}_pk`}function yr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=Cn?n:`j_${xn(r)}_${t}_fk`}function Pe(r,e,t){let n=`${r}_${e}_${t}`;if(n.length<=Cn)return n;let i=xn(n),o=r.replace(/_definition/g,"").substring(0,10),s=e.substring(0,10),a=t.replace(/_definition/g,"").substring(0,10);return`j_${i}_${o}_${s}_${a}`}function L(r){return`${r}Id`}function je(r,e,t){let n=L(r);if(r===t){let o=L(e);return{sourceColumn:n,targetColumn:o}}let i=L(t);return{sourceColumn:n,targetColumn:i}}function mr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function hr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function br(r,e,t){return`${r}_${e}_${t}_fk`}function _r(r,e,t){return`${r}_${e}_${t}_idx`}var pr,Cn,Le=B(()=>{"use strict";pr=oe(require("crypto")),Cn=63});function Xt(r){return Mi[r]??null}var X,vn,Rt,Mi,Ft=B(()=>{"use strict";X=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),vn=new Set(["_and","_or","_not"]),Rt=[...Array.from(vn),...Array.from(X)],Mi={_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 P,Nt=B(()=>{"use strict";P=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 Sr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var kr=B(()=>{"use strict"});function Be(r,e,t){throw new P({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Rt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Rt})}function Zt(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Sr();for(let i of Object.keys(e))if(i.startsWith("_")&&!X.has(i)){if(n&&i==="_id")continue;Be(i,r,t)}}function K(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(Ii.has(s)){if(Array.isArray(a))for(let l of a)K(l,e,t);else a&&typeof a=="object"&&K(a,e,t);continue}let u=o.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){Zt(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let f=Object.keys(a).filter(c=>!c.startsWith("_"));if(f.length>0){let c={};for(let p of f)c[p]=a[p];K(c,l,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Be(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&Zt(s,a,e)}}var Ii,Ye=B(()=>{"use strict";Nt();Ft();kr();Ii=new Set(["_and","_or","_not"])});function _e(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:en(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function en(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=Ei(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 Ei(r,e,t){if(r==="_and")return Cr("and",e,t);if(r==="_or")return Cr("or",e,t);if(r==="_not"){let l=en(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),o=n?.columns?.some(l=>l.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?Pi(a,e,u,t):n&&!n.columns?.find(f=>f.name===a)?(r.startsWith("_")&&r!=="_id"&&Be(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}):ji(a,e,t)}function Cr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=en(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 Pi(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},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=i.length>0&&i.every(d=>l.has(d))?{id:e}:e;return{node:en(c,u).node,hasRelationFilters:!0}}function ji(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:Di(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("_")&&!X.has(s)&&Be(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>X.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=Li(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 Li(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=Xt(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function Di(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 vt=B(()=>{"use strict";Ft();Ye()});var te,At=B(()=>{"use strict";te=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 p=this.map.get(a);return i==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let f=l.targetTableName||l.targetTable;if(!f)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:f,relationType:l.type,parentJoinId:o,joinType:i,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function q(r,e){if(r.length<=5e3)return e(r);let t=[];for(let a=0;a<r.length;a+=5e3)t.push(r.slice(a,a+5e3));let n=[],i=0;async function o(){for(;i<t.length;){let a=i++;n[a]=await e(t[a])}}let s=Math.min(4,t.length);return await Promise.all(Array.from({length:s},o)),n.flat()}function Ze(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 ce,Ar,Or,Mr,we,et=B(()=>{"use strict";ce=16,Ar=5e3,Or=4,Mr=10;we=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t){return!t||Object.keys(t).length===0?e:e.map(n=>{let i=t[n.relationName];if(!i)return n;let o=i.fields!=null?Array.isArray(i.fields)?i.fields:String(i.fields).split(",").map(s=>s.trim()).filter(Boolean):n.fields;return{...n,fields:o,userFilter:i.filter??n.userFilter,userSort:i.sort??n.userSort,userLimit:i.limit!==void 0?Number(i.limit):n.userLimit,userPage:i.page!==void 0?Number(i.page):n.userPage,nestedDeep:i.deep??n.nestedDeep}})}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:10}:e}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 b of e){let _=b[o];if(_==null)continue;let T=this.adapter.keyOf(_);s.has(T)||(s.add(T),a.push(_))}if(a.length===0){for(let b of e)b[o]=null,t.fkColumn&&t.fkColumn!==o&&delete b[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);let{isPkOnly:l,nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,u),p=this.adapter.getTargetPkField(u);if(l){for(let b of e){let _=b[o];b[o]=_!=null?this.adapter.buildScalarRef(_,p):null,t.fkColumn&&t.fkColumn!==o&&delete b[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/5e3)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(f,t.nestedDeep);m.length>0&&await this.execute(g,m,n,i+1,t.targetTable);let y=new Map;for(let b of g)y.set(this.adapter.keyOf(b[p]),b);for(let b of e){let _=b[o];b[o]=_!=null&&y.get(this.adapter.keyOf(_))||null,t.fkColumn&&t.fkColumn!==o&&delete b[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(k=>k[s]).filter(k=>k!=null);if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);let{nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),m=new Map,y=t.fields.includes(u)||t.fields.includes("*");for(let k of d){let R=k[g],O=this.adapter.keyOf(R);m.has(O)||m.set(O,[]),m.get(O).push(k)}let b=t.userLimit!==void 0&&t.userLimit>0,_=b?"per-parent-c16":"batch-in",T=b?a.length:Math.ceil(a.length/5e3)||1,w=b?Math.ceil(a.length/16):void 0,h=Array.from(m.values()).reduce((k,R)=>k+R.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:_,roundtrips:T,concurrencyWaves:w,rowsTransferred:d.length,rowsReturned:h,rowsDiscarded:d.length-h,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let k of d)this.adapter.postProcessInverseChild(k,u,y);let S=this.enrichNestedDescs(f,t.nestedDeep);S.length>0&&await this.execute(d,S,n,i+1,t.targetTable);let x=t.type==="one-to-one";for(let k of e){let R=this.adapter.keyOf(k[s]),O=m.get(R)||[];k[t.relationName]=x?O[0]||null:O}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(w=>w[s]).filter(w=>w!=null);if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);let{nestedDescs:l,fetchSpec:f}=this.adapter.resolveFields(t.fields,u),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,o,u,f),g=t.userLimit!==void 0&&t.userLimit>0,m=g?"m2m-per-parent-c16":"m2m-batch",y=g?a.length:Math.ceil(a.length/5e3)||1,b=g?Math.ceil(a.length/16):void 0,_=Array.from(p.values()).reduce((w,h)=>w+h.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:m,roundtrips:y,concurrencyWaves:b,rowsTransferred:d.length,rowsReturned:_,rowsDiscarded:d.length-_,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let T=this.enrichNestedDescs(l,t.nestedDeep);T.length>0&&d.length>0&&await this.execute(d,T,n,i+1,t.targetTable);for(let w of e){let h=this.adapter.keyOf(w[s]);w[t.relationName]=p.get(h)||[]}}}});async function ue(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,l=r[u];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var on=B(()=>{"use strict"});function N(r,e){switch(e){case"mysql":return`\`${r}\``;case"postgres":case"pg":case"sqlite":return`"${r}"`;case"mongodb":return r;default:return`\`${r}\``}}var Se=B(()=>{"use strict"});function G(r,e,t){e&&dn(r,e,t,"and")}function dn(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(){dn(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(){dn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){dn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":so(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 so(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=ao(e.field,t),o=!!e.field.isUuid,s=t.dbType==="postgres",a=n==="or"?"orWhere":"where",u=n==="or"?"orWhereRaw":"whereRaw",l=n==="or"?"orWhereIn":"whereIn",f=n==="or"?"orWhereNotIn":"whereNotIn",c=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",d=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":o&&s&&typeof e.value=="string"?r[u](`${i} = ?::uuid`,[e.value]):r[a](i,"=",e.value);return;case"neq":o&&s&&typeof e.value=="string"?r[u](`${i} != ?::uuid`,[e.value]):r[a](i,"!=",e.value);return;case"gt":o&&s&&typeof e.value=="string"?r[u](`${i} > ?::uuid`,[e.value]):r[a](i,">",e.value);return;case"gte":o&&s&&typeof e.value=="string"?r[u](`${i} >= ?::uuid`,[e.value]):r[a](i,">=",e.value);return;case"lt":o&&s&&typeof e.value=="string"?r[u](`${i} < ?::uuid`,[e.value]):r[a](i,"<",e.value);return;case"lte":o&&s&&typeof e.value=="string"?r[u](`${i} <= ?::uuid`,[e.value]):r[a](i,"<=",e.value);return;case"in":{let g=Qr(e.value);o&&s&&g.every(m=>typeof m=="string")?r[u](`${i} = ANY(?::uuid[])`,[g]):r[l](i,g);return}case"not_in":{let g=Qr(e.value);o&&s&&g.every(m=>typeof m=="string")?r[u](`${i} != ALL(?::uuid[])`,[g]):r[f](i,g);return}case"contains":Jn(r,i,e.value,"contains",t,n);return;case"starts_with":Jn(r,i,e.value,"starts_with",t,n);return;case"ends_with":Jn(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[c](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[d](i);return}}function Jn(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 ao(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function Qr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var Vn=B(()=>{"use strict"});function de(r){return r.columns.find(e=>e.isPrimary)||null}var pn=B(()=>{"use strict"});var Vr={};hn(Vr,{expandFieldsToJoinsAndSelect:()=>zn});async function zn(r,e,t,n,i,o){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}let f=l.get("")||[];for(let c of f){if(c==="*"){let g=new Set;for(let y of u.relations||[])if(y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse){let b=y.foreignKeyColumn||L(y.targetTableName);b&&g.add(b)}let m=new Set;for(let y of u.columns)g.has(y.name)||(s.push(`${r}.${y.name}`),m.add(y.name));for(let y of u.relations||[])!l.has(y.propertyName)&&!m.has(y.propertyName)&&l.set(y.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=u.relations?.find(_=>_.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let _=d.foreignKeyColumn||L(d.targetTableName||d.targetTable),T=N(r,n),w=N(_,n),h=N(p,n);s.push(`${T}.${w} as ${h}`)}let m=d.targetTableName||d.targetTable,y=o?.[p],b=y?.fields!=null?Array.isArray(y.fields)?y.fields:String(y.fields).split(",").map(_=>_.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:m,fields:b,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:y?.filter,userSort:y?.sort,userLimit:y?.limit!==void 0?Number(y.limit):void 0,userPage:y?.page!==void 0?Number(y.page):void 0,nestedDeep:y?.deep})}),{select:s,batchFetchDescriptors:a}}var Hn=B(()=>{"use strict";Le();Se()});var ct,Gn=B(()=>{"use strict";Le();Se();pn();et();Vn();At();vt();on();ct=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new te,i=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:o}=_e(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 l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,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 l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let f=n,c=i||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(f);if(!g)break;let m=g.relations?.find(_=>_.propertyName===d);if(!m)break;let y=m.targetTableName||m.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let _=m.foreignKeyColumn||L(m.propertyName),T=this.metadata?.tables?.get(y),w=T&&de(T)?.name||"id";e.leftJoin(`${y} as ${b}`,`${b}.${w}`,`${c}.${_}`)}f=y,c=b}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=N(o,this.dbType),a=t?`${t}.${N(i,this.dbType)}`:N(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${N(e,this.dbType)} as ${N(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return de(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=L(e.mappedBy)),t||(t=L(e.targetTable)),t}resolveParentPk(e){return e&&de(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ze(e),o=[];if(n.includes("*")){let l=new Set;for(let f of t.relations||[])if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let c=f.foreignKeyColumn||L(f.propertyName);c&&l.add(c)}for(let f of t.columns)l.has(f.name)||o.push(f.name);for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["id"])}else for(let l of n){let f=t.columns.find(c=>c.name===l);f?o.push(f.name):t.relations?.find(p=>p.propertyName===l)&&!i.has(l)&&i.set(l,["id"])}let s=de(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((l,f)=>{let c=t.relations?.find(p=>p.propertyName===f);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||L(c.propertyName);p&&o.push(`${p} as ${f}`)}});let a=[];return i.forEach((l,f)=>{let c=t.relations?.find(d=>d.propertyName===f);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:f,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly: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(u=>this.toKnexSelect(u));return q(t,u=>{let l=this.knex(e).select(a).whereIn(n.pkCol,u);if(o&&G(l,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,i.userSort,e);for(let f of s)l.orderBy(f.column,f.order)}return l})}async fetchInverse(e,t,n,i,o){let s=t,a=i.selectCols.find(g=>g.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,l=o?.userSort?this.parseSortTokens(o.userSort,e):[],f=o?.userLimit,c=o?.userPage;if(f!==void 0&&f>0){let g=c?(c-1)*f:0,m=i.selectCols.map(_=>this.toKnexSelect(_)),y=await ue(n,async _=>{let T=this.knex(e).select(m).where(t,_);if(u&&G(T,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(T,o.userSort,e),l.length>0)for(let w of l)T.orderBy(w.column,w.order);else T.orderBy(i.pkCol,"asc");return g>0&&T.offset(g),T.limit(f),T},16),b=[];for(let[_,T]of y.entries()){let w=n.find(h=>String(h)===_);for(let h of T)h[t]||(h[t]=w??_),b.push(h)}return{docs:b,groupKeyField:s}}let p=i.selectCols.map(g=>this.toKnexSelect(g));return{docs:await q(n,g=>{let m=this.knex(e).select(p).whereIn(t,g);if(u&&G(m,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(m,o?.userSort,e),l.length>0)for(let y of l)m.orderBy(y.column,y.order);else m.orderBy(i.pkCol,"asc");return m}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=e.map(T=>T[s]).filter(T=>T!=null);if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,f=t.junctionTargetColumn;if(!u||!l||!f)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(o.selectCols.length===1&&o.selectCols[0]===o.pkCol&&!c&&!d){let T=await q(a,h=>this.knex(u).select([`${l} as __sourceId__`,`${f} as __targetId__`]).whereIn(l,h).orderBy(f,"asc")),w=new Map;for(let h of T){let S=this.keyOf(h.__sourceId__);w.has(S)||w.set(S,[]),w.get(S).push({[o.pkCol]:h.__targetId__})}return{grouped:w,docs:[]}}let y=o.selectCols.map(T=>this.toKnexSelect(T,"t"));if(d!==void 0&&d>0){let T=g?(g-1)*d:0,w=new Map;for(let x of a)w.set(this.keyOf(x),[]);let h=await ue(a,async x=>{let k=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${o.pkCol}`).select(y).where(`${u}.${l}`,x);if(c&&G(k,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(k,t.userSort,t.targetTable,"t"),p.length>0)for(let R of p)k.orderBy(R.column,R.order);else k.orderBy(`t.${o.pkCol}`,"asc");return T>0&&k.offset(T),k.limit(d),k},16),S=[];for(let[x,k]of h.entries()){w.set(x,k);for(let R of k)S.push(R)}return{grouped:w,docs:S}}let b=await q(a,T=>{let w=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${o.pkCol}`).select([`${u}.${l} as __sourceId__`,...y]).whereIn(`${u}.${l}`,T);if(c&&G(w,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(w,t.userSort,t.targetTable,"t"),p.length>0)for(let h of p)w.orderBy(h.column,h.order);else w.orderBy(`t.${o.pkCol}`,"asc");return w}),_=new Map;for(let T of b){let w=T.__sourceId__;delete T.__sourceId__;let h=this.keyOf(w);_.has(h)||_.set(h,[]),_.get(h).push(T)}return{grouped:_,docs:b}}}});var qr={};hn(qr,{executeBatchFetches:()=>Yn});async function Yn(r,e,t,n,i=3,o=0,s,a="postgres",u,l){let f=new ct(r,a,u);await new we(f,n,l).execute(e,t,i,o,s)}var Xn=B(()=>{"use strict";et();Gn()});var fo={};hn(fo,{ALL_SUPPORTED_OPERATORS:()=>Rt,AuthenticationException:()=>Ae,AuthorizationException:()=>Oe,BadRequestException:()=>P,BatchFetchEngine:()=>we,BusinessLogicException:()=>Re,CHUNKED_FETCH_CONCURRENCY:()=>Or,ConfigurationException:()=>_t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Mr,DEFAULT_TIMEOUT_MS:()=>Bt,DOTTED_PATH_MAX_HOPS:()=>dt,DatabaseException:()=>me,DuplicateResourceException:()=>ve,ErrorHandler:()=>Ie,ExecutorEngineService:()=>Qe,ExternalServiceException:()=>ht,FIELD_OPERATORS:()=>X,FileNotFoundException:()=>Tt,FileSizeExceededException:()=>$t,FileUploadException:()=>wt,HttpException:()=>xe,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Wt,InvalidTokenException:()=>mt,IsolatedExecutorService:()=>Ve,JoinRegistry:()=>te,LOGICAL_OPERATORS:()=>vn,MongoBatchAdapter:()=>tt,MongoQueryExecutor:()=>ot,PER_PARENT_CONCURRENCY:()=>ce,QueryBuilderService:()=>ft,QueryPlanner:()=>W,ResourceNotFoundException:()=>Ne,SchemaException:()=>bt,ScriptExecutionException:()=>ye,ScriptTimeoutException:()=>ge,ServiceUnavailableException:()=>Me,SqlBatchAdapter:()=>ct,SqlQueryExecutor:()=>ut,TokenExpiredException:()=>yt,ValidationException:()=>Fe,WHERE_IN_CHUNK_SIZE:()=>Ar,WorkerPool:()=>xt,appendIsolatedExecutorRuntimeLog:()=>Q,applyOperatorToMatch:()=>Yt,applyRelationFilters:()=>Ue,applyWhereToKnex:()=>lt,assertFieldOperatorValueIsClean:()=>Zt,buildAggregateFilter:()=>it,buildMongoCharFoldMapJson:()=>Fn,buildMongoFoldTextSearchJs:()=>zt,buildRelationSubquery:()=>Et,buildSqlWherePartsFromFieldAst:()=>jt,buildWhereClause:()=>re,camelToSnake:()=>hr,chunkedFetch:()=>q,compileScriptSource:()=>se,computeEngineTuning:()=>Tn,createEnfyraKernel:()=>uo,dslOpToCompareOp:()=>Xt,encodeMainThreadToIsolate:()=>kn,escapeSqlValue:()=>Jr,executeBatchFetches:()=>Yn,executeMongoBatchFetches:()=>sn,expandFieldsToJoinsAndSelect:()=>zn,getEffectiveCpuCount:()=>wn,getEffectiveMemoryBytes:()=>St,getEngineTuning:()=>Jt,getExecutableScript:()=>mi,getForeignKeyColumnName:()=>L,getIoAbortSignal:()=>dr,getJunctionColumnNames:()=>je,getJunctionTableName:()=>Pe,getPrimaryKeyColumn:()=>de,getScriptLegacyField:()=>$n,getShortFkConstraintName:()=>yr,getShortFkName:()=>br,getShortIndexName:()=>_r,getShortPkName:()=>gr,hasAggregateQuery:()=>Dn,hasLogicalOperators:()=>fe,isExecutableJavaScript:()=>or,isScriptTable:()=>Sn,mergeAggregateValue:()=>$e,normalizeAggregateQuery:()=>rt,normalizeFlowStepScriptConfig:()=>hi,normalizeScriptLanguage:()=>Ct,normalizeScriptPatch:()=>yi,normalizeScriptRecord:()=>gi,parseBatchFields:()=>Ze,parseFields:()=>an,parseFilter:()=>_e,perParentRun:()=>ue,quoteIdentifier:()=>N,resolveExecutableScript:()=>sr,rewriteFilterDenyingFields:()=>Yr,rewriteSortDroppingDenied:()=>Xr,separateFilters:()=>H,snakeToCamel:()=>mr,throwUnsupportedFieldOperator:()=>Be,transformCode:()=>_n,validateDeepOptions:()=>Zn,validateFilterShape:()=>K,whereToMongoFilter:()=>Ge});module.exports=ii(fo);var oi={"@CACHE":"$ctx.$cache","@REPOS":"$ctx.$repos","@HELPERS":"$ctx.$helpers","@FETCH":"$ctx.$helpers.$fetch","@LOGS":"$ctx.$logs","@BODY":"$ctx.$body","@DATA":"$ctx.$data","@PARAMS":"$ctx.$params","@QUERY":"$ctx.$query","@USER":"$ctx.$user","@REQ":"$ctx.$req","@RES":"$ctx.$res","@SHARE":"$ctx.$share","@API":"$ctx.$api","@UPLOADED_FILE":"$ctx.$uploadedFile","@PKGS":"$ctx.$pkgs","@SOCKET":"$ctx.$socket","@TRIGGER":"$ctx.$trigger","@FLOW":"$ctx.$flow","@FLOW_PAYLOAD":"$ctx.$flow.$payload","@FLOW_LAST":"$ctx.$flow.$last","@FLOW_META":"$ctx.$flow.$meta","@THROW400":"$ctx.$throw['400']","@THROW401":"$ctx.$throw['401']","@THROW403":"$ctx.$throw['403']","@THROW404":"$ctx.$throw['404']","@THROW409":"$ctx.$throw['409']","@THROW422":"$ctx.$throw['422']","@THROW429":"$ctx.$throw['429']","@THROW500":"$ctx.$throw['500']","@THROW503":"$ctx.$throw['503']","@THROW":"$ctx.$throw","@ERROR":"$ctx.$error","@STATUS":"$ctx.$statusCode"},pe=0,tr=1,nr=2,bn=3,rr=4,ir=5;function _n(r){let e=r.length,t="",n=0,i=pe,o=0,s=0;for(;n<e;){let a=r[n],u=r[n+1];switch(i){case pe:if(a==='"')i=tr,t+=a,n++;else if(a==="'")i=nr,t+=a,n++;else if(a==="`")i=bn,t+=a,n++;else if(a==="/"&&u==="/")i=rr,t+=a+u,n+=2;else if(a==="/"&&u==="*")i=ir,t+=a+u,n+=2;else if(a==="@"||a==="#"||a==="%"){let l=n,f=a;for(n++;n<e;){let p=r[n];if(p>="A"&&p<="Z"||p>="0"&&p<="9"||p==="_")n++;else break}let c=r.substring(l,n);if(f==="@"){let p=oi[c];t+=p||c}else f==="#"?t+="$ctx.$repos."+c.substring(1):t+="$ctx.$pkgs."+c.substring(1)}else a==="{"?(o>0&&s++,t+=a,n++):a==="}"&&o>0?s>0?(s--,t+=a,n++):(o--,t+=a,n++,i=bn):(t+=a,n++);break;case tr:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==='"'&&(i=pe),n++);break;case nr:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==="'"&&(i=pe),n++);break;case bn:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):a==="`"?(i=pe,n++):a==="$"&&n+1<e&&r[n+1]==="{"?(t+="{",n+=2,o++,i=pe):n++;break;case rr:t+=a,a===`
|
|
2
|
+
`&&(i=pe),n++;break;case ir:t+=a,a==="*"&&u==="/"?(t+=u,n+=2,i=pe):n++;break}}return t}var Bt=3e4,Qe=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Bt)}async run(e,t,n=Bt){return this.isolatedExecutorService.run(e,t,n)}};var Kt=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 lr=require("async_hooks"),cr=oe(require("path")),ur=require("worker_threads");var ge=class extends Error{constructor(t=0,n){let i=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${i}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},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}}},E=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},xe=class extends E{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},Re=class extends E{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Fe=class extends E{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Ne=class extends E{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},ve=class extends E{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},Ae=class extends E{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},Oe=class extends E{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},yt=class extends E{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},mt=class extends E{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},me=class extends E{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},ht=class extends E{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},Me=class extends E{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},bt=class extends E{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},_t=class extends E{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},wt=class extends E{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Tt=class extends E{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},$t=class extends E{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Ie=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.businessLogic":return new Re(n||"Bad request",o);case"$throw.validation":return new Fe(n||"Validation failed",o);case"$throw.notFound":return new Ne(n||"Resource");case"$throw.duplicate":return new ve(n||"Resource","field","value");case"$throw.unauthorized":return new Ae(n||"Unauthorized");case"$throw.forbidden":return new Oe(n||"Forbidden");case"$throw.tokenExpired":return new yt;case"$throw.invalidToken":return new mt;case"$throw.database":return new me(n||"Database error",o);case"$throw.dbQuery":return new me(n||"Query error",o);case"$throw.externalService":return new ht(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new Me(n||"Service");case"$throw.rateLimit":return new xe(n||"Rate limit exceeded",429);case"$throw.scriptError":return new ye(n||"Script error",i,o);case"$throw.scriptTimeout":return new ge(o?.timeout||5e3,i);case"$throw.schema":return new bt(n||"Schema error",o);case"$throw.config":return new _t(n||"Configuration error",o);case"$throw.fileUpload":return new wt(n||"File upload error",o);case"$throw.fileNotFound":return new Tt(n||"File not found");case"$throw.fileSizeExceeded":return new $t(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new Re(n||"Bad request");case"$throw.401":return new Ae(n||"Authentication required");case"$throw.403":return new Oe(n||"Insufficient permissions");case"$throw.404":return new Ne(n||"Resource");case"$throw.409":return new ve(n||"Resource","field","value");case"$throw.422":return new Fe(n||"Validation failed");case"$throw.429":return new xe(n||"Rate limit exceeded",429);case"$throw.500":return new me(n||"Internal server error",o);case"$throw.503":return new Me(n||"Service");default:return new ye(n||"Unknown error",i)}if(t)switch(t){case 400:return new Re(n||"Bad request");case 401:return new Ae(n||"Authentication required");case 403:return new Oe(n||"Insufficient permissions");case 404:return new Ne(n||"Resource");case 409:return new ve(n||"Resource","field","value");case 422:return new Fe(n||"Validation failed");case 429:return new xe(n||"Rate limit exceeded",429);case 500:return new me(n||"Internal server error",o);case 503:return new Me(n||"Service");default:return new ye(n||"Unknown error",i,o)}return new ye(n||"Unknown error",i,o)}};var Ut=oe(require("fs")),Qt=oe(require("path")),Wt=Qt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function si(){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 ai=si();function Q(r){if(ai)try{let e=Qt.dirname(Wt);Ut.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
|
|
3
|
+
`;Ut.appendFileSync(Wt,t)}catch{}}var he=oe(require("os")),Je=oe(require("fs"));function St(){try{let r=Je.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<he.totalmem())return e}}catch{}try{let r=Je.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<he.totalmem())return e}catch{}return he.totalmem()}function wn(){let r=he.availableParallelism?.()||he.cpus()?.length||1;try{let e=Je.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(Je.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Je.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 li=.25,ci=2,ui=2048,fi=40,di=128,pi=32;function Tn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(di,Math.max(fi,Math.round(t/pi))),i=t*li,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<ui?1:ci,l=Math.max(1,Math.min(u,Math.floor(i/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:l}}function Jt(){return Tn({logicalCpuCount:wn(),totalMemoryBytes:St()})}var Ee=oe(require("typescript"));var kt={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 $n(r){return kt[r]}function Sn(r){return r in kt}function Ct(r){return r==="javascript"?"javascript":"typescript"}function se(r,e){if(r==null||r==="")return null;let t=_n(String(r));if(Ct(e)==="javascript")return t;let n=Ee.default.transpileModule(t,{compilerOptions:{target:Ee.default.ScriptTarget.ES2022,module:Ee.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ee.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),i=n.diagnostics?.find(o=>o.category===Ee.default.DiagnosticCategory.Error);if(i)throw new Error(Ee.default.flattenDiagnosticMessageText(i.messageText,`
|
|
4
4
|
`));return n.outputText.trimEnd()}function or(r){if(!r)return!1;try{return new Function(`return (async () => {
|
|
5
5
|
"use strict";
|
|
6
6
|
${r}
|
|
7
|
-
});`),!0}catch{return!1}}function pi(r,e){if(!kn(r)||!e||typeof e!="object")return e;let t={...e},n=$n(r);return n&&(t.sourceCode===void 0||t.sourceCode===null||t.sourceCode==="")&&t[n]!==void 0&&(t.sourceCode=t[n]),t.scriptLanguage=Ct(t.scriptLanguage),(t.compiledCode===void 0||t.compiledCode===null||t.compiledCode==="")&&(t.compiledCode=oe(t.sourceCode,t.scriptLanguage)),n&&n in t&&delete t[n],t}function gi(r,e,t){if(!kn(r)||!e||typeof e!="object")return e;let n=$n(r),i=Object.prototype.hasOwnProperty.call(e,"sourceCode")||(n?Object.prototype.hasOwnProperty.call(e,n):!1),o=Object.prototype.hasOwnProperty.call(e,"scriptLanguage");if(!i&&!o)return e;let s=i?e.sourceCode??(n?e[n]:void 0):t?.sourceCode??(n&&t?t[n]:void 0),a=o?e.scriptLanguage:t?.scriptLanguage,f=oe(s,a),l={...e};return i&&(l.sourceCode=s??null),l.scriptLanguage=Ct(a),l.compiledCode=f,n&&n in l&&delete l[n],l}function yi(r){return sr(r).code}function sr(r){if(!r||typeof r!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof r.compiledCode=="string"&&r.compiledCode!==""&&or(r.compiledCode))return{code:r.compiledCode,compiledCode:r.compiledCode,shouldPersistCompiledCode:!1};if(typeof r.sourceCode=="string"&&r.sourceCode!==""){let t=oe(r.sourceCode,r.scriptLanguage);return{code:t,compiledCode:t,shouldPersistCompiledCode:t!==r.compiledCode}}let e=Object.keys(St).find(t=>St[t]in r);if(e){let t=r[St[e]];if(typeof t=="string"&&t!==""){let n=oe(t,r.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==r.compiledCode}}}return typeof r.compiledCode=="string"&&r.compiledCode!==""?{code:r.compiledCode,compiledCode:r.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}function mi(r){if(!r||typeof r!="object")return r;let e=r.type;if(e!=="script"&&e!=="condition")return r;let t=r.config;if(typeof t=="string")try{t=JSON.parse(t)}catch{return r}if(!t||typeof t!="object")return r;let n={...t};return n.sourceCode=n.sourceCode??n.code??null,n.scriptLanguage=Ct(n.scriptLanguage),n.compiledCode=oe(n.sourceCode,n.scriptLanguage),delete n.code,{...r,config:typeof r.config=="string"?JSON.stringify(n):n}}var xi=cr.join(__dirname,"execution/worker.js"),Ri=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],fr=new lr.AsyncLocalStorage;function dr(){return fr.getStore()}var xt=class{constructor(e,t,n,i,o,s,a,f=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=f;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new ur.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":"Worker crashed"}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}};function Sn(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 Ve=class r{constructor(e){this.logger=new Kt(r.name);this.effectiveMemory=kt();this.isolationTuning=Jt();this.pool=new xt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,xi,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.taskDurationsMs=[];this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),f=this.pool.getWaitingCount(),l=t>.85||s>.7,u=t<.7&&s<.5,c=f>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):u&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${f})`))}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},n=e.$flow;if(n!=null)try{t.$flow=JSON.parse(JSON.stringify(n,(i,o)=>typeof o=="bigint"?String(o):o))}catch{t.$flow={}}return t}mergeCtxChanges(e,t){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),delete e.$pkgs)}spawnAndExecute(e,t,n,i){return(async()=>{let o=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((f,l)=>{let u=!1,c=new AbortController,p=setTimeout(()=>{if(u)return;u=!0,c.abort(),this.pool.unregisterTask(o,s),this.taskTimeoutTotal++,U({event:"task_timeout",id:s,timeoutMs:i}),this.pool.terminateEntry(o);let d=new Error(`Script execution timed out after ${i}ms`);d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},i+5e3);this.pool.registerTask(o,s,{abortController:c,onResult:d=>{if(!u)if(u=!0,clearTimeout(p),this.pool.unregisterTask(o,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,U({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),f(g)}else{this.taskErrorTotal++,U({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),l(g)}},onIoCall:d=>{if(u)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),o.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),o.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),o.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),o.worker,d.callId,g):d.type==="dispatchCall"&&this.handleIoCall(()=>this.execDispatchCall(d,n),o.worker,d.callId,g)}}),o.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,i){if(!i?.aborted)try{let o=await(i?fr.run(i,e):e());if(i?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:Sn(o)})}catch{}}catch(o){if(i?.aborted)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=t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return i[e.method](...n)}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 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)}isScriptParseFailure(e){let t=e.message||"";return Ri.some(n=>t.includes(n))}async run(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);U({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let f;try{let l={code:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{f=await this.spawnAndExecute("execute",l,t,i)}catch(u){let c=u,p=oe(e,"typescript")||"";if(!this.isScriptParseFailure(c)||p===e)throw u;U({event:"isolated_run_ts_retry",message:c.message}),f=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let u=l;if(U({event:"isolated_run_error",message:u.message,code:u.code,isTimeout:!!u.isTimeout}),u.isTimeout||u.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new pe(i,e);let c=u.statusCode??(typeof u.status=="number"?u.status:void 0);throw Me.createException(void 0,c,u.message||"Unknown error",e,u.details||{})}return this.mergeCtxChanges(t,f.ctxChanges||{}),U({event:"isolated_run_ok"}),f.valueAbsent?void 0:f.value}async runBatch(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);U({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let f;try{let l={codeBlocks:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{f=await this.spawnAndExecute("executeBatch",l,t,i)}catch(u){let c=u,p=e.map(g=>({...g,code:oe(g.code,"typescript")||""})),d=p.some((g,m)=>g.code!==e[m]?.code);if(!this.isScriptParseFailure(c)||!d)throw u;U({event:"isolated_batch_ts_retry",message:c.message}),f=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let u=l;if(U({event:"isolated_batch_error",message:u.message,code:u.code,isTimeout:!!u.isTimeout}),u.ctxChanges&&this.mergeCtxChanges(t,u.ctxChanges),u.isTimeout||u.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new pe(i,"(batch execution)");let c=u.statusCode??(typeof u.status=="number"?u.status:void 0);throw Me.createException(void 0,c,u.message||"Unknown error","(batch execution)",u.details||{})}return this.mergeCtxChanges(t,f.ctxChanges||{}),U({event:"isolated_batch_ok"}),{value:f.valueAbsent?void 0:f.value,shortCircuit:f.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var Rn=require("mongodb");Le();function De(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function G(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!De(r)&&(r.foreignKeyColumn||r.propertyName)||null}function Q(r){return r.mappedBy||r.foreignKeyColumn||r.propertyName||null}function Z(r){if(!r||typeof r!="object")return r;if(r instanceof Rn.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 Rn.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 ze(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,f=e.mappedBy,l=r,u=e.junctionTableName||Pe(a,f,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:u,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=je(a,f,l);return{junctionName:u,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,i=t,o=e.junctionTableName||Pe(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=je(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function Vt(r,e,t){if(!r)return{scalarFields:[],relations:[]};let n=r.tables?.get(e);if(!n)return{scalarFields:[],relations:[]};let i=new Map;for(let f of t)if(f==="*")i.has("")||i.set("",[]),i.get("").push(f);else if(f.includes(".")){let l=f.split("."),u=l[0],c=l.slice(1).join(".");i.has(u)||i.set(u,[]),i.get(u).push(c)}else n.relations?.some(u=>u.propertyName===f)?i.has(f)||i.set(f,["_id"]):(i.has("")||i.set("",[]),i.get("").push(f));let o=[],s=[],a=i.get("")||[];for(let f of a)if(f==="*"){if(n.columns)for(let l of n.columns)o.includes(l.name)||o.push(l.name);if(n.relations)for(let l of n.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else n.columns?.some(u=>u.name===f)&&!o.includes(f)&&o.push(f);for(let[f,l]of i.entries()){if(f==="")continue;let u=n.relations?.find(m=>m.propertyName===f);if(!u)continue;let c="",p="",d=!1;u.type==="many-to-one"||u.type==="one-to-one"?De(u)?(c="_id",p=Q(u)||u.propertyName,d=!0):(c=G(u)||u.propertyName,p="_id",d=!1):u.type==="one-to-many"?(c="_id",p=Q(u)||u.propertyName,d=!0):u.type==="many-to-many"&&(u.mappedBy?(c="_id",p=u.mappedBy,d=!0):(c=u.propertyName,p="_id",d=!1));let g=u.type==="one-to-many"||u.type==="many-to-many";s.push({propertyName:f,targetTable:u.targetTableName,localField:c,foreignField:p,type:g?"many":"one",isInverse:d,nestedFields:l})}return{scalarFields:o,relations:s}}var Ht=ie(require("fs")),Nn=ie(require("path"));var Fi=new RegExp("\\p{Mark}","gu");function wr(r){return r==null?"":String(r).normalize("NFKD").replace(Fi,"").toLowerCase()}function Fn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=wr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function zt(){return`function() {
|
|
7
|
+
});`),!0}catch{return!1}}function gi(r,e){if(!Sn(r)||!e||typeof e!="object")return e;let t={...e},n=$n(r);return n&&(t.sourceCode===void 0||t.sourceCode===null||t.sourceCode==="")&&t[n]!==void 0&&(t.sourceCode=t[n]),t.scriptLanguage=Ct(t.scriptLanguage),(t.compiledCode===void 0||t.compiledCode===null||t.compiledCode==="")&&(t.compiledCode=se(t.sourceCode,t.scriptLanguage)),n&&n in t&&delete t[n],t}function yi(r,e,t){if(!Sn(r)||!e||typeof e!="object")return e;let n=$n(r),i=Object.prototype.hasOwnProperty.call(e,"sourceCode")||(n?Object.prototype.hasOwnProperty.call(e,n):!1),o=Object.prototype.hasOwnProperty.call(e,"scriptLanguage");if(!i&&!o)return e;let s=i?e.sourceCode??(n?e[n]:void 0):t?.sourceCode??(n&&t?t[n]:void 0),a=o?e.scriptLanguage:t?.scriptLanguage,u=se(s,a),l={...e};return i&&(l.sourceCode=s??null),l.scriptLanguage=Ct(a),l.compiledCode=u,n&&n in l&&delete l[n],l}function mi(r){return sr(r).code}function sr(r){if(!r||typeof r!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof r.compiledCode=="string"&&r.compiledCode!==""&&or(r.compiledCode))return{code:r.compiledCode,compiledCode:r.compiledCode,shouldPersistCompiledCode:!1};if(typeof r.sourceCode=="string"&&r.sourceCode!==""){let t=se(r.sourceCode,r.scriptLanguage);return{code:t,compiledCode:t,shouldPersistCompiledCode:t!==r.compiledCode}}let e=Object.keys(kt).find(t=>kt[t]in r);if(e){let t=r[kt[e]];if(typeof t=="string"&&t!==""){let n=se(t,r.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==r.compiledCode}}}return typeof r.compiledCode=="string"&&r.compiledCode!==""?{code:r.compiledCode,compiledCode:r.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}function hi(r){if(!r||typeof r!="object")return r;let e=r.type;if(e!=="script"&&e!=="condition")return r;let t=r.config;if(typeof t=="string")try{t=JSON.parse(t)}catch{return r}if(!t||typeof t!="object")return r;let n={...t};return n.sourceCode=n.sourceCode??n.code??null,n.scriptLanguage=Ct(n.scriptLanguage),n.compiledCode=se(n.sourceCode,n.scriptLanguage),delete n.code,{...r,config:typeof r.config=="string"?JSON.stringify(n):n}}var Ri=cr.join(__dirname,"execution/worker.js"),Fi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],fr=new lr.AsyncLocalStorage;function dr(){return fr.getStore()}var xt=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 l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new ur.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":"Worker crashed"}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}};function kn(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 Ve=class r{constructor(e){this.logger=new Kt(r.name);this.effectiveMemory=St();this.isolationTuning=Jt();this.pool=new xt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ri,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.taskDurationsMs=[];this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile},n=e.$flow;if(n!=null)try{t.$flow=JSON.parse(JSON.stringify(n,(i,o)=>typeof o=="bigint"?String(o):o))}catch{t.$flow={}}return t}mergeCtxChanges(e,t){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),delete e.$pkgs)}spawnAndExecute(e,t,n,i){return(async()=>{let o=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort(),this.pool.unregisterTask(o,s),this.taskTimeoutTotal++,Q({event:"task_timeout",id:s,timeoutMs:i}),this.pool.terminateEntry(o);let d=new Error(`Script execution timed out after ${i}ms`);d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},i+5e3);this.pool.registerTask(o,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.pool.unregisterTask(o,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,Q({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,Q({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),o.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),o.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),o.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),o.worker,d.callId,g):d.type==="dispatchCall"&&this.handleIoCall(()=>this.execDispatchCall(d,n),o.worker,d.callId,g)}}),o.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,i){if(!i?.aborted)try{let o=await(i?fr.run(i,e):e());if(i?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:kn(o)})}catch{}}catch(o){if(i?.aborted)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=t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return i[e.method](...n)}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 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)}isScriptParseFailure(e){let t=e.message||"";return Fi.some(n=>t.includes(n))}async run(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);Q({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let u;try{let l={code:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("execute",l,t,i)}catch(f){let c=f,p=se(e,"typescript")||"";if(!this.isScriptParseFailure(c)||p===e)throw f;Q({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let f=l;if(Q({event:"isolated_run_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ge(i,e);let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ie.createException(void 0,c,f.message||"Unknown error",e,f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),Q({event:"isolated_run_ok"}),u.valueAbsent?void 0:u.value}async runBatch(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);Q({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let u;try{let l={codeBlocks:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",l,t,i)}catch(f){let c=f,p=e.map(g=>({...g,code:se(g.code,"typescript")||""})),d=p.some((g,m)=>g.code!==e[m]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;Q({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let f=l;if(Q({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ge(i,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ie.createException(void 0,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),Q({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var Rn=require("mongodb");Le();function De(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function Y(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!De(r)&&(r.foreignKeyColumn||r.propertyName)||null}function J(r){return r.mappedBy||r.foreignKeyColumn||r.propertyName||null}function Z(r){if(!r||typeof r!="object")return r;if(r instanceof Rn.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 Rn.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 ze(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,f=e.junctionTableName||Pe(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=je(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,i=t,o=e.junctionTableName||Pe(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=je(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function Vt(r,e,t){if(!r)return{scalarFields:[],relations:[]};let n=r.tables?.get(e);if(!n)return{scalarFields:[],relations:[]};let i=new Map;for(let u of t)if(u==="*")i.has("")||i.set("",[]),i.get("").push(u);else if(u.includes(".")){let l=u.split("."),f=l[0],c=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(c)}else n.relations?.some(f=>f.propertyName===u)?i.has(u)||i.set(u,["_id"]):(i.has("")||i.set("",[]),i.get("").push(u));let o=[],s=[],a=i.get("")||[];for(let u of a)if(u==="*"){if(n.columns)for(let l of n.columns)o.includes(l.name)||o.push(l.name);if(n.relations)for(let l of n.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else n.columns?.some(f=>f.name===u)&&!o.includes(u)&&o.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=n.relations?.find(m=>m.propertyName===u);if(!f)continue;let c="",p="",d=!1;f.type==="many-to-one"||f.type==="one-to-one"?De(f)?(c="_id",p=J(f)||f.propertyName,d=!0):(c=Y(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=J(f)||f.propertyName,d=!0):f.type==="many-to-many"&&(f.mappedBy?(c="_id",p=f.mappedBy,d=!0):(c=f.propertyName,p="_id",d=!1));let g=f.type==="one-to-many"||f.type==="many-to-many";s.push({propertyName:u,targetTable:f.targetTableName,localField:c,foreignField:p,type:g?"many":"one",isInverse:d,nestedFields:l})}return{scalarFields:o,relations:s}}var Ht=oe(require("fs")),Nn=oe(require("path"));var Ni=new RegExp("\\p{Mark}","gu");function wr(r){return r==null?"":String(r).normalize("NFKD").replace(Ni,"").toLowerCase()}function Fn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=wr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function zt(){return`function() {
|
|
8
8
|
var M = ${Fn()};
|
|
9
9
|
function foldStr(s) {
|
|
10
10
|
if (s == null) return '';
|
|
@@ -50,4 +50,4 @@ ${r}
|
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
return true;
|
|
53
|
-
}`}var Tr="mongo-fold-text-search.body.txt",He=null;function Ni(){let r=[Nn.join(__dirname,Tr),Nn.join(process.cwd(),"dist","kernel","query","utils",Tr)];for(let e of r)try{if(Ht.existsSync(e))return Ht.readFileSync(e,"utf8")}catch{}return null}function qt(){if(He!==null)return He;let r=Ni();return r?(He=r,He):(He=zt(),He)}var he=require("mongodb");function P(r,e,t,n){if(t==="_id"){if(n instanceof he.ObjectId)return n;if(typeof n=="string")try{return new he.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 he.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 he.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 he.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new he.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 he.ObjectId(n)}catch{return n}return n;default:return n}}var Gt="__mongoFoldTextTriples";function vi(r){return r==="_id"?"$_id":`$${r}`}function qe(r,e,t,n){let i=vi(e),o=r[Gt]??[];o.push({ref:i,needle:t,mode:n}),r[Gt]=o}function Oi(r){let e=r[Gt];if(delete r[Gt],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:qt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Ge(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,f=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let l=P(r,f,a,s.value);switch(s.operator){case"=":i[a]=l;break;case"!=":i[a]={$ne:l};break;case">":i[a]={$gt:l};break;case"<":i[a]={$lt:l};break;case">=":i[a]={$gte:l};break;case"<=":i[a]={$lte:l};break;case"like":i[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let u=s.value;Array.isArray(u)||(u=typeof u=="string"&&u.includes(",")?u.split(",").map(_=>_.trim()):[u]);let c=u.map(_=>P(r,f,a,_));i[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(_=>_.trim()):[p]);let d=p.map(_=>P(r,f,a,_));i[a]={$nin:d};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":qe(i,a,String(l),"contains");break;case"_starts_with":qe(i,a,String(l),"starts");break;case"_ends_with":qe(i,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(_=>_.trim())),Array.isArray(g)&&g.length===2){let _=P(r,f,a,g[0]),w=P(r,f,a,g[1]);i[a]={$gte:_,$lte:w}}break;case"_is_null":let m=l===!0||l==="true";i[a]=m?{$eq:null}:{$ne:null};break;case"_is_not_null":let y=l===!0||l==="true";i[a]=y?{$ne:null}:{$eq:null};break}}return Oi(i),i}function $r(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function Yt(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]=P(r,t,n,o);break;case"_neq":{let c=P(r,t,n,o);$r(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=o;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>P(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>P(r,t,n,c));$r(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:P(r,t,n,o)};break;case"_gte":e[n]={$gte:P(r,t,n,o)};break;case"_lt":e[n]={$lt:P(r,t,n,o)};break;case"_lte":e[n]={$lte:P(r,t,n,o)};break;case"_is_null":let f=o===!0||o==="true";e[n]=f?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=o===!0||o==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let u=o;if(typeof u=="string"&&(u=u.split(",").map(c=>c.trim())),Array.isArray(u)&&u.length===2){let c=P(r,t,n,u[0]),p=P(r,t,n,u[1]);e[n]={$gte:c,$lte:p}}break}}var In=require("mongodb");function ee(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(ee(i,e))return!0}}else if(t==="_not"){if(ee(n,e))return!0}else if(e.has(t))return!0;return!1}function z(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 f=Object.keys(a);if(f.some(u=>u.startsWith("_"))){let u=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];f.length===1&&u.includes(f[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ee(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}vt();Ot();var rn="__mongoFoldTextTriples";function Ke(r,e){if(!r)return{};let t={};return tn(r,t,e),nn(t),t}function se(r,e,t){if(!e)return{};let n=new te,{node:i}=be(e,t,r,n);return Ke(i,{metadata:r,rootTable:t})}function tn(r,e,t){switch(r.kind){case"true":return;case"false":At(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return tn(o,s,t),nn(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}At(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return tn(s,a,t),nn(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={};tn(r.child,n,t),nn(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Di(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 Di(r,e,t){let n=r.field.fieldName;if(n==="id"&&(n="_id"),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=>P(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":ne(e,n,i(r.value));return;case"neq":{let o=i(r.value);xr(t,n)?At(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):ne(e,n,{$ne:o});return}case"gt":ne(e,n,{$gt:i(r.value)});return;case"gte":ne(e,n,{$gte:i(r.value)});return;case"lt":ne(e,n,{$lt:i(r.value)});return;case"lte":ne(e,n,{$lte:i(r.value)});return;case"in":{let o=Rr(r.value).map(i);ne(e,n,{$in:o});return}case"not_in":{let o=Rr(r.value).map(i);xr(t,n)?At(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):ne(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&&ne(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":ne(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":On(e,n,String(r.value),"contains");return;case"starts_with":On(e,n,String(r.value),"starts");return;case"ends_with":On(e,n,String(r.value),"ends");return}}function ne(r,e,t){r[e]===void 0?r[e]=t:(At(r,{[e]:r[e]},{[e]:t}),delete r[e])}function At(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function xr(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Rr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function Bi(r){return r==="_id"?"$_id":`$${r}`}function On(r,e,t,n){let i=Bi(e),o=r[rn]??[];o.push({ref:i,needle:t,mode:n}),r[rn]=o}function nn(r){let e=r[rn];if(delete r[rn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:qt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function ae(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return se(t,r,e);let o=new Set((i.relations||[]).map(l=>l.propertyName));if(!ee(r,o))return se(t,r,e);if(r._and&&Array.isArray(r._and)){let u=(await Promise.all(r._and.map(c=>ae(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return u.length===0?{}:u.length===1?u[0]:{$and:u}}if(r._or&&Array.isArray(r._or)){let u=(await Promise.all(r._or.map(c=>ae(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return u.length===0?{}:{$or:u}}if(r._not){let l=await ae(r._not,e,t,n);return!l||Object.keys(l).length===0?{}:{$nor:[l]}}let{fieldFilters:s,relationFilters:a}=z(r,i),f=[];if(s&&Object.keys(s).length>0){let l=se(t,s,e);l&&Object.keys(l).length>0&&f.push(l)}if(a&&Object.keys(a).length>0)for(let[l,u]of Object.entries(a)){let c=await Ki(l,u,e,i,t,n);c&&Object.keys(c).length>0&&f.push(c)}return f.length===0?{}:f.length===1?f[0]:{$and:f}}async function Ki(r,e,t,n,i,o){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,f=i?.tables?.get(a);return!a||!f?{}:s.type==="many-to-one"||s.type==="one-to-one"?Wi(e,s,r,a,f,i,o):s.type==="one-to-many"?Ui(e,s,t,a,f,i,o):s.type==="many-to-many"?Qi(e,s,t,a,f,i,o):{}}async function Wi(r,e,t,n,i,o,s){let a=G(e)||t,f=En(r),l=Pn(f);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let u=Nr(f);if(u!==null){let g=jn(u.value);if(u.op==="eq")return{[a]:g};if(u.op==="neq")return{[a]:{$ne:g}};if(u.op==="in")return{[a]:{$in:g}};if(u.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await Mn(f,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:null}:{[a]:{$in:d}}}async function Ui(r,e,t,n,i,o,s){let a=Q(e)||t,f=En(r),l=Pn(f);if(l!==null){let p=await Fr(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let u=await Mn(f,n,i,o,s);if(!u||Object.keys(u).length===0)return{};let c=await Fr(s,n,a,u);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Qi(r,e,t,n,i,o,s){let a=ze(t,e);if(!a)return{};let f=En(r),l=Pn(f);if(l!==null){let m=await An(s,a,n,null);return l?m.length===0?{}:{_id:{$nin:m}}:m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let u=Nr(f);if(u!==null){let m=jn(u.value),y=Array.isArray(m)?m:[m],_=await An(s,a,n,{_id:{$in:y}});return _.length===0?{__impossible__:!0}:{_id:{$in:_}}}let c=await Mn(f,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await An(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function Mn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ee(r,o)?ae(r,e,n,i):se(n,r,e)}async function Fr(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 f=a[t];if(f==null)continue;let l=String(f);o.has(l)||(o.add(l),s.push(f))}return s}async function An(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(u=>u._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,f=[];for(let l of s){let u=l[e.selfColumn];if(u==null)continue;let c=String(u);a.has(c)||(a.add(c),f.push(u))}return f}function En(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 jn(r){if(Array.isArray(r))return r.map(e=>jn(e));if(typeof r!="string")return r;try{return new In.ObjectId(r)}catch{return r}}function Nr(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof In.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 It(r,e,t,n){let i=await Vt(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let m=Object.keys(g)[0];m&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(m)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,m]of Object.entries(s))if(typeof m=="object"&&m!==null)for(let[y,_]of Object.entries(m))Yt(r,d,e,g,y,_);else d[g]=m;Object.keys(d).length>0&&o.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],u=[];for(let[d,g]of Object.entries(a))if(!i.relations.some(y=>y.propertyName===d)){let y=l.find(_=>_.propertyName===d);if(y){let _="",w="";if(y.type==="many-to-one"||y.type==="one-to-one")_=G(y)||y.propertyName,w="_id";else if(y.type==="one-to-many")_="_id",w=Q(y)||y.propertyName;else if(y.type==="many-to-many")continue;let b=y.type==="one-to-many"||y.type==="many-to-many";u.push({propertyName:d,targetTable:y.targetTableName,localField:_,foreignField:w,type:b?"many":"one",nestedFields:[]})}}let c=[...i.relations,...u];for(let d of c){let g=a[d.propertyName],m=d.nestedFields&&d.nestedFields.length>0?await It(r,d.targetTable,d.nestedFields,g):g?await It(r,d.targetTable,["_id"],g):[];d.type==="one"&&m.length>0&&m.push({$limit:1}),o.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:m.length>0?m:void 0}}),d.type==="one"&&(o.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Xe(g)||o.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(i.scalarFields.length>0||i.relations.length>0||p.length>0){let d={_id:1};for(let m of i.scalarFields)d[m]=1;for(let m of c)d[m.propertyName]=1;if(t.includes("*"))for(let m of p){if(m.type==="one-to-many"||m.type==="many-to-many")continue;m.type==="many-to-many"?d[m.propertyName]={$map:{input:`$${m.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[m.propertyName]={$cond:{if:{$ne:[`$${m.propertyName}`,null]},then:{_id:`$${m.propertyName}`},else:null}}}o.push({$project:d})}return o}async function vr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],f=s.filter(u=>!i.some(c=>c.propertyName===u.propertyName)),l=n.length===a.length||n.length===0&&i.length===0;if(f.length>0||!l){let u={_id:1};for(let c of n)u[c]=1;for(let c of i)u[c.propertyName]=1;for(let c of f){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?u[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:u[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:u})}}function Xe(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Xe(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Xe(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Xe(e));if("_not"in r)return Xe(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Xe(t)))return!0}return!1}et();var Mt=require("mongodb");et();on();var tt=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let 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("-");return{field:i?n.slice(1):n,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(l=>l.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let l of i){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],m=this.normalizeMetadata()?.tables?.get(p);if(!m)break;let y=m.relations?.find(b=>b.propertyName===g);if(!y)break;let _=y.targetTableName||y.targetTable,w=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(w)){s.add(w);let b=G(y)||y.propertyName,T=d===0?null:`__sort_${c.slice(0,d).join("_")}`,h=T?`${T}.${b}`:b;o.push({$lookup:{from:_,localField:h,foreignField:"_id",as:w}},{$unwind:{path:`$${w}`,preserveNullAndEmptyArrays:!0}})}p=_}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let f={};for(let l of s)f[l]=0;return Object.keys(f).length>0&&o.push({$project:f}),o}toObjectId(e){try{return typeof e=="string"?new Mt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Mt.ObjectId||t instanceof Mt.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)})}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 Mt.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.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}=Ze(e),o={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])i.has(p.propertyName)||i.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?o[d.name]=1:t.relations?.find(m=>m.propertyName===p)&&!i.has(p)&&i.set(p,["_id"])}i.forEach((p,d)=>{let g=t.relations?.find(m=>m.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(o[g.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((p,d)=>{let g=t.relations?.find(w=>w.propertyName===d);if(!g)return;let m=g.targetTableName||g.targetTable;if(!m)return;let y,_;g.type==="many-to-one"||g.type==="one-to-one"?De(g)?(y="_id",_=Q(g)||g.propertyName):(y=G(g)||g.propertyName,_="_id"):g.type==="one-to-many"?(y="_id",_=Q(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(y="_id",_=g.mappedBy):(y=g.propertyName,_="_id")),a.push({relationName:d,type:g.type,targetTable:m,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:y,foreignField:_})});let f=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],u=[];if(!s&&l.length>0)for(let p of l)o[p.newName]===1&&o[p.oldName]!==1&&(o[p.oldName]=1,u.push(p.oldName));return{isPkOnly:f,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:l,hiddenFields:u}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?se(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await H(t,f=>{let l={_id:{$in:f}};o&&Object.keys(o).length>0&&Object.assign(l,o);let u={projection:n.projection};return s&&(u.sort=s),this.db.collection(e).find(l,u).toArray()});return this.applyReadFallback(a,n)}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=n.filter(y=>y!=null).map(y=>this.toObjectId(y)),f=o?.userFilter?se(this.normalizeMetadata(),o.userFilter,e):null,l=o?.userLimit,u=o?.userPage,c=this.hasDottedSort(o?.userSort);if(l!==void 0){let y=u?(u-1)*l:0,_=await ce(a,async b=>{let T={[t]:b};if(f&&Object.keys(f).length>0&&Object.assign(T,f),c){let x=this.buildSortAggregatePipeline(e,T,o.userSort);y>0&&x.push({$skip:y}),x.push({$limit:l}),s&&x.push({$project:s});let R=await this.db.collection(e).aggregate(x).toArray();return this.applyReadFallback(R,i)}let k={sort:this.buildSortFromTokens(o?.userSort)||{_id:1}};s&&(k.projection=s);let S=this.db.collection(e).find(T,k);return y>0&&S.skip(y),S.limit(l),this.applyReadFallback(await S.toArray(),i)},16),w=[];for(let[b,T]of _.entries()){let h=a.find(k=>this.keyOf(k)===b);for(let k of T)k[t]||(k[t]=h??b),w.push(k)}return{docs:w,groupKeyField:t}}if(c){let y=[],_=await ce(a,async w=>{let b={[t]:w};f&&Object.keys(f).length>0&&Object.assign(b,f);let T=this.buildSortAggregatePipeline(e,b,o.userSort);s&&T.push({$project:s});let h=await this.db.collection(e).aggregate(T).toArray();return this.applyReadFallback(h,i)},16);for(let w of _.values())for(let b of w)y.push(b);return{docs:y,groupKeyField:t}}let p={[t]:{$in:a}};f&&Object.keys(f).length>0&&Object.assign(p,f);let d=this.buildSortFromTokens(o?.userSort)||{_id:1},g={projection:s,sort:d},m=await H(a,y=>this.db.collection(e).find({[t]:{$in:y},...f||{}},g).toArray());return{docs:this.applyReadFallback(m,i),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}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=ze(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let f=e.map(b=>b._id).filter(b=>b!=null),l=new Map;for(let b of e)l.set(this.keyOf(b._id),[]);if(f.length===0)return{grouped:l,docs:[]};let u=await H(f,b=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:b}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(u.length===0)return{grouped:l,docs:[]};let c=t.userFilter?se(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0){let b=d?(d-1)*p:0,T=await ce(f,async k=>{let x=(await this.db.collection(a.junctionName).find({[a.selfColumn]:k},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(W=>W[a.otherColumn]).filter(W=>W!=null);if(x.length===0)return[];let R={_id:{$in:x}};if(c&&Object.keys(c).length>0&&Object.assign(R,c),this.hasDottedSort(t.userSort)){let W=this.buildSortAggregatePipeline(t.targetTable,R,t.userSort);b>0&&W.push({$skip:b}),W.push({$limit:p}),o.projection&&W.push({$project:o.projection});let Se=await this.db.collection(t.targetTable).aggregate(W).toArray();return this.applyReadFallback(Se,o)}let A={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};o.projection&&(A.projection=o.projection);let j=this.db.collection(t.targetTable).find(R,A);return b>0&&j.skip(b),j.limit(p),this.applyReadFallback(await j.toArray(),o)},16),h=[];for(let[k,S]of T.entries()){l.set(k,S);for(let x of S)h.push(x)}return{grouped:l,docs:h}}let g=new Set,m=[];for(let b of u){let T=b[a.otherColumn];if(T==null)continue;let h=this.keyOf(T);g.has(h)||(g.add(h),m.push(T))}let y=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!c,_=[],w=new Map;if(y)for(let b of m)w.set(this.keyOf(b),{_id:b});else{let b={_id:{$in:m}};c&&Object.keys(c).length>0&&Object.assign(b,c);let T=this.hasDottedSort(t.userSort),h;if(T){let k=this.buildSortAggregatePipeline(t.targetTable,b,t.userSort);o.projection&&k.push({$project:o.projection}),h=await this.db.collection(t.targetTable).aggregate(k).toArray()}else{let k=this.buildSortFromTokens(t.userSort)||{_id:1},S=this.projectionWithSortFields(o.projection,t.userSort),x={sort:k};S.projection&&(x.projection=S.projection),h=await H(m,R=>this.db.collection(t.targetTable).find({_id:{$in:R},...c||{}},x).toArray()),this.sortDocsInMemory(h,t.userSort),this.removeHiddenFields(h,S.hiddenFields)}_=this.applyReadFallback(h,o);for(let k of _)w.set(this.keyOf(k._id),k)}if(t.userSort){let b=new Map;for(let T of u){let h=this.keyOf(T[a.selfColumn]),k=this.keyOf(T[a.otherColumn]);b.has(k)||b.set(k,[]),b.get(k).push(h)}for(let T of _){let h=b.get(this.keyOf(T._id))||[];for(let k of h)l.get(k)?.push(T)}}else for(let b of u){let T=this.keyOf(b[a.selfColumn]),h=this.keyOf(b[a.otherColumn]),k=w.get(h);if(!k)continue;let S=l.get(T);S&&S.push(k)}return{grouped:l,docs:_}}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 sn(r,e,t,n,i=3,o=0,s,a,f,l){let u=await l?.getActiveFieldRenamesByTable?.(),c=new tt(r,a,u);await new _e(c,n,f).execute(e,t,i,o,s)}async function Ln(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,f=o?.tables?.get(e.table),l=new Set((f?.relations??[]).map(h=>h.propertyName)),u=!!e.mongoRawFilter&&!!o&&ee(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&u){let h=await ae(e.mongoRawFilter,e.table,o,i);h&&Object.keys(h).length>0&&n.push({$match:h})}else if(p){let h=Ke(c.filterTree,{metadata:o,rootTable:e.table});Object.keys(h).length>0&&n.push({$match:h})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let h=Ge(o,e.where,e.table,s);n.push({$match:h})}let d=e.plan,g=d?d.hasRelationSort:e.sort?.some(h=>{if(!h.field.includes("."))return!1;let k=h.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(S=>S.propertyName===k)??!1})??!1,m=u||g,y=()=>d?.sortItems?zi(d.sortItems):e.sort?Vi(e.sort):null;if(!e.mongoFieldsExpanded){let h=y();if(h&&n.push({$sort:h}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),e.select){let S={};for(let x of e.select)S[x]=1;n.push({$project:S})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let k=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:k,pipeline:n}:{results:Ir(k),pipeline:n}}let{scalarFields:_,relations:w}=e.mongoFieldsExpanded;if(!m){let h=y();h&&n.push({$sort:h}),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 b=[];for(let h of w){let k=e.mongoRawFilter?.[h.propertyName],S=e.sort?.some(x=>x.field.startsWith(`${h.propertyName}.`));if(k||S){if(h.nestedFields&&h.nestedFields.length>0){let R=await It(o,h.targetTable,h.nestedFields??[],k);h.type==="one"&&R.length>0&&R.push({$limit:1}),n.push({$lookup:{from:h.targetTable,localField:h.localField,foreignField:h.foreignField,as:h.propertyName,pipeline:R.length>0?R:void 0}})}else if(k){let R=await It(o,h.targetTable,["_id"],k);h.type==="one"&&R.length>0&&R.push({$limit:1}),n.push({$lookup:{from:h.targetTable,localField:h.localField,foreignField:h.foreignField,as:h.propertyName,pipeline:R.length>0?R:void 0}})}else n.push({$lookup:{from:h.targetTable,localField:h.localField,foreignField:h.foreignField,as:h.propertyName}});h.type==="one"&&(n.push({$unwind:{path:`$${h.propertyName}`,preserveNullAndEmptyArrays:!0}}),k&&(nt(k)||n.push({$match:{[h.propertyName]:{$ne:null}}})))}else b.push(h)}if(m){let h=y();h&&n.push({$sort:h}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}await vr(o,n,e.table,_,[...w]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let T=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:T,pipeline:n};if(b.length>0&&T.length>0){let h=e.deep||{},k=b.map(x=>{let X=o?.tables?.get(e.table)?.relations?.find(j=>j.propertyName===x.propertyName),O=h[x.propertyName],A=O?.fields!=null?Array.isArray(O.fields)?O.fields:String(O.fields).split(",").map(j=>j.trim()).filter(Boolean):x.nestedFields&&x.nestedFields.length>0?x.nestedFields:["_id"];return{relationName:x.propertyName,type:X?.type,targetTable:x.targetTable,fields:A,isInverse:X?.isInverse,mappedBy:X?.mappedBy,junctionTableName:X?.junctionTableName,localField:x.localField,foreignField:x.foreignField,userFilter:O?.filter,userSort:O?.sort,userLimit:O?.limit!==void 0?Number(O.limit):void 0,userPage:O?.page!==void 0?Number(O.page):void 0,nestedDeep:O?.deep}}),S=Ji(o);S&&await sn(i,T,k,S,3,0,e.table,o,void 0,t.mongoPhysicalMigrationService)}return{results:Ir(T),pipeline:n}}function Ji(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 Vi(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 zi(r){let e={};for(let t of r){let n=t.joinId!==null?t.fullPath:t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function nt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>nt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>nt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>nt(e));if("_not"in r)return nt(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||nt(t)))return!0}return!1}function Ir(r){return r.map(Z)}function Mr(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(Hi(o,i,e));return{scalarFields:t,relations:n}}function Hi(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&De(n)?(i="_id",o=Q(n)||r.propertyName,s=!0):(i=n&&G(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",f=Er(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:f}}function Er(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=Er(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Ye();Ot();vt();function an(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(c=>c.name==="_id"&&c.isPrimary),a=o.columns?.some(c=>c.name==="id"),f=s&&!a?"_id":"id",l=new Map,u=[];for(let c of r){let p=c==="id"?f:c;if(p==="*")u.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),m=p.substring(d+1);if(!o.relations?.some(_=>_.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(m)}else if(o.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[f]);else{if(!o.columns?.some(m=>m.name===p))continue;u.push(p)}}if(u.includes("*")){i.nodes.push({kind:"wildcard"});for(let c of o.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[f])}else for(let c of u)i.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=o.relations?.find(y=>y.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,m={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Pr(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let y=n.registerWithParent(e,c,t,"left",null,"data");m.joinId=y}i.nodes.push(m)}return i}function Pr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(u=>u.name==="_id"&&u.isPrimary),o=n.columns?.some(u=>u.name==="id"),s=i&&!o?"_id":"id",a=new Map,f=[];for(let u of r){let c=u==="id"?s:u;if(c==="*")f.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(y=>y.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;f.push(c)}}let l=[];if(f.includes("*")){l.push({kind:"wildcard"});for(let u of n.relations||[])a.has(u.propertyName)||a.set(u.propertyName,[s])}else for(let u of f)l.push({kind:"scalar",name:u});for(let[u,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===u);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:u,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Pr(c,d,t)})}return l}var K=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:f,metadata:l,dbType:u}=e,c=l?.tables?.get(t),p=new te,d=this.parseFields(n),g=null;d&&c&&(g=an(d,t,l,p));let m=!1,y=null;if(i&&c){let O=be(i,t,l,p);y=O.node,m=O.hasRelationFilters}let _=this.parseSort(o),w=[],b=!1;for(let O of _){let A=O.startsWith("-"),j=A?O.substring(1):O,W=A?"desc":"asc";if(j.includes(".")&&c){let Se=j.split(".")[0];if(c.relations?.find(C=>C.propertyName===Se)){let C=this.registerSortJoinChain(j,t,l,p,null);C&&(w.push({joinId:C.lastJoinId,field:C.field,direction:W,fullPath:j}),b=!0);continue}}w.push({joinId:null,field:j,direction:W,fullPath:j})}w.length===0&&w.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let T=this.parseLimit(a),h=this.parsePage(s),k=h!==void 0&&T!==void 0?(h-1)*T:void 0,S=this.parseMeta(f),x=S.includes("totalCount")||S.includes("*"),R=S.includes("filterCount")||S.includes("*"),X=p.getAll();return{table:t,dbType:u,rawFields:d,rawFilter:i??null,joins:X,sortItems:w,limit:T,offset:k,needsTotalCount:x,needsFilterCount:R,hasRelationFilters:m,hasRelationSort:b,filterTree:y,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),f=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let u=l.relations?.find(d=>d.propertyName===a);if(!u||u.type!=="many-to-one"&&u.type!=="one-to-one")return null;let c=i.registerWithParent(t,a,n,"left",o,"sort");if(!c)return null;if(!f.includes("."))return{lastJoinId:c,field:f};let p=u.targetTableName||u.targetTable;return this.registerSortJoinChain(f,p,n,i,c)}};Nt();Ft();var qi=new Set(["count","sum","avg","min","max","countRecords"]),Gi=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),Yi=new Set(["_and","_or","_not"]);function we(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function I(r,e){let t=r.replace(/^aggregate\./,"");throw new E(e,{path:r,aggregate:{[t]:e}})}function Xi(r){return typeof r!="string"?!1:Gi.has(r.toLowerCase())}function jr(r){return Object.keys(r).length===0}function Zi(r,e,t){return r===!0?{}:(r==null&&I(t,`aggregate.${e} condition must be true or an object`),we(r)||I(t,`aggregate.${e} condition must be true or an object`),r)}function eo(r,e,t){let n=r?.tables?.get(e);return n||I(t,`Table "${e}" metadata is not available`),n}function Lr(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&I(e,"aggregate.countRecords relation target is not available"),t}function ln(r,e,t,n){let i=eo(t,e,n);for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){Array.isArray(s)||I(n,`aggregate.countRecords ${o} condition must be an array`);for(let u of s)we(u)||I(n,`aggregate.countRecords ${o} items must be objects`),ln(u,e,t,n);continue}if(o==="_not"){we(s)||I(n,"aggregate.countRecords _not condition must be an object"),ln(s,e,t,n);continue}(o.startsWith("_")||Yi.has(o))&&I(n,`Unsupported aggregate.countRecords condition key "${o}"`);let a=i.columns?.find(u=>u.name===o),f=i.relations?.find(u=>u.propertyName===o);if(!a&&!f&&I(n,`Unknown aggregate.countRecords field or relation "${o}" on table "${e}"`),we(s)||I(n,`aggregate.countRecords condition for "${o}" must be an object`),a){for(let u of Object.keys(s))Y.has(u)||I(n,`aggregate.countRecords condition for "${o}" only supports field operators`);continue}let l=Lr(f,n);ln(s,l,t,n)}}function Dn(r){return we(r)&&Object.keys(r).length>0}function rt(r,e,t){if(!Dn(r))return[];we(r)||I("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||I("aggregate",`Table "${e}" metadata is not available`);let i=[];for(let[o,s]of Object.entries(r)){let a=`aggregate.${o}`;(!o||typeof o!="string")&&I("aggregate","aggregate field name must be a non-empty string"),we(s)||I(a,"aggregate field config must be an object");let f=o,l=a,u=n.columns?.find(d=>d.name===o),c=n.relations?.find(d=>d.propertyName===o);!u&&!c&&I(l,`Unknown aggregate field or relation "${o}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&I(l,"aggregate field must define at least one operation");for(let[d,g]of p){qi.has(d)||I(l,`Unsupported aggregate operation "${d}"`);let m=Zi(g,d,l);if(c&&d!=="countRecords"&&I(l,`aggregate.${d} is not supported on relation "${o}"; use countRecords`),u&&d==="countRecords"&&I(l,`aggregate.countRecords requires a relation, but "${o}" is a field`),u&&(d==="sum"||d==="avg")&&!Xi(u.type)&&I(l,`aggregate.${d} requires a numeric field, but "${o}" is "${u.type}"`),u)for(let y of Object.keys(m))Y.has(y)||I(l,`aggregate.${d} condition for "${o}" only supports field operators`);if(c&&d==="countRecords"){let y=Lr(c,l);ln(m,y,t,l)}i.push({field:o,outputKey:f,path:l,op:d,condition:m})}}return i}function it(r,e){let t=[];return we(r)&&!jr(r)&&t.push(r),jr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function Te(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var ot=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new K;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(B(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.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),f=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&ee(n.mongoRawFilter,f);if((i.includes("filterCount")||i.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?Ke(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let u=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(i.includes("filterCount")||i.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:u,...(i.length>0||c)&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[];if(e.fields&&e.fields.length>0){let s=e.plan;if(s?.fieldTree?e.mongoFieldsExpanded=Mr(s.fieldTree,this.metadata):(console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await Vt(this.metadata,e.table,e.fields)),this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.hiddenFields}}e.where&&(e.where=e.where.map(s=>s.field.includes(".")?s:{...s,field:`${e.table}.${s.field}`}));let n=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 n.aggregate(e.pipeline).toArray()).map(Z);let{results:i,pipeline:o}=await Ln(n,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,i,t):i}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Ln(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={},o=this.db.collection(e.table);for(let s of n){let a=it(t,s);B(a,e.table,e.metadata);let l=new K().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);Te(i,s,p);continue}let u=l.hasRelationFilters?await ae(a,e.table,e.metadata,this.db):l.filterTree?Ke(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await o.countDocuments(u);else{let[{value:p}={value:null}]=await o.aggregate([{$match:u},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}Te(i,s,c)}return i}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table)?.relations?.find(u=>u.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let f=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(o.type==="one-to-many"){let c=(await this.db.collection(e.table).find(f,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[o.foreignKeyColumn]:{$in:c}}]})}if(o.type==="many-to-many"){let u=ze(e.table,o);if(!u)return 0;let p=(await this.db.collection(e.table).find(f,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(m=>m!=null);if(p.length===0)return 0;let g=(await this.db.collection(u.junctionName).find({[u.selfColumn]:{$in:p}},{projection:{[u.otherColumn]:1}}).toArray()).map(m=>m[u.otherColumn]).filter(m=>m!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(o.type==="many-to-one"||o.type==="one-to-one"){let u=o.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(f,{projection:{[u]:1}}).toArray()).map(d=>d[u]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};B(t,e,n);let o=new K().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return o.hasRelationFilters?await ae(t,e,n,this.db):o.filterTree?Ke(o.filterTree,{metadata:n,rootTable:e}):{}}};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}};var to=["_and","_or","_not"];function ue(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>ue(e));for(let e of Object.keys(r))if(to.includes(e)||typeof r[e]=="object"&&r[e]!==null&&ue(r[e]))return!0;return!1}var Dr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function no(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function un(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 ro(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)||un(r,t,i),e}function Br(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,f=un(e,i,s),l=ro(e,n,i,o,s);switch(t){case"_eq":f&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} = ?::uuid`,[n]):r.where(a,"=",l);break;case"_neq":f&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} != ?::uuid`,[n]):r.where(a,"!=",l);break;case"_gt":f&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} > ?::uuid`,[n]):r.where(a,">",l);break;case"_gte":f&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} >= ?::uuid`,[n]):r.where(a,">=",l);break;case"_lt":f&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} < ?::uuid`,[n]):r.where(a,"<",l);break;case"_lte":f&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} <= ?::uuid`,[n]):r.where(a,"<=",l);break;case"_in":let u=n;Array.isArray(u)||(u=typeof u=="string"&&u.includes(",")?u.split(",").map(p=>p.trim()):[u]),f&&o==="postgres"&&u.every(p=>typeof p=="string")?r.whereRaw(`${a} = ANY(?::uuid[])`,[u]):r.whereIn(a,u);break;case"_not_in":case"_nin":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(p=>p.trim()):[c]),f&&o==="postgres"&&c.every(p=>typeof p=="string")?r.whereRaw(`${a} != ALL(?::uuid[])`,[c]):r.whereNotIn(a,c);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${a})) 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,no(t),n)}}function io(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 st(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(){st(this,s,t,"and",i,o)}):r.orWhere(function(){st(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(io(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let f of a)this.where(function(){st(this,f,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let f of a)this.orWhere(function(){st(this,f,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){st(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>Dr.includes(l)))for(let[l,u]of Object.entries(a))Dr.includes(l)&&(n==="and"?r.where(function(){Br(this,s,l,u,t,i,o)}):r.orWhere(function(){Br(this,s,l,u,t,i,o)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s;un(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(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let f=t&&!s.includes(".")?`${t}.${s}`:s;un(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(`${f} = ?::uuid`,[a]):r.orWhereRaw(`${f} = ?::uuid`,[a]):n==="and"?r.where(f,"=",a):r.orWhere(f,"=",a)}}}}function re(r,e,t,n,i){return!e||typeof e!="object"||st(r,e,t,"and",n,i),r}$e();function Wn(r,e,t){return`${N(r,t)}.${N(e,t)}`}function ke(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 Kr(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 at(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function Un(r,e,t,n,i,o){let s=[];for(let[a,f]of Object.entries(o)){let l=await Et(r,e,a,f,t,n,i);if(l!==null)s.push(`EXISTS (${l})`);else{let u=t.relations.find(c=>c.propertyName===a);if(u&&u.foreignKeyColumn){let c=Wn(e,u.foreignKeyColumn,n),d=f.id;if(d&&typeof d=="object"){let g=at(d._is_null),m=at(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(m===!0)s.push(`${c} IS NOT NULL`);else if(m===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let y=ke(d._eq,n);s.push(`${c} = ${y}`)}else if(d._neq!==void 0){let y=ke(d._neq,n);s.push(`${c} != ${y}`)}else if(d._in!==void 0){let _=(Array.isArray(d._in)?d._in:[d._in]).map(w=>ke(w,n)).join(", ");s.push(`${c} IN (${_})`)}else if(d._not_in!==void 0||d._nin!==void 0){let y=d._not_in??d._nin,w=(Array.isArray(y)?y:[y]).map(b=>ke(b,n)).join(", ");s.push(`${c} NOT IN (${w})`)}else if(d._gt!==void 0){let y=ke(d._gt,n);s.push(`${c} > ${y}`)}else if(d._gte!==void 0){let y=ke(d._gte,n);s.push(`${c} >= ${y}`)}else if(d._lt!==void 0){let y=ke(d._lt,n);s.push(`${c} < ${y}`)}else if(d._lte!==void 0){let y=ke(d._lte,n);s.push(`${c} <= ${y}`)}}}}}return s}function Qn(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 Bn(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 f=[];for(let l of a._and)if(Qn(l)){let u=e(t).select(`${t}.id`);await We(e,u,l,t,n,i,o),f.push({idSubquery:u})}else{let{fieldFilters:u,relationFilters:c}=z(l,n),p=await Un(e,t,n,i,o,c);f.push({fieldFilters:u,subqueries:p})}s.push(f)}else if(Qn(a)){let f=e(t).select(`${t}.id`);await We(e,f,a,t,n,i,o),s.push([{idSubquery:f}])}else{let{fieldFilters:f,relationFilters:l}=z(a,n),u=await Un(e,t,n,i,o,l);s.push([{fieldFilters:f,subqueries:u}])}return s}function Wr(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&&re(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function Kn(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let f of s)Wr(this,f,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function fn(r,e,t,n,i,o,s){let a=Kr(e,i),f=Kr(n,o),l=`${N(r,s)}.${N(e,s)}`,u=`${N(t,s)}.${N(n,s)}`;if(s==="postgres"){if(a&&!f)return`${l} = ${u}::uuid`;if(!a&&f)return`${l}::uuid = ${u}`}return`${l} = ${u}`}async function Et(r,e,t,n,i,o,s){let a=i.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let f=a.targetTableName||a.targetTable;if(!f)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let u=s?await s(f):null,c;switch(a.type){case"one-to-many":c=r(f).select(r.raw("1")).whereRaw(fn(f,a.foreignKeyColumn,e,"id",u,i,o));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(f,r.raw(fn(a.junctionTableName,a.junctionTargetColumn,f,"id",p,u,o))).whereRaw(fn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,i,o));break;case"many-to-one":case"one-to-one":c=r(f).select(r.raw("1")).whereRaw(fn(f,"id",e,a.foreignKeyColumn,u,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?u?await We(r,c,n,f,u,o,s):c=re(c,n,f,o,u||void 0):c=re(c,n,f,o),c.toString()}async function We(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let u=await Bn(l._or,r,n,i,o,s);e.where(function(){Kn(this,u,n,i,o)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let u of l._and)await We(r,e,u,n,i,o,s);else await We(r,e,l,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let l=await Bn(t._or,r,n,i,o,s);e.where(function(){Kn(this,l,n,i,o)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(Qn(d)){let g=r(n).select(`${n}.id`);await We(r,g,d,n,i,o,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:m}=z(d,i),y=await Un(r,n,i,o,s,m);p.push({fieldFilters:g,subqueries:y})}e.whereNot(function(){for(let d of p)Wr(this,d,n,i,o)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Bn(l._or,r,n,i,o,s);e.whereNot(function(){Kn(this,p,n,i,o)});return}let{fieldFilters:u,relationFilters:c}=z(l,i);e.whereNot(function(){Object.keys(u).length>0&&re(this,u,n,o,i)});for(let[p,d]of Object.entries(c)){let g=await Et(r,n,p,d,i,o,s);if(g===null){let m=i.relations.find(y=>y.propertyName===p);if(m&&m.foreignKeyColumn){let y=Wn(n,m.foreignKeyColumn,o),w=d.id;if(w&&typeof w=="object"){let b=at(w._is_null),T=at(w._is_not_null);if(b===!0)e.whereRaw(`${y} IS NOT NULL`);else if(b===!1)e.whereRaw(`${y} IS NULL`);else if(T===!0)e.whereRaw(`${y} IS NULL`);else if(T===!1)e.whereRaw(`${y} IS NOT NULL`);else if(w._eq!==void 0)e.whereRaw(`${y} != ?`,[w._eq]);else if(w._neq!==void 0)e.whereRaw(`${y} = ?`,[w._neq]);else if(w._in!==void 0){let h=Array.isArray(w._in)?w._in:[w._in];e.whereRaw(`${y} NOT IN (${h.map(()=>"?").join(", ")})`,h)}else if(w._not_in!==void 0||w._nin!==void 0){let h=w._not_in??w._nin,k=Array.isArray(h)?h:[h];e.whereRaw(`${y} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:f}=z(t,i);Object.keys(a).length>0&&re(e,a,n,o,i);for(let[l,u]of Object.entries(f)){let c=await Et(r,n,l,u,i,o,s);if(c===null){let p=i.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Wn(n,p.foreignKeyColumn,o),m=u.id;if(m&&typeof m=="object"){let y=at(m._is_null),_=at(m._is_not_null);if(y===!0)e.whereRaw(`${d} IS NULL`);else if(y===!1)e.whereRaw(`${d} IS NOT NULL`);else if(_===!0)e.whereRaw(`${d} IS NOT NULL`);else if(_===!1)e.whereRaw(`${d} IS NULL`);else if(m._eq!==void 0)e.whereRaw(`${d} = ?`,[m._eq]);else if(m._neq!==void 0)e.whereRaw(`${d} != ?`,[m._neq]);else if(m._in!==void 0){let w=Array.isArray(m._in)?m._in:[m._in];e.whereRaw(`${d} IN (${w.map(()=>"?").join(", ")})`,w)}else if(m._not_in!==void 0||m._nin!==void 0){let w=m._not_in??m._nin,b=Array.isArray(w)?w:[w];e.whereRaw(`${d} NOT IN (${b.map(()=>"?").join(", ")})`,b)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Ue(r,e,t,n,i,o,s){await We(r,e,t,n,i,o,s)}$e();Vn();Ye();Le();$e();function lt(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],f=s[s.length-1],l=Pt(n,a,f,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",l);break;case"!=":r=r.where(o.field,"!=",l);break;case">":r=r.where(o.field,">",l);break;case"<":r=r.where(o.field,"<",l);break;case">=":r=r.where(o.field,">=",l);break;case"<=":r=r.where(o.field,"<=",l);break;case"like":r=r.where(o.field,"like",l);break;case"in":let u=Array.isArray(o.value)?o.value.map(m=>Pt(n,a,f,m)):[l];r=r.whereIn(o.field,u);break;case"not in":let c=Array.isArray(o.value)?o.value.map(m=>Pt(n,a,f,m)):[l];r=r.whereNotIn(o.field,c);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 p=o.value;if(typeof p=="string"&&(p=p.split(",").map(m=>m.trim())),Array.isArray(p)&&p.length===2){let m=Pt(n,a,f,p[0]),y=Pt(n,a,f,p[1]);r=r.whereBetween(o.field,[m,y])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function jt(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 f=a.map(l=>{let u=jt(l,e,t,n);return u.length>0?`(${u.join(" AND ")})`:null}).filter(l=>l!==null);f.length>0&&i.push(`(${f.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let f=a.map(l=>{let u=jt(l,e,t,n);return u.length>0?`(${u.join(" AND ")})`:null}).filter(l=>l!==null);f.length>0&&i.push(`(${f.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let f=jt(a,e,t,n);f.length>0&&i.push(`NOT (${f.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[f,l]of Object.entries(a)){let u=`${N(e,n)}.${N(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=o.columns?.find(m=>m.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(f==="_eq")i.push(`${u} = ${c}`);else if(f==="_neq")i.push(`${u} != ${c}`);else if(f==="_gt")i.push(`${u} > ${c}`);else if(f==="_gte")i.push(`${u} >= ${c}`);else if(f==="_lt")i.push(`${u} < ${c}`);else if(f==="_lte")i.push(`${u} <= ${c}`);else if(f==="_is_null")i.push(`${u} IS NULL`);else if(f==="_is_not_null")i.push(`${u} IS NOT NULL`);else if(f==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${u} IN (${d})`)}else if(f==="_not_in"||f==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${u} NOT IN (${d})`)}else if(f==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${u}) LIKE '%${p.toLowerCase()}%'`)}else if(f==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${u})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${u}) LIKE '${p.toLowerCase()}%'`)}else if(f==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?i.push(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${u}) LIKE '%${p.toLowerCase()}'`)}else if(f==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);i.push(`${u} BETWEEN ${p} AND ${d}`)}}else{let f=`${N(e,n)}.${N(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),i.push(`${f} = ${l}`)}return i}function Qr(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 Pt(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}}$e();pn();Le();async function Vr(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Hn(),Jr)),f=await a(e,t,n,i,o,s);return{select:f.select,batchFetchDescriptors:f.batchFetchDescriptors}}catch{return{select:t}}}function qn(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 zr(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||L(o);if(!s)return null;let a=c=>N(c,i),f=n?.tables?.get(o),u=(f?fe(f):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(u)} = ${a(t)}.${a(s)})`}var ut=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&&B(e.filter,e.tableName,e.metadata),!e.plan){let $=new K;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,f=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!f&&!a&&l){i&&i.setQueryPath("simple");let $=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),$}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map($=>$.trim())));let p=e.filter;if(e.filter&&!ue(e.filter)){c.where=[];for(let[$,C]of Object.entries(e.filter))if(typeof C=="object"&&C!==null)for(let[F,Ce]of Object.entries(C)){let v;if(F==="_eq")v="=";else if(F==="_neq")v="!=";else if(F==="_in")v="in";else if(F==="_not_in"||F==="_nin")v="not in";else if(F==="_gt")v=">";else if(F==="_gte")v=">=";else if(F==="_lt")v="<";else if(F==="_lte")v="<=";else if(F==="_contains")v="_contains";else if(F==="_starts_with")v="_starts_with";else if(F==="_ends_with")v="_ends_with";else if(F==="_between")v="_between";else if(F==="_is_null")v="_is_null";else if(F==="_is_not_null")v="_is_not_null";else if(F==="_like")v="like";else if(F==="_ilike")v="ilike";else continue;c.where.push({field:$,operator:v,value:Ce})}else c.where.push({field:$,operator:"=",value:C})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(C=>C.trim());c.sort=$.map(C=>{let F=C.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,m=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,y=m===void 0||Number.isNaN(m)?void 0:m;y&&g!==void 0?(c.offset=(y-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let _=e.plan?.sortItems??(c.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),w=[],b=[];for(let $ of _)if($.joinId===null){if($.field.includes(".")&&!e.plan){let C=$.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(v=>v.propertyName===C))continue}w.push({field:$.field.includes(".")?$.field:`${c.table}.${$.field}`,direction:$.direction})}else{let C=e.plan?.joins.find(F=>F.id===$.joinId);if(C&&(C.relationType==="many-to-one"||C.relationType==="one-to-one")){let F=zr(C.relationMeta,$.field,c.table,this.metadata,this.dbType);F&&b.push({sql:F,direction:$.direction})}}let T=[];if(c.fields&&c.fields.length>0){let $=qn(this.metadata),C=await Vr(this.knex,c.table,c.fields,$,this.dbType,this.maxQueryDepth,e.deep);c.select=[...c.select||[],...C.select],T=C.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map($=>$.field.includes(".")?$:{...$,field:`${c.table}.${$.field}`})),c.sort=w;let h=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),S=k.includes("filterCount")||k.includes("*"),x=k.includes("totalCount")||k.includes("*");if(c.select){let $=c.select.map(C=>typeof C=="string"&&C.trim().startsWith("(")?this.knex.raw(C):typeof C=="string"&&/ as /i.test(C)?this.knex.raw(C):C);h=h.select($)}if(S&&h.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),x){let $=N(c.table,this.dbType);h.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let R=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(ue(p)||Object.keys(p).length>0)){let $=this.metadata?.tables?.get(c.table);(!R&&$&&$.relations&&$.relations.length>0?z(p,$).hasRelations:!1)?await Ue(this.knex,h,p,c.table,$,this.dbType,F=>this.metadata?.tables?.get(F)):e.plan?.filterTree?q(h,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),h=re(h,p,c.table,this.dbType,$))}else c.where&&c.where.length>0&&(h=lt(h,c.where,c.table,this.metadata,this.dbType));if(c.sort)for(let $ of c.sort){let C=$.field.includes(".")?$.field:`${c.table}.${$.field}`;h=h.orderBy(C,$.direction)}for(let $ of b)h=h.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`);c.groupBy&&(h=h.groupBy(c.groupBy)),c.offset&&(h=h.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&(h=h.limit(c.limit));let X=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:h.toSQL().toNative()});let O;if(e.debugMode&&(O=h.toSQL().toNative().sql),e.debugMode&&i){let $=h.toSQL().toNative();i.setSql($.sql);try{let C=$.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${C}`,$.bindings);i.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(C){i.setExplain({error:String(C)})}}let A,j=performance.now();A=await h,i&&i.dur("db_execute",j,{table:e.tableName});let W=0;if(S&&A.length>0&&(W=Number(A[0].__filter_count__||0),A.forEach($=>{delete $.__filter_count__})),x&&A.length>0&&A[0].__total_count__!==void 0&&(X=Number(A[0].__total_count__||0),A.forEach($=>{delete $.__total_count__})),T&&T.length>0&&A.length>0){let $=qn(this.metadata);if($){let{executeBatchFetches:C}=await Promise.resolve().then(()=>(Xn(),Hr));await C(this.knex,A,T,$,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,i)}}if(this.knexService){let $=performance.now();A=await this.knexService.parseResult(A,c.table),i&&i.dur("db_parseResult",$,{table:e.tableName})}else{let $=(C,F)=>{if(!C||!this.metadata)return C;let Ce=this.metadata.tables?.get(F);if(!Ce)return C;if(Array.isArray(C))return C.map(J=>$(J,F));if(typeof C!="object"||Buffer.isBuffer(C))return C;let v={...C};for(let J of Ce.columns)if(J.type==="simple-json"&&v[J.name]&&typeof v[J.name]=="string")try{v[J.name]=JSON.parse(v[J.name])}catch{}for(let[J,V]of Object.entries(v))if(V&&typeof V=="object"&&!Array.isArray(V)&&!Buffer.isBuffer(V)){let mn=V;if(mn.id!==void 0||mn.createdAt!==void 0){let pt=Ce.relations?.find(gt=>gt.propertyName===J);pt&&(v[J]=$(V,pt.targetTableName))}}else if(Array.isArray(V)&&V.length>0&&typeof V[0]=="object"&&V[0].id!==void 0){let pt=Ce.relations?.find(gt=>gt.propertyName===J);pt&&(v[J]=V.map(gt=>$(gt,pt.targetTableName)))}return v};A=$(A,c.table)}i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName}));let Se=await this.executeAggregate(c,p);return{data:A,...(k.length>0||Se)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:X}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:W}:{},...Se?{aggregate:Se}:{}}},...O!==void 0&&{sql:O}}}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&&q(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let y of t.sortItems){let _=y.field.includes(".")?y.field:`${n}.${y.field}`;o=o.orderBy(_,y.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(y=>y.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),f=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),f){let y=N(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${y}) as __total_count__`))}let l=e.debugTrace,u;if(e.debugMode){let y=o.toSQL().toNative();if(u=y.sql,l){l.setSql(y.sql);try{let _=y.sql.replace(/\$\d+/g,"?"),w=await this.knex.raw(`EXPLAIN ${_}`,y.bindings);l.setExplain(this.dbType==="postgres"?w.rows:w[0])}catch(_){l.setExplain({error:String(_)})}}}let c=performance.now(),p;p=await o,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(y=>delete y.__filter_count__)),f&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(y=>delete y.__total_count__));let m=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||m)&&{meta:{...f?{totalCount:g}:{},...a?{filterCount:d}:{},...m?{aggregate:m}:{}}},...u!==void 0&&{sql:u}}}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={};for(let o of n){let s=it(t,o);B(s,e.table,e.metadata);let f=new K().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(o.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,o);Te(i,o,d);continue}let l=this.knex(e.table);if(f.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Ue(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else f.filterTree&&q(l,f.filterTree,{dbType:this.dbType,rootTable:e.table});let u=`${N(e.table,this.dbType)}.${N(o.field,this.dbType)}`,c=o.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${o.op.toUpperCase()}(${u}) as value`),p=await l.clearSelect().select(c).first();Te(i,o,p?.value??0)}return i}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table),o=i?.relations?.find(c=>c.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let f=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new K().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,f,t,e.table,i,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&q(f,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){B(n.condition,s,e.metadata);let p=new K().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&q(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(o.type==="one-to-many")l.whereIn(`${s}.${o.foreignKeyColumn}`,f);else if(o.type==="many-to-many"){let c=o.junctionTableName||Pe(e.table,o.propertyName,s),p=je(e.table,o.propertyName,s),d=o.junctionSourceColumn||p.sourceColumn,g=o.junctionTargetColumn||p.targetColumn;l.whereIn(`${s}.id`,this.knex(c).select(`${c}.${g}`).whereIn(`${c}.${d}`,f))}else(o.type==="many-to-one"||o.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${o.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,f),this.whereNotNull(`${e.table}.${o.foreignKeyColumn}`)});let u=await l.first();return Number(u?.value??0)}};var gn=require("mongodb"),ft=class{constructor(e){this.debugLog=[];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()}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(!gn.ObjectId)return e;if(typeof e=="string")try{return new gn.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=Ge(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:lt(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(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 K().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")return new ot(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new ut(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(o).toArray(),f=[];for(let l of a){let u=await this.mongoService.updateOne(e.table,l._id,e.data);f.push(u)}return f});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),s=await this.mongoService.collection(e.table).find(i).toArray(),a=0;for(let f of s)await this.mongoService.deleteOne(e.table,f._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let 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 gn.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,f=this.mapFilterOperatorToSql(s);t.push({field:n,operator:f,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t){return this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let s=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return Z(s)}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 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 delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[a,f]of Object.entries(t))a==="id"||a==="_id"?i._id=this.safeObjectId(f):i[a]=f;return await this.mongoService.collection(e).find(i).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}};Xn();Gn();Hn();$e();pn();et();Nt();Ye();var qr=new Set(["fields","filter","sort","limit","page","deep"]),dt=3;function Zn(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new E(`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,f]of Object.entries(e)){let l=s.get(a);if(!l)throw new E(`Unknown relation '${a}' on '${r}'`);if(!f||typeof f!="object")continue;for(let p of Object.keys(f))if(!qr.has(p))throw new E(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...qr].join(", ")}`);let u=l.type;if(f.limit!==void 0&&(u==="many-to-one"||u==="one-to-one"))throw new E(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(f.page!==void 0&&f.limit===void 0)throw new E(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(f.filter&&(B(f.filter,c,t),yn(f.filter,0,a,r)),f.sort){let p=Array.isArray(f.sort)?f.sort:String(f.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;ao(g,c,t,a,r)}}f.deep&&Zn(c,f.deep,t,n+1,i)}}}function ao(r,e,t,n,i){let o=r.split(".");if(o.length-1>dt)throw new E(`Sort path '${r}' exceeds max dotted hops of ${dt} (relation '${n}' on '${i}')`);let a=e;for(let f=0;f<o.length;f++){let l=o[f],u=f===o.length-1,c=t?.tables?.get(a);if(!c)throw new E(`Sort path '${r}' references unknown table '${a}' (relation '${n}' on '${i}')`);if(c.columns?.find(g=>g.name===l)){if(!u)throw new E(`Sort path '${r}' references column '${l}' in non-terminal position (relation '${n}' on '${i}')`);return}let d=c.relations?.find(g=>g.propertyName===l);if(!d)throw new E(`Sort path '${r}' references unknown field '${l}' on '${a}' (relation '${n}' on '${i}')`);if(!u){let g=d.type;if(g==="one-to-many"||g==="many-to-many")throw new E(`Sort path '${r}' passes through '${l}' which is a ${g} relation \u2014 sort path must only traverse many-to-one or one-to-one (owner-side) relations (relation '${n}' on '${i}')`);a=d.targetTableName||d.targetTable||a}}}var lo=new Set(["_and","_or","_not"]);function yn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(lo.has(i)){if(Array.isArray(o))for(let l of o)yn(l,e,t,n);else o&&typeof o=="object"&&yn(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>dt)throw new E(`Filter path exceeds max dotted hops of ${dt} at '${i}' (relation '${t}' on '${n}')`);let f={};for(let l of Object.keys(o))l.startsWith("_")||(f[l]=o[l]);yn(f,a,t,n)}}function Gr(r,e,t,n){return!r||typeof r!="object"?r:Lt(r,e,t,n)}function Lt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Lt(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 c=(Array.isArray(s)?s:[s]).map(p=>Lt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(i[o]=c);continue}if(o==="_not"){let u=Lt(s,e,t,n);u!=null&&Object.keys(u).length>0&&(i[o]=u);continue}let a=t?.tables?.get(e),f=a?.relations?.find(u=>u.propertyName===o);if(f){if(!n(e,o,"relation"))continue;let u=f.targetTableName||f.targetTable;if(!u)continue;let c=Lt(s,u,t,n);c!=null&&Object.keys(c).length>0&&(i[o]=c);continue}if(a?.columns?.find(u=>u.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function Yr(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 l=(s.startsWith("-")?s.slice(1):s).split("."),u=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,m=t?.tables?.get(c);if(!m){u=!1;break}if(g)m.columns?.find(_=>_.name===d)?n(c,d,"column")||(u=!1):m.relations?.find(w=>w.propertyName===d)&&(n(c,d,"relation")||(u=!1));else{let y=m.relations?.find(_=>_.propertyName===d);if(!y){u=!1;break}if(!n(c,d,"relation")){u=!1;break}c=y.targetTableName||y.targetTable||c}}u&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}vt();Ye();Ot();on();Ft();Le();Nt();function co(r){let e=new ft({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new Ve({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Qe({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,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,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,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,transformCode,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|
|
53
|
+
}`}var Tr="mongo-fold-text-search.body.txt",He=null;function vi(){let r=[Nn.join(__dirname,Tr),Nn.join(process.cwd(),"dist","kernel","query","utils",Tr)];for(let e of r)try{if(Ht.existsSync(e))return Ht.readFileSync(e,"utf8")}catch{}return null}function qt(){if(He!==null)return He;let r=vi();return r?(He=r,He):(He=zt(),He)}var be=require("mongodb");function j(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 Gt="__mongoFoldTextTriples";function Ai(r){return r==="_id"?"$_id":`$${r}`}function qe(r,e,t,n){let i=Ai(e),o=r[Gt]??[];o.push({ref:i,needle:t,mode:n}),r[Gt]=o}function Oi(r){let e=r[Gt];if(delete r[Gt],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:qt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Ge(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 l=j(r,u,a,s.value);switch(s.operator){case"=":i[a]=l;break;case"!=":i[a]={$ne:l};break;case">":i[a]={$gt:l};break;case"<":i[a]={$lt:l};break;case">=":i[a]={$gte:l};break;case"<=":i[a]={$lte:l};break;case"like":i[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(b=>b.trim()):[f]);let c=f.map(b=>j(r,u,a,b));i[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(b=>b.trim()):[p]);let d=p.map(b=>j(r,u,a,b));i[a]={$nin:d};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":qe(i,a,String(l),"contains");break;case"_starts_with":qe(i,a,String(l),"starts");break;case"_ends_with":qe(i,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(b=>b.trim())),Array.isArray(g)&&g.length===2){let b=j(r,u,a,g[0]),_=j(r,u,a,g[1]);i[a]={$gte:b,$lte:_}}break;case"_is_null":let m=l===!0||l==="true";i[a]=m?{$eq:null}:{$ne:null};break;case"_is_not_null":let y=l===!0||l==="true";i[a]=y?{$ne:null}:{$eq:null};break}}return Oi(i),i}function $r(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function Yt(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]=j(r,t,n,o);break;case"_neq":{let c=j(r,t,n,o);$r(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=o;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>j(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>j(r,t,n,c));$r(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:j(r,t,n,o)};break;case"_gte":e[n]={$gte:j(r,t,n,o)};break;case"_lt":e[n]={$lt:j(r,t,n,o)};break;case"_lte":e[n]={$lte:j(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 l=o===!0||o==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=o;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=j(r,t,n,f[0]),p=j(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var Mn=require("mongodb");function ee(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(ee(i,e))return!0}}else if(t==="_not"){if(ee(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(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ee(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}vt();At();var rn="__mongoFoldTextTriples";function Ke(r,e){if(!r)return{};let t={};return tn(r,t,e),nn(t),t}function ae(r,e,t){if(!e)return{};let n=new te,{node:i}=_e(e,t,r,n);return Ke(i,{metadata:r,rootTable:t})}function tn(r,e,t){switch(r.kind){case"true":return;case"false":Ot(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return tn(o,s,t),nn(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}Ot(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return tn(s,a,t),nn(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={};tn(r.child,n,t),nn(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Bi(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 Bi(r,e,t){let n=r.field.fieldName;if(n==="id"&&(n="_id"),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=>j(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":ne(e,n,i(r.value));return;case"neq":{let o=i(r.value);xr(t,n)?Ot(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):ne(e,n,{$ne:o});return}case"gt":ne(e,n,{$gt:i(r.value)});return;case"gte":ne(e,n,{$gte:i(r.value)});return;case"lt":ne(e,n,{$lt:i(r.value)});return;case"lte":ne(e,n,{$lte:i(r.value)});return;case"in":{let o=Rr(r.value).map(i);ne(e,n,{$in:o});return}case"not_in":{let o=Rr(r.value).map(i);xr(t,n)?Ot(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):ne(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&&ne(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":ne(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":An(e,n,String(r.value),"contains");return;case"starts_with":An(e,n,String(r.value),"starts");return;case"ends_with":An(e,n,String(r.value),"ends");return}}function ne(r,e,t){r[e]===void 0?r[e]=t:(Ot(r,{[e]:r[e]},{[e]:t}),delete r[e])}function Ot(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function xr(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Rr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function Ki(r){return r==="_id"?"$_id":`$${r}`}function An(r,e,t,n){let i=Ki(e),o=r[rn]??[];o.push({ref:i,needle:t,mode:n}),r[rn]=o}function nn(r){let e=r[rn];if(delete r[rn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:qt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function le(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return ae(t,r,e);let o=new Set((i.relations||[]).map(l=>l.propertyName));if(!ee(r,o))return ae(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>le(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>le(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not){let l=await le(r._not,e,t,n);return!l||Object.keys(l).length===0?{}:{$nor:[l]}}let{fieldFilters:s,relationFilters:a}=H(r,i),u=[];if(s&&Object.keys(s).length>0){let l=ae(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await Wi(l,f,e,i,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Wi(r,e,t,n,i,o){let s=(n.relations||[]).find(l=>l.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"?Ui(e,s,r,a,u,i,o):s.type==="one-to-many"?Qi(e,s,t,a,u,i,o):s.type==="many-to-many"?Ji(e,s,t,a,u,i,o):{}}async function Ui(r,e,t,n,i,o,s){let a=Y(e)||t,u=En(r),l=Pn(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Nr(u);if(f!==null){let g=jn(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await In(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:null}:{[a]:{$in:d}}}async function Qi(r,e,t,n,i,o,s){let a=J(e)||t,u=En(r),l=Pn(u);if(l!==null){let p=await Fr(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await In(u,n,i,o,s);if(!f||Object.keys(f).length===0)return{};let c=await Fr(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Ji(r,e,t,n,i,o,s){let a=ze(t,e);if(!a)return{};let u=En(r),l=Pn(u);if(l!==null){let m=await On(s,a,n,null);return l?m.length===0?{}:{_id:{$nin:m}}:m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let f=Nr(u);if(f!==null){let m=jn(f.value),y=Array.isArray(m)?m:[m],b=await On(s,a,n,{_id:{$in:y}});return b.length===0?{__impossible__:!0}:{_id:{$in:b}}}let c=await In(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await On(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function In(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ee(r,o)?le(r,e,n,i):ae(n,r,e)}async function Fr(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 l=String(u);o.has(l)||(o.add(l),s.push(u))}return s}async function On(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._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 l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function En(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 jn(r){if(Array.isArray(r))return r.map(e=>jn(e));if(typeof r!="string")return r;try{return new Mn.ObjectId(r)}catch{return r}}function Nr(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Mn.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 Mt(r,e,t,n){let i=await Vt(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let m=Object.keys(g)[0];m&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(m)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,m]of Object.entries(s))if(typeof m=="object"&&m!==null)for(let[y,b]of Object.entries(m))Yt(r,d,e,g,y,b);else d[g]=m;Object.keys(d).length>0&&o.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!i.relations.some(y=>y.propertyName===d)){let y=l.find(b=>b.propertyName===d);if(y){let b="",_="";if(y.type==="many-to-one"||y.type==="one-to-one")b=Y(y)||y.propertyName,_="_id";else if(y.type==="one-to-many")b="_id",_=J(y)||y.propertyName;else if(y.type==="many-to-many")continue;let T=y.type==="one-to-many"||y.type==="many-to-many";f.push({propertyName:d,targetTable:y.targetTableName,localField:b,foreignField:_,type:T?"many":"one",nestedFields:[]})}}let c=[...i.relations,...f];for(let d of c){let g=a[d.propertyName],m=d.nestedFields&&d.nestedFields.length>0?await Mt(r,d.targetTable,d.nestedFields,g):g?await Mt(r,d.targetTable,["_id"],g):[];d.type==="one"&&m.length>0&&m.push({$limit:1}),o.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:m.length>0?m:void 0}}),d.type==="one"&&(o.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Xe(g)||o.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(i.scalarFields.length>0||i.relations.length>0||p.length>0){let d={_id:1};for(let m of i.scalarFields)d[m]=1;for(let m of c)d[m.propertyName]=1;if(t.includes("*"))for(let m of p){if(m.type==="one-to-many"||m.type==="many-to-many")continue;m.type==="many-to-many"?d[m.propertyName]={$map:{input:`$${m.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[m.propertyName]={$cond:{if:{$ne:[`$${m.propertyName}`,null]},then:{_id:`$${m.propertyName}`},else:null}}}o.push({$project:d})}return o}async function vr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(f=>!i.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of i)f[c.propertyName]=1;for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function Xe(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Xe(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Xe(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Xe(e));if("_not"in r)return Xe(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Xe(t)))return!0}return!1}et();var It=require("mongodb");et();on();var tt=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let 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("-");return{field:i?n.slice(1):n,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(l=>l.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let l of i){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],m=this.normalizeMetadata()?.tables?.get(p);if(!m)break;let y=m.relations?.find(T=>T.propertyName===g);if(!y)break;let b=y.targetTableName||y.targetTable,_=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(_)){s.add(_);let T=Y(y)||y.propertyName,w=d===0?null:`__sort_${c.slice(0,d).join("_")}`,h=w?`${w}.${T}`:T;o.push({$lookup:{from:b,localField:h,foreignField:"_id",as:_}},{$unwind:{path:`$${_}`,preserveNullAndEmptyArrays:!0}})}p=b}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new It.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof It.ObjectId||t instanceof It.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 It.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.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}=Ze(e),o={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])i.has(p.propertyName)||i.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?o[d.name]=1:t.relations?.find(m=>m.propertyName===p)&&!i.has(p)&&i.set(p,["_id"])}i.forEach((p,d)=>{let g=t.relations?.find(m=>m.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(o[g.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((p,d)=>{let g=t.relations?.find(_=>_.propertyName===d);if(!g)return;let m=g.targetTableName||g.targetTable;if(!m)return;let y,b;g.type==="many-to-one"||g.type==="one-to-one"?De(g)?(y="_id",b=J(g)||g.propertyName):(y=Y(g)||g.propertyName,b="_id"):g.type==="one-to-many"?(y="_id",b=J(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(y="_id",b=g.mappedBy):(y=g.propertyName,b="_id")),a.push({relationName:d,type:g.type,targetTable:m,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:y,foreignField:b})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)o[p.newName]===1&&o[p.oldName]!==1&&(o[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?ae(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await q(t,u=>{let l={_id:{$in:u}};o&&Object.keys(o).length>0&&Object.assign(l,o);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(y=>y!=null).map(y=>this.toObjectId(y)),u=o?.userFilter?ae(this.normalizeMetadata(),o.userFilter,e):null,l=o?.userLimit,f=o?.userPage,c=this.hasDottedSort(o?.userSort);if(l!==void 0&&l>0){let y=f?(f-1)*l:0,b=await ue(a,async T=>{let w={[t]:T};if(u&&Object.keys(u).length>0&&Object.assign(w,u),c){let k=this.buildSortAggregatePipeline(e,w,o.userSort);y>0&&k.push({$skip:y}),k.push({$limit:l}),s&&k.push({$project:s});let R=await this.db.collection(e).aggregate(k).toArray();return this.applyReadFallback(R,i)}let S={sort:this.buildSortFromTokens(o?.userSort)||{_id:1}};s&&(S.projection=s);let x=this.db.collection(e).find(w,S);return y>0&&x.skip(y),x.limit(l),this.applyReadFallback(await x.toArray(),i)},16),_=[];for(let[T,w]of b.entries()){let h=a.find(S=>this.keyOf(S)===T);for(let S of w)S[t]||(S[t]=h??T),_.push(S)}return{docs:_,groupKeyField:t}}if(c){let y=[],b=await ue(a,async _=>{let T={[t]:_};u&&Object.keys(u).length>0&&Object.assign(T,u);let w=this.buildSortAggregatePipeline(e,T,o.userSort);s&&w.push({$project:s});let h=await this.db.collection(e).aggregate(w).toArray();return this.applyReadFallback(h,i)},16);for(let _ of b.values())for(let T of _)y.push(T);return{docs:y,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(o?.userSort)||{_id:1},g={projection:s,sort:d},m=await q(a,y=>this.db.collection(e).find({[t]:{$in:y},...u||{}},g).toArray());return{docs:this.applyReadFallback(m,i),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}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=ze(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(w=>w._id).filter(w=>w!=null),l=new Map;for(let w of e)l.set(this.keyOf(w._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await q(u,w=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:w}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?ae(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let w=d?(d-1)*p:0,h=await ue(u,async x=>{let R=(await this.db.collection(a.junctionName).find({[a.selfColumn]:x},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(U=>U[a.otherColumn]).filter(U=>U!=null);if(R.length===0)return[];let O={_id:{$in:R}};if(c&&Object.keys(c).length>0&&Object.assign(O,c),this.hasDottedSort(t.userSort)){let U=this.buildSortAggregatePipeline(t.targetTable,O,t.userSort);w>0&&U.push({$skip:w}),U.push({$limit:p}),o.projection&&U.push({$project:o.projection});let $=await this.db.collection(t.targetTable).aggregate(U).toArray();return this.applyReadFallback($,o)}let D={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};o.projection&&(D.projection=o.projection);let ie=this.db.collection(t.targetTable).find(O,D);return w>0&&ie.skip(w),ie.limit(p),this.applyReadFallback(await ie.toArray(),o)},16),S=[];for(let[x,k]of h.entries()){l.set(x,k);for(let R of k)S.push(R)}return{grouped:l,docs:S}}let g=new Set,m=[];for(let w of f){let h=w[a.otherColumn];if(h==null)continue;let S=this.keyOf(h);g.has(S)||(g.add(S),m.push(h))}let y=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!c,b=[],_=new Map;if(y)b=m.map(w=>({_id:w})),this.sortDocsByPk(b);else{let w={_id:{$in:m}};c&&Object.keys(c).length>0&&Object.assign(w,c);let h=this.hasDottedSort(t.userSort),S;if(h){let x=this.buildSortAggregatePipeline(t.targetTable,w,t.userSort);o.projection&&x.push({$project:o.projection}),S=await this.db.collection(t.targetTable).aggregate(x).toArray()}else{let x=this.buildSortFromTokens(t.userSort)||{_id:1},k=this.projectionWithSortFields(o.projection,t.userSort),R={sort:x};k.projection&&(R.projection=k.projection),S=await q(m,O=>this.db.collection(t.targetTable).find({_id:{$in:O},...c||{}},R).toArray()),t.userSort?this.sortDocsInMemory(S,t.userSort):this.sortDocsByPk(S),this.removeHiddenFields(S,k.hiddenFields)}b=this.applyReadFallback(S,o)}for(let w of b)_.set(this.keyOf(w._id),w);let T=new Map;for(let w of f){let h=this.keyOf(w[a.selfColumn]),S=this.keyOf(w[a.otherColumn]);_.has(S)&&(T.has(S)||T.set(S,[]),T.get(S).push(h))}for(let w of b){let h=T.get(this.keyOf(w._id))||[];for(let S of h)l.get(S)?.push(w)}return{grouped:l,docs:b}}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 sn(r,e,t,n,i=3,o=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new tt(r,a,f);await new we(c,n,u).execute(e,t,i,o,s)}async function Ln(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),l=new Set((u?.relations??[]).map(h=>h.propertyName)),f=!!e.mongoRawFilter&&!!o&&ee(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&f){let h=await le(e.mongoRawFilter,e.table,o,i);h&&Object.keys(h).length>0&&n.push({$match:h})}else if(p){let h=Ke(c.filterTree,{metadata:o,rootTable:e.table});Object.keys(h).length>0&&n.push({$match:h})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let h=Ge(o,e.where,e.table,s);n.push({$match:h})}let d=e.plan,m=d?d.hasRelationSort:e.sort?.some(h=>{if(!h.field.includes("."))return!1;let S=h.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(x=>x.propertyName===S)??!1})??!1,y=()=>d?.sortItems?Hi(d.sortItems):e.sort?zi(e.sort):null;if(!e.mongoFieldsExpanded){let h=y();if(h&&n.push({$sort:h}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),e.select){let x={};for(let k of e.select)x[k]=1;n.push({$project:x})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let S=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:S,pipeline:n}:{results:Ir(S),pipeline:n}}let{scalarFields:b,relations:_}=e.mongoFieldsExpanded;if(!m){let h=y();h&&n.push({$sort:h}),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 T=[];for(let h of _)if(e.sort?.some(x=>x.field.startsWith(`${h.propertyName}.`))){let x=e.mongoRawFilter?.[h.propertyName];if(h.nestedFields&&h.nestedFields.length>0){let R=await Mt(o,h.targetTable,h.nestedFields??[],x);h.type==="one"&&R.length>0&&R.push({$limit:1}),n.push({$lookup:{from:h.targetTable,localField:h.localField,foreignField:h.foreignField,as:h.propertyName,pipeline:R.length>0?R:void 0}})}else if(x){let R=await Mt(o,h.targetTable,["_id"],x);h.type==="one"&&R.length>0&&R.push({$limit:1}),n.push({$lookup:{from:h.targetTable,localField:h.localField,foreignField:h.foreignField,as:h.propertyName,pipeline:R.length>0?R:void 0}})}else n.push({$lookup:{from:h.targetTable,localField:h.localField,foreignField:h.foreignField,as:h.propertyName}});h.type==="one"&&(n.push({$unwind:{path:`$${h.propertyName}`,preserveNullAndEmptyArrays:!0}}),x&&(nt(x)||n.push({$match:{[h.propertyName]:{$ne:null}}})))}else T.push(h);if(m){let h=y();h&&n.push({$sort:h}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}await vr(o,n,e.table,b,[..._]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let w=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:w,pipeline:n};if(T.length>0&&w.length>0){let h=e.deep||{},S=T.map(k=>{let O=o?.tables?.get(e.table)?.relations?.find(D=>D.propertyName===k.propertyName),A=h[k.propertyName],I=A?.fields!=null?Array.isArray(A.fields)?A.fields:String(A.fields).split(",").map(D=>D.trim()).filter(Boolean):k.nestedFields&&k.nestedFields.length>0?k.nestedFields:["_id"];return{relationName:k.propertyName,type:O?.type,targetTable:k.targetTable,fields:I,isInverse:O?.isInverse,mappedBy:O?.mappedBy,junctionTableName:O?.junctionTableName,localField:k.localField,foreignField:k.foreignField,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}}),x=Vi(o);x&&await sn(i,w,S,x,3,0,e.table,o,void 0,t.mongoPhysicalMigrationService)}return{results:Ir(w),pipeline:n}}function Vi(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 zi(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 Hi(r){let e={};for(let t of r){let n=t.joinId!==null?t.fullPath:t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function nt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>nt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>nt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>nt(e));if("_not"in r)return nt(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||nt(t)))return!0}return!1}function Ir(r){return r.map(Z)}function Er(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(qi(o,i,e));return{scalarFields:t,relations:n}}function qi(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&De(n)?(i="_id",o=J(n)||r.propertyName,s=!0):(i=n&&Y(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&J(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=Pr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Pr(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=Pr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Ye();At();vt();function an(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(c=>c.name==="_id"&&c.isPrimary),a=o.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),m=p.substring(d+1);if(!o.relations?.some(b=>b.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(m)}else if(o.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!o.columns?.some(m=>m.name===p))continue;f.push(p)}}if(f.includes("*")){i.nodes.push({kind:"wildcard"});for(let c of o.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)i.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=o.relations?.find(y=>y.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,m={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:jr(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let y=n.registerWithParent(e,c,t,"left",null,"data");m.joinId=y}i.nodes.push(m)}return i}function jr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),o=n.columns?.some(f=>f.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(y=>y.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:jr(c,d,t)})}return l}var W=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new te,d=this.parseFields(n),g=null;d&&c&&(g=an(d,t,l,p));let m=!1,y=null;if(i&&c){let A=_e(i,t,l,p);y=A.node,m=A.hasRelationFilters}let b=this.parseSort(o),_=[],T=!1;for(let A of b){let I=A.startsWith("-"),D=I?A.substring(1):A,ie=I?"desc":"asc";if(D.includes(".")&&c){let U=D.split(".")[0];if(c.relations?.find(C=>C.propertyName===U)){let C=this.registerSortJoinChain(D,t,l,p,null);C&&(_.push({joinId:C.lastJoinId,field:C.field,direction:ie,fullPath:D}),T=!0);continue}}_.push({joinId:null,field:D,direction:ie,fullPath:D})}_.length===0&&_.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let w=this.parseLimit(a),h=this.parsePage(s),S=h!==void 0&&w!==void 0?(h-1)*w:void 0,x=this.parseMeta(u),k=x.includes("totalCount")||x.includes("*"),R=x.includes("filterCount")||x.includes("*"),O=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:i??null,joins:O,sortItems:_,limit:w,offset:S,needsTotalCount:k,needsFilterCount:R,hasRelationFilters:m,hasRelationSort:T,filterTree:y,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}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),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=i.registerWithParent(t,a,n,"left",o,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,i,c)}};Nt();Ft();var Gi=new Set(["count","sum","avg","min","max","countRecords"]),Yi=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),Xi=new Set(["_and","_or","_not"]);function Te(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function M(r,e){let t=r.replace(/^aggregate\./,"");throw new P(e,{path:r,aggregate:{[t]:e}})}function Zi(r){return typeof r!="string"?!1:Yi.has(r.toLowerCase())}function Lr(r){return Object.keys(r).length===0}function eo(r,e,t){return r===!0?{}:(r==null&&M(t,`aggregate.${e} condition must be true or an object`),Te(r)||M(t,`aggregate.${e} condition must be true or an object`),r)}function to(r,e,t){let n=r?.tables?.get(e);return n||M(t,`Table "${e}" metadata is not available`),n}function Dr(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&M(e,"aggregate.countRecords relation target is not available"),t}function ln(r,e,t,n){let i=to(t,e,n);for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){Array.isArray(s)||M(n,`aggregate.countRecords ${o} condition must be an array`);for(let f of s)Te(f)||M(n,`aggregate.countRecords ${o} items must be objects`),ln(f,e,t,n);continue}if(o==="_not"){Te(s)||M(n,"aggregate.countRecords _not condition must be an object"),ln(s,e,t,n);continue}(o.startsWith("_")||Xi.has(o))&&M(n,`Unsupported aggregate.countRecords condition key "${o}"`);let a=i.columns?.find(f=>f.name===o),u=i.relations?.find(f=>f.propertyName===o);if(!a&&!u&&M(n,`Unknown aggregate.countRecords field or relation "${o}" on table "${e}"`),Te(s)||M(n,`aggregate.countRecords condition for "${o}" must be an object`),a){for(let f of Object.keys(s))X.has(f)||M(n,`aggregate.countRecords condition for "${o}" only supports field operators`);continue}let l=Dr(u,n);ln(s,l,t,n)}}function Dn(r){return Te(r)&&Object.keys(r).length>0}function rt(r,e,t){if(!Dn(r))return[];Te(r)||M("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||M("aggregate",`Table "${e}" metadata is not available`);let i=[];for(let[o,s]of Object.entries(r)){let a=`aggregate.${o}`;(!o||typeof o!="string")&&M("aggregate","aggregate field name must be a non-empty string"),Te(s)||M(a,"aggregate field config must be an object");let u=o,l=a,f=n.columns?.find(d=>d.name===o),c=n.relations?.find(d=>d.propertyName===o);!f&&!c&&M(l,`Unknown aggregate field or relation "${o}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&M(l,"aggregate field must define at least one operation");for(let[d,g]of p){Gi.has(d)||M(l,`Unsupported aggregate operation "${d}"`);let m=eo(g,d,l);if(c&&d!=="countRecords"&&M(l,`aggregate.${d} is not supported on relation "${o}"; use countRecords`),f&&d==="countRecords"&&M(l,`aggregate.countRecords requires a relation, but "${o}" is a field`),f&&(d==="sum"||d==="avg")&&!Zi(f.type)&&M(l,`aggregate.${d} requires a numeric field, but "${o}" is "${f.type}"`),f)for(let y of Object.keys(m))X.has(y)||M(l,`aggregate.${d} condition for "${o}" only supports field operators`);if(c&&d==="countRecords"){let y=Dr(c,l);ln(m,y,t,l)}i.push({field:o,outputKey:u,path:l,op:d,condition:m})}}return i}function it(r,e){let t=[];return Te(r)&&!Lr(r)&&t.push(r),Lr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function $e(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var ot=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new W;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(K(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.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(p=>p.propertyName)),l=!!n.mongoRawFilter&&ee(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?Ke(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(i.includes("filterCount")||i.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(i.length>0||c)&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[];if(e.fields&&e.fields.length>0){let s=e.plan;if(s?.fieldTree?e.mongoFieldsExpanded=Er(s.fieldTree,this.metadata):(console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await Vt(this.metadata,e.table,e.fields)),this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.hiddenFields}}e.where&&(e.where=e.where.map(s=>s.field.includes(".")?s:{...s,field:`${e.table}.${s.field}`}));let n=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 n.aggregate(e.pipeline).toArray()).map(Z);let{results:i,pipeline:o}=await Ln(n,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,i,t):i}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Ln(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={},o=this.db.collection(e.table);for(let s of n){let a=it(t,s);K(a,e.table,e.metadata);let l=new W().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);$e(i,s,p);continue}let f=l.hasRelationFilters?await le(a,e.table,e.metadata,this.db):l.filterTree?Ke(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await o.countDocuments(f);else{let[{value:p}={value:null}]=await o.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}$e(i,s,c)}return i}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(o.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[o.foreignKeyColumn]:{$in:c}}]})}if(o.type==="many-to-many"){let f=ze(e.table,o);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(m=>m!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(m=>m[f.otherColumn]).filter(m=>m!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(o.type==="many-to-one"||o.type==="one-to-one"){let f=o.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};K(t,e,n);let o=new W().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return o.hasRelationFilters?await le(t,e,n,this.db):o.filterTree?Ke(o.filterTree,{metadata:n,rootTable:e}):{}}};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}};var no=["_and","_or","_not"];function fe(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>fe(e));for(let e of Object.keys(r))if(no.includes(e)||typeof r[e]=="object"&&r[e]!==null&&fe(r[e]))return!0;return!1}var Br=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function ro(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function un(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 io(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)||un(r,t,i),e}function Kr(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=un(e,i,s),l=io(e,n,i,o,s);switch(t){case"_eq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} = ?::uuid`,[n]):r.where(a,"=",l);break;case"_neq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} != ?::uuid`,[n]):r.where(a,"!=",l);break;case"_gt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} > ?::uuid`,[n]):r.where(a,">",l);break;case"_gte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} >= ?::uuid`,[n]):r.where(a,">=",l);break;case"_lt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} < ?::uuid`,[n]):r.where(a,"<",l);break;case"_lte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} <= ?::uuid`,[n]):r.where(a,"<=",l);break;case"_in":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${a} = ANY(?::uuid[])`,[f]):r.whereIn(a,f);break;case"_not_in":case"_nin":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(p=>p.trim()):[c]),u&&o==="postgres"&&c.every(p=>typeof p=="string")?r.whereRaw(`${a} != ALL(?::uuid[])`,[c]):r.whereNotIn(a,c);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${a})) 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,ro(t),n)}}function oo(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 st(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(){st(this,s,t,"and",i,o)}):r.orWhere(function(){st(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(oo(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){st(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>Br.includes(l)))for(let[l,f]of Object.entries(a))Br.includes(l)&&(n==="and"?r.where(function(){Kr(this,s,l,f,t,i,o)}):r.orWhere(function(){Kr(this,s,l,f,t,i,o)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s;un(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(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s;un(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(`${u} = ?::uuid`,[a]):r.orWhereRaw(`${u} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function re(r,e,t,n,i){return!e||typeof e!="object"||st(r,e,t,"and",n,i),r}Se();function Wn(r,e,t){return`${N(r,t)}.${N(e,t)}`}function ke(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 Wr(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 at(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function Un(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let l=await Et(r,e,a,u,t,n,i);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Wn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=at(d._is_null),m=at(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(m===!0)s.push(`${c} IS NOT NULL`);else if(m===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let y=ke(d._eq,n);s.push(`${c} = ${y}`)}else if(d._neq!==void 0){let y=ke(d._neq,n);s.push(`${c} != ${y}`)}else if(d._in!==void 0){let b=(Array.isArray(d._in)?d._in:[d._in]).map(_=>ke(_,n)).join(", ");s.push(`${c} IN (${b})`)}else if(d._not_in!==void 0||d._nin!==void 0){let y=d._not_in??d._nin,_=(Array.isArray(y)?y:[y]).map(T=>ke(T,n)).join(", ");s.push(`${c} NOT IN (${_})`)}else if(d._gt!==void 0){let y=ke(d._gt,n);s.push(`${c} > ${y}`)}else if(d._gte!==void 0){let y=ke(d._gte,n);s.push(`${c} >= ${y}`)}else if(d._lt!==void 0){let y=ke(d._lt,n);s.push(`${c} < ${y}`)}else if(d._lte!==void 0){let y=ke(d._lte,n);s.push(`${c} <= ${y}`)}}}}}return s}function Qn(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 Bn(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 l of a._and)if(Qn(l)){let f=e(t).select(`${t}.id`);await We(e,f,l,t,n,i,o),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=H(l,n),p=await Un(e,t,n,i,o,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(Qn(a)){let u=e(t).select(`${t}.id`);await We(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=H(a,n),f=await Un(e,t,n,i,o,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Ur(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&&re(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function Kn(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)Ur(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function fn(r,e,t,n,i,o,s){let a=Wr(e,i),u=Wr(n,o),l=`${N(r,s)}.${N(e,s)}`,f=`${N(t,s)}.${N(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Et(r,e,t,n,i,o,s){let a=i.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(fn(u,a.foreignKeyColumn,e,"id",f,i,o));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(fn(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,o))).whereRaw(fn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,i,o));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(fn(u,"id",e,a.foreignKeyColumn,f,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await We(r,c,n,u,f,o,s):c=re(c,n,u,o,f||void 0):c=re(c,n,u,o),c.toString()}async function We(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Bn(l._or,r,n,i,o,s);e.where(function(){Kn(this,f,n,i,o)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await We(r,e,f,n,i,o,s);else await We(r,e,l,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let l=await Bn(t._or,r,n,i,o,s);e.where(function(){Kn(this,l,n,i,o)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(Qn(d)){let g=r(n).select(`${n}.id`);await We(r,g,d,n,i,o,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:m}=H(d,i),y=await Un(r,n,i,o,s,m);p.push({fieldFilters:g,subqueries:y})}e.whereNot(function(){for(let d of p)Ur(this,d,n,i,o)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Bn(l._or,r,n,i,o,s);e.whereNot(function(){Kn(this,p,n,i,o)});return}let{fieldFilters:f,relationFilters:c}=H(l,i);e.whereNot(function(){Object.keys(f).length>0&&re(this,f,n,o,i)});for(let[p,d]of Object.entries(c)){let g=await Et(r,n,p,d,i,o,s);if(g===null){let m=i.relations.find(y=>y.propertyName===p);if(m&&m.foreignKeyColumn){let y=Wn(n,m.foreignKeyColumn,o),_=d.id;if(_&&typeof _=="object"){let T=at(_._is_null),w=at(_._is_not_null);if(T===!0)e.whereRaw(`${y} IS NOT NULL`);else if(T===!1)e.whereRaw(`${y} IS NULL`);else if(w===!0)e.whereRaw(`${y} IS NULL`);else if(w===!1)e.whereRaw(`${y} IS NOT NULL`);else if(_._eq!==void 0)e.whereRaw(`${y} != ?`,[_._eq]);else if(_._neq!==void 0)e.whereRaw(`${y} = ?`,[_._neq]);else if(_._in!==void 0){let h=Array.isArray(_._in)?_._in:[_._in];e.whereRaw(`${y} NOT IN (${h.map(()=>"?").join(", ")})`,h)}else if(_._not_in!==void 0||_._nin!==void 0){let h=_._not_in??_._nin,S=Array.isArray(h)?h:[h];e.whereRaw(`${y} IN (${S.map(()=>"?").join(", ")})`,S)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=H(t,i);Object.keys(a).length>0&&re(e,a,n,o,i);for(let[l,f]of Object.entries(u)){let c=await Et(r,n,l,f,i,o,s);if(c===null){let p=i.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Wn(n,p.foreignKeyColumn,o),m=f.id;if(m&&typeof m=="object"){let y=at(m._is_null),b=at(m._is_not_null);if(y===!0)e.whereRaw(`${d} IS NULL`);else if(y===!1)e.whereRaw(`${d} IS NOT NULL`);else if(b===!0)e.whereRaw(`${d} IS NOT NULL`);else if(b===!1)e.whereRaw(`${d} IS NULL`);else if(m._eq!==void 0)e.whereRaw(`${d} = ?`,[m._eq]);else if(m._neq!==void 0)e.whereRaw(`${d} != ?`,[m._neq]);else if(m._in!==void 0){let _=Array.isArray(m._in)?m._in:[m._in];e.whereRaw(`${d} IN (${_.map(()=>"?").join(", ")})`,_)}else if(m._not_in!==void 0||m._nin!==void 0){let _=m._not_in??m._nin,T=Array.isArray(_)?_:[_];e.whereRaw(`${d} NOT IN (${T.map(()=>"?").join(", ")})`,T)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Ue(r,e,t,n,i,o,s){await We(r,e,t,n,i,o,s)}Se();Vn();Ye();Le();Se();function lt(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],l=Pt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",l);break;case"!=":r=r.where(o.field,"!=",l);break;case">":r=r.where(o.field,">",l);break;case"<":r=r.where(o.field,"<",l);break;case">=":r=r.where(o.field,">=",l);break;case"<=":r=r.where(o.field,"<=",l);break;case"like":r=r.where(o.field,"like",l);break;case"in":let f=Array.isArray(o.value)?o.value.map(m=>Pt(n,a,u,m)):[l];r=r.whereIn(o.field,f);break;case"not in":let c=Array.isArray(o.value)?o.value.map(m=>Pt(n,a,u,m)):[l];r=r.whereNotIn(o.field,c);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 p=o.value;if(typeof p=="string"&&(p=p.split(",").map(m=>m.trim())),Array.isArray(p)&&p.length===2){let m=Pt(n,a,u,p[0]),y=Pt(n,a,u,p[1]);r=r.whereBetween(o.field,[m,y])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function jt(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(l=>{let f=jt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=jt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=jt(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,l]of Object.entries(a)){let f=`${N(e,n)}.${N(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=o.columns?.find(m=>m.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${f} = ${c}`);else if(u==="_neq")i.push(`${f} != ${c}`);else if(u==="_gt")i.push(`${f} > ${c}`);else if(u==="_gte")i.push(`${f} >= ${c}`);else if(u==="_lt")i.push(`${f} < ${c}`);else if(u==="_lte")i.push(`${f} <= ${c}`);else if(u==="_is_null")i.push(`${f} IS NULL`);else if(u==="_is_not_null")i.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);i.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${N(e,n)}.${N(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),i.push(`${u} = ${l}`)}return i}function Jr(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 Pt(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}}Se();pn();Le();async function zr(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Hn(),Vr)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function qn(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 Hr(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||L(o);if(!s)return null;let a=c=>N(c,i),u=n?.tables?.get(o),f=(u?de(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(f)} = ${a(t)}.${a(s)})`}var ut=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&&K(e.filter,e.tableName,e.metadata),!e.plan){let $=new W;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,l=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&l){i&&i.setQueryPath("simple");let $=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),$}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map($=>$.trim())));let p=e.filter;if(e.filter&&!fe(e.filter)){c.where=[];for(let[$,C]of Object.entries(e.filter))if(typeof C=="object"&&C!==null)for(let[F,Ce]of Object.entries(C)){let v;if(F==="_eq")v="=";else if(F==="_neq")v="!=";else if(F==="_in")v="in";else if(F==="_not_in"||F==="_nin")v="not in";else if(F==="_gt")v=">";else if(F==="_gte")v=">=";else if(F==="_lt")v="<";else if(F==="_lte")v="<=";else if(F==="_contains")v="_contains";else if(F==="_starts_with")v="_starts_with";else if(F==="_ends_with")v="_ends_with";else if(F==="_between")v="_between";else if(F==="_is_null")v="_is_null";else if(F==="_is_not_null")v="_is_not_null";else if(F==="_like")v="like";else if(F==="_ilike")v="ilike";else continue;c.where.push({field:$,operator:v,value:Ce})}else c.where.push({field:$,operator:"=",value:C})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(C=>C.trim());c.sort=$.map(C=>{let F=C.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,m=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,y=m===void 0||Number.isNaN(m)?void 0:m;y&&g!==void 0?(c.offset=(y-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let b=e.plan?.sortItems??(c.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),_=[],T=[];for(let $ of b)if($.joinId===null){if($.field.includes(".")&&!e.plan){let C=$.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(v=>v.propertyName===C))continue}_.push({field:$.field.includes(".")?$.field:`${c.table}.${$.field}`,direction:$.direction})}else{let C=e.plan?.joins.find(F=>F.id===$.joinId);if(C&&(C.relationType==="many-to-one"||C.relationType==="one-to-one")){let F=Hr(C.relationMeta,$.field,c.table,this.metadata,this.dbType);F&&T.push({sql:F,direction:$.direction})}}let w=[];if(c.fields&&c.fields.length>0){let $=qn(this.metadata),C=await zr(this.knex,c.table,c.fields,$,this.dbType,this.maxQueryDepth,e.deep);c.select=[...c.select||[],...C.select],w=C.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map($=>$.field.includes(".")?$:{...$,field:`${c.table}.${$.field}`})),c.sort=_;let h=this.knex(c.table),S=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),x=S.includes("filterCount")||S.includes("*"),k=S.includes("totalCount")||S.includes("*");if(c.select){let $=c.select.map(C=>typeof C=="string"&&C.trim().startsWith("(")?this.knex.raw(C):typeof C=="string"&&/ as /i.test(C)?this.knex.raw(C):C);h=h.select($)}if(x&&h.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),k){let $=N(c.table,this.dbType);h.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let R=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(fe(p)||Object.keys(p).length>0)){let $=this.metadata?.tables?.get(c.table);(!R&&$&&$.relations&&$.relations.length>0?H(p,$).hasRelations:!1)?await Ue(this.knex,h,p,c.table,$,this.dbType,F=>this.metadata?.tables?.get(F)):e.plan?.filterTree?G(h,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),h=re(h,p,c.table,this.dbType,$))}else c.where&&c.where.length>0&&(h=lt(h,c.where,c.table,this.metadata,this.dbType));if(c.sort)for(let $ of c.sort){let C=$.field.includes(".")?$.field:`${c.table}.${$.field}`;h=h.orderBy(C,$.direction)}for(let $ of T)h=h.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`);c.groupBy&&(h=h.groupBy(c.groupBy)),c.offset&&(h=h.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&(h=h.limit(c.limit));let O=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:h.toSQL().toNative()});let A;if(e.debugMode&&(A=h.toSQL().toNative().sql),e.debugMode&&i){let $=h.toSQL().toNative();i.setSql($.sql);try{let C=$.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${C}`,$.bindings);i.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(C){i.setExplain({error:String(C)})}}let I,D=performance.now();I=await h,i&&i.dur("db_execute",D,{table:e.tableName});let ie=0;if(x&&I.length>0&&(ie=Number(I[0].__filter_count__||0),I.forEach($=>{delete $.__filter_count__})),k&&I.length>0&&I[0].__total_count__!==void 0&&(O=Number(I[0].__total_count__||0),I.forEach($=>{delete $.__total_count__})),w&&w.length>0&&I.length>0){let $=qn(this.metadata);if($){let{executeBatchFetches:C}=await Promise.resolve().then(()=>(Xn(),qr));await C(this.knex,I,w,$,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,i)}}if(this.knexService){let $=performance.now();I=await this.knexService.parseResult(I,c.table),i&&i.dur("db_parseResult",$,{table:e.tableName})}else{let $=(C,F)=>{if(!C||!this.metadata)return C;let Ce=this.metadata.tables?.get(F);if(!Ce)return C;if(Array.isArray(C))return C.map(V=>$(V,F));if(typeof C!="object"||Buffer.isBuffer(C))return C;let v={...C};for(let V of Ce.columns)if(V.type==="simple-json"&&v[V.name]&&typeof v[V.name]=="string")try{v[V.name]=JSON.parse(v[V.name])}catch{}for(let[V,z]of Object.entries(v))if(z&&typeof z=="object"&&!Array.isArray(z)&&!Buffer.isBuffer(z)){let mn=z;if(mn.id!==void 0||mn.createdAt!==void 0){let pt=Ce.relations?.find(gt=>gt.propertyName===V);pt&&(v[V]=$(z,pt.targetTableName))}}else if(Array.isArray(z)&&z.length>0&&typeof z[0]=="object"&&z[0].id!==void 0){let pt=Ce.relations?.find(gt=>gt.propertyName===V);pt&&(v[V]=z.map(gt=>$(gt,pt.targetTableName)))}return v};I=$(I,c.table)}i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName}));let U=await this.executeAggregate(c,p);return{data:I,...(S.length>0||U)&&{meta:{...S.includes("totalCount")||S.includes("*")?{totalCount:O}:{},...S.includes("filterCount")||S.includes("*")?{filterCount:ie}:{},...U?{aggregate:U}:{}}},...A!==void 0&&{sql:A}}}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&&G(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let y of t.sortItems){let b=y.field.includes(".")?y.field:`${n}.${y.field}`;o=o.orderBy(b,y.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(y=>y.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 y=N(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${y}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let y=o.toSQL().toNative();if(f=y.sql,l){l.setSql(y.sql);try{let b=y.sql.replace(/\$\d+/g,"?"),_=await this.knex.raw(`EXPLAIN ${b}`,y.bindings);l.setExplain(this.dbType==="postgres"?_.rows:_[0])}catch(b){l.setExplain({error:String(b)})}}}let c=performance.now(),p;p=await o,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(y=>delete y.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(y=>delete y.__total_count__));let m=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||m)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...m?{aggregate:m}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={};for(let o of n){let s=it(t,o);K(s,e.table,e.metadata);let u=new W().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(o.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,o);$e(i,o,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Ue(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&G(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${N(e.table,this.dbType)}.${N(o.field,this.dbType)}`,c=o.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${o.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();$e(i,o,p?.value??0)}return i}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table),o=i?.relations?.find(c=>c.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new W().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,u,t,e.table,i,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&G(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){K(n.condition,s,e.metadata);let p=new W().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&G(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(o.type==="one-to-many")l.whereIn(`${s}.${o.foreignKeyColumn}`,u);else if(o.type==="many-to-many"){let c=o.junctionTableName||Pe(e.table,o.propertyName,s),p=je(e.table,o.propertyName,s),d=o.junctionSourceColumn||p.sourceColumn,g=o.junctionTargetColumn||p.targetColumn;l.whereIn(`${s}.id`,this.knex(c).select(`${c}.${g}`).whereIn(`${c}.${d}`,u))}else(o.type==="many-to-one"||o.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${o.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${o.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var gn=require("mongodb"),ft=class{constructor(e){this.debugLog=[];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()}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(!gn.ObjectId)return e;if(typeof e=="string")try{return new gn.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=Ge(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:lt(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(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 W().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")return new ot(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new ut(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(o).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let 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),s=await this.mongoService.collection(e.table).find(i).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let 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 gn.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,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t){return this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let s=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return Z(s)}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 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 delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?i._id=this.safeObjectId(u):i[a]=u;return await this.mongoService.collection(e).find(i).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}};Xn();Gn();Hn();Se();pn();et();Nt();Ye();var Gr=new Set(["fields","filter","sort","limit","page","deep"]),dt=3;function Zn(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new P(`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 l=s.get(a);if(!l)throw new P(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!Gr.has(p))throw new P(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...Gr].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new P(`'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 P(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(K(u.filter,c,t),yn(u.filter,0,a,r)),u.sort){let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;lo(g,c,t,a,r)}}u.deep&&Zn(c,u.deep,t,n+1,i)}}}function lo(r,e,t,n,i){let o=r.split(".");if(o.length-1>dt)throw new P(`Sort path '${r}' exceeds max dotted hops of ${dt} (relation '${n}' on '${i}')`);let a=e;for(let u=0;u<o.length;u++){let l=o[u],f=u===o.length-1,c=t?.tables?.get(a);if(!c)throw new P(`Sort path '${r}' references unknown table '${a}' (relation '${n}' on '${i}')`);if(c.columns?.find(g=>g.name===l)){if(!f)throw new P(`Sort path '${r}' references column '${l}' in non-terminal position (relation '${n}' on '${i}')`);return}let d=c.relations?.find(g=>g.propertyName===l);if(!d)throw new P(`Sort path '${r}' references unknown field '${l}' on '${a}' (relation '${n}' on '${i}')`);if(!f){let g=d.type;if(g==="one-to-many"||g==="many-to-many")throw new P(`Sort path '${r}' passes through '${l}' which is a ${g} relation \u2014 sort path must only traverse many-to-one or one-to-one (owner-side) relations (relation '${n}' on '${i}')`);a=d.targetTableName||d.targetTable||a}}}var co=new Set(["_and","_or","_not"]);function yn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(co.has(i)){if(Array.isArray(o))for(let l of o)yn(l,e,t,n);else o&&typeof o=="object"&&yn(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>dt)throw new P(`Filter path exceeds max dotted hops of ${dt} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(o))l.startsWith("_")||(u[l]=o[l]);yn(u,a,t,n)}}function Yr(r,e,t,n){return!r||typeof r!="object"?r:Lt(r,e,t,n)}function Lt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Lt(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 c=(Array.isArray(s)?s:[s]).map(p=>Lt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(i[o]=c);continue}if(o==="_not"){let f=Lt(s,e,t,n);f!=null&&Object.keys(f).length>0&&(i[o]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Lt(s,f,t,n);c!=null&&Object.keys(c).length>0&&(i[o]=c);continue}if(a?.columns?.find(f=>f.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function Xr(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 l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,m=t?.tables?.get(c);if(!m){f=!1;break}if(g)m.columns?.find(b=>b.name===d)?n(c,d,"column")||(f=!1):m.relations?.find(_=>_.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let y=m.relations?.find(b=>b.propertyName===d);if(!y){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=y.targetTableName||y.targetTable||c}}f&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}vt();Ye();At();on();Ft();Le();Nt();function uo(r){let e=new ft({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new Ve({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Qe({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,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,transformCode,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|