@enfyra/kernel 1.1.30 → 1.1.31

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.
@@ -733,11 +733,15 @@ function __resetTask(snapshot, taskId, timeoutMs) {
733
733
  $ctx.$pkgs = $pkgs;
734
734
  $ctx.$share = $ctx.$share || {};
735
735
  $ctx.$share.$logs = __logs;
736
+ const __createRepoProxy = (table, access) => new Proxy({}, {
737
+ get: (_, method) => async (...args) =>
738
+ __call('repoCall', JSON.stringify({ table: String(table), access, method: String(method), argsJson: JSON.stringify(args) }))
739
+ });
740
+ const __secureRepos = new Proxy({}, {
741
+ get: (_, table) => __createRepoProxy(table, 'secure')
742
+ });
736
743
  $ctx.$repos = new Proxy({}, {
737
- get: (_, table) => new Proxy({}, {
738
- get: (_, method) => async (...args) =>
739
- __call('repoCall', JSON.stringify({ table: String(table), method: String(method), argsJson: JSON.stringify(args) }))
740
- })
744
+ get: (_, table) => String(table) === 'secure' ? __secureRepos : __createRepoProxy(table)
741
745
  });
742
746
  $ctx.$helpers = new Proxy({}, {
743
747
  get: (_, name) => {
@@ -764,6 +768,12 @@ function __resetTask(snapshot, taskId, timeoutMs) {
764
768
  get: (_, method) => async (...args) =>
765
769
  __call('cacheCall', JSON.stringify({ method: String(method), argsJson: JSON.stringify(args) }))
766
770
  });
771
+ $ctx.$transaction = {
772
+ run: async (...args) =>
773
+ __call('transactionCall', JSON.stringify({
774
+ argsJson: await __stringifyRuntimeArgs(args)
775
+ }))
776
+ };
767
777
  $ctx.$storage = new Proxy({}, {
768
778
  get: (_, method) => async (...args) =>
769
779
  __call('storageCall', JSON.stringify({ method: String(method), argsJson: await __stringifyRuntimeArgs(args) }))
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var ai=Object.create;var Ut=Object.defineProperty;var li=Object.getOwnPropertyDescriptor;var ci=Object.getOwnPropertyNames;var ui=Object.getPrototypeOf,fi=Object.prototype.hasOwnProperty;var U=(r,e)=>()=>(r&&(e=r(r=0)),e);var Cn=(r,e)=>{for(var t in e)Ut(r,t,{get:e[t],enumerable:!0})},ur=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ci(e))!fi.call(r,o)&&o!==t&&Ut(r,o,{get:()=>e[o],enumerable:!(n=li(e,o))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?ai(ui(r)):{},ur(e||!r||!r.__esModule?Ut(t,"default",{value:r,enumerable:!0}):t,r)),di=r=>ur(Ut({},"__esModule",{value:!0}),r);function wr(r){return In.createHash("md5").update(r).digest("hex").substring(0,8)}function $r(r){return r.length<=_r-3?`${r}_pk`:`j_${wr(r)}_pk`}function Sr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=_r?n:`j_${wr(r)}_${t}_fk`}function xt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${In.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function z(r){return`${r}Id`}function vt(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Tr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function kr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Fr(r,e,t){return`${r}_${e}_${t}_fk`}function Cr(r,e,t){return`${r}_${e}_${t}_idx`}var In,_r,Ue=U(()=>{"use strict";In=fe(require("crypto")),_r=63});function nn(r){return Ji[r]??null}var ie,On,Nt,Ji,Mt=U(()=>{"use strict";ie=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),On=new Set(["_and","_or","_not"]),Nt=[...Array.from(On),...Array.from(ie)],Ji={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var v,pe=U(()=>{"use strict";v=class extends Error{constructor(t="Bad Request",n){let o=Array.isArray(t),i=o?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,o&&(this.messages=t)}}});function Ir(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Nr=U(()=>{"use strict"});function Oe(r,e,t){throw new v({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Nt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Nt})}function rn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Ir();for(let o of Object.keys(e))if(o.startsWith("_")&&!ie.has(o)){if(n&&o==="_id")continue;Oe(o,r,t)}}function Q(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),o=new Set((n?.columns??[]).map(s=>s.name)),i=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(qi.has(s)){if(Array.isArray(a))for(let l of a)Q(l,e,t);else a&&typeof a=="object"&&Q(a,e,t);continue}let u=i.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){rn(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let f=Object.keys(a).filter(c=>!c.startsWith("_"));if(f.length>0){let c={};for(let p of f)c[p]=a[p];Q(c,l,t)}}}continue}s.startsWith("_")&&!o.has(s)&&s!=="_id"&&Oe(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&rn(s,a,e)}}var qi,ze=U(()=>{"use strict";pe();Mt();Nr();qi=new Set(["_and","_or","_not"])});function ge(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:on(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function on(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[o,i]of Object.entries(r)){let s=zi(o,i,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function zi(r,e,t){if(r==="_and")return Mr("and",e,t);if(r==="_or")return Mr("or",e,t);if(r==="_not"){let l=on(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),o=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),i=n?.columns?.some(l=>l.name==="id"),a=r==="id"?o&&!i?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?Vi(a,e,u,t):n&&!n.columns?.find(f=>f.name===a)?(r.startsWith("_")&&r!=="_id"&&Oe(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):Hi(a,e,t)}function Mr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],o=!1;for(let i of e){let s=on(i,t);s.hasRelationFilters&&(o=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:o}:n.length===1?{node:n[0],hasRelationFilters:o}:{node:{kind:r,children:n},hasRelationFilters:o}}function Vi(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let o=Object.keys(e),i=o.length===1&&(o[0]==="_is_null"||o[0]==="_is_not_null"||o[0]==="_eq"||o[0]==="_neq"||o[0]==="_in"||o[0]==="_not_in"||o[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(i&&o[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&o[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:o[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=o.length>0&&o.every(d=>l.has(d))?{id:e}:e;return{node:on(c,u).node,hasRelationFilters:!0}}function Hi(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:Yi(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!ie.has(s)&&Oe(s,r,t.tableName);let o=Object.entries(e).filter(([s])=>ie.has(s));if(o.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){let u=Gi(n,s,a);u&&i.push(u)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function Gi(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=nn(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function Yi(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.find(s=>s.name===n);if(!o)return!1;let i=(o.type||"").toLowerCase();return i==="uuid"||i==="uuidv4"||i.includes("uuid")}var At=U(()=>{"use strict";Mt();ze()});var oe,Ot=U(()=>{"use strict";oe=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t;if(this.map.has(a)){let p=this.map.get(a);return o==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let f=l.targetTableName||l.targetTable;if(!f)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:f,relationType:l.type,parentJoinId:i,joinType:o,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function ee(r,e){if(r.length<=Fe)return e(r);let t=[];for(let a=0;a<r.length;a+=Fe)t.push(r.slice(a,a+Fe));let n=[],o=0;async function i(){for(;o<t.length;){let a=o++;n[a]=await e(t[a])}}let s=Math.min(Wn,t.length);return await Promise.all(Array.from({length:s},i)),n.flat()}function He(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let o=n.split("."),i=o[0],s=o.slice(1).join(".");t.has(i)||t.set(i,[]),t.get(i).push(s)}return{rootFields:e,subRelations:t}}var se,Fe,Wn,Un,Ce,Ge=U(()=>{"use strict";pe();se=16,Fe=5e3,Wn=4,Un=10;Ce=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let o=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(l=>l.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),i=new Set(o.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(i.has(s))continue;let u=n?.relations?.find(f=>f.propertyName===s);if(!u)continue;let l=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];o.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:l,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return o}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Un}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))n.has(i)||o.push(i);return o}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new v(`Sort field '${i}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===i),a=i==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new v(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,o=0,i){if(e.length===0||t.length===0||o>=n)return;let s;i&&(s=await this.metadataGetter(i)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,o):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,o,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,o,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,o){let i=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let m of e){let b=m[i];if(b==null)continue;let S=this.adapter.keyOf(b);s.has(S)||(s.add(S),a.push(b))}if(a.length===0){for(let m of e)m[t.relationName]=null,i!==t.relationName&&delete m[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:l,nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),p=this.adapter.getTargetPkField(u);if(l){for(let m of e){let b=m[i];m[t.relationName]=b!=null?this.adapter.buildScalarRef(b,p):null,i!==t.relationName&&delete m[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/Fe)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(f,t.nestedDeep,u);y.length>0&&await this.execute(g,y,n,o+1,t.targetTable);let h=new Map;for(let m of g)h.set(this.adapter.keyOf(m[p]),m);for(let m of e){let b=m[i];m[t.relationName]=b!=null&&h.get(this.adapter.keyOf(b))||null,i!==t.relationName&&delete m[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn]}}async fetchInverseRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=e.map(R=>R[s]).filter(R=>R!=null);if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,l);let{nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),y=new Map,h=t.fields.includes(u)||t.fields.includes("*");for(let R of d){let M=R[g],T=this.adapter.keyOf(M);y.has(T)||y.set(T,[]),y.get(T).push(R)}let m=t.userLimit!==void 0&&t.userLimit>0,b=m?"per-parent-c16":"batch-in",S=m?a.length:Math.ceil(a.length/Fe)||1,_=m?Math.ceil(a.length/se):void 0,$=Array.from(y.values()).reduce((R,M)=>R+M.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:b,roundtrips:S,concurrencyWaves:_,rowsTransferred:d.length,rowsReturned:$,rowsDiscarded:d.length-$,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let R of d)this.adapter.postProcessInverseChild(R,u,h);let k=this.enrichNestedDescs(f,t.nestedDeep,l);k.length>0&&await this.execute(d,k,n,o+1,t.targetTable);let N=t.type==="one-to-one";for(let R of e){let M=this.adapter.keyOf(R[s]),T=y.get(M)||[];R[t.relationName]=N?T[0]||null:T}}async fetchM2MRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=e.map(_=>_[s]).filter(_=>_!=null);if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:l,fetchSpec:f}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,i,u,f),g=t.userLimit!==void 0&&t.userLimit>0,y=g?"m2m-per-parent-c16":"m2m-batch",h=g?a.length:Math.ceil(a.length/Fe)||1,m=g?Math.ceil(a.length/se):void 0,b=Array.from(p.values()).reduce((_,$)=>_+$.length,0);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:y,roundtrips:h,concurrencyWaves:m,rowsTransferred:d.length,rowsReturned:b,rowsDiscarded:d.length-b,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let S=this.enrichNestedDescs(l,t.nestedDeep,u);S.length>0&&d.length>0&&await this.execute(d,S,n,o+1,t.targetTable);for(let _ of e){let $=this.adapter.keyOf(_[s]);_[t.relationName]=p.get($)||[]}}}});async function be(r,e,t){let n=new Map,o=0;async function i(){for(;o<r.length;){let u=o++,l=r[u];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},i);return await Promise.all(a),n}var dn=U(()=>{"use strict"});function C(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function ve(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:C(t,e)).join(".")}var le=U(()=>{"use strict"});function te(r,e,t){e&&wn(r,e,t,"and")}function wn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let o=function(){for(let i of e.children)this.where(function(){wn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"or":{let o=function(){for(let i of e.children)this.orWhere(function(){wn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"not":{let o=function(){this.whereNot(function(){wn(this,e.child,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"compare":Ro(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function Ro(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let o=xo(e.field,t),i=ve(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",l=n==="or"?"orWhereRaw":"whereRaw",f=n==="or"?"orWhereIn":"whereIn",c=n==="or"?"orWhereNotIn":"whereNotIn",p=n==="or"?"orWhereBetween":"whereBetween",d=n==="or"?"orWhereNull":"whereNull",g=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[l](`${i} = ?::uuid`,[e.value]):r[u](o,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[l](`${i} != ?::uuid`,[e.value]):r[u](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[l](`${i} > ?::uuid`,[e.value]):r[u](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[l](`${i} >= ?::uuid`,[e.value]):r[u](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[l](`${i} < ?::uuid`,[e.value]):r[u](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[l](`${i} <= ?::uuid`,[e.value]):r[u](o,"<=",e.value);return;case"in":{let y=Yr(e.value);s&&a&&y.every(h=>typeof h=="string")?r[l](`${i} = ANY(?::uuid[])`,[y]):r[f](o,y);return}case"not_in":{let y=Yr(e.value);s&&a&&y.every(h=>typeof h=="string")?r[l](`${i} != ALL(?::uuid[])`,[y]):r[c](o,y);return}case"contains":tr(r,i,e.value,"contains",t,n);return;case"starts_with":tr(r,i,e.value,"starts_with",t,n);return;case"ends_with":tr(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[p](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[d](o):r[g](o);return}}function tr(r,e,t,n,o,i){let s=i==="or"?"orWhereRaw":"whereRaw";if(o.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(o.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function xo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function Yr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var nr=U(()=>{"use strict";le()});function G(r){return r.columns.find(e=>e.isPrimary)||null}var Kt=U(()=>{"use strict"});var Zr={};Cn(Zr,{expandFieldsToJoinsAndSelect:()=>rr});async function rr(r,e,t,n,o,i){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}if(i&&typeof i=="object")for(let[c,p]of Object.entries(i)){if(l.has(c))continue;let d=p&&typeof p=="object"&&p.fields!=null?Array.isArray(p.fields)?p.fields:String(p.fields).split(",").map(g=>g.trim()).filter(Boolean):["*"];l.set(c,d)}let f=l.get("")||[];for(let c of f){if(c==="*"){let g=new Set;for(let h of u.relations||[])if(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse){let m=h.foreignKeyColumn||z(h.propertyName);m&&g.add(m)}let y=new Set;for(let h of u.columns)g.has(h.name)||(s.push(`${r}.${h.name}`),y.add(h.name));for(let h of u.relations||[])!l.has(h.propertyName)&&!y.has(h.propertyName)&&l.set(h.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=u.relations?.find(b=>b.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let b=d.foreignKeyColumn||z(d.propertyName),S=C(r,n),_=C(b,n),$=C(p,n);s.push(`${S}.${_} as ${$}`)}let y=d.targetTableName||d.targetTable,h=i?.[p],m=h?.fields!=null?Array.isArray(h.fields)?h.fields:String(h.fields).split(",").map(b=>b.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:y,fields:m,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:h?.filter,userSort:h?.sort,userLimit:h?.limit!==void 0?Number(h.limit):void 0,userPage:h?.page!==void 0?Number(h.page):void 0,nestedDeep:h?.deep})}),{select:s,batchFetchDescriptors:a}}var ir=U(()=>{"use strict";Ue();le()});var ot,sr=U(()=>{"use strict";Ue();le();Kt();Ge();nr();Ot();At();dn();ot=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new oe,o=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:i}=ge(e,t,o,n);return i}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),u=(s?i.slice(1):i).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,o){if(!t||!this.metadata)return;let i=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of i){let l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let f=n,c=o||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(f);if(!g)break;let y=g.relations?.find(b=>b.propertyName===d);if(!y)break;let h=y.targetTableName||y.targetTable,m=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(m)){s.add(m);let b=y.foreignKeyColumn||z(y.propertyName),S=this.metadata?.tables?.get(h),_=S&&G(S)?.name||"id";e.leftJoin(`${h} as ${m}`,`${m}.${_}`,`${c}.${b}`)}f=h,c=m}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let o=e.substring(0,n),i=e.substring(n+4),s=C(i,this.dbType),a=t?`${t}.${C(o,this.dbType)}`:C(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${C(e,this.dbType)} as ${C(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return G(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=z(e.mappedBy)),t||(t=z(e.targetTable)),t}resolveParentPk(e){return e&&G(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:o}=He(e),i=[];if(n.includes("*")){let l=new Set;for(let f of t.relations||[])if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let c=f.foreignKeyColumn||z(f.propertyName);c&&l.add(c)}for(let f of t.columns)l.has(f.name)||i.push(f.name);for(let f of t.relations||[])o.has(f.propertyName)||o.set(f.propertyName,["id"])}else for(let l of n){let f=t.columns.find(c=>c.name===l);f?i.push(f.name):t.relations?.find(p=>p.propertyName===l)&&!o.has(l)&&o.set(l,["id"])}let s=G(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((l,f)=>{let c=t.relations?.find(p=>p.propertyName===f);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||z(c.propertyName);p&&i.push(`${p} as ${f}`)}});let a=[];return o.forEach((l,f)=>{let c=t.relations?.find(d=>d.propertyName===f);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:f,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.parseSortTokens(o.userSort,e):[],a=n.selectCols.map(u=>this.toKnexSelect(u));return ee(t,u=>{let l=this.knex(e).select(a).whereIn(n.pkCol,u);if(i&&te(l,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,o.userSort,e);for(let f of s)l.orderBy(f.column,f.order)}return l})}async fetchInverse(e,t,n,o,i){let s=t,a=o.selectCols.find(g=>g.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let u=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,l=i?.userSort?this.parseSortTokens(i.userSort,e):[],f=i?.userLimit,c=i?.userPage;if(f!==void 0&&f>0){let g=c?(c-1)*f:0,y=o.selectCols.map(b=>this.toKnexSelect(b)),h=await be(n,async b=>{let S=this.knex(e).select(y).where(t,b);if(u&&te(S,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(S,i.userSort,e),l.length>0)for(let _ of l)S.orderBy(_.column,_.order);else S.orderBy(o.pkCol,"asc");return g>0&&S.offset(g),S.limit(f),S},se),m=[];for(let[b,S]of h.entries()){let _=n.find($=>String($)===b);for(let $ of S)$[t]||($[t]=_??b),m.push($)}return{docs:m,groupKeyField:s}}let p=o.selectCols.map(g=>this.toKnexSelect(g));return{docs:await ee(n,g=>{let y=this.knex(e).select(p).whereIn(t,g);if(u&&te(y,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(y,i?.userSort,e),l.length>0)for(let h of l)y.orderBy(h.column,h.order);else y.orderBy(o.pkCol,"asc");return y}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,o,i){let s=this.resolveParentPk(n),a=e.map(S=>S[s]).filter(S=>S!=null);if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,f=t.junctionTargetColumn;if(!u||!l||!f)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(i.selectCols.length===1&&i.selectCols[0]===i.pkCol&&!c&&!d){let S=await ee(a,$=>this.knex(u).select([`${l} as __sourceId__`,`${f} as __targetId__`]).whereIn(l,$).orderBy(f,"asc")),_=new Map;for(let $ of S){let k=this.keyOf($.__sourceId__);_.has(k)||_.set(k,[]),_.get(k).push({[i.pkCol]:$.__targetId__})}return{grouped:_,docs:[]}}let h=i.selectCols.map(S=>this.toKnexSelect(S,"t"));if(d!==void 0&&d>0){let S=g?(g-1)*d:0,_=new Map;for(let N of a)_.set(this.keyOf(N),[]);let $=await be(a,async N=>{let R=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${i.pkCol}`).select(h).where(`${u}.${l}`,N);if(c&&te(R,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(R,t.userSort,t.targetTable,"t"),p.length>0)for(let M of p)R.orderBy(M.column,M.order);else R.orderBy(`t.${i.pkCol}`,"asc");return S>0&&R.offset(S),R.limit(d),R},se),k=[];for(let[N,R]of $.entries()){_.set(N,R);for(let M of R)k.push(M)}return{grouped:_,docs:k}}let m=await ee(a,S=>{let _=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${i.pkCol}`).select([`${u}.${l} as __sourceId__`,...h]).whereIn(`${u}.${l}`,S);if(c&&te(_,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(_,t.userSort,t.targetTable,"t"),p.length>0)for(let $ of p)_.orderBy($.column,$.order);else _.orderBy(`t.${i.pkCol}`,"asc");return _}),b=new Map;for(let S of m){let _=S.__sourceId__;delete S.__sourceId__;let $=this.keyOf(_);b.has($)||b.set($,[]),b.get($).push(S)}return{grouped:b,docs:m}}}});var ni={};Cn(ni,{executeBatchFetches:()=>ar});async function ar(r,e,t,n,o=3,i=0,s,a="postgres",u,l){let f=new ot(r,a,u);await new Ce(f,n,l).execute(e,t,o,i,s)}var lr=U(()=>{"use strict";Ge();sr()});var Mo={};Cn(Mo,{ALL_SUPPORTED_OPERATORS:()=>Nt,AuthenticationException:()=>gt,AuthorizationException:()=>ht,BadRequestException:()=>v,BatchFetchEngine:()=>Ce,BusinessLogicException:()=>ut,CHUNKED_FETCH_CONCURRENCY:()=>Wn,ConfigurationException:()=>$t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Un,DEFAULT_TIMEOUT_MS:()=>Qt,DOTTED_PATH_MAX_HOPS:()=>kn,DatabaseException:()=>De,DuplicateResourceException:()=>pt,ErrorHandler:()=>Ne,ExecutorEngineService:()=>Be,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>ie,FileNotFoundException:()=>Tt,FileSizeExceededException:()=>kt,FileUploadException:()=>St,HttpException:()=>E,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>qt,InvalidTokenException:()=>mt,IsolatedExecutorService:()=>We,JoinRegistry:()=>oe,LOGICAL_OPERATORS:()=>On,MongoBatchAdapter:()=>Ye,MongoQueryExecutor:()=>tt,PER_PARENT_CONCURRENCY:()=>se,QueryBuilderService:()=>at,QueryPlanner:()=>J,ResourceNotFoundException:()=>dt,SchemaException:()=>wt,ScriptContractService:()=>Gt,ScriptExecutionException:()=>$e,ScriptTimeoutException:()=>we,ServiceUnavailableException:()=>_t,SqlBatchAdapter:()=>ot,SqlQueryExecutor:()=>st,TokenExpiredException:()=>yt,ValidationException:()=>ft,WHERE_IN_CHUNK_SIZE:()=>Fe,WorkerPool:()=>Ct,appendIsolatedExecutorRuntimeLog:()=>X,applyOperatorToMatch:()=>tn,applyRelationFilters:()=>Le,applyWhereToKnex:()=>it,assertFieldOperatorValueIsClean:()=>rn,buildAggregateFilter:()=>et,buildMongoCharFoldMapJson:()=>Mn,buildMongoFoldTextSearchJs:()=>Yt,buildRelationSubquery:()=>Lt,buildSqlWherePartsFromFieldAst:()=>Dt,buildWhereClause:()=>ce,camelToSnake:()=>kr,chunkedFetch:()=>ee,compileScriptSource:()=>Oi,computeEngineTuning:()=>xn,createEnfyraKernel:()=>No,dslOpToCompareOp:()=>nn,encodeMainThreadToIsolate:()=>vn,escapeSqlValue:()=>Xr,executeBatchFetches:()=>ar,executeMongoBatchFetches:()=>pn,expandFieldsToJoinsAndSelect:()=>rr,getEffectiveCpuCount:()=>Rn,getEffectiveMemoryBytes:()=>Ft,getEngineTuning:()=>Ht,getExecutableScript:()=>Li,getForeignKeyColumnName:()=>z,getIoAbortSignal:()=>br,getJunctionColumnNames:()=>vt,getJunctionTableName:()=>xt,getPrimaryKeyColumn:()=>G,getScriptLegacyField:()=>Ni,getShortFkConstraintName:()=>Sr,getShortFkName:()=>Fr,getShortIndexName:()=>Cr,getShortPkName:()=>$r,hasAggregateQuery:()=>Hn,hasLogicalOperators:()=>_e,isExecutableJavaScript:()=>Ei,isScriptTable:()=>Mi,mergeAggregateValue:()=>xe,normalizeAggregateQuery:()=>Ze,normalizeFlowStepScriptConfig:()=>Di,normalizeScriptLanguage:()=>Ai,normalizeScriptPatch:()=>ji,normalizeScriptRecord:()=>Pi,parseBatchFields:()=>He,parseFields:()=>gn,parseFilter:()=>ge,perParentRun:()=>be,quoteIdentifier:()=>C,quoteQualifiedIdentifier:()=>ve,resolveExecutableScript:()=>Bi,rewriteFilterDenyingFields:()=>oi,rewriteSortDroppingDenied:()=>si,scriptContractService:()=>ne,separateFilters:()=>H,snakeToCamel:()=>Tr,throwUnsupportedFieldOperator:()=>Oe,validateDeepOptions:()=>cr,validateFilterShape:()=>Q,whereToMongoFilter:()=>qe});module.exports=di(Mo);var Qt=3e4,Be=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Qt)}async run(e,t,n=Qt,o={}){return this.isolatedExecutorService.run(e,t,n,o)}};var Jt=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var pr=require("async_hooks"),gr=fe(require("path")),hr=require("stream"),yr=require("worker_threads");var we=class extends Error{constructor(t=0,n){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},$e=class extends Error{constructor(t,n,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...o}}},D=class extends Error{constructor(t,n,o,i){super(t);this.statusCode=n;this.errorCode=o;this.name=this.constructor.name,this.details=i}},E=class extends D{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ut=class extends D{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},ft=class extends D{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},dt=class extends D{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},pt=class extends D{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},gt=class extends D{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},ht=class extends D{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},yt=class extends D{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},mt=class extends D{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},De=class extends D{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},bt=class extends D{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},_t=class extends D{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},wt=class extends D{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},$t=class extends D{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},St=class extends D{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Tt=class extends D{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},kt=class extends D{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Ne=class{static createException(e,t,n,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new E(n||"Error",t||500,i);case"$throw.businessLogic":return new ut(n||"Bad request",i);case"$throw.validation":return new ft(n||"Validation failed",i);case"$throw.notFound":return new dt(i?.resource||n||"Resource",i?.identifier);case"$throw.duplicate":return new pt(i?.resource||n||"Resource",i?.field||"field",i?.value||"value");case"$throw.unauthorized":return new gt(n||"Unauthorized");case"$throw.forbidden":return new ht(n||"Forbidden");case"$throw.tokenExpired":return new yt;case"$throw.invalidToken":return new mt;case"$throw.database":return new De(n||"Database error",i);case"$throw.dbQuery":return new De(n||"Query error",i);case"$throw.externalService":return new bt(n||"Service",n||"Error",i);case"$throw.serviceUnavailable":return new _t(n||"Service");case"$throw.rateLimit":return new E(n||"Rate limit exceeded",429);case"$throw.scriptError":return new $e(n||"Script error",o,i);case"$throw.scriptTimeout":return new we(i?.timeout||5e3,o);case"$throw.schema":return new wt(n||"Schema error",i);case"$throw.config":return new $t(n||"Configuration error",i);case"$throw.fileUpload":return new St(n||"File upload error",i);case"$throw.fileNotFound":return new Tt(n||"File not found");case"$throw.fileSizeExceeded":return new kt(i?.maxSize||"unknown",i?.actualSize||"unknown");case"$throw.400":return new E(n||"Bad request",400,i);case"$throw.401":return new E(n||"Authentication required",401,i);case"$throw.403":return new E(n||"Insufficient permissions",403,i);case"$throw.404":return new E(n||"Not found",404,i);case"$throw.409":return new E(n||"Conflict",409,i);case"$throw.422":return new E(n||"Validation failed",422,i);case"$throw.429":return new E(n||"Rate limit exceeded",429,i);case"$throw.500":return new E(n||"Internal server error",500,i);case"$throw.503":return new E(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o)}if(t)switch(t){case 400:return new E(n||"Bad request",400,i);case 401:return new E(n||"Authentication required",401,i);case 403:return new E(n||"Insufficient permissions",403,i);case 404:return new E(n||"Not found",404,i);case 409:return new E(n||"Conflict",409,i);case 422:return new E(n||"Validation failed",422,i);case 429:return new E(n||"Rate limit exceeded",429,i);case 500:return new E(n||"Internal server error",500,i);case 503:return new E(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o,i)}return new $e(n||"Unknown error",o,i)}};var zt=fe(require("fs")),Vt=fe(require("path")),qt=Vt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function pi(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var gi=pi();function X(r){if(gi)try{let e=Vt.dirname(qt);zt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
- `;zt.appendFileSync(qt,t)}catch{}}var Se=fe(require("os")),Ke=fe(require("fs"));function Ft(){try{let r=Ke.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Se.totalmem())return e}}catch{}try{let r=Ke.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Se.totalmem())return e}catch{}return Se.totalmem()}function Rn(){let r=Se.availableParallelism?.()||Se.cpus()?.length||1;try{let e=Ke.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let o=parseInt(t,10),i=parseInt(n,10);if(o>0&&i>0)return Math.max(1,Math.ceil(o/i))}}catch{}try{let e=parseInt(Ke.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Ke.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var hi=.25,yi=2,mi=2048,bi=40,_i=128,wi=32;function xn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(_i,Math.max(bi,Math.round(t/wi))),o=t*hi,i=Math.max(1,Math.floor(o/n)),s=Math.max(1,Math.min(e,2,i)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<mi?1:yi,l=Math.max(1,Math.min(u,Math.floor(o/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:l}}function Ht(){return xn({logicalCpuCount:Rn(),totalMemoryBytes:Ft()})}var Ii=gr.join(__dirname,"execution/worker.js"),mr=new pr.AsyncLocalStorage;function br(){return mr.getStore()}var Ct=class{constructor(e,t,n,o,i,s,a,u=6e4){this.scriptPath=i;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=o,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new yr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let o=t.tasks.get(n.id);o&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),o.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):o.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,o=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:o?"Worker terminated":"Worker crashed"}});t.tasks.clear();let i=this.entries.indexOf(t);i!==-1&&this.entries.splice(i,1),!n&&!o&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},dr=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function vn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var We=class r{constructor(e){this.logger=new Jt(r.name);this.effectiveMemory=Ft();this.isolationTuning=Ht();this.pool=new Ct(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ii,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),o=process.cpuUsage(this.prevCpuUsage),i=Number(n-this.prevCpuTime)/1e3,s=i>0?(o.user+o.system)/i:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let o of Object.keys(e)){if(!o.startsWith("$")||o in t||dr.has(o))continue;let i=this.cloneSnapshotValue(e[o]);i!==void 0&&(t[o]=i)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,o]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||dr.has(n)||n==="$env"||(e[n]=o));delete e.$pkgs}}spawnAndExecute(e,t,n,o){return(async()=>{let i=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort();let d=new Error(`Script execution timed out after ${o}ms`);this.cleanupResponseStream(s,d),this.pool.unregisterTask(i,s),this.taskTimeoutTotal++,X({event:"task_timeout",id:s,timeoutMs:o}),this.pool.terminateEntry(i),d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},o);this.pool.registerTask(i,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.cleanupResponseStream(s),this.pool.unregisterTask(i,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,X({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,X({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),this.cleanupResponseStream(s,g),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),i.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),i.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),i.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),i.worker,d.callId,g):d.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(d,n,i.worker),i.worker,d.callId,g):d.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(d,n),i.worker,d.callId,g):d.type==="resCall"&&this.handleIoCall(()=>this.execResCall(d,n),i.worker,d.callId,g)}}),i.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,o){if(!o?.aborted)try{let i=await(o?mr.run(o,e):e());if(o?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:vn(i)})}catch{}}catch(i){if(o?.aborted)return;try{let s={__userThrow:!0,message:i.message,statusCode:i.statusCode,code:i.errorCode??i.code,details:i.details,messages:i.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$repos?.[e.table];if(!o||typeof o[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return o[e.method](...n)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),o=e.name.split("."),i=t?.$helpers;for(let s of o)i=i?.[s];if(typeof i!="function")throw new Error(`Helper not found: ${e.name}`);return i(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$socket?.[e.method];if(typeof o!="function")throw new Error(`Socket method not found: ${e.method}`);return o(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$cache?.[e.method];if(typeof o!="function")throw new Error(`Cache method not found: ${e.method}`);return o(...n)}async execStorageCall(e,t,n){let o=this.parseStorageArgs(e.argsJson,n,e.id),i=t?.$storage?.[e.method];if(typeof i!="function")throw new Error(`Storage method not found: ${e.method}`);return i(...o)}parseStorageArgs(e,t,n){return JSON.parse(e,(o,i)=>{if(i?.__fnRef&&typeof i.__fnRef=="string"){let s=i.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return i})}invokeRuntimeCallback(e,t,n,o){let i=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{f(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),l=c=>{if(!(c?.type!=="runtimeCallbackResult"||c.callId!==i)){if(f(),c.error){a(new Error(c.error));return}s(c.value)}},f=()=>{clearTimeout(u),e.off("message",l)};e.on("message",l),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:n,argsJson:JSON.stringify(o)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$trigger;if(typeof o!="function")throw new Error("$trigger is not available");return o(...n)}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new hr.PassThrough;return this.responseStreams.set(e.id,{stream:u}),a.call(t.$res,u,s),!0}if(e.method==="streamChunk"){let i=this.responseStreams.get(e.id);if(!i)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return i.stream.write(s)||await new Promise((a,u)=>{let l=()=>{c(),a()},f=p=>{c(),u(p)},c=()=>{i.stream.off("drain",l),i.stream.off("error",f)};i.stream.once("drain",l),i.stream.once("error",f)}),!0}if(e.method==="streamEnd"){let i=this.responseStreams.get(e.id);return i&&(i.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let i=this.responseStreams.get(e.id);if(i){let s=e.error?.message||"Response stream failed";i.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),o=t?.$res?.[e.method];if(typeof o!="function")throw new Error(`Response method not found: ${e.method}`);return o.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),t?n.stream.destroy(t):n.stream.end())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}async run(e,t,n,o={}){let i=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);X({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let l;try{let f={code:e,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};l=await this.spawnAndExecute("execute",f,t,i)}catch(f){let c=f;if(X({event:"isolated_run_error",message:c.message,code:c.code,isTimeout:!!c.isTimeout}),c.isTimeout||c.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,e);let p=c.statusCode??(typeof c.status=="number"?c.status:void 0);throw Ne.createException(c.errorPath,p,c.message||"Unknown error",e,c.details||{})}return this.mergeCtxChanges(t,l.ctxChanges||{}),X({event:"isolated_run_ok"}),l.valueAbsent?void 0:l.value}async runBatch(e,t,n){let o=Math.max(1,Math.trunc(Number(n)||3e4)),i=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(i),a=this.createSnapshot(t);X({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let u;try{let f={codeBlocks:e.map(c=>this.toWorkerCodeBlock(c)),pkgSources:s,snapshot:a,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};u=await this.spawnAndExecute("executeBatch",f,t,o)}catch(l){let f=l;if(X({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(o,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ne.createException(f.errorPath,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),X({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((i,s)=>i-s),o=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[o]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((o,i)=>o+i,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(o=>o.lastHeapRatio||0))}}};var Me=fe(require("typescript")),Rt={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Ni(r){return ne.getLegacyField(r)}function Mi(r){return ne.isScriptTable(r)}function Ai(r){return ne.normalizeLanguage(r)}var Gt=class{getLegacyField(e){return Rt[e]}isScriptTable(e){return e in Rt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),i=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(i),i}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},o=this.getLegacyField(e);return o&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[o]!==void 0&&(n.sourceCode=n[o]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),o&&o in n&&delete n[o],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(o?Object.prototype.hasOwnProperty.call(t,o):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!i&&!s)return t;let a=i?t.sourceCode??(o?t[o]:void 0):n?.sourceCode??(o&&n?n[o]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,l={...t};return i&&(l.sourceCode=a??null),l.scriptLanguage=this.normalizeLanguage(u),l.compiledCode=this.compileSource(a,l.scriptLanguage),o&&o in l&&delete l[o],l}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(Rt).find(n=>Rt[n]in e);if(t){let n=e[Rt[t]];if(typeof n=="string"&&n!==""){let o=this.compileSource(n,e.scriptLanguage);return{code:o,compiledCode:o,shouldPersistCompiledCode:o!==e.compiledCode}}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let n={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};n.sourceCode=n.sourceCode??i.sourceCode??i.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??i.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,o=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Me.default.transpileModule(e,{compilerOptions:{target:Me.default.ScriptTarget.ES2022,module:Me.default.ModuleKind.CommonJS,importsNotUsedAsValues:Me.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(o=>o.category===Me.default.DiagnosticCategory.Error);if(n)throw new Error(Me.default.flattenDiagnosticMessageText(n.messageText,`
1
+ "use strict";var mi=Object.create;var Gt=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var wi=Object.getPrototypeOf,$i=Object.prototype.hasOwnProperty;var Q=(r,e)=>()=>(r&&(e=r(r=0)),e);var En=(r,e)=>{for(var t in e)Gt(r,t,{get:e[t],enumerable:!0})},_r=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _i(e))!$i.call(r,o)&&o!==t&&Gt(r,o,{get:()=>e[o],enumerable:!(n=bi(e,o))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?mi(wi(r)):{},_r(e||!r||!r.__esModule?Gt(t,"default",{value:r,enumerable:!0}):t,r)),Ti=r=>_r(Gt({},"__esModule",{value:!0}),r);function vr(r){return Ln.createHash("md5").update(r).digest("hex").substring(0,8)}function Ir(r){return r.length<=xr-3?`${r}_pk`:`j_${vr(r)}_pk`}function Nr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=xr?n:`j_${vr(r)}_${t}_fk`}function Mt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Ln.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function H(r){return`${r}Id`}function Ot(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Mr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Or(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Ar(r,e,t){return`${r}_${e}_${t}_fk`}function Er(r,e,t){return`${r}_${e}_${t}_idx`}var Ln,xr,Je=Q(()=>{"use strict";Ln=fe(require("crypto")),xr=63});function un(r){return to[r]??null}var oe,Un,Et,to,Pt=Q(()=>{"use strict";oe=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Un=new Set(["_and","_or","_not"]),Et=[...Array.from(Un),...Array.from(oe)],to={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var x,ge=Q(()=>{"use strict";x=class extends Error{constructor(t="Bad Request",n){let o=Array.isArray(t),i=o?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,o&&(this.messages=t)}}});function Lr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Dr=Q(()=>{"use strict"});function Ee(r,e,t){throw new x({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Et.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Et})}function dn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Lr();for(let o of Object.keys(e))if(o.startsWith("_")&&!oe.has(o)){if(n&&o==="_id")continue;Ee(o,r,t)}}function J(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),o=new Set((n?.columns??[]).map(s=>s.name)),i=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(no.has(s)){if(Array.isArray(a))for(let l of a)J(l,e,t);else a&&typeof a=="object"&&J(a,e,t);continue}let u=i.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){dn(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let d=Object.keys(a).filter(c=>!c.startsWith("_"));if(d.length>0){let c={};for(let p of d)c[p]=a[p];J(c,l,t)}}}continue}s.startsWith("_")&&!o.has(s)&&s!=="_id"&&Ee(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&dn(s,a,e)}}var no,He=Q(()=>{"use strict";ge();Pt();Dr();no=new Set(["_and","_or","_not"])});function he(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:fn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function fn(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[o,i]of Object.entries(r)){let s=ro(o,i,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function ro(r,e,t){if(r==="_and")return Wr("and",e,t);if(r==="_or")return Wr("or",e,t);if(r==="_not"){let l=fn(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),o=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),i=n?.columns?.some(l=>l.name==="id"),a=r==="id"?o&&!i?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?io(a,e,u,t):n&&!n.columns?.find(d=>d.name===a)?(r.startsWith("_")&&r!=="_id"&&Ee(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):oo(a,e,t)}function Wr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],o=!1;for(let i of e){let s=fn(i,t);s.hasRelationFilters&&(o=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:o}:n.length===1?{node:n[0],hasRelationFilters:o}:{node:{kind:r,children:n},hasRelationFilters:o}}function io(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let o=Object.keys(e),i=o.length===1&&(o[0]==="_is_null"||o[0]==="_is_not_null"||o[0]==="_eq"||o[0]==="_neq"||o[0]==="_in"||o[0]==="_not_in"||o[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(i&&o[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&o[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:o[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=o.length>0&&o.every(f=>l.has(f))?{id:e}:e;return{node:fn(c,u).node,hasRelationFilters:!0}}function oo(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:ao(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!oe.has(s)&&Ee(s,r,t.tableName);let o=Object.entries(e).filter(([s])=>oe.has(s));if(o.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){let u=so(n,s,a);u&&i.push(u)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function so(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=un(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function ao(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.find(s=>s.name===n);if(!o)return!1;let i=(o.type||"").toLowerCase();return i==="uuid"||i==="uuidv4"||i.includes("uuid")}var jt=Q(()=>{"use strict";Pt();He()});var se,Bt=Q(()=>{"use strict";se=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t;if(this.map.has(a)){let p=this.map.get(a);return o==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let d=l.targetTableName||l.targetTable;if(!d)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:d,relationType:l.type,parentJoinId:i,joinType:o,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function K(r,e,t=ae){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(r.length<=t)return e(r);let n=[];for(let u=0;u<r.length;u+=t)n.push(r.slice(u,u+t));let o=[],i=0;async function s(){for(;i<n.length;){let u=i++;o[u]=await e(n[u])}}let a=Math.min(Yn,n.length);return await Promise.all(Array.from({length:a},s)),o.flat()}function Ye(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let o=n.split("."),i=o[0],s=o.slice(1).join(".");t.has(i)||t.set(i,[]),t.get(i).push(s)}return{rootFields:e,subRelations:t}}var je,ae,Yn,Xn,ke,Xe=Q(()=>{"use strict";ge();je=16,ae=5e3,Yn=4,Xn=10;ke=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let o=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(l=>l.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),i=new Set(o.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(i.has(s))continue;let u=n?.relations?.find(d=>d.propertyName===s);if(!u)continue;let l=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];o.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:l,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return o}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Xn}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))n.has(i)||o.push(i);return o}uniqueValues(e){let t=new Set,n=[];for(let o of e){if(o==null)continue;let i=this.adapter.keyOf(o);t.has(i)||(t.add(i),n.push(o))}return n}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new x(`Sort field '${i}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===i),a=i==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new x(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,o=0,i){if(e.length===0||t.length===0||o>=n)return;let s;i&&(s=await this.metadataGetter(i)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,o):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,o,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,o,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,o){let i=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let w of e){let S=w[i];if(S==null)continue;let T=this.adapter.keyOf(S);s.has(T)||(s.add(T),a.push(S))}if(a.length===0){for(let w of e)w[t.relationName]=null,i!==t.relationName&&delete w[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:l,nestedDescs:d,fetchSpec:c}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),p=this.adapter.getTargetPkField(u);if(l){for(let w of e){let S=w[i];w[t.relationName]=S!=null?this.adapter.buildScalarRef(S,p):null,i!==t.relationName&&delete w[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn]}return}let f=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t),y=Array.isArray(g)?g:g.docs,h=Array.isArray(g)?void 0:g.stats;this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??"batch-in",roundtrips:h?.roundtrips??(Math.ceil(a.length/ae)||1),concurrencyWaves:h?.concurrencyWaves,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??y.length,rowsReturned:y.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(d,t.nestedDeep,u);m.length>0&&await this.execute(y,m,n,o+1,t.targetTable);let b=new Map;for(let w of y)b.set(this.adapter.keyOf(w[p]),w);for(let w of e){let S=w[i];w[t.relationName]=S!=null&&b.get(this.adapter.keyOf(S))||null,i!==t.relationName&&delete w[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn]}}async fetchInverseRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=this.uniqueValues(e.map(O=>O[s]));if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,l);let{nestedDescs:d,fetchSpec:c}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),l),p=performance.now(),{docs:f,groupKeyField:g,stats:y}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),h=new Map,m=t.fields.includes(u)||t.fields.includes("*");for(let O of f){let L=O[g],$=this.adapter.keyOf(L);h.has($)||h.set($,[]),h.get($).push(O)}let b=t.userLimit!==void 0&&t.userLimit>0,w=b?"per-parent-c16":"batch-in",S=b?a.length:Math.ceil(a.length/ae)||1,T=b?Math.ceil(a.length/je):void 0,k=Array.from(h.values()).reduce((O,L)=>O+L.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:y?.strategy??w,roundtrips:y?.roundtrips??S,concurrencyWaves:y?.concurrencyWaves??T,ioConcurrency:y?.ioConcurrency,rowsTransferred:y?.rowsTransferred??f.length,rowsReturned:k,rowsDiscarded:Math.max(0,(y?.rowsTransferred??f.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let O of f)this.adapter.postProcessInverseChild(O,u,m);let R=this.enrichNestedDescs(d,t.nestedDeep,l);R.length>0&&await this.execute(f,R,n,o+1,t.targetTable);let I=t.type==="one-to-one";for(let O of e){let L=this.adapter.keyOf(O[s]),$=h.get(L)||[];O[t.relationName]=I?$[0]||null:$}}async fetchM2MRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=this.uniqueValues(e.map(T=>T[s]));if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:l,fetchSpec:d}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),c=performance.now(),{grouped:p,docs:f,stats:g}=await this.adapter.fetchM2M(e,t,i,u,d),y=t.userLimit!==void 0&&t.userLimit>0,h=y?"m2m-per-parent-c16":"m2m-batch",m=y?a.length:Math.ceil(a.length/ae)||1,b=y?Math.ceil(a.length/je):void 0,w=Array.from(p.values()).reduce((T,k)=>T+k.length,0);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??h,roundtrips:g?.roundtrips??m,concurrencyWaves:g?.concurrencyWaves??b,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??f.length,rowsReturned:w,rowsDiscarded:g?.rowsDiscarded??Math.max(0,(g?.rowsTransferred??f.length)-w),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let S=this.enrichNestedDescs(l,t.nestedDeep,u);S.length>0&&f.length>0&&await this.execute(f,S,n,o+1,t.targetTable);for(let T of e){let k=this.adapter.keyOf(T[s]);T[t.relationName]=p.get(k)||[]}}}});var Hr,Re,_n=Q(()=>{"use strict";Hr=2,Re=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});function F(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function Ie(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:F(t,e)).join(".")}var ue=Q(()=>{"use strict"});function ne(r,e,t){e&&xn(r,e,t,"and")}function xn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let o=function(){for(let i of e.children)this.where(function(){xn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"or":{let o=function(){for(let i of e.children)this.orWhere(function(){xn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"not":{let o=function(){this.whereNot(function(){xn(this,e.child,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"compare":jo(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function jo(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let o=Bo(e.field,t),i=Ie(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",l=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",c=n==="or"?"orWhereNotIn":"whereNotIn",p=n==="or"?"orWhereBetween":"whereBetween",f=n==="or"?"orWhereNull":"whereNull",g=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[l](`${i} = ?::uuid`,[e.value]):r[u](o,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[l](`${i} != ?::uuid`,[e.value]):r[u](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[l](`${i} > ?::uuid`,[e.value]):r[u](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[l](`${i} >= ?::uuid`,[e.value]):r[u](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[l](`${i} < ?::uuid`,[e.value]):r[u](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[l](`${i} <= ?::uuid`,[e.value]):r[u](o,"<=",e.value);return;case"in":{let y=ai(e.value);s&&a&&y.every(h=>typeof h=="string")?r[l](`${i} = ANY(?::uuid[])`,[y]):r[d](o,y);return}case"not_in":{let y=ai(e.value);s&&a&&y.every(h=>typeof h=="string")?r[l](`${i} != ALL(?::uuid[])`,[y]):r[c](o,y);return}case"contains":ur(r,i,e.value,"contains",t,n);return;case"starts_with":ur(r,i,e.value,"starts_with",t,n);return;case"ends_with":ur(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[p](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[f](o):r[g](o);return}}function ur(r,e,t,n,o,i){let s=i==="or"?"orWhereRaw":"whereRaw";if(o.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(o.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function Bo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function ai(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var dr=Q(()=>{"use strict";ue()});function X(r){return r.columns.find(e=>e.isPrimary)||null}var qt=Q(()=>{"use strict"});var ci={};En(ci,{expandFieldsToJoinsAndSelect:()=>fr});async function fr(r,e,t,n,o,i){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),f=p[0],g=p.slice(1).join(".");l.has(f)||l.set(f,[]),l.get(f).push(g)}if(i&&typeof i=="object")for(let[c,p]of Object.entries(i)){if(l.has(c))continue;let f=p&&typeof p=="object"&&p.fields!=null?Array.isArray(p.fields)?p.fields:String(p.fields).split(",").map(g=>g.trim()).filter(Boolean):["*"];l.set(c,f)}let d=l.get("")||[];for(let c of d){if(c==="*"){let g=new Set;for(let h of u.relations||[])if(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse){let m=h.foreignKeyColumn||H(h.propertyName);m&&g.add(m)}let y=new Set;for(let h of u.columns)g.has(h.name)||(s.push(`${r}.${h.name}`),y.add(h.name));for(let h of u.relations||[])!l.has(h.propertyName)&&!y.has(h.propertyName)&&l.set(h.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let f=u.relations?.find(b=>b.propertyName===p);if(!f)return;if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let b=f.foreignKeyColumn||H(f.propertyName),w=F(r,n),S=F(b,n),T=F(p,n);s.push(`${w}.${S} as ${T}`)}let y=f.targetTableName||f.targetTable,h=i?.[p],m=h?.fields!=null?Array.isArray(h.fields)?h.fields:String(h.fields).split(",").map(b=>b.trim()).filter(Boolean):c;a.push({relationName:p,type:f.type,targetTable:y,fields:m,isInverse:f.isInverse,fkColumn:f.foreignKeyColumn,mappedBy:f.mappedBy,junctionTableName:f.junctionTableName,junctionSourceColumn:f.junctionSourceColumn,junctionTargetColumn:f.junctionTargetColumn,userFilter:h?.filter,userSort:h?.sort,userLimit:h?.limit!==void 0?Number(h.limit):void 0,userPage:h?.page!==void 0?Number(h.page):void 0,nestedDeep:h?.deep})}),{select:s,batchFetchDescriptors:a}}var pr=Q(()=>{"use strict";Je();ue()});var zt,Vt,vn,lt,Lo,ct,hr=Q(()=>{"use strict";Je();ue();qt();Xe();_n();dr();Bt();jt();zt="__enfyra_row_number__",Vt="__sourceId__",vn="__targetId__",lt="__enfyra_partitioned__",Lo=5e4,ct=class{constructor(e,t="postgres",n,o=new Re){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=o;this.pkField="id"}chunkCount(e,t=ae){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?Lo:ae}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}buildPartitionRowNumber(e,t,n){let o=[...t];o.some(s=>s.column===n)||o.push({column:n,order:"asc"});let i=o.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${i}) as ??`,[e,...o.map(s=>s.column),zt])}buildPartitionSlice(e,t,n,o){return this.knex.from(e.as(lt)).select(`${lt}.*`).where(`${lt}.${zt}`,">",n).andWhere(`${lt}.${zt}`,"<=",n+o).orderBy(`${lt}.${t}`,"asc").orderBy(`${lt}.${zt}`,"asc")}removePartitionFields(e){for(let t of e)delete t[zt]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new se,o=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:i}=he(e,t,o,n);return i}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),u=(s?i.slice(1):i).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,o){if(!t||!this.metadata)return;let i=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of i){let l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let d=n,c=o||n;for(let p=0;p<l.length-1;p++){let f=l[p],g=this.metadata?.tables?.get(d);if(!g)break;let y=g.relations?.find(b=>b.propertyName===f);if(!y)break;let h=y.targetTableName||y.targetTable,m=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(m)){s.add(m);let b=y.foreignKeyColumn||H(y.propertyName),w=this.metadata?.tables?.get(h),S=w&&X(w)?.name||"id";e.leftJoin(`${h} as ${m}`,`${m}.${S}`,`${c}.${b}`)}d=h,c=m}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let o=e.substring(0,n),i=e.substring(n+4),s=F(i,this.dbType),a=t?`${t}.${F(o,this.dbType)}`:F(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${F(e,this.dbType)} as ${F(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return X(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=H(e.mappedBy)),t||(t=H(e.targetTable)),t}resolveParentPk(e){return e&&X(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:o}=Ye(e),i=[];if(n.includes("*")){let l=new Set;for(let d of t.relations||[])if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let c=d.foreignKeyColumn||H(d.propertyName);c&&l.add(c)}for(let d of t.columns)l.has(d.name)||i.push(d.name);for(let d of t.relations||[])o.has(d.propertyName)||o.set(d.propertyName,["id"])}else for(let l of n){let d=t.columns.find(c=>c.name===l);d?i.push(d.name):t.relations?.find(p=>p.propertyName===l)&&!o.has(l)&&o.set(l,["id"])}let s=X(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((l,d)=>{let c=t.relations?.find(p=>p.propertyName===d);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||H(c.propertyName);p&&i.push(`${p} as ${d}`)}});let a=[];return o.forEach((l,d)=>{let c=t.relations?.find(f=>f.propertyName===d);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:d,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.parseSortTokens(o.userSort,e):[],a=n.selectCols.map(l=>this.toKnexSelect(l)),u=await K(t,l=>{let d=this.knex(e).select(a).whereIn(n.pkCol,l);if(i&&ne(d,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,o.userSort,e);for(let c of s)d.orderBy(c.column,c.order)}return this.runQuery(d)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,o,i){let s=t,a=o.selectCols.find(g=>g.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let u=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,l=i?.userSort?this.parseSortTokens(i.userSort,e):[],d=i?.userLimit,c=i?.userPage;if(d!==void 0&&d>0){let g=c?(c-1)*d:0,y=o.selectCols.map(m=>this.toKnexSelect(m)),h=await K(n,async m=>{let b=this.knex(e).select(y).select(this.buildPartitionRowNumber(`${e}.${t}`,l,`${e}.${o.pkCol}`)).whereIn(`${e}.${t}`,m);u&&ne(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,i.userSort,e);let w=await this.runQuery(this.buildPartitionSlice(b,s,g,d));return this.removePartitionFields(w),w});return{docs:h,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}let p=o.selectCols.map(g=>this.toKnexSelect(g)),f=await K(n,g=>{let y=this.knex(e).select(p).whereIn(t,g);if(u&&ne(y,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(y,i?.userSort,e),l.length>0)for(let h of l)y.orderBy(h.column,h.order);else y.orderBy(o.pkCol,"asc");return this.runQuery(y)});return{docs:f,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}async selectM2MEdges(e,t,n,o,i,s,a,u){let l=`t.${s}`,d=!!a||u.some(y=>y.column!==l),c=d?u:u.map(y=>({...y,column:`${n}.${i}`})),p=t.userLimit,f=t.userPage;if(p!==void 0&&p>0){let y=f?(f-1)*p:0;return(await K(e,async m=>{let b=this.knex(n).select({[Vt]:`${n}.${o}`,[vn]:`${n}.${i}`}).whereIn(`${n}.${o}`,m);d&&(b=b.join(`${t.targetTable} as t`,`${n}.${i}`,`t.${s}`),a&&ne(b,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.buildPartitionRowNumber(`${n}.${o}`,c,d?l:`${n}.${i}`));let w=await this.runQuery(this.buildPartitionSlice(b,Vt,y,p));return this.removePartitionFields(w),w})).map(m=>({sourceId:m[Vt],targetId:m[vn]}))}return(await K(e,y=>{let h=this.knex(n).select({[Vt]:`${n}.${o}`,[vn]:`${n}.${i}`}).whereIn(`${n}.${o}`,y);if(d&&(h=h.join(`${t.targetTable} as t`,`${n}.${i}`,`t.${s}`),a&&ne(h,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(h,t.userSort,t.targetTable,"t")),h.orderBy(`${n}.${o}`,"asc"),c.length>0){for(let m of c)h.orderBy(m.column,m.order);d&&!c.some(m=>m.column===l)&&h.orderBy(l,"asc")}else h.orderBy(`${n}.${i}`,"asc");return this.runQuery(h)})).map(y=>({sourceId:y[Vt],targetId:y[vn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let o=n.selectCols.map(i=>this.toKnexSelect(i));return K(t,i=>this.runQuery(this.knex(e).select(o).whereIn(n.pkCol,i)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,o,i){let s=this.resolveParentPk(n),a=this.uniqueValues(e.map(R=>R[s]));if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,d=t.junctionTargetColumn;if(!u||!l||!d)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"):[],f=await this.selectM2MEdges(a,t,u,l,d,i.pkCol,c,p),g=new Map;for(let R of a)g.set(this.keyOf(R),[]);let y=i.selectCols.length===1&&i.selectCols[0]===i.pkCol,h=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),b=`t.${i.pkCol}`,w=!c&&p.every(R=>R.column===b);if(y){let R=new Map;for(let I of f){let O=this.keyOf(I.targetId);R.has(O)||R.set(O,{[i.pkCol]:I.targetId}),g.get(this.keyOf(I.sourceId))?.push(R.get(O))}return{grouped:g,docs:[],stats:{strategy:w?h?"m2m-junction-partitioned-top-k":"m2m-junction-batch":h?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length,rowsDiscarded:0}}}let S=this.uniqueValues(f.map(R=>R.targetId)),T=await this.loadM2MTargets(t.targetTable,S,i),k=new Map(T.map(R=>[this.keyOf(R[i.pkCol]),R]));for(let R of f){let I=k.get(this.keyOf(R.targetId));I&&g.get(this.keyOf(R.sourceId))?.push(I)}return{grouped:g,docs:T,stats:{strategy:h?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+(S.length>0?this.chunkCount(S,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length+T.length,rowsDiscarded:0}}}}});var fi={};En(fi,{executeBatchFetches:()=>yr});async function yr(r,e,t,n,o=3,i=0,s,a="postgres",u,l){let d=new ct(r,a,u);await new ke(d,n,l).execute(e,t,o,i,s)}var mr=Q(()=>{"use strict";Xe();hr()});var Uo={};En(Uo,{ALL_SUPPORTED_OPERATORS:()=>Et,AuthenticationException:()=>bt,AuthorizationException:()=>_t,BadRequestException:()=>x,BatchExecutionBudget:()=>Re,BatchFetchEngine:()=>ke,BusinessLogicException:()=>gt,CHUNKED_FETCH_CONCURRENCY:()=>Yn,ConfigurationException:()=>kt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Xn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Hr,DEFAULT_TIMEOUT_MS:()=>Yt,DOTTED_PATH_MAX_HOPS:()=>On,DatabaseException:()=>Ke,DuplicateResourceException:()=>mt,ErrorHandler:()=>Me,ExecutorEngineService:()=>We,ExternalServiceException:()=>Tt,FIELD_OPERATORS:()=>oe,FileNotFoundException:()=>Ft,FileSizeExceededException:()=>xt,FileUploadException:()=>Rt,HttpException:()=>E,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Zt,InvalidTokenException:()=>$t,IsolatedExecutorService:()=>Qe,JoinRegistry:()=>se,LOGICAL_OPERATORS:()=>Un,MongoBatchAdapter:()=>et,MongoQueryExecutor:()=>it,PER_PARENT_CONCURRENCY:()=>je,QueryBuilderService:()=>dt,QueryPlanner:()=>q,ResourceNotFoundException:()=>yt,SchemaException:()=>Ct,ScriptContractService:()=>rn,ScriptExecutionException:()=>$e,ScriptTimeoutException:()=>we,ServiceUnavailableException:()=>St,SqlBatchAdapter:()=>ct,SqlQueryExecutor:()=>ut,TokenExpiredException:()=>wt,ValidationException:()=>ht,WHERE_IN_CHUNK_SIZE:()=>ae,WorkerPool:()=>It,appendIsolatedExecutorRuntimeLog:()=>ee,applyOperatorToMatch:()=>cn,applyRelationFilters:()=>De,applyWhereToKnex:()=>at,assertFieldOperatorValueIsClean:()=>dn,buildAggregateFilter:()=>rt,buildMongoCharFoldMapJson:()=>Wn,buildMongoFoldTextSearchJs:()=>on,buildRelationSubquery:()=>Ut,buildSqlWherePartsFromFieldAst:()=>Jt,buildWhereClause:()=>de,camelToSnake:()=>Or,chunkedFetch:()=>K,compileScriptSource:()=>Qi,computeEngineTuning:()=>jn,createEnfyraKernel:()=>Ko,dslOpToCompareOp:()=>un,encodeMainThreadToIsolate:()=>Bn,escapeSqlValue:()=>li,executeBatchFetches:()=>yr,executeMongoBatchFetches:()=>$n,expandFieldsToJoinsAndSelect:()=>fr,getEffectiveCpuCount:()=>Pn,getEffectiveMemoryBytes:()=>vt,getEngineTuning:()=>nn,getExecutableScript:()=>Vi,getForeignKeyColumnName:()=>H,getIoAbortSignal:()=>Fr,getJunctionColumnNames:()=>Ot,getJunctionTableName:()=>Mt,getPrimaryKeyColumn:()=>X,getScriptLegacyField:()=>Wi,getShortFkConstraintName:()=>Nr,getShortFkName:()=>Ar,getShortIndexName:()=>Er,getShortPkName:()=>Ir,hasAggregateQuery:()=>ir,hasLogicalOperators:()=>_e,isExecutableJavaScript:()=>Ji,isScriptTable:()=>Ki,mergeAggregateValue:()=>ve,normalizeAggregateQuery:()=>nt,normalizeFlowStepScriptConfig:()=>Gi,normalizeScriptLanguage:()=>Ui,normalizeScriptPatch:()=>zi,normalizeScriptRecord:()=>qi,parseBatchFields:()=>Ye,parseFields:()=>Tn,parseFilter:()=>he,perParentRun:()=>wn,quoteIdentifier:()=>F,quoteQualifiedIdentifier:()=>Ie,resolveExecutableScript:()=>Hi,rewriteFilterDenyingFields:()=>hi,rewriteSortDroppingDenied:()=>yi,scriptContractService:()=>re,separateFilters:()=>Y,snakeToCamel:()=>Mr,throwUnsupportedFieldOperator:()=>Ee,validateDeepOptions:()=>br,validateFilterShape:()=>J,whereToMongoFilter:()=>Ve});module.exports=Ti(Uo);var Yt=3e4,We=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Yt)}async run(e,t,n=Yt,o={}){return this.isolatedExecutorService.run(e,t,n,o)}};var Xt=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var Tr=require("async_hooks"),Sr=fe(require("path")),Cr=require("stream"),kr=require("worker_threads");var we=class extends Error{constructor(t=0,n){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},$e=class extends Error{constructor(t,n,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...o}}},B=class extends Error{constructor(t,n,o,i){super(t);this.statusCode=n;this.errorCode=o;this.name=this.constructor.name,this.details=i}},E=class extends B{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},gt=class extends B{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},ht=class extends B{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},yt=class extends B{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},mt=class extends B{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},bt=class extends B{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},_t=class extends B{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},wt=class extends B{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},$t=class extends B{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Ke=class extends B{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},Tt=class extends B{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},St=class extends B{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},Ct=class extends B{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},kt=class extends B{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Rt=class extends B{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Ft=class extends B{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},xt=class extends B{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Me=class{static createException(e,t,n,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new E(n||"Error",t||500,i);case"$throw.businessLogic":return new gt(n||"Bad request",i);case"$throw.validation":return new ht(n||"Validation failed",i);case"$throw.notFound":return new yt(i?.resource||n||"Resource",i?.identifier);case"$throw.duplicate":return new mt(i?.resource||n||"Resource",i?.field||"field",i?.value||"value");case"$throw.unauthorized":return new bt(n||"Unauthorized");case"$throw.forbidden":return new _t(n||"Forbidden");case"$throw.tokenExpired":return new wt;case"$throw.invalidToken":return new $t;case"$throw.database":return new Ke(n||"Database error",i);case"$throw.dbQuery":return new Ke(n||"Query error",i);case"$throw.externalService":return new Tt(n||"Service",n||"Error",i);case"$throw.serviceUnavailable":return new St(n||"Service");case"$throw.rateLimit":return new E(n||"Rate limit exceeded",429);case"$throw.scriptError":return new $e(n||"Script error",o,i);case"$throw.scriptTimeout":return new we(i?.timeout||5e3,o);case"$throw.schema":return new Ct(n||"Schema error",i);case"$throw.config":return new kt(n||"Configuration error",i);case"$throw.fileUpload":return new Rt(n||"File upload error",i);case"$throw.fileNotFound":return new Ft(n||"File not found");case"$throw.fileSizeExceeded":return new xt(i?.maxSize||"unknown",i?.actualSize||"unknown");case"$throw.400":return new E(n||"Bad request",400,i);case"$throw.401":return new E(n||"Authentication required",401,i);case"$throw.403":return new E(n||"Insufficient permissions",403,i);case"$throw.404":return new E(n||"Not found",404,i);case"$throw.409":return new E(n||"Conflict",409,i);case"$throw.422":return new E(n||"Validation failed",422,i);case"$throw.429":return new E(n||"Rate limit exceeded",429,i);case"$throw.500":return new E(n||"Internal server error",500,i);case"$throw.503":return new E(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o)}if(t)switch(t){case 400:return new E(n||"Bad request",400,i);case 401:return new E(n||"Authentication required",401,i);case 403:return new E(n||"Insufficient permissions",403,i);case 404:return new E(n||"Not found",404,i);case 409:return new E(n||"Conflict",409,i);case 422:return new E(n||"Validation failed",422,i);case 429:return new E(n||"Rate limit exceeded",429,i);case 500:return new E(n||"Internal server error",500,i);case 503:return new E(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o,i)}return new $e(n||"Unknown error",o,i)}};var en=fe(require("fs")),tn=fe(require("path")),Zt=tn.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 Ci=Si();function ee(r){if(Ci)try{let e=tn.dirname(Zt);en.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
+ `;en.appendFileSync(Zt,t)}catch{}}var Te=fe(require("os")),Ue=fe(require("fs"));function vt(){try{let r=Ue.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Te.totalmem())return e}}catch{}try{let r=Ue.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Te.totalmem())return e}catch{}return Te.totalmem()}function Pn(){let r=Te.availableParallelism?.()||Te.cpus()?.length||1;try{let e=Ue.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let o=parseInt(t,10),i=parseInt(n,10);if(o>0&&i>0)return Math.max(1,Math.ceil(o/i))}}catch{}try{let e=parseInt(Ue.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Ue.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var ki=.25,Ri=2,Fi=2048,xi=40,vi=128,Ii=32;function jn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(vi,Math.max(xi,Math.round(t/Ii))),o=t*ki,i=Math.max(1,Math.floor(o/n)),s=Math.max(1,Math.min(e,2,i)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<Fi?1:Ri,l=Math.max(1,Math.min(u,Math.floor(o/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:l}}function nn(){return jn({logicalCpuCount:Pn(),totalMemoryBytes:vt()})}var Di=Sr.join(__dirname,"execution/worker.js"),Rr=new Tr.AsyncLocalStorage;function Fr(){return Rr.getStore()}var It=class{constructor(e,t,n,o,i,s,a,u=6e4){this.scriptPath=i;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=o,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new kr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let o=t.tasks.get(n.id);o&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),o.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):o.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,o=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:o?"Worker terminated":"Worker crashed"}});t.tasks.clear();let i=this.entries.indexOf(t);i!==-1&&this.entries.splice(i,1),!n&&!o&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},$r=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Bn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var Qe=class r{constructor(e){this.logger=new Xt(r.name);this.effectiveMemory=vt();this.isolationTuning=nn();this.pool=new It(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Di,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),o=process.cpuUsage(this.prevCpuUsage),i=Number(n-this.prevCpuTime)/1e3,s=i>0?(o.user+o.system)/i:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,d=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):d&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let o of Object.keys(e)){if(!o.startsWith("$")||o in t||$r.has(o))continue;let i=this.cloneSnapshotValue(e[o]);i!==void 0&&(t[o]=i)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,o]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||$r.has(n)||n==="$env"||(e[n]=o));delete e.$pkgs}}spawnAndExecute(e,t,n,o){return(async()=>{let i=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let d=!1,c=new AbortController,p=setTimeout(()=>{if(d)return;d=!0,c.abort();let f=new Error(`Script execution timed out after ${o}ms`);this.cleanupResponseStream(s,f),this.pool.unregisterTask(i,s),this.taskTimeoutTotal++,ee({event:"task_timeout",id:s,timeoutMs:o}),this.pool.terminateEntry(i),f.code="ERR_SCRIPT_EXECUTION_TIMEOUT",f.isTimeout=!0,l(f)},o);this.pool.registerTask(i,s,{abortController:c,onResult:f=>{if(!d)if(d=!0,clearTimeout(p),this.cleanupResponseStream(s),this.pool.unregisterTask(i,s),this.recordTaskDuration(Date.now()-a),f.success){this.taskDoneTotal++,ee({event:"task_done",id:s,ok:!0});let g={value:f.value,valueAbsent:f.valueAbsent===!0,ctxChanges:f.ctxChanges};f.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,ee({event:"task_done",id:s,ok:!1,message:f.error?.message});let g=new Error(f.error?.message||"Handler execution failed");g.statusCode=f.error?.statusCode,g.code=f.error?.code,g.details=f.error?.details,f.error?.stack&&(g.stack=f.error.stack),f.ctxChanges&&(g.ctxChanges=f.ctxChanges),this.cleanupResponseStream(s,g),l(g)}},onIoCall:f=>{if(d)return;let g=c.signal;f.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(f,n),i.worker,f.callId,g):f.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(f,n,i.worker),i.worker,f.callId,g):f.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(f,n),i.worker,f.callId,g):f.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(f,n),i.worker,f.callId,g):f.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(f,n),i.worker,f.callId,g):f.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(f,n,i.worker),i.worker,f.callId,g):f.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(f,n),i.worker,f.callId,g):f.type==="resCall"&&this.handleIoCall(()=>this.execResCall(f,n),i.worker,f.callId,g)}}),i.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,o){if(!o?.aborted)try{let i=await(o?Rr.run(o,e):e());if(o?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:Bn(i)})}catch{}}catch(i){if(o?.aborted)return;try{let s={__userThrow:!0,message:i.message,statusCode:i.statusCode,code:i.errorCode??i.code,details:i.details,messages:i.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),o=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!o||typeof o[e.method]!="function"){let i=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${i}${e.table}.${e.method}`)}return o[e.method](...n)}async execTransactionCall(e,t,n){let i=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof i!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,i)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),o=e.name.split("."),i=t?.$helpers;for(let s of o)i=i?.[s];if(typeof i!="function")throw new Error(`Helper not found: ${e.name}`);return i(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$socket?.[e.method];if(typeof o!="function")throw new Error(`Socket method not found: ${e.method}`);return o(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$cache?.[e.method];if(typeof o!="function")throw new Error(`Cache method not found: ${e.method}`);return o(...n)}async execStorageCall(e,t,n){let o=this.parseStorageArgs(e.argsJson,n,e.id),i=t?.$storage?.[e.method];if(typeof i!="function")throw new Error(`Storage method not found: ${e.method}`);return i(...o)}parseStorageArgs(e,t,n){return JSON.parse(e,(o,i)=>{if(i?.__fnRef&&typeof i.__fnRef=="string"){let s=i.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return i})}invokeRuntimeCallback(e,t,n,o){let i=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),l=c=>{if(!(c?.type!=="runtimeCallbackResult"||c.callId!==i)){if(d(),c.error){a(new Error(c.error));return}s(c.value)}},d=()=>{clearTimeout(u),e.off("message",l)};e.on("message",l),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:n,argsJson:JSON.stringify(o)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$trigger;if(typeof o!="function")throw new Error("$trigger is not available");return o(...n)}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new Cr.PassThrough;return this.responseStreams.set(e.id,{stream:u}),a.call(t.$res,u,s),!0}if(e.method==="streamChunk"){let i=this.responseStreams.get(e.id);if(!i)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return i.stream.write(s)||await new Promise((a,u)=>{let l=()=>{c(),a()},d=p=>{c(),u(p)},c=()=>{i.stream.off("drain",l),i.stream.off("error",d)};i.stream.once("drain",l),i.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let i=this.responseStreams.get(e.id);return i&&(i.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let i=this.responseStreams.get(e.id);if(i){let s=e.error?.message||"Response stream failed";i.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),o=t?.$res?.[e.method];if(typeof o!="function")throw new Error(`Response method not found: ${e.method}`);return o.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),t?n.stream.destroy(t):n.stream.end())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}async run(e,t,n,o={}){let i=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);ee({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let l;try{let d={code:e,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};l=await this.spawnAndExecute("execute",d,t,i)}catch(d){let c=d;if(ee({event:"isolated_run_error",message:c.message,code:c.code,isTimeout:!!c.isTimeout}),c.isTimeout||c.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,e);let p=c.statusCode??(typeof c.status=="number"?c.status:void 0);throw Me.createException(c.errorPath,p,c.message||"Unknown error",e,c.details||{})}return this.mergeCtxChanges(t,l.ctxChanges||{}),ee({event:"isolated_run_ok"}),l.valueAbsent?void 0:l.value}async runBatch(e,t,n){let o=Math.max(1,Math.trunc(Number(n)||3e4)),i=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(i),a=this.createSnapshot(t);ee({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let u;try{let d={codeBlocks:e.map(c=>this.toWorkerCodeBlock(c)),pkgSources:s,snapshot:a,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};u=await this.spawnAndExecute("executeBatch",d,t,o)}catch(l){let d=l;if(ee({event:"isolated_batch_error",message:d.message,code:d.code,isTimeout:!!d.isTimeout}),d.ctxChanges&&this.mergeCtxChanges(t,d.ctxChanges),d.isTimeout||d.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(o,"(batch execution)");let c=d.statusCode??(typeof d.status=="number"?d.status:void 0);throw Me.createException(d.errorPath,c,d.message||"Unknown error","(batch execution)",d.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),ee({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((i,s)=>i-s),o=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[o]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((o,i)=>o+i,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(o=>o.lastHeapRatio||0))}}};var Oe=fe(require("typescript")),Nt={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Wi(r){return re.getLegacyField(r)}function Ki(r){return re.isScriptTable(r)}function Ui(r){return re.normalizeLanguage(r)}var rn=class{getLegacyField(e){return Nt[e]}isScriptTable(e){return e in Nt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),i=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(i),i}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},o=this.getLegacyField(e);return o&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[o]!==void 0&&(n.sourceCode=n[o]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),o&&o in n&&delete n[o],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(o?Object.prototype.hasOwnProperty.call(t,o):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!i&&!s)return t;let a=i?t.sourceCode??(o?t[o]:void 0):n?.sourceCode??(o&&n?n[o]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,l={...t};return i&&(l.sourceCode=a??null),l.scriptLanguage=this.normalizeLanguage(u),l.compiledCode=this.compileSource(a,l.scriptLanguage),o&&o in l&&delete l[o],l}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(Nt).find(n=>Nt[n]in e);if(t){let n=e[Nt[t]];if(typeof n=="string"&&n!==""){let o=this.compileSource(n,e.scriptLanguage);return{code:o,compiledCode:o,shouldPersistCompiledCode:o!==e.compiledCode}}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let n={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};n.sourceCode=n.sourceCode??i.sourceCode??i.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??i.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,o=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Oe.default.transpileModule(e,{compilerOptions:{target:Oe.default.ScriptTarget.ES2022,module:Oe.default.ModuleKind.CommonJS,importsNotUsedAsValues:Oe.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(o=>o.category===Oe.default.DiagnosticCategory.Error);if(n)throw new Error(Oe.default.flattenDiagnosticMessageText(n.messageText,`
3
3
  `));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
4
4
  "use strict";
5
5
  ${e}
6
- });`)}},ne=new Gt;function Oi(r,e){return ne.compileSource(r,e)}function Ei(r){return ne.isExecutableJavaScript(r)}function Pi(r,e){return ne.normalizeRecord(r,e)}function ji(r,e,t){return ne.normalizePatch(r,e,t)}function Li(r){return ne.getExecutableScript(r)}function Bi(r){return ne.resolveExecutableScript(r)}function Di(r){return ne.normalizeFlowStepScriptConfig(r)}var Sn=require("node:fs"),ri=require("node:path");var Nn=require("mongodb");Ue();function Ae(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function V(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ae(r)&&(r.foreignKeyColumn||r.propertyName)||null}function W(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ae(r){if(!r||typeof r!="object")return r;if(r instanceof Nn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ae(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((o,i)=>parseInt(o)-parseInt(i)).map(o=>t[o]);return new Nn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?ae(n):n;return e}function de(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,f=e.junctionTableName||xt(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=vt(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,o=t,i=e.junctionTableName||xt(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=vt(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function It(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let o=r.tables?.get(e);if(!o)return{scalarFields:[],relations:[]};let i=new Map;for(let l of t)if(l==="*")i.has("")||i.set("",[]),i.get("").push(l);else if(l.includes(".")){let f=l.split("."),c=f[0],p=f.slice(1).join(".");i.has(c)||i.set(c,[]),i.get(c).push(p)}else o.relations?.some(c=>c.propertyName===l)?i.has(l)||i.set(l,["_id"]):(i.has("")||i.set("",[]),i.get("").push(l));if(n&&typeof n=="object")for(let[l,f]of Object.entries(n)){if(i.has(l))continue;let c=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(p=>p.trim()).filter(Boolean):["*"];i.set(l,c)}let s=[],a=[],u=i.get("")||[];for(let l of u)if(l==="*"){if(o.columns)for(let f of o.columns)s.includes(f.name)||s.push(f.name);if(o.relations)for(let f of o.relations)i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else o.columns?.some(c=>c.name===l)&&!s.includes(l)&&s.push(l);for(let[l,f]of i.entries()){if(l==="")continue;let c=o.relations?.find(h=>h.propertyName===l);if(!c)continue;let p="",d="",g=!1;c.type==="many-to-one"||c.type==="one-to-one"?Ae(c)?(p="_id",d=W(c)||c.propertyName,g=!0):(p=V(c)||c.propertyName,d="_id",g=!1):c.type==="one-to-many"?(p="_id",d=W(c)||c.propertyName,g=!0):c.type==="many-to-many"&&(c.mappedBy?(p="_id",d=c.mappedBy,g=!0):(p=c.propertyName,d="_id",g=!1));let y=c.type==="one-to-many"||c.type==="many-to-many";a.push({propertyName:l,targetTable:c.targetTableName,localField:p,foreignField:d,type:y?"many":"one",isInverse:g,nestedFields:f})}return{scalarFields:s,relations:a}}var Xt=fe(require("fs")),An=fe(require("path"));var Ki=new RegExp("\\p{Mark}","gu");function Rr(r){return r==null?"":String(r).normalize("NFKD").replace(Ki,"").toLowerCase()}function Mn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Rr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Yt(){return`function() {
7
- var M = ${Mn()};
6
+ });`)}},re=new rn;function Qi(r,e){return re.compileSource(r,e)}function Ji(r){return re.isExecutableJavaScript(r)}function qi(r,e){return re.normalizeRecord(r,e)}function zi(r,e,t){return re.normalizePatch(r,e,t)}function Vi(r){return re.getExecutableScript(r)}function Hi(r){return re.resolveExecutableScript(r)}function Gi(r){return re.normalizeFlowStepScriptConfig(r)}var Nn=require("node:fs"),pi=require("node:path");var Dn=require("mongodb");Je();function Ae(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")&&!Ae(r)&&(r.foreignKeyColumn||r.propertyName)||null}function U(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ce(r){if(!r||typeof r!="object")return r;if(r instanceof Dn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ce(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((o,i)=>parseInt(o)-parseInt(i)).map(o=>t[o]);return new Dn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?ce(n):n;return e}function pe(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,d=e.junctionTableName||Mt(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=Ot(a,u,l);return{junctionName:d,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,o=t,i=e.junctionTableName||Mt(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=Ot(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function At(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let o=r.tables?.get(e);if(!o)return{scalarFields:[],relations:[]};let i=new Map;for(let l of t)if(l==="*")i.has("")||i.set("",[]),i.get("").push(l);else if(l.includes(".")){let d=l.split("."),c=d[0],p=d.slice(1).join(".");i.has(c)||i.set(c,[]),i.get(c).push(p)}else o.relations?.some(c=>c.propertyName===l)?i.has(l)||i.set(l,["_id"]):(i.has("")||i.set("",[]),i.get("").push(l));if(n&&typeof n=="object")for(let[l,d]of Object.entries(n)){if(i.has(l))continue;let c=d&&typeof d=="object"&&d.fields!=null?Array.isArray(d.fields)?d.fields:String(d.fields).split(",").map(p=>p.trim()).filter(Boolean):["*"];i.set(l,c)}let s=[],a=[],u=i.get("")||[];for(let l of u)if(l==="*"){if(o.columns)for(let d of o.columns)s.includes(d.name)||s.push(d.name);if(o.relations)for(let d of o.relations)i.has(d.propertyName)||i.set(d.propertyName,["_id"])}else o.columns?.some(c=>c.name===l)&&!s.includes(l)&&s.push(l);for(let[l,d]of i.entries()){if(l==="")continue;let c=o.relations?.find(h=>h.propertyName===l);if(!c)continue;let p="",f="",g=!1;c.type==="many-to-one"||c.type==="one-to-one"?Ae(c)?(p="_id",f=U(c)||c.propertyName,g=!0):(p=G(c)||c.propertyName,f="_id",g=!1):c.type==="one-to-many"?(p="_id",f=U(c)||c.propertyName,g=!0):c.type==="many-to-many"&&(c.mappedBy?(p="_id",f=c.mappedBy,g=!0):(p=c.propertyName,f="_id",g=!1));let y=c.type==="one-to-many"||c.type==="many-to-many";a.push({propertyName:l,targetTable:c.targetTableName,localField:p,foreignField:f,type:y?"many":"one",isInverse:g,nestedFields:d})}return{scalarFields:s,relations:a}}var sn=fe(require("fs")),Kn=fe(require("path"));var Yi=new RegExp("\\p{Mark}","gu");function Pr(r){return r==null?"":String(r).normalize("NFKD").replace(Yi,"").toLowerCase()}function Wn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Pr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function on(){return`function() {
7
+ var M = ${Wn()};
8
8
  function foldStr(s) {
9
9
  if (s == null) return '';
10
10
  s = String(s);
@@ -49,5 +49,5 @@ ${e}
49
49
  }
50
50
  }
51
51
  return true;
52
- }`}var xr="mongo-fold-text-search.body.txt",Qe=null;function Wi(){let r=[An.join(__dirname,xr),An.join(process.cwd(),"dist","kernel","query","utils",xr)];for(let e of r)try{if(Xt.existsSync(e))return Xt.readFileSync(e,"utf8")}catch{}return null}function Zt(){if(Qe!==null)return Qe;let r=Wi();return r?(Qe=r,Qe):(Qe=Yt(),Qe)}var Te=require("mongodb");function K(r,e,t,n){if(t==="_id"){if(n instanceof Te.ObjectId)return n;if(typeof n=="string")try{return new Te.ObjectId(n)}catch{return n}return n}let o=r?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new Te.ObjectId(n)}catch{return n}return n;default:return n}}var en="__mongoFoldTextTriples";function Ui(r){return r==="_id"?"$_id":`$${r}`}function Je(r,e,t,n){let o=Ui(e),i=r[en]??[];i.push({ref:o,needle:t,mode:n}),r[en]=i}function Qi(r){let e=r[en];if(delete r[en],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:Zt(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}function qe(r,e,t,n){let o={},i=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";i&&a==="id"&&(a="_id");let l=K(r,u,a,s.value);switch(s.operator){case"=":o[a]=l;break;case"!=":o[a]={$ne:l};break;case">":o[a]={$gt:l};break;case"<":o[a]={$lt:l};break;case">=":o[a]={$gte:l};break;case"<=":o[a]={$lte:l};break;case"like":o[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let c=f.map(m=>K(r,u,a,m));o[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(m=>m.trim()):[p]);let d=p.map(m=>K(r,u,a,m));o[a]={$nin:d};break;case"is null":o[a]=null;break;case"is not null":o[a]={$ne:null};break;case"_contains":Je(o,a,String(l),"contains");break;case"_starts_with":Je(o,a,String(l),"starts");break;case"_ends_with":Je(o,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(m=>m.trim())),Array.isArray(g)&&g.length===2){let m=K(r,u,a,g[0]),b=K(r,u,a,g[1]);o[a]={$gte:m,$lte:b}}break;case"_is_null":let y=l===!0||l==="true";o[a]=y?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=l===!0||l==="true";o[a]=h?{$ne:null}:{$eq:null};break}}return Qi(o),o}function vr(r,e,t){let o=r?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function tn(r,e,t,n,o,i){switch(o){case"_contains":Je(e,n,String(i),"contains");break;case"_starts_with":Je(e,n,String(i),"starts");break;case"_ends_with":Je(e,n,String(i),"ends");break;case"_eq":e[n]=K(r,t,n,i);break;case"_neq":{let c=K(r,t,n,i);vr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=i;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>K(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>K(r,t,n,c));vr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:K(r,t,n,i)};break;case"_gte":e[n]={$gte:K(r,t,n,i)};break;case"_lt":e[n]={$lt:K(r,t,n,i)};break;case"_lte":e[n]={$lte:K(r,t,n,i)};break;case"_is_null":let u=i===!0||i==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=i===!0||i==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=i;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=K(r,t,n,f[0]),p=K(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var Dn=require("mongodb");function re(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let o of n)if(re(o,e))return!0}}else if(t==="_not"){if(re(n,e))return!0}else if(e.has(t))return!0;return!1}function H(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let i=re(r,o);return{fieldFilters:t,relationFilters:n,hasRelations:i}}At();Ot();var sn="__mongoFoldTextTriples";function Ee(r,e){if(!r)return{};let t={};return Et(r,t,e),ke(t),t}function Xi(r,e){if(!r)return{};let t={};return Pn(r,t,e),ke(t),t}function ye(r,e,t){if(!e)return{};let n=new oe,{node:o}=ge(e,t,r,n);return Ee(o,{metadata:r,rootTable:t})}function an(r,e,t){if(!e)return{};let n=new oe,{node:o}=ge(e,t,r,n);return Xi(o,{metadata:r,rootTable:t})}function Et(r,e,t){switch(r.kind){case"true":return;case"false":he(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=r.children.map(i=>{let s={};return Et(i,s,t),ke(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}he(e,...o);return}case"or":{let o=r.children.map(s=>{let a={};return Et(s,a,t),ke(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;let i=e.$or;e.$or=i?[...i,...o]:o;return}case"not":{let n={};Et(r.child,n,t),ke(n);let o=e.$nor;e.$nor=o?[...o,n]:[n];return}case"compare":Or(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Or(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let o=i=>K(t.metadata,t.rootTable,n,i);switch(r.op){case"eq":Z(e,n,o(r.value));return;case"neq":{let i=o(r.value);jn(t,n)?he(e,{[n]:{$ne:null}},{[n]:{$ne:i}}):Z(e,n,{$ne:i});return}case"gt":Z(e,n,{$gt:o(r.value)});return;case"gte":Z(e,n,{$gte:o(r.value)});return;case"lt":Z(e,n,{$lt:o(r.value)});return;case"lte":Z(e,n,{$lte:o(r.value)});return;case"in":{let i=Ar(r.value).map(o);Z(e,n,{$in:i});return}case"not_in":{let i=Ar(r.value).map(o);jn(t,n)?he(e,{[n]:{$ne:null}},{[n]:{$nin:i}}):Z(e,n,{$nin:i});return}case"between":{let i=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&Z(e,n,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":Z(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":En(e,n,String(r.value),"contains");return;case"starts_with":En(e,n,String(r.value),"starts");return;case"ends_with":En(e,n,String(r.value),"ends");return}}function Pn(r,e,t){switch(r.kind){case"true":he(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let o=r.children.map(s=>{let a={};return Pn(s,a,t),ke(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}let i=e.$or;e.$or=i?[...i,...o]:o;return}case"or":{let o=r.children.map(i=>{let s={};return Pn(i,s,t),ke(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}he(e,...o);return}case"not":Et(r.child,e,t);return;case"compare":Zi(r,e,t);return;case"relation_exists":{Z(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function Zi(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){Z(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let o={};Or(r,o,t),ke(o);let i={$nor:[o]};jn(t,n)?he(e,i,{[n]:{$ne:null}}):he(e,i)}function Z(r,e,t){r[e]===void 0?r[e]=t:(he(r,{[e]:r[e]},{[e]:t}),delete r[e])}function he(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function jn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(o=>o.name===e);return n?n.isNullable!==!1:!0}function Ar(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function eo(r){return r==="_id"?"$_id":`$${r}`}function En(r,e,t,n){let o=eo(e),i=r[sn]??[];i.push({ref:o,needle:t,mode:n}),r[sn]=i}function ke(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:Zt(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}async function me(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return ye(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!re(r,i))return ye(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>me(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>me(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not)return await Bn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=H(r,o),u=[];if(s&&Object.keys(s).length>0){let l=ye(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await to(l,f,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Bn(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return an(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!re(r,i))return an(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>Bn(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$or:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>Bn(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._not)return me(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=H(r,o),u=[];if(s&&Object.keys(s).length>0){let l=an(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await ro(l,f,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function to(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?no(e,s,r,a,u,o,i):s.type==="one-to-many"?jr(e,s,t,a,u,o,i):s.type==="many-to-many"?Lr(e,s,t,a,u,o,i):{}}async function no(r,e,t,n,o,i,s){let a=V(e)||t,u=cn(r),l=un(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Kn(u);if(f!==null){let g=fn(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await ln(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{__impossible__:!0}:{[a]:{$in:d}}}async function ro(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return io(e,s,r,a,u,o,i);if(s.type==="one-to-many"){let l=await jr(e,s,t,a,u,o,i);return Pr(l)}if(s.type==="many-to-many"){let l=await Lr(e,s,t,a,u,o,i);return Pr(l)}return{}}async function io(r,e,t,n,o,i,s){let a=V(e)||t,u=cn(r),l=un(u);if(l!==null)return l?{[a]:{$ne:null}}:{[a]:null};let f=Kn(u);if(f!==null){let g=fn(f.value);if(f.op==="eq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(f.op==="neq")return{[a]:g};if(f.op==="in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]};if(f.op==="not_in")return{[a]:{$in:g}}}let c=await ln(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{[a]:null};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:d}},{[a]:{$ne:null}}]}}async function jr(r,e,t,n,o,i,s){let a=W(e)||t,u=cn(r),l=un(u);if(l!==null){let p=await Er(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await ln(u,n,o,i,s);if(!f||Object.keys(f).length===0)return{};let c=await Er(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Lr(r,e,t,n,o,i,s){let a=de(t,e);if(!a)return{};let u=cn(r),l=un(u);if(l!==null){let y=await Ln(s,a,n,null);return l?y.length===0?{}:{_id:{$nin:y}}:y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let f=Kn(u);if(f!==null){let y=fn(f.value),h=Array.isArray(y)?y:[y],m=await Ln(s,a,n,{_id:{$in:h}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let c=await ln(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await Ln(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function ln(r,e,t,n,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return re(r,i)?me(r,e,n,o):ye(n,r,e)}async function Er(r,e,t,n){let o=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let u=a[t];if(u==null)continue;let l=String(u);i.has(l)||(i.add(l),s.push(u))}return s}function Pr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function Ln(r,e,t,n){let o=null;n&&t&&(o=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(Boolean));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await r.collection(e.junctionName).find(i,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function cn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function un(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function fn(r){if(Array.isArray(r))return r.map(e=>fn(e));if(typeof r!="string")return r;try{return new Dn.ObjectId(r)}catch{return r}}function Kn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Dn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function Pt(r,e,t,n){let o=await It(r,e,t),i=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let y=Object.keys(g)[0];y&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(y)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,y]of Object.entries(s))if(typeof y=="object"&&y!==null)for(let[h,m]of Object.entries(y))tn(r,d,e,g,h,m);else d[g]=y;Object.keys(d).length>0&&i.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!o.relations.some(h=>h.propertyName===d)){let h=l.find(m=>m.propertyName===d);if(h){let m="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")m=V(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")m="_id",b=W(h)||h.propertyName;else if(h.type==="many-to-many")continue;let S=h.type==="one-to-many"||h.type==="many-to-many";f.push({propertyName:d,targetTable:h.targetTableName,localField:m,foreignField:b,type:S?"many":"one",nestedFields:[]})}}let c=[...o.relations,...f];for(let d of c){let g=a[d.propertyName],y=d.nestedFields&&d.nestedFields.length>0?await Pt(r,d.targetTable,d.nestedFields,g):g?await Pt(r,d.targetTable,["_id"],g):[];d.type==="one"&&y.length>0&&y.push({$limit:1}),i.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:y.length>0?y:void 0}}),d.type==="one"&&(i.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Ve(g)||i.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(o.scalarFields.length>0||o.relations.length>0||p.length>0){let d={_id:1};for(let y of o.scalarFields)d[y]=1;for(let y of c)d[y.propertyName]=1,y.type==="one"&&y.localField&&y.localField!==y.propertyName&&(d[y.localField]=1);if(t.includes("*"))for(let y of p){if(y.type==="one-to-many"||y.type==="many-to-many")continue;y.type==="many-to-many"?d[y.propertyName]={$map:{input:`$${y.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[y.propertyName]={$cond:{if:{$ne:[`$${y.propertyName}`,null]},then:{_id:`$${y.propertyName}`},else:null}}}i.push({$project:d})}return i}async function Br(r,e,t,n,o){let i=r?.tables?.get(t),s=i?.relations||[],a=i?.columns||[],u=s.filter(f=>!o.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&o.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of o)f[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(f[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function Ve(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ve(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ve(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ve(e));if("_not"in r)return Ve(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ve(t)))return!0}return!1}Ge();var jt=require("mongodb");Ge();dn();var Ye=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let o=n.field.split(".");if(o.length===1)t[o[0]]=n.order;else{let i=`__sort_${o.slice(0,-1).join("_")}`;t[`${i}.${o[o.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let o=n.startsWith("-");return{field:o?n.slice(1):n,order:o?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let o=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),i=[{$match:t}],s=new Set;for(let l of o){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],y=this.normalizeMetadata()?.tables?.get(p);if(!y)break;let h=y.relations?.find(S=>S.propertyName===g);if(!h)break;let m=h.targetTableName||h.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let S=V(h)||h.propertyName,_=d===0?null:`__sort_${c.slice(0,d).join("_")}`,$=_?`${_}.${S}`:S;i.push({$lookup:{from:m,localField:$,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=m}}let a=this.buildSortFromTokens(n);a&&i.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&i.push({$project:u}),i}toObjectId(e){try{return typeof e=="string"?new jt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof jt.ObjectId||t instanceof jt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(o=>!o.field.includes("."));n.length!==0&&e.sort((o,i)=>{for(let s of n){let a=this.compareSortValues(o[s.field],i[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(o._id,i._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},o=[];for(let i of this.parseSortTokens(t))i.field.includes(".")||n[i.field]===void 0&&(n[i.field]=1,o.push(i.field));return{projection:n,hiddenFields:o}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let o of t)delete n[o]}keyOf(e){return e==null?"":e instanceof jt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:o}=He(e),i={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])o.has(p.propertyName)||o.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?i[d.name]=1:t.relations?.find(y=>y.propertyName===p)&&!o.has(p)&&o.set(p,["_id"])}o.forEach((p,d)=>{let g=t.relations?.find(y=>y.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[V(g)||g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let y=g.targetTableName||g.targetTable;if(!y)return;let h,m;g.type==="many-to-one"||g.type==="one-to-one"?Ae(g)?(h="_id",m=W(g)||g.propertyName):(h=V(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(h="_id",m=W(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(h="_id",m=g.mappedBy):(h=g.propertyName,m="_id")),a.push({relationName:d,type:g.type,targetTable:y,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:h,foreignField:m})});let u=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)i[p.newName]===1&&i[p.oldName]!==1&&(i[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?ye(this.normalizeMetadata(),o.userFilter,e):null,s=this.buildSortFromTokens(o?.userSort),a=await ee(t,u=>{let l={_id:{$in:u}};i&&Object.keys(i).length>0&&Object.assign(l,i);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,o,i){let s=o.projection?{...o.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(h=>h!=null).map(h=>this.toObjectId(h)),u=i?.userFilter?ye(this.normalizeMetadata(),i.userFilter,e):null,l=i?.userLimit,f=i?.userPage,c=this.hasDottedSort(i?.userSort);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,m=await be(a,async S=>{let _={[t]:S};if(u&&Object.keys(u).length>0&&Object.assign(_,u),c){let R=this.buildSortAggregatePipeline(e,_,i.userSort);h>0&&R.push({$skip:h}),R.push({$limit:l}),s&&R.push({$project:s});let M=await this.db.collection(e).aggregate(R).toArray();return this.applyReadFallback(M,o)}let k={sort:this.buildSortFromTokens(i?.userSort)||{_id:1}};s&&(k.projection=s);let N=this.db.collection(e).find(_,k);return h>0&&N.skip(h),N.limit(l),this.applyReadFallback(await N.toArray(),o)},se),b=[];for(let[S,_]of m.entries()){let $=a.find(k=>this.keyOf(k)===S);for(let k of _)k[t]||(k[t]=$??S),b.push(k)}return{docs:b,groupKeyField:t}}if(s&&(s[t]=1),c){let h=[],m=await be(a,async b=>{let S={[t]:b};u&&Object.keys(u).length>0&&Object.assign(S,u);let _=this.buildSortAggregatePipeline(e,S,i.userSort);s&&_.push({$project:s});let $=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback($,o)},se);for(let b of m.values())for(let S of b)h.push(S);return{docs:h,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(i?.userSort)||{_id:1},g={projection:s,sort:d},y=await ee(a,h=>this.db.collection(e).find({[t]:{$in:h},...u||{}},g).toArray());return{docs:this.applyReadFallback(y,o),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,o,i){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=de(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(_=>_._id).filter(_=>_!=null),l=new Map;for(let _ of e)l.set(this.keyOf(_._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await ee(u,_=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:_}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?ye(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let _=d?(d-1)*p:0,$=await be(u,async N=>{let M=(await this.db.collection(a.junctionName).find({[a.selfColumn]:N},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(P=>P[a.otherColumn]).filter(P=>P!=null);if(M.length===0)return[];let T={_id:{$in:M}};if(c&&Object.keys(c).length>0&&Object.assign(T,c),this.hasDottedSort(t.userSort)){let P=this.buildSortAggregatePipeline(t.targetTable,T,t.userSort);_>0&&P.push({$skip:_}),P.push({$limit:p}),i.projection&&P.push({$project:i.projection});let w=await this.db.collection(t.targetTable).aggregate(P).toArray();return this.applyReadFallback(w,i)}let O={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};i.projection&&(O.projection=i.projection);let B=this.db.collection(t.targetTable).find(T,O);return _>0&&B.skip(_),B.limit(p),this.applyReadFallback(await B.toArray(),i)},se),k=[];for(let[N,R]of $.entries()){l.set(N,R);for(let M of R)k.push(M)}return{grouped:l,docs:k}}let g=new Set,y=[];for(let _ of f){let $=_[a.otherColumn];if($==null)continue;let k=this.keyOf($);g.has(k)||(g.add(k),y.push($))}let h=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1&&!c,m=[],b=new Map;if(h)m=y.map(_=>({_id:_})),this.sortDocsByPk(m);else{let _={_id:{$in:y}};c&&Object.keys(c).length>0&&Object.assign(_,c);let $=this.hasDottedSort(t.userSort),k;if($){let N=this.buildSortAggregatePipeline(t.targetTable,_,t.userSort);i.projection&&N.push({$project:i.projection}),k=await this.db.collection(t.targetTable).aggregate(N).toArray()}else{let N=this.buildSortFromTokens(t.userSort)||{_id:1},R=this.projectionWithSortFields(i.projection,t.userSort),M={sort:N};R.projection&&(M.projection=R.projection),k=await ee(y,T=>this.db.collection(t.targetTable).find({_id:{$in:T},...c||{}},M).toArray()),t.userSort?this.sortDocsInMemory(k,t.userSort):this.sortDocsByPk(k),this.removeHiddenFields(k,R.hiddenFields)}m=this.applyReadFallback(k,i)}for(let _ of m)b.set(this.keyOf(_._id),_);let S=new Map;for(let _ of f){let $=this.keyOf(_[a.selfColumn]),k=this.keyOf(_[a.otherColumn]);b.has(k)&&(S.has(k)||S.set(k,[]),S.get(k).push($))}for(let _ of m){let $=S.get(this.keyOf(_._id))||[];for(let k of $)l.get(k)?.push(_)}return{grouped:l,docs:m}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let o=new Set(t.hiddenFields??[]);for(let i of e)for(let s of n)i[s.newName]===void 0&&i[s.oldName]!==void 0&&(i[s.newName]=i[s.oldName]),(o.has(s.oldName)||i[s.newName]!==void 0)&&delete i[s.oldName];return e}};async function pn(r,e,t,n,o=3,i=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new Ye(r,a,f);await new Ce(c,n,u).execute(e,t,o,i,s)}async function Qn(r,e,t){let n=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,u=i?.tables?.get(e.table),l=new Set((u?.relations??[]).map(T=>T.propertyName)),f=!!e.mongoRawFilter&&!!i&&re(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&f){let T=await me(e.mongoRawFilter,e.table,i,o);T&&Object.keys(T).length>0&&n.push({$match:T})}else if(p){let T=Ee(c.filterTree,{metadata:i,rootTable:e.table});Object.keys(T).length>0&&n.push({$match:T})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let T=qe(i,e.where,e.table,s);n.push({$match:T})}let d=e.plan,y=d?d.hasRelationSort:e.sort?.some(T=>{if(!T.field.includes("."))return!1;let L=T.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(I=>I.propertyName===L)??!1})??!1,h=()=>d?.sortItems?fo(d.sortItems):e.sort?uo(e.sort):null,m=d?.sortItems?oo(d.sortItems):[],b=d?.sortItems?so(d.sortItems):[],S=()=>{!d||m.length===0||ao(n,e.table,d.sortItems,i)},_=()=>{!d||b.length===0||lo(n,e.table,d.sortItems,i)},$=()=>{let T=[...m,...b];T.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(T.map(L=>[L,0]))})};if(!e.mongoFieldsExpanded){S(),_();let T=h();if(T&&n.push({$sort:T}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),$(),e.select){let I={};for(let O of e.select)I[O]=1;n.push({$project:I})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let L=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:L,pipeline:n}:{results:Dr(L),pipeline:n}}let{scalarFields:k,relations:N}=e.mongoFieldsExpanded;if(!y){S(),_();let T=h();T&&n.push({$sort:T}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let R=[];for(let T of N)if(e.sort?.some(I=>I.field.startsWith(`${T.propertyName}.`))){let I=e.mongoRawFilter?.[T.propertyName];if(T.nestedFields&&T.nestedFields.length>0){let B=await Pt(i,T.targetTable,T.nestedFields??[],I);T.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName,pipeline:B.length>0?B:void 0}})}else if(I){let B=await Pt(i,T.targetTable,["_id"],I);T.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName,pipeline:B.length>0?B:void 0}})}else n.push({$lookup:{from:T.targetTable,localField:T.localField,foreignField:T.foreignField,as:T.propertyName}});T.type==="one"&&(n.push({$unwind:{path:`$${T.propertyName}`,preserveNullAndEmptyArrays:!0}}),I&&(Xe(I)||n.push({$match:{[T.propertyName]:{$ne:null}}})))}else R.push(T);if(y){S(),_();let T=h();T&&n.push({$sort:T}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}$(),await Br(i,n,e.table,k,[...N]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let M=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:M,pipeline:n};if(R.length>0&&M.length>0){let T=e.deep||{},L=R.map(O=>{let P=i?.tables?.get(e.table)?.relations?.find(x=>x.propertyName===O.propertyName),w=T[O.propertyName],F=w?.fields!=null?Array.isArray(w.fields)?w.fields:String(w.fields).split(",").map(x=>x.trim()).filter(Boolean):O.nestedFields&&O.nestedFields.length>0?O.nestedFields:["_id"];return{relationName:O.propertyName,type:P?.type,targetTable:O.targetTable,fields:F,isInverse:P?.isInverse,mappedBy:P?.mappedBy,junctionTableName:P?.junctionTableName,localField:O.localField,foreignField:O.foreignField,userFilter:w?.filter,userSort:w?.sort,userLimit:w?.limit!==void 0?Number(w.limit):void 0,userPage:w?.page!==void 0?Number(w.page):void 0,nestedDeep:w?.deep}}),I=co(i);I&&await pn(o,M,L,I,3,0,e.table,i,void 0,t.mongoPhysicalMigrationService)}return{results:Dr(M),pipeline:n}}function Jn(r){return`__sort_count_${r.relationName||r.field}`}function qn(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function oo(r){return r.filter(e=>e.function==="count").map(Jn)}function so(r){return r.filter(e=>e.function==="max"||e.function==="min").map(qn)}function ao(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=Jn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=W(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=de(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function lo(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=n?.tables?.get(l),c=f?.columns?.find(h=>h.isPrimary)?.name||(f?.columns?.some(h=>h.name==="_id")?"_id":"id"),p=s.aggregateField,d=p==="id"&&f?.columns?.some(h=>h.name==="_id")?"_id":p,g=qn(s),y=s.function==="min"?"$min":"$max";if(!(!a||!l||!p)){if(a.type==="one-to-many"){let h=W(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[y]:`$${d}`}}}],as:g}}),r.push({$addFields:{[g]:{$arrayElemAt:[`$${g}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=de(e,a);if(!h)continue;let m=`${g}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:m}}),r.push({$lookup:{from:l,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${c}`,"$$targetIds"]}}},{$group:{_id:null,value:{[y]:`$${d}`}}}],as:g}}),r.push({$addFields:{[g]:{$arrayElemAt:[`$${g}.value`,0]}}}),r.push({$project:{[m]:0}})}}}}function co(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function uo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function fo(r){let e={};for(let t of r){let n=t.function==="count"?Jn(t):t.function==="max"||t.function==="min"?qn(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Xe(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Xe(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Xe(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Xe(e));if("_not"in r)return Xe(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Xe(t)))return!0}return!1}function Dr(r){return r.map(ae)}function Kr(r,e){let t=[],n=[],o=e?.tables?.get(r.rootTable);if(!o)return{scalarFields:t,relations:n};for(let i of r.nodes)if(i.kind==="wildcard")for(let s of o.columns||[])t.includes(s.name)||t.push(s.name);else i.kind==="scalar"?o.columns?.some(a=>a.name===i.name)&&!t.includes(i.name)&&t.push(i.name):i.kind==="relation"&&n.push(po(i,o,e));return{scalarFields:t,relations:n}}function po(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),o,i,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ae(n)?(o="_id",i=W(n)||r.propertyName,s=!0):(o=n&&V(n)||r.propertyName,i="_id",s=!1):r.relationType==="one-to-many"?(o="_id",i=n&&W(n)||r.propertyName,s=!0):n?.mappedBy?(o="_id",i=n.mappedBy,s=!0):(o=r.propertyName,i="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Wr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:u}}function Wr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Wr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let o of n)e.push(`${t.propertyName}.${o}`)}return e}ze();Ot();At();function gn(r,e,t,n){let o={rootTable:e,nodes:[]};if(!r||r.length===0)return o;let i=t?.tables?.get(e);if(!i)return o;let s=i.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=i.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),y=p.substring(d+1);if(!i.relations?.some(m=>m.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(y)}else if(i.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!i.columns?.some(y=>y.name===p))continue;f.push(p)}}if(f.includes("*")){o.nodes.push({kind:"wildcard"});for(let c of i.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)o.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=i.relations?.find(h=>h.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,y={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Ur(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let h=n.registerWithParent(e,c,t,"left",null,"data");y.joinId=h}o.nodes.push(y)}return o}function Ur(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let o=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),i=n.columns?.some(f=>f.name==="id"),s=o&&!i?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Ur(c,d,t)})}return l}pe();pe();var go=new Set(["_and","_or","_not"]);function Qr(r,e){return r?.tables?.get(e)??null}function ho(r,e,t){return Qr(r,e)?.columns?.find(n=>n.name===t)}function zn(r,e,t){return Qr(r,e)?.relations?.find(n=>n.propertyName===t)}function yo(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let o=n.indexOf(".");return o<=0||o!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,o).trim(),fieldName:n.slice(o+1).trim()}}function Vn(r,e,t,n){if(ho(r,e,t)?.isEncrypted===!0)throw new v(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Pe(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Pe(n,e,t);return}for(let[n,o]of Object.entries(r)){if(go.has(n)){Pe(o,e,t);continue}if(n.startsWith("_"))continue;let i=zn(t,e,n);if(i){let s=i.targetTableName||i.targetTable;s&&Pe(o,s,t);continue}Vn(t,e,n,"filter")}}}function hn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(!i)continue;let s=yo(i);if(s){if(s.functionName==="count")continue;let l=zn(t,e,s.relationName),f=l?.targetTableName||l?.targetTable;f&&Vn(t,f,s.fieldName,"sort");continue}let a=i.split("."),u=e;for(let l=0;l<a.length;l++){let f=a[l];if(l===a.length-1){Vn(t,u,f,"sort");break}let p=zn(t,u,f);if(!p)break;u=p.targetTableName||p.targetTable||u}}}var J=class{plan(e){let{tableName:t,fields:n,filter:o,sort:i,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new oe,d=this.parseFields(n),g=null;d&&c&&(g=gn(d,t,l,p));let y=!1,h=null;if(o&&c){Pe(o,t,l);let L=ge(o,t,l,p);h=L.node,y=L.hasRelationFilters}let m=this.parseSort(i);c&&hn(m,t,l);let b=[],S=!1;for(let L of m){let I=L.startsWith("-"),O=I?L.substring(1):L,B=I?"desc":"asc";if(c){let P=this.parseRelationAggregateSort(t,c,O,l);if(P){b.push({joinId:null,field:O,direction:B,fullPath:O,function:P.functionName,relationName:P.relationName,aggregateField:P.aggregateField,relationMeta:P.relationMeta});continue}this.assertLocalSortField(t,c,O)}b.push({joinId:null,field:O,direction:B,fullPath:O})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let _=this.parseLimit(a),$=this.parsePage(s),k=$!==void 0&&_!==void 0?($-1)*_:void 0,N=this.parseMeta(u),R=N.includes("totalCount")||N.includes("*"),M=N.includes("filterCount")||N.includes("*"),T=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:o??null,joins:T,sortItems:b,limit:_,offset:k,needsTotalCount:R,needsFilterCount:M,hasRelationFilters:y,hasRelationSort:S,filterTree:h,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new v(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let o=t.columns?.some(s=>s.name===n),i=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!o&&!i)throw new v(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,o){let i=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!i){if(/^_(count|max|min)\(/.test(n))throw new v(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=i[1],a=i[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new v(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===h);if(!m)throw new v(`Sort relation '${h}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new v(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new v(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=a.slice(0,u).trim(),f=a.slice(u+1).trim();if(!l||!f)throw new v(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=t.relations?.find(h=>h.propertyName===l);if(!c)throw new v(`Sort relation '${l}' does not exist on '${e}'.`);if(c.type!=="one-to-many"&&c.type!=="many-to-many")throw new v(`Sort function '_${s}(${l}.${f})' is only supported for list relations on '${e}'.`);let p=c.targetTableName||c.targetTable,d=o?.tables?.get(p);if(!d)throw new v(`Sort function '${n}' references unknown target table '${p}' on '${e}'.`);let g=d.columns?.find(h=>h.name===f),y=f==="id"&&d.columns?.some(h=>h.name==="_id");if(!g&&!y)throw new v(`Sort field '${f}' does not exist on '${p}' for function '_${s}(${l}.${f})'.`);if(g?.isEncrypted===!0)throw new v(`Encrypted field '${f}' on '${p}' cannot be used for sort.`);return{functionName:s,relationName:l,aggregateField:f,relationMeta:c}}registerSortJoinChain(e,t,n,o,i){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=o.registerWithParent(t,a,n,"left",i,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,o,c)}};pe();Mt();var mo=new Set(["count","sum","avg","min","max","countRecords"]),bo=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),_o=new Set(["_and","_or","_not"]);function Re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function j(r,e){let t=r.replace(/^aggregate\./,"");throw new v(e,{path:r,aggregate:{[t]:e}})}function wo(r){return typeof r!="string"?!1:bo.has(r.toLowerCase())}function Jr(r){return Object.keys(r).length===0}function $o(r,e,t){return r===!0?{}:(r==null&&j(t,`aggregate.${e} condition must be true or an object`),Re(r)||j(t,`aggregate.${e} condition must be true or an object`),r)}function So(r,e,t){let n=r?.tables?.get(e);return n||j(t,`Table "${e}" metadata is not available`),n}function qr(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&j(e,"aggregate.countRecords relation target is not available"),t}function yn(r,e,t,n){let o=So(t,e,n);for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){Array.isArray(s)||j(n,`aggregate.countRecords ${i} condition must be an array`);for(let f of s)Re(f)||j(n,`aggregate.countRecords ${i} items must be objects`),yn(f,e,t,n);continue}if(i==="_not"){Re(s)||j(n,"aggregate.countRecords _not condition must be an object"),yn(s,e,t,n);continue}(i.startsWith("_")||_o.has(i))&&j(n,`Unsupported aggregate.countRecords condition key "${i}"`);let a=o.columns?.find(f=>f.name===i),u=o.relations?.find(f=>f.propertyName===i);if(!a&&!u&&j(n,`Unknown aggregate.countRecords field or relation "${i}" on table "${e}"`),Re(s)||j(n,`aggregate.countRecords condition for "${i}" must be an object`),a){for(let f of Object.keys(s))ie.has(f)||j(n,`aggregate.countRecords condition for "${i}" only supports field operators`);continue}let l=qr(u,n);yn(s,l,t,n)}}function Hn(r){return Re(r)&&Object.keys(r).length>0}function Ze(r,e,t){if(!Hn(r))return[];Re(r)||j("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||j("aggregate",`Table "${e}" metadata is not available`);let o=[];for(let[i,s]of Object.entries(r)){let a=`aggregate.${i}`;(!i||typeof i!="string")&&j("aggregate","aggregate field name must be a non-empty string"),Re(s)||j(a,"aggregate field config must be an object");let u=i,l=a,f=n.columns?.find(d=>d.name===i),c=n.relations?.find(d=>d.propertyName===i);!f&&!c&&j(l,`Unknown aggregate field or relation "${i}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&j(l,"aggregate field must define at least one operation");for(let[d,g]of p){mo.has(d)||j(l,`Unsupported aggregate operation "${d}"`);let y=$o(g,d,l);if(c&&d!=="countRecords"&&j(l,`aggregate.${d} is not supported on relation "${i}"; use countRecords`),f&&d==="countRecords"&&j(l,`aggregate.countRecords requires a relation, but "${i}" is a field`),f&&(d==="sum"||d==="avg")&&!wo(f.type)&&j(l,`aggregate.${d} requires a numeric field, but "${i}" is "${f.type}"`),f)for(let h of Object.keys(y))ie.has(h)||j(l,`aggregate.${d} condition for "${i}" only supports field operators`);if(c&&d==="countRecords"){let h=qr(c,l);yn(y,h,t,l)}o.push({field:i,outputKey:u,path:l,op:d,condition:y})}}return o}function et(r,e){let t=[];return Re(r)&&!Jr(r)&&t.push(r),Jr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function xe(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var tt=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new J;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(Q(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let o=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),i=0,s=0;(o.includes("totalCount")||o.includes("*"))&&(i=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&re(n.mongoRawFilter,u);if((o.includes("filterCount")||o.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?Ee(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(o.includes("filterCount")||o.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(o.length>0||c)&&{meta:{...o.includes("totalCount")||o.includes("*")?{totalCount:i}:{},...o.includes("filterCount")||o.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,o=this.metadata?.tables?.get(e.table),i=o?.relations&&o.relations.length>0;if(e.fields&&e.fields.length>0||n||i){let l=e.plan,f=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&l?.fieldTree){if(e.mongoFieldsExpanded=Kr(l.fieldTree,this.metadata),n){let c=await It(this.metadata,e.table,[],e.deep),p=new Set(e.mongoFieldsExpanded.relations.map(d=>d.propertyName));e.mongoFieldsExpanded.relations.push(...c.relations.filter(d=>!p.has(d.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await It(this.metadata,e.table,f,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let c=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:c.scalarFields},t=c.hiddenFields}}e.where&&(e.where=e.where.map(l=>l.field.includes(".")?l:{...l,field:`${e.table}.${l.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(ae);let{results:a,pipeline:u}=await Qn(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:o}=await Qn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,n}async executeAggregate(e,t){let n=Ze(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={},i=this.db.collection(e.table);for(let s of n){let a=et(t,s);Q(a,e.table,e.metadata);let l=new J().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);xe(o,s,p);continue}let f=l.hasRelationFilters?await me(a,e.table,e.metadata,this.db):l.filterTree?Ee(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await i.countDocuments(f);else{let[{value:p}={value:null}]=await i.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}xe(o,s,c)}return o}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(i.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[i.foreignKeyColumn]:{$in:c}}]})}if(i.type==="many-to-many"){let f=de(e.table,i);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(y=>y!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(y=>y[f.otherColumn]).filter(y=>y!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(i.type==="many-to-one"||i.type==="one-to-one"){let f=i.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};Q(t,e,n);let i=new J().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return i.hasRelationFilters?await me(t,e,n,this.db):i.filterTree?Ee(i.filterTree,{metadata:n,rootTable:e}):{}}};var mn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};pe();le();var To=["_and","_or","_not"];function _e(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>_e(e));for(let e of Object.keys(r))if(To.includes(e)||typeof r[e]=="object"&&r[e]!==null&&_e(r[e]))return!0;return!1}var zr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function ko(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function bn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let o=t.columns.find(s=>s.name===n);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function Fo(r,e,t,n,o){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||bn(r,t,o),e}function Vr(r,e,t,n,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,u=ve(a,i??"postgres"),l=bn(e,o,s),f=Fo(e,n,o,i,s);switch(t){case"_eq":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",f);break;case"_neq":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",f);break;case"_gt":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",f);break;case"_gte":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",f);break;case"_lt":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",f);break;case"_lte":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",f);break;case"_in":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]),l&&i==="postgres"&&c.every(d=>typeof d=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[c]):r.whereIn(a,c);break;case"_not_in":case"_nin":let p=n;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(d=>d.trim()):[p]),l&&i==="postgres"&&p.every(d=>typeof d=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[p]):r.whereNotIn(a,p);break;case"_contains":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,ko(t),n)}}function Co(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.some(s=>s.name===n),i=t.relations?.some(s=>s.propertyName===n);return o||i}function nt(r,e,t,n="and",o,i){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){nt(this,s,t,"and",o,i)}):r.orWhere(function(){nt(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e))if(Co(s,t,i)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){nt(this,u,t,"and",o,i)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){nt(this,u,t,"and",o,i)})});continue}if(s==="_not"){r.whereNot(function(){nt(this,a,t,"and",o,i)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>zr.includes(l)))for(let[l,f]of Object.entries(a))zr.includes(l)&&(n==="and"?r.where(function(){Vr(this,s,l,f,t,o,i)}):r.orWhere(function(){Vr(this,s,l,f,t,o,i)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s,f=ve(l,o??"postgres");bn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${f} = ?::uuid`,[a]):r.orWhereRaw(`${f} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,l=ve(u,o??"postgres");bn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function ce(r,e,t,n,o){return!e||typeof e!="object"||nt(r,e,t,"and",n,o),r}le();function Xn(r,e,t){return`${C(r,t)}.${C(e,t)}`}function Ie(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Hr(r,e){if(!e)return!1;let t=e.columns.find(o=>o.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function rt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function Zn(r,e,t,n,o,i){let s=[];for(let[a,u]of Object.entries(i)){let l=await Lt(r,e,a,u,t,n,o);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Xn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=rt(d._is_null),y=rt(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(y===!0)s.push(`${c} IS NOT NULL`);else if(y===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let h=Ie(d._eq,n);s.push(`${c} = ${h}`)}else if(d._neq!==void 0){let h=Ie(d._neq,n);s.push(`${c} != ${h}`)}else if(d._in!==void 0){let m=(Array.isArray(d._in)?d._in:[d._in]).map(b=>Ie(b,n)).join(", ");s.push(`${c} IN (${m})`)}else if(d._not_in!==void 0||d._nin!==void 0){let h=d._not_in??d._nin,b=(Array.isArray(h)?h:[h]).map(S=>Ie(S,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let h=Ie(d._gt,n);s.push(`${c} > ${h}`)}else if(d._gte!==void 0){let h=Ie(d._gte,n);s.push(`${c} >= ${h}`)}else if(d._lt!==void 0){let h=Ie(d._lt,n);s.push(`${c} < ${h}`)}else if(d._lte!==void 0){let h=Ie(d._lte,n);s.push(`${c} <= ${h}`)}}}}}return s}function er(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function Gn(r,e,t,n,o,i){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(er(l)){let f=e(t).select(`${t}.id`);await je(e,f,l,t,n,o,i),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=H(l,n),p=await Zn(e,t,n,o,i,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(er(a)){let u=e(t).select(`${t}.id`);await je(e,u,a,t,n,o,i),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=H(a,n),f=await Zn(e,t,n,o,i,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Gr(r,e,t,n,o){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let i=e;Object.keys(i.fieldFilters).length===0&&i.subqueries.length===0||r.where(function(){Object.keys(i.fieldFilters).length>0&&ce(this,i.fieldFilters,t,o,n);for(let s of i.subqueries)this.whereRaw(s)})}function Yn(r,e,t,n,o){let i=!0;for(let s of e){let a=function(){for(let u of s)Gr(this,u,t,n,o)};i?(r.where(a),i=!1):r.orWhere(a)}}function _n(r,e,t,n,o,i,s){let a=Hr(e,o),u=Hr(n,i),l=`${C(r,s)}.${C(e,s)}`,f=`${C(t,s)}.${C(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Lt(r,e,t,n,o,i,s){let a=o.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(_n(u,a.foreignKeyColumn,e,"id",f,o,i));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(_n(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,i))).whereRaw(_n(a.junctionTableName,a.junctionSourceColumn,e,"id",p,o,i));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(_n(u,"id",e,a.foreignKeyColumn,f,o,i));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await je(r,c,n,u,f,i,s):c=ce(c,n,u,i,f||void 0):c=ce(c,n,u,i),c.toString()}async function je(r,e,t,n,o,i,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Gn(l._or,r,n,o,i,s);e.where(function(){Yn(this,f,n,o,i)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await je(r,e,f,n,o,i,s);else await je(r,e,l,n,o,i,s);return}if(t._or&&Array.isArray(t._or)){let l=await Gn(t._or,r,n,o,i,s);e.where(function(){Yn(this,l,n,o,i)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(er(d)){let g=r(n).select(`${n}.id`);await je(r,g,d,n,o,i,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:y}=H(d,o),h=await Zn(r,n,o,i,s,y);p.push({fieldFilters:g,subqueries:h})}e.whereNot(function(){for(let d of p)Gr(this,d,n,o,i)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Gn(l._or,r,n,o,i,s);e.whereNot(function(){Yn(this,p,n,o,i)});return}let{fieldFilters:f,relationFilters:c}=H(l,o);e.whereNot(function(){Object.keys(f).length>0&&ce(this,f,n,i,o)});for(let[p,d]of Object.entries(c)){let g=await Lt(r,n,p,d,o,i,s);if(g===null){let y=o.relations.find(h=>h.propertyName===p);if(y&&y.foreignKeyColumn){let h=Xn(n,y.foreignKeyColumn,i),b=d.id;if(b&&typeof b=="object"){let S=rt(b._is_null),_=rt(b._is_not_null);if(S===!0)e.whereRaw(`${h} IS NOT NULL`);else if(S===!1)e.whereRaw(`${h} IS NULL`);else if(_===!0)e.whereRaw(`${h} IS NULL`);else if(_===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let $=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${$.map(()=>"?").join(", ")})`,$)}else if(b._not_in!==void 0||b._nin!==void 0){let $=b._not_in??b._nin,k=Array.isArray($)?$:[$];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=H(t,o);Object.keys(a).length>0&&ce(e,a,n,i,o);for(let[l,f]of Object.entries(u)){let c=await Lt(r,n,l,f,o,i,s);if(c===null){let p=o.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Xn(n,p.foreignKeyColumn,i),y=f.id;if(y&&typeof y=="object"){let h=rt(y._is_null),m=rt(y._is_not_null);if(h===!0)e.whereRaw(`${d} IS NULL`);else if(h===!1)e.whereRaw(`${d} IS NOT NULL`);else if(m===!0)e.whereRaw(`${d} IS NOT NULL`);else if(m===!1)e.whereRaw(`${d} IS NULL`);else if(y._eq!==void 0)e.whereRaw(`${d} = ?`,[y._eq]);else if(y._neq!==void 0)e.whereRaw(`${d} != ?`,[y._neq]);else if(y._in!==void 0){let b=Array.isArray(y._in)?y._in:[y._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(y._not_in!==void 0||y._nin!==void 0){let b=y._not_in??y._nin,S=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${S.map(()=>"?").join(", ")})`,S)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Le(r,e,t,n,o,i,s){await je(r,e,t,n,o,i,s)}le();nr();ze();le();function it(r,e,t,n,o){for(let i of e){let s=i.field.split("."),a=t||s[0],u=s[s.length-1],l=Bt(n,a,u,i.value);switch(i.operator){case"=":r=r.where(i.field,"=",l);break;case"!=":r=r.where(i.field,"!=",l);break;case">":r=r.where(i.field,">",l);break;case"<":r=r.where(i.field,"<",l);break;case">=":r=r.where(i.field,">=",l);break;case"<=":r=r.where(i.field,"<=",l);break;case"like":r=r.where(i.field,"like",l);break;case"in":let f=Array.isArray(i.value)?i.value.map(y=>Bt(n,a,u,y)):[l];r=r.whereIn(i.field,f);break;case"not in":let c=Array.isArray(i.value)?i.value.map(y=>Bt(n,a,u,y)):[l];r=r.whereNotIn(i.field,c);break;case"is null":r=r.whereNull(i.field);break;case"is not null":r=r.whereNotNull(i.field);break;case"_contains":r=r.where(i.field,"like",`%${i.value}%`);break;case"_starts_with":r=r.where(i.field,"like",`${i.value}%`);break;case"_ends_with":r=r.where(i.field,"like",`%${i.value}`);break;case"_between":let p=i.value;if(typeof p=="string"&&(p=p.split(",").map(y=>y.trim())),Array.isArray(p)&&p.length===2){let y=Bt(n,a,u,p[0]),h=Bt(n,a,u,p[1]);r=r.whereBetween(i.field,[y,h])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(i.field):r.whereNotNull(i.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(i.field):r.whereNull(i.field);break}}return r}function Dt(r,e,t,n){let o=[],i=t;if(!r||typeof r!="object")return o;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let f=Dt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=Dt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Dt(a,e,t,n);u.length>0&&o.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let f=`${C(e,n)}.${C(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=i.columns?.find(y=>y.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")o.push(`${f} = ${c}`);else if(u==="_neq")o.push(`${f} != ${c}`);else if(u==="_gt")o.push(`${f} > ${c}`);else if(u==="_gte")o.push(`${f} >= ${c}`);else if(u==="_lt")o.push(`${f} < ${c}`);else if(u==="_lte")o.push(`${f} <= ${c}`);else if(u==="_is_null")o.push(`${f} IS NULL`);else if(u==="_is_not_null")o.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):o.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);o.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${C(e,n)}.${C(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),o.push(`${u} = ${l}`)}return o}function Xr(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Bt(r,e,t,n){if(n==null)return n;let o=r?.tables?.get(e);if(!o?.columns)return n;let i=o.columns.find(s=>s.name===t);if(!i)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}le();Kt();Ue();async function ei(r,e,t,n,o,i,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(ir(),Zr)),u=await a(e,t,n,o,i,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function or(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function ti(r,e,t,n,o){let i=r.targetTableName||r.targetTable;if(!i)return null;let s=r.foreignKeyColumn||z(r.propertyName);if(!s)return null;let a=c=>C(c,o),u=n?.tables?.get(i),f=(u?G(u):null)?.name||"id";return`(SELECT ${a(i)}.${a(e)} FROM ${a(i)} WHERE ${a(i)}.${a(f)} = ${a(t)}.${a(s)})`}Kt();var st=class r{constructor(e,t,n,o){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=o;this.logger=new mn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let o=e.debugTrace;if(e.filter&&Q(e.filter,e.tableName,e.metadata),!e.plan){let w=new J;e={...e,plan:w.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let i=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!u&&!a&&l){o&&o.setQueryPath("simple");let w=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),w}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(w=>w.trim())));let p=e.filter;if(e.filter&&!_e(e.filter)){c.where=[];for(let[w,F]of Object.entries(e.filter))if(typeof F=="object"&&F!==null)for(let[x,ue]of Object.entries(F)){let A;if(x==="_eq")A="=";else if(x==="_neq")A="!=";else if(x==="_in")A="in";else if(x==="_not_in"||x==="_nin")A="not in";else if(x==="_gt")A=">";else if(x==="_gte")A=">=";else if(x==="_lt")A="<";else if(x==="_lte")A="<=";else if(x==="_contains")A="_contains";else if(x==="_starts_with")A="_starts_with";else if(x==="_ends_with")A="_ends_with";else if(x==="_between")A="_between";else if(x==="_is_null")A="_is_null";else if(x==="_is_not_null")A="_is_not_null";else if(x==="_like")A="like";else if(x==="_ilike")A="ilike";else continue;c.where.push({field:w,operator:A,value:ue})}else c.where.push({field:w,operator:"=",value:F})}if(e.sort){let w=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(F=>F.trim());c.sort=w.map(F=>{let x=F.trim();return x.startsWith("-")?{field:x.substring(1),direction:"desc"}:{field:x,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,y=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=y===void 0||Number.isNaN(y)?void 0:y;h&&g!==void 0?(c.offset=(h-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let m=e.plan?.sortItems??(c.sort??[]).map(w=>({joinId:null,field:w.field,direction:w.direction,fullPath:w.field})),b=[],S=[];for(let w of m){if(w.function==="count"){let F={sql:this.buildRelationCountSortSubquery(c.table,w),direction:w.direction};S.push(F);continue}if(w.function==="max"||w.function==="min"){let F={sql:this.buildRelationAggregateSortSubquery(c.table,w),direction:w.direction};S.push(F);continue}if(w.joinId===null){if(w.field.includes(".")&&!e.plan){let x=w.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(q=>q.propertyName===x))continue}let F={field:w.field.includes(".")?w.field:`${c.table}.${w.field}`,direction:w.direction};b.push(F),S.push(F)}else{let F=e.plan?.joins.find(x=>x.id===w.joinId);if(F&&(F.relationType==="many-to-one"||F.relationType==="one-to-one")){let x=ti(F.relationMeta,w.field,c.table,this.metadata,this.dbType);if(x){let ue={sql:x,direction:w.direction};S.push(ue)}}}}let _=[];if(c.fields&&c.fields.length>0||u||a){let w=or(this.metadata),F=c.fields&&c.fields.length>0?c.fields:["*"],x=await ei(this.knex,c.table,F,w,this.dbType,this.maxQueryDepth,e.deep);x.select.length>0&&(c.select=[...c.select||[],...x.select]),_=x.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(w=>w.field.includes(".")?w:{...w,field:`${c.table}.${w.field}`})),c.sort=b;let $=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(w=>w.trim()).filter(Boolean),N=k.includes("filterCount")||k.includes("*"),R=k.includes("totalCount")||k.includes("*");if(c.select){let w=c.select.map(F=>typeof F=="string"&&F.trim().startsWith("(")?this.knex.raw(F):typeof F=="string"&&/ as /i.test(F)?this.knex.raw(F):F);$=$.select(w)}if(N&&$.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),R){let w=C(c.table,this.dbType);$.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) as __total_count__`))}let M=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(_e(p)||Object.keys(p).length>0)){let w=this.metadata?.tables?.get(c.table);(!M&&w&&w.relations&&w.relations.length>0?H(p,w).hasRelations:!1)?await Le(this.knex,$,p,c.table,w,this.dbType,x=>this.metadata?.tables?.get(x)):e.plan?.filterTree?te($,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),$=ce($,p,c.table,this.dbType,w))}else c.where&&c.where.length>0&&($=it($,c.where,c.table,this.metadata,this.dbType));for(let w of S)if(w.field){let F=w.field.includes(".")?w.field:`${c.table}.${w.field}`;$=$.orderBy(F,w.direction)}else w.sql&&($=$.orderByRaw(`${w.sql} ${w.direction.toUpperCase()}`));c.groupBy&&($=$.groupBy(c.groupBy)),c.offset&&($=$.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&($=$.limit(c.limit));let T=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:$.toSQL().toNative()});let L;if(e.debugMode&&(L=$.toSQL().toNative().sql),e.debugMode&&o){let w=$.toSQL().toNative();o.setSql(w.sql);try{let F=w.sql.replace(/\$\d+/g,"?"),x=await this.knex.raw(`EXPLAIN ${F}`,w.bindings);o.setExplain(this.dbType==="postgres"?x.rows:x[0])}catch(F){o.setExplain({error:String(F)})}}let I,O=performance.now();I=await $,o&&o.dur("db_execute",O,{table:e.tableName});let B=0;if(N&&I.length>0&&(B=Number(I[0].__filter_count__||0),I.forEach(w=>{delete w.__filter_count__})),R&&I.length>0&&I[0].__total_count__!==void 0&&(T=Number(I[0].__total_count__||0),I.forEach(w=>{delete w.__total_count__})),_&&_.length>0&&I.length>0){let w=or(this.metadata);if(w){let{executeBatchFetches:F}=await Promise.resolve().then(()=>(lr(),ni));await F(this.knex,I,_,w,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,o)}}if(this.knexService){let w=performance.now();I=await this.knexService.parseResult(I,c.table),o&&o.dur("db_parseResult",w,{table:e.tableName})}else{let w=(F,x)=>{if(!F||!this.metadata)return F;let ue=this.metadata.tables?.get(x);if(!ue)return F;if(Array.isArray(F))return F.map(q=>w(q,x));if(typeof F!="object"||Buffer.isBuffer(F))return F;let A={...F};for(let q of ue.columns)if(q.type==="simple-json"&&A[q.name]&&typeof A[q.name]=="string")try{A[q.name]=JSON.parse(A[q.name])}catch{}for(let[q,Y]of Object.entries(A))if(Y&&typeof Y=="object"&&!Array.isArray(Y)&&!Buffer.isBuffer(Y)){let Fn=Y;if(Fn.id!==void 0||Fn.createdAt!==void 0){let lt=ue.relations?.find(ct=>ct.propertyName===q);lt&&(A[q]=w(Y,lt.targetTableName))}}else if(Array.isArray(Y)&&Y.length>0&&typeof Y[0]=="object"&&Y[0].id!==void 0){let lt=ue.relations?.find(ct=>ct.propertyName===q);lt&&(A[q]=Y.map(ct=>w(ct,lt.targetTableName)))}return A};I=w(I,c.table)}o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName}));let P=await this.executeAggregate(c,p);return{data:I,...(k.length>0||P)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:T}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:B}:{},...P?{aggregate:P}:{}}},...L!==void 0&&{sql:L}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=G(s)?.name||"id",u=C(e,this.dbType),l=C(a,this.dbType);if(!n||!i)throw new v(`Sort relation '${o}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new v(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let c=C(i,this.dbType),p=C(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=this.resolveManyToManyContract(n,o,e),c=C(f.tableName,this.dbType),p=C(f.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new v(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),l=G(a)?.name||"id",f=G(u)?.name||"id",c=C(e,this.dbType),p=C(l,this.dbType),d=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!d||!n||!s||!i)throw new v(`Sort function '${t.field}' is not supported on '${e}'.`);let g=C(s,this.dbType),y=C(i,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new v(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let m=C(h,this.dbType);return`(SELECT ${d}(${g}.${y}) FROM ${g} WHERE ${g}.${m} = ${c}.${p})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,o,e),m=C(h.tableName,this.dbType),b=C(h.sourceColumn,this.dbType),S=C(h.targetColumn,this.dbType),_=C(f,this.dbType);return`(SELECT ${d}(${g}.${y}) FROM ${m} JOIN ${g} ON ${g}.${_} = ${m}.${S} WHERE ${m}.${b} = ${c}.${p})`}throw new v(`Sort function '_${t.function}(${o}.${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new v(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(n).select(o);t.filterTree&&te(i,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let m=h.field.includes(".")?h.field:`${n}.${h.field}`;i=i.orderBy(m,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=C(n,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let h=i.toSQL().toNative();if(f=h.sql,l){l.setSql(h.sql);try{let m=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,h.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){l.setExplain({error:String(m)})}}}let c=performance.now(),p;p=await i,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(h=>delete h.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(h=>delete h.__total_count__));let y=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||y)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...y?{aggregate:y}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=Ze(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={};for(let i of n){let s=et(t,i);Q(s,e.table,e.metadata);let u=new J().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(i.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,i);xe(o,i,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Le(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&te(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${C(e.table,this.dbType)}.${C(i.field,this.dbType)}`,c=i.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${i.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();xe(o,i,p?.value??0)}return o}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table),i=o?.relations?.find(c=>c.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new J().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Le(this.knex,u,t,e.table,o,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&te(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){Q(n.condition,s,e.metadata);let p=new J().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Le(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&te(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(i.type==="one-to-many")l.whereIn(`${s}.${i.foreignKeyColumn}`,u);else if(i.type==="many-to-many"){let c=this.resolveManyToManyContract(i,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(i.type==="many-to-one"||i.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${i.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${i.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var $n=require("mongodb"),at=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,Sn.mkdirSync)((0,ri.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!$n.ObjectId)return e;if(typeof e=="string")try{return new $n.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),o=qe(n,e,t,this.dbType);return o._id!==void 0&&(o._id=this.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,n){let o=await this.getMetadataForQuery();return{query:it(e,t,n??"",o,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.mongoService.insertOne(e.table,n);t.push(ae(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.knexService.insertWithCascade(e.table,n);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),o=performance.now(),s=new J().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",o,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb")return new tt(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new st(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(i).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);if(e.returning){let i=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(i,e.where,e.table),await i.select(e.returning)}return{affected:o.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(o).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let i=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,i)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n.count("* as count").first();return Number(o?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",i):t.id=this.normalizeWhereFilterValue("id",i):t[o]=this.normalizeWhereFilterValue(o,i);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof $n.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,o]of Object.entries(e))t[n]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[n,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.entries(o)[0];if(i){let[s,a]=i,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return ae(a)}let o=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),s=o||t.id;return await i(e).where("id",s).first()})}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let o of n)this.batchInserts.items.push({table:e,data:o});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...n.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.mongoService.insertOne(e,o.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.knexService.insertWithCascade(e,o.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let o=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,o)),this.runBatchInsertWithIsolation(e,t.slice(o))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let o=t.get(n.table);o?o.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,o=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let i=e[n++];await t(i)}});await Promise.all(o)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,Sn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
53
- `)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return ae(i)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let o=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:o}=await this.applyWhereToKnex(o,s,e))}let i=await o.count("* as count").first();return Number(i?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let o=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:o})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[i,s]of Object.entries(t))i==="id"||i==="_id"?o._id=this.safeObjectId(s):o[i]=s;return this.mongoService.findOne(e,o)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?o._id=this.safeObjectId(u):o[a]=u;return await this.mongoService.collection(e).find(o).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=n||t.id;return await o(e).where("id",i).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let i=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await i.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await i.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};lr();sr();ir();le();Kt();Ge();pe();ze();var ii=new Set(["fields","filter","sort","limit","page","deep"]),kn=3;function cr(r,e,t,n=0,o=3){if(!e||typeof e!="object")return;if(n>=o)throw new v(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(r),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let l=s.get(a);if(!l)throw new v(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!ii.has(p))throw new v(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...ii].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new v(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new v(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(Q(u.filter,c,t),Pe(u.filter,c,t),Tn(u.filter,0,a,r)),u.sort){hn(u.sort,c,t);let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;vo(g,c,t,a,r)}}u.deep&&cr(c,u.deep,t,n+1,o)}}}function vo(r,e,t,n,o){if(r.includes("."))throw new v(`Sort field '${r}' is not supported for relation '${n}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new v(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${o}')`);let s=i.columns?.some(u=>u.name===r),a=r==="id"&&i.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new v(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${o}')`)}var Io=new Set(["_and","_or","_not"]);function Tn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[o,i]of Object.entries(r)){if(Io.has(o)){if(Array.isArray(i))for(let l of i)Tn(l,e,t,n);else i&&typeof i=="object"&&Tn(i,e,t,n);continue}if(o.startsWith("_")||!i||typeof i!="object"||Array.isArray(i)||!Object.keys(i).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>kn)throw new v(`Filter path exceeds max dotted hops of ${kn} at '${o}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(i))l.startsWith("_")||(u[l]=i[l]);Tn(u,a,t,n)}}function oi(r,e,t,n){return!r||typeof r!="object"?r:Wt(r,e,t,n)}function Wt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let i=r.map(s=>Wt(s,e,t,n)).filter(s=>s!=null);return i.length>0?i:null}let o={};for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){let c=(Array.isArray(s)?s:[s]).map(p=>Wt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(o[i]=c);continue}if(i==="_not"){let f=Wt(s,e,t,n);f!=null&&Object.keys(f).length>0&&(o[i]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===i);if(u){if(!n(e,i,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Wt(s,f,t,n);c!=null&&Object.keys(c).length>0&&(o[i]=c);continue}if(a?.columns?.find(f=>f.name===i)){if(!n(e,i,"column"))continue;o[i]=s;continue}o[i]=s}return o}function si(r,e,t,n){if(!r)return r;let o=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,y=t?.tables?.get(c);if(!y){f=!1;break}if(g)y.columns?.find(m=>m.name===d)?n(c,d,"column")||(f=!1):y.relations?.find(b=>b.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let h=y.relations?.find(m=>m.propertyName===d);if(!h){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=h.targetTableName||h.targetTable||c}}f&&i.push(s)}if(i.length!==0)return Array.isArray(r)?i:i.join(",")}At();ze();Ot();dn();Mt();Ue();pe();function No(r){let e=new at({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,o=()=>(t||(t=new We({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),i=()=>(n||(n=new Be({isolatedExecutorService:o()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return o()},get executorEngineService(){return i()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
52
+ }`}var jr="mongo-fold-text-search.body.txt",qe=null;function Xi(){let r=[Kn.join(__dirname,jr),Kn.join(process.cwd(),"dist","kernel","query","utils",jr)];for(let e of r)try{if(sn.existsSync(e))return sn.readFileSync(e,"utf8")}catch{}return null}function an(){if(qe!==null)return qe;let r=Xi();return r?(qe=r,qe):(qe=on(),qe)}var Se=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof Se.ObjectId)return n;if(typeof n=="string")try{return new Se.ObjectId(n)}catch{return n}return n}let o=r?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.ObjectId(n)}catch{return n}return n}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.ObjectId(n)}catch{return n}return n}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new Se.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new Se.ObjectId(n)}catch{return n}return n;default:return n}}var ln="__mongoFoldTextTriples";function Zi(r){return r==="_id"?"$_id":`$${r}`}function ze(r,e,t,n){let o=Zi(e),i=r[ln]??[];i.push({ref:o,needle:t,mode:n}),r[ln]=i}function eo(r){let e=r[ln];if(delete r[ln],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:an(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}function Ve(r,e,t,n){let o={},i=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";i&&a==="id"&&(a="_id");let l=W(r,u,a,s.value);switch(s.operator){case"=":o[a]=l;break;case"!=":o[a]={$ne:l};break;case">":o[a]={$gt:l};break;case"<":o[a]={$lt:l};break;case">=":o[a]={$gte:l};break;case"<=":o[a]={$lte:l};break;case"like":o[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let c=d.map(m=>W(r,u,a,m));o[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(m=>m.trim()):[p]);let f=p.map(m=>W(r,u,a,m));o[a]={$nin:f};break;case"is null":o[a]=null;break;case"is not null":o[a]={$ne:null};break;case"_contains":ze(o,a,String(l),"contains");break;case"_starts_with":ze(o,a,String(l),"starts");break;case"_ends_with":ze(o,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(m=>m.trim())),Array.isArray(g)&&g.length===2){let m=W(r,u,a,g[0]),b=W(r,u,a,g[1]);o[a]={$gte:m,$lte:b}}break;case"_is_null":let y=l===!0||l==="true";o[a]=y?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=l===!0||l==="true";o[a]=h?{$ne:null}:{$eq:null};break}}return eo(o),o}function Br(r,e,t){let o=r?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function cn(r,e,t,n,o,i){switch(o){case"_contains":ze(e,n,String(i),"contains");break;case"_starts_with":ze(e,n,String(i),"starts");break;case"_ends_with":ze(e,n,String(i),"ends");break;case"_eq":e[n]=W(r,t,n,i);break;case"_neq":{let c=W(r,t,n,i);Br(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=i;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(f=>f.trim()):[c]);let p=c.map(f=>W(r,t,n,f));e[n]={$in:p};break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>W(r,t,n,c));Br(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:W(r,t,n,i)};break;case"_gte":e[n]={$gte:W(r,t,n,i)};break;case"_lt":e[n]={$lt:W(r,t,n,i)};break;case"_lte":e[n]={$lte:W(r,t,n,i)};break;case"_is_null":let u=i===!0||i==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=i===!0||i==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let d=i;if(typeof d=="string"&&(d=d.split(",").map(c=>c.trim())),Array.isArray(d)&&d.length===2){let c=W(r,t,n,d[0]),p=W(r,t,n,d[1]);e[n]={$gte:c,$lte:p}}break}}var Hn=require("mongodb");function ie(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let o of n)if(ie(o,e))return!0}}else if(t==="_not"){if(ie(n,e))return!0}else if(e.has(t))return!0;return!1}function Y(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let i=ie(r,o);return{fieldFilters:t,relationFilters:n,hasRelations:i}}jt();Bt();var pn="__mongoFoldTextTriples";function Pe(r,e){if(!r)return{};let t={};return Lt(r,t,e),Ce(t),t}function lo(r,e){if(!r)return{};let t={};return Jn(r,t,e),Ce(t),t}function me(r,e,t){if(!e)return{};let n=new se,{node:o}=he(e,t,r,n);return Pe(o,{metadata:r,rootTable:t})}function gn(r,e,t){if(!e)return{};let n=new se,{node:o}=he(e,t,r,n);return lo(o,{metadata:r,rootTable:t})}function Lt(r,e,t){switch(r.kind){case"true":return;case"false":ye(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=r.children.map(i=>{let s={};return Lt(i,s,t),Ce(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}ye(e,...o);return}case"or":{let o=r.children.map(s=>{let a={};return Lt(s,a,t),Ce(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;let i=e.$or;e.$or=i?[...i,...o]:o;return}case"not":{let n={};Lt(r.child,n,t),Ce(n);let o=e.$nor;e.$nor=o?[...o,n]:[n];return}case"compare":Ur(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Ur(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let o=i=>W(t.metadata,t.rootTable,n,i);switch(r.op){case"eq":te(e,n,o(r.value));return;case"neq":{let i=o(r.value);qn(t,n)?ye(e,{[n]:{$ne:null}},{[n]:{$ne:i}}):te(e,n,{$ne:i});return}case"gt":te(e,n,{$gt:o(r.value)});return;case"gte":te(e,n,{$gte:o(r.value)});return;case"lt":te(e,n,{$lt:o(r.value)});return;case"lte":te(e,n,{$lte:o(r.value)});return;case"in":{let i=Kr(r.value).map(o);te(e,n,{$in:i});return}case"not_in":{let i=Kr(r.value).map(o);qn(t,n)?ye(e,{[n]:{$ne:null}},{[n]:{$nin:i}}):te(e,n,{$nin:i});return}case"between":{let i=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&te(e,n,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":te(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Qn(e,n,String(r.value),"contains");return;case"starts_with":Qn(e,n,String(r.value),"starts");return;case"ends_with":Qn(e,n,String(r.value),"ends");return}}function Jn(r,e,t){switch(r.kind){case"true":ye(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let o=r.children.map(s=>{let a={};return Jn(s,a,t),Ce(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}let i=e.$or;e.$or=i?[...i,...o]:o;return}case"or":{let o=r.children.map(i=>{let s={};return Jn(i,s,t),Ce(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}ye(e,...o);return}case"not":Lt(r.child,e,t);return;case"compare":co(r,e,t);return;case"relation_exists":{te(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function co(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){te(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let o={};Ur(r,o,t),Ce(o);let i={$nor:[o]};qn(t,n)?ye(e,i,{[n]:{$ne:null}}):ye(e,i)}function te(r,e,t){r[e]===void 0?r[e]=t:(ye(r,{[e]:r[e]},{[e]:t}),delete r[e])}function ye(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function qn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(o=>o.name===e);return n?n.isNullable!==!1:!0}function Kr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function uo(r){return r==="_id"?"$_id":`$${r}`}function Qn(r,e,t,n){let o=uo(e),i=r[pn]??[];i.push({ref:o,needle:t,mode:n}),r[pn]=i}function Ce(r){let e=r[pn];if(delete r[pn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:an(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}async function be(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return me(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!ie(r,i))return me(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(c=>be(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(c=>be(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Vn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=Y(r,o),u=[];if(s&&Object.keys(s).length>0){let l=me(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,d]of Object.entries(a)){let c=await fo(l,d,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Vn(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return gn(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!ie(r,i))return gn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(c=>Vn(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(c=>Vn(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return be(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=Y(r,o),u=[];if(s&&Object.keys(s).length>0){let l=gn(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,d]of Object.entries(a)){let c=await go(l,d,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function fo(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?po(e,s,r,a,u,o,i):s.type==="one-to-many"?qr(e,s,t,a,u,o,i):s.type==="many-to-many"?zr(e,s,t,a,u,o,i):{}}async function po(r,e,t,n,o,i,s){let a=G(e)||t,u=yn(r),l=mn(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let d=Gn(u);if(d!==null){let g=bn(d.value);if(d.op==="eq")return{[a]:g};if(d.op==="neq")return{[a]:{$ne:g}};if(d.op==="in")return{[a]:{$in:g}};if(d.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await hn(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let f=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return f.length===0?{__impossible__:!0}:{[a]:{$in:f}}}async function go(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return ho(e,s,r,a,u,o,i);if(s.type==="one-to-many"){let l=await qr(e,s,t,a,u,o,i);return Jr(l)}if(s.type==="many-to-many"){let l=await zr(e,s,t,a,u,o,i);return Jr(l)}return{}}async function ho(r,e,t,n,o,i,s){let a=G(e)||t,u=yn(r),l=mn(u);if(l!==null)return l?{[a]:{$ne:null}}:{[a]:null};let d=Gn(u);if(d!==null){let g=bn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:g};if(d.op==="in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:g}}}let c=await hn(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{[a]:null};let f=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return f.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:f}},{[a]:{$ne:null}}]}}async function qr(r,e,t,n,o,i,s){let a=U(e)||t,u=yn(r),l=mn(u);if(l!==null){let p=await Qr(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let d=await hn(u,n,o,i,s);if(!d||Object.keys(d).length===0)return{};let c=await Qr(s,n,a,d);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function zr(r,e,t,n,o,i,s){let a=pe(t,e);if(!a)return{};let u=yn(r),l=mn(u);if(l!==null){let y=await zn(s,a,n,null);return l?y.length===0?{}:{_id:{$nin:y}}:y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let d=Gn(u);if(d!==null){let y=bn(d.value),h=Array.isArray(y)?y:[y],m=await zn(s,a,n,{_id:{$in:h}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let c=await hn(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let f=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);if(f.length===0)return{__impossible__:!0};let g=await zn(s,a,n,{_id:{$in:f}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function hn(r,e,t,n,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return ie(r,i)?be(r,e,n,o):me(n,r,e)}async function Qr(r,e,t,n){let o=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let u=a[t];if(u==null)continue;let l=String(u);i.has(l)||(i.add(l),s.push(u))}return s}function Jr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function zn(r,e,t,n){let o=null;n&&t&&(o=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await r.collection(e.junctionName).find(i,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let d=l[e.selfColumn];if(d==null)continue;let c=String(d);a.has(c)||(a.add(c),u.push(d))}return u}function yn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function mn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function bn(r){if(Array.isArray(r))return r.map(e=>bn(e));if(typeof r!="string")return r;try{return new Hn.ObjectId(r)}catch{return r}}function Gn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Hn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function Dt(r,e,t,n){let o=await At(r,e,t),i=[],s={},a={};if(n&&typeof n=="object")for(let[f,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let y=Object.keys(g)[0];y&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(y)?s[f]=g:a[f]=g}else s[f]=g;if(Object.keys(s).length>0){let f={};for(let[g,y]of Object.entries(s))if(typeof y=="object"&&y!==null)for(let[h,m]of Object.entries(y))cn(r,f,e,g,h,m);else f[g]=y;Object.keys(f).length>0&&i.push({$match:f})}let l=r?.tables?.get(e)?.relations||[],d=[];for(let[f,g]of Object.entries(a))if(!o.relations.some(h=>h.propertyName===f)){let h=l.find(m=>m.propertyName===f);if(h){let m="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")m=G(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")m="_id",b=U(h)||h.propertyName;else if(h.type==="many-to-many")continue;let w=h.type==="one-to-many"||h.type==="many-to-many";d.push({propertyName:f,targetTable:h.targetTableName,localField:m,foreignField:b,type:w?"many":"one",nestedFields:[]})}}let c=[...o.relations,...d];for(let f of c){let g=a[f.propertyName],y=f.nestedFields&&f.nestedFields.length>0?await Dt(r,f.targetTable,f.nestedFields,g):g?await Dt(r,f.targetTable,["_id"],g):[];f.type==="one"&&y.length>0&&y.push({$limit:1}),i.push({$lookup:{from:f.targetTable,localField:f.localField,foreignField:f.foreignField,as:f.propertyName,pipeline:y.length>0?y:void 0}}),f.type==="one"&&(i.push({$unwind:{path:`$${f.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Ge(g)||i.push({$match:{[f.propertyName]:{$ne:null}}})))}let p=l.filter(f=>!c.some(g=>g.propertyName===f.propertyName));if(o.scalarFields.length>0||o.relations.length>0||p.length>0){let f={_id:1};for(let y of o.scalarFields)f[y]=1;for(let y of c)f[y.propertyName]=1,y.type==="one"&&y.localField&&y.localField!==y.propertyName&&(f[y.localField]=1);if(t.includes("*"))for(let y of p){if(y.type==="one-to-many"||y.type==="many-to-many")continue;y.type==="many-to-many"?f[y.propertyName]={$map:{input:`$${y.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[y.propertyName]={$cond:{if:{$ne:[`$${y.propertyName}`,null]},then:{_id:`$${y.propertyName}`},else:null}}}i.push({$project:f})}return i}async function Vr(r,e,t,n,o){let i=r?.tables?.get(t),s=i?.relations||[],a=i?.columns||[],u=s.filter(d=>!o.some(c=>c.propertyName===d.propertyName)),l=n.length===a.length||n.length===0&&o.length===0;if(u.length>0||!l){let d={_id:1};for(let c of n)d[c]=1;for(let c of o)d[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(d[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?d[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:d})}}function Ge(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ge(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ge(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ge(e));if("_not"in r)return Ge(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ge(t)))return!0}return!1}Xe();var Kt=require("mongodb");Xe();_n();async function wn(r,e,t){let n=new Map,o=0;async function i(){for(;o<r.length;){let u=o++,l=r[u];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},i);return await Promise.all(a),n}var le="__sourceId__",Fe="__targetId__",Ze="__enfyra_target__",Wt="__enfyra_top_n_documents__",et=class{constructor(e,t,n,o=new Re){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=o;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/ae)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let o={...t};for(let i of n)o[i]=1;e.push({$project:o})}}appendTopNStages(e,t,n,o,i){e.push({$group:{_id:`$${t}`,[Wt]:{$topN:{sortBy:n,output:"$$ROOT",n:o+i}}}},{$project:{[Wt]:{$slice:[`$${Wt}`,o,i]}}},{$unwind:`$${Wt}`},{$replaceRoot:{newRoot:`$${Wt}`}})}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let o=n.field.split(".");if(o.length===1)t[o[0]]=n.order;else{let i=`__sort_${o.slice(0,-1).join("_")}`;t[`${i}.${o[o.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let o=n.startsWith("-"),i=o?n.slice(1):n;return{field:i==="id"?"_id":i,order:o?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let o=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),i=[{$match:t}],s=new Set;for(let l of o){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let f=0;f<c.length-1;f++){let g=c[f],y=this.normalizeMetadata()?.tables?.get(p);if(!y)break;let h=y.relations?.find(w=>w.propertyName===g);if(!h)break;let m=h.targetTableName||h.targetTable,b=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(b)){s.add(b);let w=G(h)||h.propertyName,S=f===0?null:`__sort_${c.slice(0,f).join("_")}`,T=S?`${S}.${w}`:w;i.push({$lookup:{from:m,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=m}}let a=this.buildSortFromTokens(n);a&&i.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&i.push({$project:u}),i}toObjectId(e){try{return typeof e=="string"?new Kt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Kt.ObjectId||t instanceof Kt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(o=>!o.field.includes("."));n.length!==0&&e.sort((o,i)=>{for(let s of n){let a=this.compareSortValues(o[s.field],i[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(o._id,i._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},o=[];for(let i of this.parseSortTokens(t))i.field.includes(".")||n[i.field]===void 0&&(n[i.field]=1,o.push(i.field));return{projection:n,hiddenFields:o}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let o of t)delete n[o]}keyOf(e){return e==null?"":e instanceof Kt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:o}=Ye(e),i={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])o.has(p.propertyName)||o.set(p.propertyName,["_id"])}else for(let p of n){let f=t.columns.find(g=>g.name===p);f?i[f.name]=1:t.relations?.find(y=>y.propertyName===p)&&!o.has(p)&&o.set(p,["_id"])}o.forEach((p,f)=>{let g=t.relations?.find(y=>y.propertyName===f);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[G(g)||g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((p,f)=>{let g=t.relations?.find(b=>b.propertyName===f);if(!g)return;let y=g.targetTableName||g.targetTable;if(!y)return;let h,m;g.type==="many-to-one"||g.type==="one-to-one"?Ae(g)?(h="_id",m=U(g)||g.propertyName):(h=G(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(h="_id",m=U(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(h="_id",m=g.mappedBy):(h=g.propertyName,m="_id")),a.push({relationName:f,type:g.type,targetTable:y,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:h,foreignField:m})});let u=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&l.length>0)for(let p of l)i[p.newName]===1&&i[p.oldName]!==1&&(i[p.oldName]=1,d.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:l,hiddenFields:d}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?me(this.normalizeMetadata(),o.userFilter,e):null,s=this.buildSortFromTokens(o?.userSort),a=await K(t,l=>{let d={_id:{$in:l}};i&&Object.keys(i).length>0&&Object.assign(d,i);let c={projection:n.projection};return s&&(c.sort=s),this.runQuery(()=>this.db.collection(e).find(d,c).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,o,i){let s=o.projection?{...o.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(m=>this.toObjectId(m))),u=i?.userFilter?me(this.normalizeMetadata(),i.userFilter,e):null,l=i?.userLimit,d=i?.userPage,c=this.hasDottedSort(i?.userSort);if(l!==void 0&&l>0){let m=d?(d-1)*l:0;if(c)throw new Error(`Dotted sort is not supported for batch relation '${i?.relationName}'`);let b=this.buildStableSort(i?.userSort),w=await K(a,async S=>{let T={[t]:{$in:S}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,m,l),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let R=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(R,o)});return{docs:w,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:w.length}}}if(s&&(s[t]=1),c){let m=[],b=await wn(a,async w=>{let S={[t]:w};u&&Object.keys(u).length>0&&Object.assign(S,u);let T=this.buildSortAggregatePipeline(e,S,i.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,o)},je);for(let w of b.values())for(let S of w)m.push(S);return{docs:m,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/je),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let f=this.buildSortFromTokens(i?.userSort)||{_id:1},g={projection:s,sort:f},y=await K(a,m=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:m},...u||{}},g).toArray())),h=this.applyReadFallback(y,o);return{docs:h,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let o=n.projection?{projection:n.projection}:void 0,i=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},o).toArray()));return this.applyReadFallback(i,n)}async fetchM2MTopK(e,t,n,o,i,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let m of e)u.set(this.keyOf(m),[]);let l=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,d=!i&&this.m2mSortCanUseJunction(t.userSort),c=this.parseSortTokens(t.userSort).find(m=>m.field==="_id")?.order??1,p=this.buildStableSort(t.userSort),f=await K(e,async m=>{if(d){let S=[{$match:{[n.selfColumn]:{$in:m}}}];return this.appendTopNStages(S,n.selfColumn,{[n.otherColumn]:c},s,a),S.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:c}},{$project:{_id:0,[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(S).toArray())).map(k=>({sourceId:k[le],targetId:k[Fe]}))}let b=[{$match:{[n.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ze}},{$unwind:`$${Ze}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ze}`,{[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&b.push({$match:i}),this.appendTopNStages(b,le,p,s,a),b.push({$sort:{[le]:1,...p}}),b.push({$project:{_id:0,[le]:1,[Fe]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(S=>({sourceId:S[le],targetId:S[Fe]}))});if(l){let m=new Map;for(let b of f){let w=this.keyOf(b.targetId);m.has(w)||m.set(w,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(m.get(w))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length,rowsDiscarded:0}}}let g=this.uniqueValues(f.map(m=>m.targetId)),y=await this.loadM2MTargets(t.targetTable,g,o),h=new Map(y.map(m=>[this.keyOf(m._id),m]));for(let m of f){let b=h.get(this.keyOf(m.targetId));b&&u.get(this.keyOf(m.sourceId))?.push(b)}return{grouped:u,docs:y,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(g.length>0?this.chunkCount(g):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length+y.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,o,i){let s=new Map;for(let y of e)s.set(this.keyOf(y),[]);let a=!i&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,l=this.buildStableSort(t.userSort),d=await K(e,async y=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:y}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(w=>({sourceId:w[n.selfColumn],targetId:w[n.otherColumn]}));let h=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ze}},{$unwind:`$${Ze}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ze}`,{[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&h.push({$match:i}),h.push({$sort:{[le]:1,...l}},{$project:{_id:0,[le]:1,[Fe]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(h).toArray())).map(b=>({sourceId:b[le],targetId:b[Fe]}))});if(o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1){let y=new Map;for(let h of d){let m=this.keyOf(h.targetId);y.has(m)||y.set(m,{_id:h.targetId}),s.get(this.keyOf(h.sourceId))?.push(y.get(m))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let p=this.uniqueValues(d.map(y=>y.targetId)),f=await this.loadM2MTargets(t.targetTable,p,o),g=new Map(f.map(y=>[this.keyOf(y._id),y]));for(let y of d){let h=g.get(this.keyOf(y.targetId));h&&s.get(this.keyOf(y.sourceId))?.push(h)}return{grouped:s,docs:f,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(p.length>0?this.chunkCount(p):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+f.length,rowsDiscarded:0}}}async fetchM2M(e,t,n,o,i){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=pe(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=this.uniqueValues(e.map(k=>k._id)),l=new Map;for(let k of e)l.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:l,docs:[]};let d=t.userFilter?me(this.normalizeMetadata(),t.userFilter,t.targetTable):null,c=t.userLimit,p=t.userPage;if(c!==void 0&&c>0){let k=p?(p-1)*c:0;return this.fetchM2MTopK(u,t,a,i,d,k,c)}let f=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1&&!d,g=this.hasDottedSort(t.userSort);if(!g)return this.fetchM2MEdgeBatch(u,t,a,i,d);let y=await K(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(y.length===0)return{grouped:l,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,m=[];for(let k of y){let R=k[a.otherColumn];if(R==null)continue;let I=this.keyOf(R);h.has(I)||(h.add(I),m.push(R))}let b=[],w=new Map;if(f)b=m.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:m}};d&&Object.keys(d).length>0&&Object.assign(k,d);let R;if(g){let I=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);i.projection&&I.push({$project:i.projection}),R=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(I).toArray())}else{let I=this.buildSortFromTokens(t.userSort)||{_id:1},O=this.projectionWithSortFields(i.projection,t.userSort),L={sort:I};O.projection&&(L.projection=O.projection),R=await K(m,$=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:$},...d||{}},L).toArray())),t.userSort?this.sortDocsInMemory(R,t.userSort):this.sortDocsByPk(R),this.removeHiddenFields(R,O.hiddenFields)}b=this.applyReadFallback(R,i)}for(let k of b)w.set(this.keyOf(k._id),k);let S=new Map;for(let k of y){let R=this.keyOf(k[a.selfColumn]),I=this.keyOf(k[a.otherColumn]);w.has(I)&&(S.has(I)||S.set(I,[]),S.get(I).push(R))}for(let k of b){let R=S.get(this.keyOf(k._id))||[];for(let I of R)l.get(I)?.push(k)}let T=f||m.length===0?0:this.chunkCount(m);return{grouped:l,docs:b,stats:{strategy:f?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let o=new Set(t.hiddenFields??[]);for(let i of e)for(let s of n)i[s.newName]===void 0&&i[s.oldName]!==void 0&&(i[s.newName]=i[s.oldName]),(o.has(s.oldName)||i[s.newName]!==void 0)&&delete i[s.oldName];return e}};async function $n(r,e,t,n,o=3,i=0,s,a,u,l){let d=await l?.getActiveFieldRenamesByTable?.(),c=new et(r,a,d);await new ke(c,n,u).execute(e,t,o,i,s)}async function Zn(r,e,t){let n=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,u=i?.tables?.get(e.table),l=new Set((u?.relations??[]).map($=>$.propertyName)),d=!!e.mongoRawFilter&&!!i&&ie(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&d){let $=await be(e.mongoRawFilter,e.table,i,o);$&&Object.keys($).length>0&&n.push({$match:$})}else if(p){let $=Pe(c.filterTree,{metadata:i,rootTable:e.table});Object.keys($).length>0&&n.push({$match:$})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let $=Ve(i,e.where,e.table,s);n.push({$match:$})}let f=e.plan,y=f?f.hasRelationSort:e.sort?.some($=>{if(!$.field.includes("."))return!1;let N=$.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===N)??!1})??!1,h=()=>f?.sortItems?To(f.sortItems):e.sort?$o(e.sort):null,m=f?.sortItems?yo(f.sortItems):[],b=f?.sortItems?mo(f.sortItems):[],w=()=>{!f||m.length===0||bo(n,e.table,f.sortItems,i)},S=()=>{!f||b.length===0||_o(n,e.table,f.sortItems,i)},T=()=>{let $=[...m,...b];$.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries($.map(N=>[N,0]))})};if(!e.mongoFieldsExpanded){w(),S();let $=h();if($&&n.push({$sort:$}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),T(),e.select){let A={};for(let D of e.select)A[D]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let N=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:N,pipeline:n}:{results:Gr(N),pipeline:n}}let{scalarFields:k,relations:R}=e.mongoFieldsExpanded;if(!y){w(),S();let $=h();$&&n.push({$sort:$}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let I=[];for(let $ of R)if(e.sort?.some(A=>A.field.startsWith(`${$.propertyName}.`))){let A=e.mongoRawFilter?.[$.propertyName];if($.nestedFields&&$.nestedFields.length>0){let j=await Dt(i,$.targetTable,$.nestedFields??[],A);$.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:$.targetTable,localField:$.localField,foreignField:$.foreignField,as:$.propertyName,pipeline:j.length>0?j:void 0}})}else if(A){let j=await Dt(i,$.targetTable,["_id"],A);$.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:$.targetTable,localField:$.localField,foreignField:$.foreignField,as:$.propertyName,pipeline:j.length>0?j:void 0}})}else n.push({$lookup:{from:$.targetTable,localField:$.localField,foreignField:$.foreignField,as:$.propertyName}});$.type==="one"&&(n.push({$unwind:{path:`$${$.propertyName}`,preserveNullAndEmptyArrays:!0}}),A&&(tt(A)||n.push({$match:{[$.propertyName]:{$ne:null}}})))}else I.push($);if(y){w(),S();let $=h();$&&n.push({$sort:$}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}T(),await Vr(i,n,e.table,k,[...R]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let O=performance.now(),L=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",O,{table:e.table}),e.mongoCountOnly)return{results:L,pipeline:n};if(I.length>0&&L.length>0){let $=e.deep||{},N=I.map(D=>{let _=i?.tables?.get(e.table)?.relations?.find(V=>V.propertyName===D.propertyName),C=$[D.propertyName],v=C?.fields!=null?Array.isArray(C.fields)?C.fields:String(C.fields).split(",").map(V=>V.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:_?.type,targetTable:D.targetTable,fields:v,isInverse:_?.isInverse,mappedBy:_?.mappedBy,junctionTableName:_?.junctionTableName,localField:D.localField,foreignField:D.foreignField,userFilter:C?.filter,userSort:C?.sort,userLimit:C?.limit!==void 0?Number(C.limit):void 0,userPage:C?.page!==void 0?Number(C.page):void 0,nestedDeep:C?.deep}}),A=wo(i);A&&await $n(o,L,N,A,3,0,e.table,i,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Gr(L),pipeline:n}}function er(r){return`__sort_count_${r.relationName||r.field}`}function tr(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function yo(r){return r.filter(e=>e.function==="count").map(er)}function mo(r){return r.filter(e=>e.function==="max"||e.function==="min").map(tr)}function bo(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,d=er(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=U(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=pe(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function _o(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,d=n?.tables?.get(l),c=d?.columns?.find(h=>h.isPrimary)?.name||(d?.columns?.some(h=>h.name==="_id")?"_id":"id"),p=s.aggregateField,f=p==="id"&&d?.columns?.some(h=>h.name==="_id")?"_id":p,g=tr(s),y=s.function==="min"?"$min":"$max";if(!(!a||!l||!p)){if(a.type==="one-to-many"){let h=U(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[y]:`$${f}`}}}],as:g}}),r.push({$addFields:{[g]:{$arrayElemAt:[`$${g}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=pe(e,a);if(!h)continue;let m=`${g}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:m}}),r.push({$lookup:{from:l,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${c}`,"$$targetIds"]}}},{$group:{_id:null,value:{[y]:`$${f}`}}}],as:g}}),r.push({$addFields:{[g]:{$arrayElemAt:[`$${g}.value`,0]}}}),r.push({$project:{[m]:0}})}}}}function wo(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function $o(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 To(r){let e={};for(let t of r){let n=t.function==="count"?er(t):t.function==="max"||t.function==="min"?tr(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function tt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>tt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>tt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>tt(e));if("_not"in r)return tt(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||tt(t)))return!0}return!1}function Gr(r){return r.map(ce)}function Yr(r,e){let t=[],n=[],o=e?.tables?.get(r.rootTable);if(!o)return{scalarFields:t,relations:n};for(let i of r.nodes)if(i.kind==="wildcard")for(let s of o.columns||[])t.includes(s.name)||t.push(s.name);else i.kind==="scalar"?o.columns?.some(a=>a.name===i.name)&&!t.includes(i.name)&&t.push(i.name):i.kind==="relation"&&n.push(So(i,o,e));return{scalarFields:t,relations:n}}function So(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),o,i,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ae(n)?(o="_id",i=U(n)||r.propertyName,s=!0):(o=n&&G(n)||r.propertyName,i="_id",s=!1):r.relationType==="one-to-many"?(o="_id",i=n&&U(n)||r.propertyName,s=!0):n?.mappedBy?(o="_id",i=n.mappedBy,s=!0):(o=r.propertyName,i="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Xr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:u}}function Xr(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=Xr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let o of n)e.push(`${t.propertyName}.${o}`)}return e}He();Bt();jt();function Tn(r,e,t,n){let o={rootTable:e,nodes:[]};if(!r||r.length===0)return o;let i=t?.tables?.get(e);if(!i)return o;let s=i.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=i.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,d=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")d.push("*");else if(p.includes(".")){let f=p.indexOf("."),g=p.substring(0,f),y=p.substring(f+1);if(!i.relations?.some(m=>m.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(y)}else if(i.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!i.columns?.some(y=>y.name===p))continue;d.push(p)}}if(d.includes("*")){o.nodes.push({kind:"wildcard"});for(let c of i.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of d)o.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let f=i.relations?.find(h=>h.propertyName===c);if(!f)continue;let g=f.targetTableName||f.targetTable,y={kind:"relation",propertyName:c,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:g,children:Zr(p,g,t)};if(f.type==="many-to-one"||f.type==="one-to-one"){let h=n.registerWithParent(e,c,t,"left",null,"data");y.joinId=h}o.nodes.push(y)}return o}function Zr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let o=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),i=n.columns?.some(d=>d.name==="id"),s=o&&!i?"_id":"id",a=new Map,u=[];for(let d of r){let c=d==="id"?s:d;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),f=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(h=>h.propertyName===f))continue;a.has(f)||a.set(f,[]),a.get(f).push(g)}else if(n.relations?.some(f=>f.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 d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)l.push({kind:"scalar",name:d});for(let[d,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===d);if(!p)continue;let f=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:d,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:f,children:Zr(c,f,t)})}return l}ge();ge();var Co=new Set(["_and","_or","_not"]);function ei(r,e){return r?.tables?.get(e)??null}function ko(r,e,t){return ei(r,e)?.columns?.find(n=>n.name===t)}function nr(r,e,t){return ei(r,e)?.relations?.find(n=>n.propertyName===t)}function Ro(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let o=n.indexOf(".");return o<=0||o!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,o).trim(),fieldName:n.slice(o+1).trim()}}function rr(r,e,t,n){if(ko(r,e,t)?.isEncrypted===!0)throw new x(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Be(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Be(n,e,t);return}for(let[n,o]of Object.entries(r)){if(Co.has(n)){Be(o,e,t);continue}if(n.startsWith("_"))continue;let i=nr(t,e,n);if(i){let s=i.targetTableName||i.targetTable;s&&Be(o,s,t);continue}rr(t,e,n,"filter")}}}function Sn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(!i)continue;let s=Ro(i);if(s){if(s.functionName==="count")continue;let l=nr(t,e,s.relationName),d=l?.targetTableName||l?.targetTable;d&&rr(t,d,s.fieldName,"sort");continue}let a=i.split("."),u=e;for(let l=0;l<a.length;l++){let d=a[l];if(l===a.length-1){rr(t,u,d,"sort");break}let p=nr(t,u,d);if(!p)break;u=p.targetTableName||p.targetTable||u}}}var q=class{plan(e){let{tableName:t,fields:n,filter:o,sort:i,page:s,limit:a,meta:u,metadata:l,dbType:d}=e,c=l?.tables?.get(t),p=new se,f=this.parseFields(n),g=null;f&&c&&(g=Tn(f,t,l,p));let y=!1,h=null;if(o&&c){Be(o,t,l);let $=he(o,t,l,p);h=$.node,y=$.hasRelationFilters}let m=this.parseSort(i);c&&Sn(m,t,l);let b=[],w=!1;for(let $ of m){let N=$.startsWith("-"),A=N?$.substring(1):$,D=N?"desc":"asc";if(c){let j=this.parseRelationAggregateSort(t,c,A,l);if(j){b.push({joinId:null,field:A,direction:D,fullPath:A,function:j.functionName,relationName:j.relationName,aggregateField:j.aggregateField,relationMeta:j.relationMeta});continue}this.assertLocalSortField(t,c,A)}b.push({joinId:null,field:A,direction:D,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let S=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&S!==void 0?(T-1)*S:void 0,R=this.parseMeta(u),I=R.includes("totalCount")||R.includes("*"),O=R.includes("filterCount")||R.includes("*"),L=p.getAll();return{table:t,dbType:d,rawFields:f,rawFilter:o??null,joins:L,sortItems:b,limit:S,offset:k,needsTotalCount:I,needsFilterCount:O,hasRelationFilters:y,hasRelationSort:w,filterTree:h,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new x(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let o=t.columns?.some(s=>s.name===n),i=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!o&&!i)throw new x(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,o){let i=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!i){if(/^_(count|max|min)\(/.test(n))throw new x(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=i[1],a=i[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===h);if(!m)throw new x(`Sort relation '${h}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new x(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!l||!d)throw new x(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=t.relations?.find(h=>h.propertyName===l);if(!c)throw new x(`Sort relation '${l}' does not exist on '${e}'.`);if(c.type!=="one-to-many"&&c.type!=="many-to-many")throw new x(`Sort function '_${s}(${l}.${d})' is only supported for list relations on '${e}'.`);let p=c.targetTableName||c.targetTable,f=o?.tables?.get(p);if(!f)throw new x(`Sort function '${n}' references unknown target table '${p}' on '${e}'.`);let g=f.columns?.find(h=>h.name===d),y=d==="id"&&f.columns?.some(h=>h.name==="_id");if(!g&&!y)throw new x(`Sort field '${d}' does not exist on '${p}' for function '_${s}(${l}.${d})'.`);if(g?.isEncrypted===!0)throw new x(`Encrypted field '${d}' on '${p}' cannot be used for sort.`);return{functionName:s,relationName:l,aggregateField:d,relationMeta:c}}registerSortJoinChain(e,t,n,o,i){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let d=l.relations?.find(f=>f.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let c=o.registerWithParent(t,a,n,"left",i,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,p,n,o,c)}};ge();Pt();var Fo=new Set(["count","sum","avg","min","max","countRecords"]),xo=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),vo=new Set(["_and","_or","_not"]);function xe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function P(r,e){let t=r.replace(/^aggregate\./,"");throw new x(e,{path:r,aggregate:{[t]:e}})}function Io(r){return typeof r!="string"?!1:xo.has(r.toLowerCase())}function ti(r){return Object.keys(r).length===0}function No(r,e,t){return r===!0?{}:(r==null&&P(t,`aggregate.${e} condition must be true or an object`),xe(r)||P(t,`aggregate.${e} condition must be true or an object`),r)}function Mo(r,e,t){let n=r?.tables?.get(e);return n||P(t,`Table "${e}" metadata is not available`),n}function ni(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&P(e,"aggregate.countRecords relation target is not available"),t}function Cn(r,e,t,n){let o=Mo(t,e,n);for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){Array.isArray(s)||P(n,`aggregate.countRecords ${i} condition must be an array`);for(let d of s)xe(d)||P(n,`aggregate.countRecords ${i} items must be objects`),Cn(d,e,t,n);continue}if(i==="_not"){xe(s)||P(n,"aggregate.countRecords _not condition must be an object"),Cn(s,e,t,n);continue}(i.startsWith("_")||vo.has(i))&&P(n,`Unsupported aggregate.countRecords condition key "${i}"`);let a=o.columns?.find(d=>d.name===i),u=o.relations?.find(d=>d.propertyName===i);if(!a&&!u&&P(n,`Unknown aggregate.countRecords field or relation "${i}" on table "${e}"`),xe(s)||P(n,`aggregate.countRecords condition for "${i}" must be an object`),a){for(let d of Object.keys(s))oe.has(d)||P(n,`aggregate.countRecords condition for "${i}" only supports field operators`);continue}let l=ni(u,n);Cn(s,l,t,n)}}function ir(r){return xe(r)&&Object.keys(r).length>0}function nt(r,e,t){if(!ir(r))return[];xe(r)||P("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||P("aggregate",`Table "${e}" metadata is not available`);let o=[];for(let[i,s]of Object.entries(r)){let a=`aggregate.${i}`;(!i||typeof i!="string")&&P("aggregate","aggregate field name must be a non-empty string"),xe(s)||P(a,"aggregate field config must be an object");let u=i,l=a,d=n.columns?.find(f=>f.name===i),c=n.relations?.find(f=>f.propertyName===i);!d&&!c&&P(l,`Unknown aggregate field or relation "${i}" on table "${e}"`);let p=Object.entries(s).filter(([f])=>f!=="as");p.length===0&&P(l,"aggregate field must define at least one operation");for(let[f,g]of p){Fo.has(f)||P(l,`Unsupported aggregate operation "${f}"`);let y=No(g,f,l);if(c&&f!=="countRecords"&&P(l,`aggregate.${f} is not supported on relation "${i}"; use countRecords`),d&&f==="countRecords"&&P(l,`aggregate.countRecords requires a relation, but "${i}" is a field`),d&&(f==="sum"||f==="avg")&&!Io(d.type)&&P(l,`aggregate.${f} requires a numeric field, but "${i}" is "${d.type}"`),d)for(let h of Object.keys(y))oe.has(h)||P(l,`aggregate.${f} condition for "${i}" only supports field operators`);if(c&&f==="countRecords"){let h=ni(c,l);Cn(y,h,t,l)}o.push({field:i,outputKey:u,path:l,op:f,condition:y})}}return o}function rt(r,e){let t=[];return xe(r)&&!ti(r)&&t.push(r),ti(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function ve(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var it=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new q;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata,debugTrace:e.debugTrace};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(J(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(f=>f.trim());n.sort=p.map(f=>{let g=f.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,f=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*f,n.limit=f}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let o=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),i=0,s=0;(o.includes("totalCount")||o.includes("*"))&&(i=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&ie(n.mongoRawFilter,u);if((o.includes("filterCount")||o.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?Pe(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(f)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],f;try{f=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){f={error:String(g)}}return{pipeline:p,explain:f}}if(l&&(o.includes("filterCount")||o.includes("*"))){let p={...n,mongoCountOnly:!0},f=await this.selectLegacy(p);s=f.length>0?f[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:d,...(o.length>0||c)&&{meta:{...o.includes("totalCount")||o.includes("*")?{totalCount:i}:{},...o.includes("filterCount")||o.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,o=this.metadata?.tables?.get(e.table),i=o?.relations&&o.relations.length>0;if(e.fields&&e.fields.length>0||n||i){let l=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&l?.fieldTree){if(e.mongoFieldsExpanded=Yr(l.fieldTree,this.metadata),n){let c=await At(this.metadata,e.table,[],e.deep),p=new Set(e.mongoFieldsExpanded.relations.map(f=>f.propertyName));e.mongoFieldsExpanded.relations.push(...c.relations.filter(f=>!p.has(f.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await At(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let c=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:c.scalarFields},t=c.hiddenFields}}e.where&&(e.where=e.where.map(l=>l.field.includes(".")?l:{...l,field:`${e.table}.${l.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(ce);let{results:a,pipeline:u}=await Zn(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:o}=await Zn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,n}async executeAggregate(e,t){let n=nt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={},i=this.db.collection(e.table);for(let s of n){let a=rt(t,s);J(a,e.table,e.metadata);let l=new q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);ve(o,s,p);continue}let d=l.hasRelationFilters?await be(a,e.table,e.metadata,this.db):l.filterTree?Pe(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await i.countDocuments(d);else{let[{value:p}={value:null}]=await i.aggregate([{$match:d},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}ve(o,s,c)}return o}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table)?.relations?.find(d=>d.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(i.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[i.foreignKeyColumn]:{$in:c}}]})}if(i.type==="many-to-many"){let d=pe(e.table,i);if(!d)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(y=>y!=null);if(p.length===0)return 0;let g=(await this.db.collection(d.junctionName).find({[d.selfColumn]:{$in:p}},{projection:{[d.otherColumn]:1}}).toArray()).map(y=>y[d.otherColumn]).filter(y=>y!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(i.type==="many-to-one"||i.type==="one-to-one"){let d=i.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[d]:1}}).toArray()).map(f=>f[d]).filter(f=>f!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};J(t,e,n);let i=new q().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return i.hasRelationFilters?await be(t,e,n,this.db):i.filterTree?Pe(i.filterTree,{metadata:n,rootTable:e}):{}}};var kn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};ge();ue();var Oo=["_and","_or","_not"];function _e(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>_e(e));for(let e of Object.keys(r))if(Oo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&_e(r[e]))return!0;return!1}var ri=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Ao(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Rn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let o=t.columns.find(s=>s.name===n);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function Eo(r,e,t,n,o){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||Rn(r,t,o),e}function ii(r,e,t,n,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,u=Ie(a,i??"postgres"),l=Rn(e,o,s),d=Eo(e,n,o,i,s);switch(t){case"_eq":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":l&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(f=>f.trim()):[c]),l&&i==="postgres"&&c.every(f=>typeof f=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[c]):r.whereIn(a,c);break;case"_not_in":case"_nin":let p=n;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(f=>f.trim()):[p]),l&&i==="postgres"&&p.every(f=>typeof f=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[p]):r.whereNotIn(a,p);break;case"_contains":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):i==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,Ao(t),n)}}function Po(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.some(s=>s.name===n),i=t.relations?.some(s=>s.propertyName===n);return o||i}function ot(r,e,t,n="and",o,i){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){ot(this,s,t,"and",o,i)}):r.orWhere(function(){ot(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e))if(Po(s,t,i)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){ot(this,u,t,"and",o,i)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){ot(this,u,t,"and",o,i)})});continue}if(s==="_not"){r.whereNot(function(){ot(this,a,t,"and",o,i)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>ri.includes(l)))for(let[l,d]of Object.entries(a))ri.includes(l)&&(n==="and"?r.where(function(){ii(this,s,l,d,t,o,i)}):r.orWhere(function(){ii(this,s,l,d,t,o,i)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s,d=Ie(l,o??"postgres");Rn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,l=Ie(u,o??"postgres");Rn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function de(r,e,t,n,o){return!e||typeof e!="object"||ot(r,e,t,"and",n,o),r}ue();function ar(r,e,t){return`${F(r,t)}.${F(e,t)}`}function Ne(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function oi(r,e){if(!e)return!1;let t=e.columns.find(o=>o.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function st(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function lr(r,e,t,n,o,i){let s=[];for(let[a,u]of Object.entries(i)){let l=await Ut(r,e,a,u,t,n,o);if(l!==null)s.push(`EXISTS (${l})`);else{let d=t.relations.find(c=>c.propertyName===a);if(d&&d.foreignKeyColumn){let c=ar(e,d.foreignKeyColumn,n),f=u.id;if(f&&typeof f=="object"){let g=st(f._is_null),y=st(f._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(y===!0)s.push(`${c} IS NOT NULL`);else if(y===!1)s.push(`${c} IS NULL`);else if(f._eq!==void 0){let h=Ne(f._eq,n);s.push(`${c} = ${h}`)}else if(f._neq!==void 0){let h=Ne(f._neq,n);s.push(`${c} != ${h}`)}else if(f._in!==void 0){let m=(Array.isArray(f._in)?f._in:[f._in]).map(b=>Ne(b,n)).join(", ");s.push(`${c} IN (${m})`)}else if(f._not_in!==void 0||f._nin!==void 0){let h=f._not_in??f._nin,b=(Array.isArray(h)?h:[h]).map(w=>Ne(w,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(f._gt!==void 0){let h=Ne(f._gt,n);s.push(`${c} > ${h}`)}else if(f._gte!==void 0){let h=Ne(f._gte,n);s.push(`${c} >= ${h}`)}else if(f._lt!==void 0){let h=Ne(f._lt,n);s.push(`${c} < ${h}`)}else if(f._lte!==void 0){let h=Ne(f._lte,n);s.push(`${c} <= ${h}`)}}}}}return s}function cr(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function or(r,e,t,n,o,i){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(cr(l)){let d=e(t).select(`${t}.id`);await Le(e,d,l,t,n,o,i),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:c}=Y(l,n),p=await lr(e,t,n,o,i,c);u.push({fieldFilters:d,subqueries:p})}s.push(u)}else if(cr(a)){let u=e(t).select(`${t}.id`);await Le(e,u,a,t,n,o,i),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=Y(a,n),d=await lr(e,t,n,o,i,l);s.push([{fieldFilters:u,subqueries:d}])}return s}function si(r,e,t,n,o){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let i=e;Object.keys(i.fieldFilters).length===0&&i.subqueries.length===0||r.where(function(){Object.keys(i.fieldFilters).length>0&&de(this,i.fieldFilters,t,o,n);for(let s of i.subqueries)this.whereRaw(s)})}function sr(r,e,t,n,o){let i=!0;for(let s of e){let a=function(){for(let u of s)si(this,u,t,n,o)};i?(r.where(a),i=!1):r.orWhere(a)}}function Fn(r,e,t,n,o,i,s){let a=oi(e,o),u=oi(n,i),l=`${F(r,s)}.${F(e,s)}`,d=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${d}::uuid`;if(!a&&u)return`${l}::uuid = ${d}`}return`${l} = ${d}`}async function Ut(r,e,t,n,o,i,s){let a=o.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let d=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",d,o,i));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(Fn(a.junctionTableName,a.junctionTargetColumn,u,"id",p,d,i))).whereRaw(Fn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,o,i));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(Fn(u,"id",e,a.foreignKeyColumn,d,o,i));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Le(r,c,n,u,d,i,s):c=de(c,n,u,i,d||void 0):c=de(c,n,u,i),c.toString()}async function Le(r,e,t,n,o,i,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let d=await or(l._or,r,n,o,i,s);e.where(function(){sr(this,d,n,o,i)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let d of l._and)await Le(r,e,d,n,o,i,s);else await Le(r,e,l,n,o,i,s);return}if(t._or&&Array.isArray(t._or)){let l=await or(t._or,r,n,o,i,s);e.where(function(){sr(this,l,n,o,i)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let f of l._and)if(cr(f)){let g=r(n).select(`${n}.id`);await Le(r,g,f,n,o,i,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:y}=Y(f,o),h=await lr(r,n,o,i,s,y);p.push({fieldFilters:g,subqueries:h})}e.whereNot(function(){for(let f of p)si(this,f,n,o,i)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await or(l._or,r,n,o,i,s);e.whereNot(function(){sr(this,p,n,o,i)});return}let{fieldFilters:d,relationFilters:c}=Y(l,o);e.whereNot(function(){Object.keys(d).length>0&&de(this,d,n,i,o)});for(let[p,f]of Object.entries(c)){let g=await Ut(r,n,p,f,o,i,s);if(g===null){let y=o.relations.find(h=>h.propertyName===p);if(y&&y.foreignKeyColumn){let h=ar(n,y.foreignKeyColumn,i),b=f.id;if(b&&typeof b=="object"){let w=st(b._is_null),S=st(b._is_not_null);if(w===!0)e.whereRaw(`${h} IS NOT NULL`);else if(w===!1)e.whereRaw(`${h} IS NULL`);else if(S===!0)e.whereRaw(`${h} IS NULL`);else if(S===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=Y(t,o);Object.keys(a).length>0&&de(e,a,n,i,o);for(let[l,d]of Object.entries(u)){let c=await Ut(r,n,l,d,o,i,s);if(c===null){let p=o.relations.find(f=>f.propertyName===l);if(p&&p.foreignKeyColumn){let f=ar(n,p.foreignKeyColumn,i),y=d.id;if(y&&typeof y=="object"){let h=st(y._is_null),m=st(y._is_not_null);if(h===!0)e.whereRaw(`${f} IS NULL`);else if(h===!1)e.whereRaw(`${f} IS NOT NULL`);else if(m===!0)e.whereRaw(`${f} IS NOT NULL`);else if(m===!1)e.whereRaw(`${f} IS NULL`);else if(y._eq!==void 0)e.whereRaw(`${f} = ?`,[y._eq]);else if(y._neq!==void 0)e.whereRaw(`${f} != ?`,[y._neq]);else if(y._in!==void 0){let b=Array.isArray(y._in)?y._in:[y._in];e.whereRaw(`${f} IN (${b.map(()=>"?").join(", ")})`,b)}else if(y._not_in!==void 0||y._nin!==void 0){let b=y._not_in??y._nin,w=Array.isArray(b)?b:[b];e.whereRaw(`${f} NOT IN (${w.map(()=>"?").join(", ")})`,w)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function De(r,e,t,n,o,i,s){await Le(r,e,t,n,o,i,s)}ue();dr();He();ue();function at(r,e,t,n,o){for(let i of e){let s=i.field.split("."),a=t||s[0],u=s[s.length-1],l=Qt(n,a,u,i.value);switch(i.operator){case"=":r=r.where(i.field,"=",l);break;case"!=":r=r.where(i.field,"!=",l);break;case">":r=r.where(i.field,">",l);break;case"<":r=r.where(i.field,"<",l);break;case">=":r=r.where(i.field,">=",l);break;case"<=":r=r.where(i.field,"<=",l);break;case"like":r=r.where(i.field,"like",l);break;case"in":let d=Array.isArray(i.value)?i.value.map(y=>Qt(n,a,u,y)):[l];r=r.whereIn(i.field,d);break;case"not in":let c=Array.isArray(i.value)?i.value.map(y=>Qt(n,a,u,y)):[l];r=r.whereNotIn(i.field,c);break;case"is null":r=r.whereNull(i.field);break;case"is not null":r=r.whereNotNull(i.field);break;case"_contains":r=r.where(i.field,"like",`%${i.value}%`);break;case"_starts_with":r=r.where(i.field,"like",`${i.value}%`);break;case"_ends_with":r=r.where(i.field,"like",`%${i.value}`);break;case"_between":let p=i.value;if(typeof p=="string"&&(p=p.split(",").map(y=>y.trim())),Array.isArray(p)&&p.length===2){let y=Qt(n,a,u,p[0]),h=Qt(n,a,u,p[1]);r=r.whereBetween(i.field,[y,h])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(i.field):r.whereNotNull(i.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(i.field):r.whereNull(i.field);break}}return r}function Jt(r,e,t,n){let o=[],i=t;if(!r||typeof r!="object")return o;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let d=Jt(l,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let d=Jt(l,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Jt(a,e,t,n);u.length>0&&o.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let d=`${F(e,n)}.${F(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,f=i.columns?.find(y=>y.name===s);f&&(f.type?.toLowerCase()==="uuid"||f.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")o.push(`${d} = ${c}`);else if(u==="_neq")o.push(`${d} != ${c}`);else if(u==="_gt")o.push(`${d} > ${c}`);else if(u==="_gte")o.push(`${d} >= ${c}`);else if(u==="_lt")o.push(`${d} < ${c}`);else if(u==="_lte")o.push(`${d} <= ${c}`);else if(u==="_is_null")o.push(`${d} IS NULL`);else if(u==="_is_not_null")o.push(`${d} IS NOT NULL`);else if(u==="_in"){let f=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${d} IN (${f})`)}else if(u==="_not_in"||u==="_nin"){let f=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${d} NOT IN (${f})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${d}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${d}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):o.push(`lower(${d}) 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]),f=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);o.push(`${d} BETWEEN ${p} AND ${f}`)}}else{let u=`${F(e,n)}.${F(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),o.push(`${u} = ${l}`)}return o}function li(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Qt(r,e,t,n){if(n==null)return n;let o=r?.tables?.get(e);if(!o?.columns)return n;let i=o.columns.find(s=>s.name===t);if(!i)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}ue();qt();Je();async function ui(r,e,t,n,o,i,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(pr(),ci)),u=await a(e,t,n,o,i,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function gr(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function di(r,e,t,n,o){let i=r.targetTableName||r.targetTable;if(!i)return null;let s=r.foreignKeyColumn||H(r.propertyName);if(!s)return null;let a=c=>F(c,o),u=n?.tables?.get(i),d=(u?X(u):null)?.name||"id";return`(SELECT ${a(i)}.${a(e)} FROM ${a(i)} WHERE ${a(i)}.${a(d)} = ${a(t)}.${a(s)})`}qt();var ut=class r{constructor(e,t,n,o){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=o;this.logger=new kn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let o=e.debugTrace;if(e.filter&&J(e.filter,e.tableName,e.metadata),!e.plan){let _=new q;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 i=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!u&&!a&&l){o&&o.setQueryPath("simple");let _=await this.executeSimple(e,i);return o&&o.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&&!_e(e.filter)){c.where=[];for(let[_,C]of Object.entries(e.filter))if(typeof C=="object"&&C!==null)for(let[v,V]of Object.entries(C)){let M;if(v==="_eq")M="=";else if(v==="_neq")M="!=";else if(v==="_in")M="in";else if(v==="_not_in"||v==="_nin")M="not in";else if(v==="_gt")M=">";else if(v==="_gte")M=">=";else if(v==="_lt")M="<";else if(v==="_lte")M="<=";else if(v==="_contains")M="_contains";else if(v==="_starts_with")M="_starts_with";else if(v==="_ends_with")M="_ends_with";else if(v==="_between")M="_between";else if(v==="_is_null")M="_is_null";else if(v==="_is_not_null")M="_is_not_null";else if(v==="_like")M="like";else if(v==="_ilike")M="ilike";else continue;c.where.push({field:_,operator:M,value:V})}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 v=C.trim();return v.startsWith("-")?{field:v.substring(1),direction:"desc"}:{field:v,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let f=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=f===void 0||Number.isNaN(f)?void 0:f<0?0:f,y=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=y===void 0||Number.isNaN(y)?void 0:y;h&&g!==void 0?(c.offset=(h-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let m=e.plan?.sortItems??(c.sort??[]).map(_=>({joinId:null,field:_.field,direction:_.direction,fullPath:_.field})),b=[],w=[];for(let _ of m){if(_.function==="count"){let C={sql:this.buildRelationCountSortSubquery(c.table,_),direction:_.direction};w.push(C);continue}if(_.function==="max"||_.function==="min"){let C={sql:this.buildRelationAggregateSortSubquery(c.table,_),direction:_.direction};w.push(C);continue}if(_.joinId===null){if(_.field.includes(".")&&!e.plan){let v=_.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(z=>z.propertyName===v))continue}let C={field:_.field.includes(".")?_.field:`${c.table}.${_.field}`,direction:_.direction};b.push(C),w.push(C)}else{let C=e.plan?.joins.find(v=>v.id===_.joinId);if(C&&(C.relationType==="many-to-one"||C.relationType==="one-to-one")){let v=di(C.relationMeta,_.field,c.table,this.metadata,this.dbType);if(v){let V={sql:v,direction:_.direction};w.push(V)}}}}let S=[];if(c.fields&&c.fields.length>0||u||a){let _=gr(this.metadata),C=c.fields&&c.fields.length>0?c.fields:["*"],v=await ui(this.knex,c.table,C,_,this.dbType,this.maxQueryDepth,e.deep);v.select.length>0&&(c.select=[...c.select||[],...v.select]),S=v.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(_=>_.field.includes(".")?_:{..._,field:`${c.table}.${_.field}`})),c.sort=b;let T=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(_=>_.trim()).filter(Boolean),R=k.includes("filterCount")||k.includes("*"),I=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);T=T.select(_)}if(R&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),I){let _=F(c.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${_}) as __total_count__`))}let O=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(_e(p)||Object.keys(p).length>0)){let _=this.metadata?.tables?.get(c.table);(!O&&_&&_.relations&&_.relations.length>0?Y(p,_).hasRelations:!1)?await De(this.knex,T,p,c.table,_,this.dbType,v=>this.metadata?.tables?.get(v)):e.plan?.filterTree?ne(T,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),T=de(T,p,c.table,this.dbType,_))}else c.where&&c.where.length>0&&(T=at(T,c.where,c.table,this.metadata,this.dbType));for(let _ of w)if(_.field){let C=_.field.includes(".")?_.field:`${c.table}.${_.field}`;T=T.orderBy(C,_.direction)}else _.sql&&(T=T.orderByRaw(`${_.sql} ${_.direction.toUpperCase()}`));c.groupBy&&(T=T.groupBy(c.groupBy)),c.offset&&(T=T.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&(T=T.limit(c.limit));let L=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:T.toSQL().toNative()});let $;if(e.debugMode&&($=T.toSQL().toNative().sql),e.debugMode&&o){let _=T.toSQL().toNative();o.setSql(_.sql);try{let C=_.sql.replace(/\$\d+/g,"?"),v=await this.knex.raw(`EXPLAIN ${C}`,_.bindings);o.setExplain(this.dbType==="postgres"?v.rows:v[0])}catch(C){o.setExplain({error:String(C)})}}let N,A=performance.now();N=await T,o&&o.dur("db_execute",A,{table:e.tableName});let D=0;if(R&&N.length>0&&(D=Number(N[0].__filter_count__||0),N.forEach(_=>{delete _.__filter_count__})),I&&N.length>0&&N[0].__total_count__!==void 0&&(L=Number(N[0].__total_count__||0),N.forEach(_=>{delete _.__total_count__})),S&&S.length>0&&N.length>0){let _=gr(this.metadata);if(_){let{executeBatchFetches:C}=await Promise.resolve().then(()=>(mr(),fi));await C(this.knex,N,S,_,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,o)}}if(this.knexService){let _=performance.now();N=await this.knexService.parseResult(N,c.table),o&&o.dur("db_parseResult",_,{table:e.tableName})}else{let _=(C,v)=>{if(!C||!this.metadata)return C;let V=this.metadata.tables?.get(v);if(!V)return C;if(Array.isArray(C))return C.map(z=>_(z,v));if(typeof C!="object"||Buffer.isBuffer(C))return C;let M={...C};for(let z of V.columns)if(z.type==="simple-json"&&M[z.name]&&typeof M[z.name]=="string")try{M[z.name]=JSON.parse(M[z.name])}catch{}for(let[z,Z]of Object.entries(M))if(Z&&typeof Z=="object"&&!Array.isArray(Z)&&!Buffer.isBuffer(Z)){let An=Z;if(An.id!==void 0||An.createdAt!==void 0){let ft=V.relations?.find(pt=>pt.propertyName===z);ft&&(M[z]=_(Z,ft.targetTableName))}}else if(Array.isArray(Z)&&Z.length>0&&typeof Z[0]=="object"&&Z[0].id!==void 0){let ft=V.relations?.find(pt=>pt.propertyName===z);ft&&(M[z]=Z.map(pt=>_(pt,ft.targetTableName)))}return M};N=_(N,c.table)}o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName}));let j=await this.executeAggregate(c,p);return{data:N,...(k.length>0||j)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:L}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:D}:{},...j?{aggregate:j}:{}}},...$!==void 0&&{sql:$}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=X(s)?.name||"id",u=F(e,this.dbType),l=F(a,this.dbType);if(!n||!i)throw new x(`Sort relation '${o}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new x(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let c=F(i,this.dbType),p=F(d,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,o,e),c=F(d.tableName,this.dbType),p=F(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new x(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),l=X(a)?.name||"id",d=X(u)?.name||"id",c=F(e,this.dbType),p=F(l,this.dbType),f=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!f||!n||!s||!i)throw new x(`Sort function '${t.field}' is not supported on '${e}'.`);let g=F(s,this.dbType),y=F(i,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new x(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let m=F(h,this.dbType);return`(SELECT ${f}(${g}.${y}) FROM ${g} WHERE ${g}.${m} = ${c}.${p})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,o,e),m=F(h.tableName,this.dbType),b=F(h.sourceColumn,this.dbType),w=F(h.targetColumn,this.dbType),S=F(d,this.dbType);return`(SELECT ${f}(${g}.${y}) FROM ${m} JOIN ${g} ON ${g}.${S} = ${m}.${w} WHERE ${m}.${b} = ${c}.${p})`}throw new x(`Sort function '_${t.function}(${o}.${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new x(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(n).select(o);t.filterTree&&ne(i,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let m=h.field.includes(".")?h.field:`${n}.${h.field}`;i=i.orderBy(m,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=F(n,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let l=e.debugTrace,d;if(e.debugMode){let h=i.toSQL().toNative();if(d=h.sql,l){l.setSql(h.sql);try{let m=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,h.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){l.setExplain({error:String(m)})}}}let c=performance.now(),p;p=await i,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let f=0,g=0;a&&p.length>0&&(f=Number(p[0].__filter_count__||0),p.forEach(h=>delete h.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(h=>delete h.__total_count__));let y=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||y)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:f}:{},...y?{aggregate:y}:{}}},...d!==void 0&&{sql:d}}}async executeAggregate(e,t){let n=nt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={};for(let i of n){let s=rt(t,i);J(s,e.table,e.metadata);let u=new q().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(i.op==="countRecords"){let f=await this.executeRelationCountRecords(e,t,i);ve(o,i,f);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let f=e.metadata?.tables?.get(e.table);await De(this.knex,l,s,e.table,f,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&ne(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let d=`${F(e.table,this.dbType)}.${F(i.field,this.dbType)}`,c=i.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${i.op.toUpperCase()}(${d}) as value`),p=await l.clearSelect().select(c).first();ve(o,i,p?.value??0)}return o}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table),i=o?.relations?.find(c=>c.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await De(this.knex,u,t,e.table,o,this.dbType,f=>e.metadata?.tables?.get(f)):p.filterTree&&ne(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){J(n.condition,s,e.metadata);let p=new q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await De(this.knex,l,n.condition,s,a,this.dbType,f=>e.metadata?.tables?.get(f)):p.filterTree&&ne(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(i.type==="one-to-many")l.whereIn(`${s}.${i.foreignKeyColumn}`,u);else if(i.type==="many-to-many"){let c=this.resolveManyToManyContract(i,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(i.type==="many-to-one"||i.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${i.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${i.foreignKeyColumn}`)});let d=await l.first();return Number(d?.value??0)}};var In=require("mongodb"),dt=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,Nn.mkdirSync)((0,pi.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!In.ObjectId)return e;if(typeof e=="string")try{return new In.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),o=Ve(n,e,t,this.dbType);return o._id!==void 0&&(o._id=this.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,n){let o=await this.getMetadataForQuery();return{query:at(e,t,n??"",o,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.mongoService.insertOne(e.table,n);t.push(ce(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.knexService.insertWithCascade(e.table,n);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),o=performance.now(),s=new q().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",o,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let c=await new it(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});return a&&a.dur("qb_total_select",t,{table:e.tableName}),c}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 i=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(i).toArray(),u=[];for(let l of a){let d=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(d)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);if(e.returning){let i=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(i,e.where,e.table),await i.select(e.returning)}return{affected:o.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(o).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let i=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,i)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n.count("* as count").first();return Number(o?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",i):t.id=this.normalizeWhereFilterValue("id",i):t[o]=this.normalizeWhereFilterValue(o,i);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof In.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,o]of Object.entries(e))t[n]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[n,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.entries(o)[0];if(i){let[s,a]=i,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return ce(a)}let o=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),s=o||t.id;return await i(e).where("id",s).first()})}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let o of n)this.batchInserts.items.push({table:e,data:o});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...n.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.mongoService.insertOne(e,o.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.knexService.insertWithCascade(e,o.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let o=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,o)),this.runBatchInsertWithIsolation(e,t.slice(o))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let o=t.get(n.table);o?o.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,o=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let i=e[n++];await t(i)}});await Promise.all(o)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,Nn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
53
+ `)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return ce(i)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let o=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:o}=await this.applyWhereToKnex(o,s,e))}let i=await o.count("* as count").first();return Number(i?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let o=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:o})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[i,s]of Object.entries(t))i==="id"||i==="_id"?o._id=this.safeObjectId(s):o[i]=s;return this.mongoService.findOne(e,o)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?o._id=this.safeObjectId(u):o[a]=u;return await this.mongoService.collection(e).find(o).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=n||t.id;return await o(e).where("id",i).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let i=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await i.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await i.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};mr();hr();pr();ue();qt();Xe();_n();ge();He();var gi=new Set(["fields","filter","sort","limit","page","deep"]),On=3;function br(r,e,t,n=0,o=3){if(!e||typeof e!="object")return;if(n>=o)throw new x(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(r),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let l=s.get(a);if(!l)throw new x(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!gi.has(p))throw new x(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...gi].join(", ")}`);let d=l.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new x(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new x(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(J(u.filter,c,t),Be(u.filter,c,t),Mn(u.filter,0,a,r)),u.sort){Sn(u.sort,c,t);let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(f=>f.trim()).filter(Boolean);for(let f of p){let g=f.startsWith("-")?f.slice(1):f;Do(g,c,t,a,r)}}u.deep&&br(c,u.deep,t,n+1,o)}}}function Do(r,e,t,n,o){if(r.includes("."))throw new x(`Sort field '${r}' is not supported for relation '${n}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new x(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${o}')`);let s=i.columns?.some(u=>u.name===r),a=r==="id"&&i.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new x(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${o}')`)}var Wo=new Set(["_and","_or","_not"]);function Mn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[o,i]of Object.entries(r)){if(Wo.has(o)){if(Array.isArray(i))for(let l of i)Mn(l,e,t,n);else i&&typeof i=="object"&&Mn(i,e,t,n);continue}if(o.startsWith("_")||!i||typeof i!="object"||Array.isArray(i)||!Object.keys(i).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>On)throw new x(`Filter path exceeds max dotted hops of ${On} at '${o}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(i))l.startsWith("_")||(u[l]=i[l]);Mn(u,a,t,n)}}function hi(r,e,t,n){return!r||typeof r!="object"?r:Ht(r,e,t,n)}function Ht(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let i=r.map(s=>Ht(s,e,t,n)).filter(s=>s!=null);return i.length>0?i:null}let o={};for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){let c=(Array.isArray(s)?s:[s]).map(p=>Ht(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(o[i]=c);continue}if(i==="_not"){let d=Ht(s,e,t,n);d!=null&&Object.keys(d).length>0&&(o[i]=d);continue}let a=t?.tables?.get(e),u=a?.relations?.find(d=>d.propertyName===i);if(u){if(!n(e,i,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let c=Ht(s,d,t,n);c!=null&&Object.keys(c).length>0&&(o[i]=c);continue}if(a?.columns?.find(d=>d.name===i)){if(!n(e,i,"column"))continue;o[i]=s;continue}o[i]=s}return o}function yi(r,e,t,n){if(!r)return r;let o=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let l=(s.startsWith("-")?s.slice(1):s).split("."),d=!0,c=e;for(let p=0;p<l.length;p++){let f=l[p],g=p===l.length-1,y=t?.tables?.get(c);if(!y){d=!1;break}if(g)y.columns?.find(m=>m.name===f)?n(c,f,"column")||(d=!1):y.relations?.find(b=>b.propertyName===f)&&(n(c,f,"relation")||(d=!1));else{let h=y.relations?.find(m=>m.propertyName===f);if(!h){d=!1;break}if(!n(c,f,"relation")){d=!1;break}c=h.targetTableName||h.targetTable||c}}d&&i.push(s)}if(i.length!==0)return Array.isArray(r)?i:i.join(",")}jt();He();Bt();Pt();Je();ge();function Ko(r){let e=new dt({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,o=()=>(t||(t=new Qe({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),i=()=>(n||(n=new We({isolatedExecutorService:o()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return o()},get executorEngineService(){return i()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.30",
3
+ "version": "1.1.31",
4
4
  "source": "bundled-compiled-kernel"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.30",
3
+ "version": "1.1.31",
4
4
  "description": "Closed-distribution Enfyra kernel runtime",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "packageManager": "yarn@4.17.0",