@enfyra/kernel 2.0.1 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +5 -5
- package/dist/package-metadata.json +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var _s=Object.create;var Nr=Object.defineProperty;var Ss=Object.getOwnPropertyDescriptor;var $s=Object.getOwnPropertyNames;var Ts=Object.getPrototypeOf,ks=Object.prototype.hasOwnProperty;var Q=(n,e)=>()=>(n&&(e=n(n=0)),e);var Un=(n,e)=>{for(var t in e)Nr(n,t,{get:e[t],enumerable:!0})},No=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $s(e))!ks.call(n,o)&&o!==t&&Nr(n,o,{get:()=>e[o],enumerable:!(r=Ss(e,o))||r.enumerable});return n};var Je=(n,e,t)=>(t=n!=null?_s(Ts(n)):{},No(e||!n||!n.__esModule?Nr(t,"default",{value:n,enumerable:!0}):t,n)),Es=n=>No(Nr({},"__esModule",{value:!0}),n);function ca(n){return!!(typeof n._bsontype=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof RegExp)}function Xe(n,e=new WeakMap){if(!n||typeof n!="object")return n;let t=e.get(n);if(t)return t;if(Array.isArray(n)){let i=[];e.set(n,i);for(let s of n)i.push(Xe(s,e));return i}if(n instanceof Map){let i=new Map;e.set(n,i);for(let[s,a]of n)i.set(Xe(s,e),Xe(a,e));return i}if(n instanceof Set){let i=new Set;e.set(n,i);for(let s of n)i.add(Xe(s,e));return i}if(n instanceof Date)return new Date(n.getTime());if(ca(n))return n;let r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null)throw new TypeError("Join metadata must contain plain cloneable values");let o=Object.create(r);e.set(n,o);for(let[i,s]of Object.entries(n))Object.defineProperty(o,i,{value:Xe(s,e),enumerable:!0,configurable:!0,writable:!0});return o}function to(n){return{...n,relationMeta:Xe(n.relationMeta),purposes:[...n.purposes]}}var Te,sr=Q(()=>{"use strict";Te=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){let t=this.map.get(e);return t?to(t):void 0}getAll(){return Array.from(this.map.values(),to)}createCheckpoint(){return this.getAll()}restoreCheckpoint(e){let t=new Map;for(let r of e){let o=to(r);if(t.has(o.id))throw new Error(`Duplicate join registry checkpoint ID "${o.id}"`);t.set(o.id,o)}for(let r of t.values()){if(r.parentJoinId===null){if(r.id!==r.propertyName)throw new Error(`Invalid root join ID "${r.id}"`);continue}let o=t.get(r.parentJoinId);if(!o||o.targetTable!==r.parentTable||r.id!==`${r.parentJoinId}.${r.propertyName}`)throw new Error(`Invalid parent join for "${r.id}"`)}this.map.clear();for(let[r,o]of t)this.map.set(r,o)}registerWithParent(e,t,r,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t,c=r?.tables?.get(e);if(!c)return null;let u=c.relations?.find(d=>d.propertyName===t);if(!u)return null;let l=u.targetTableName||u.targetTable;if(!l)return null;if(i!==null){let d=this.map.get(i);if(!d||d.targetTable!==e)throw new Error(`Invalid parent join for "${a}"`)}if(this.map.has(a)){let d=this.map.get(a);if(d.parentTable!==e||d.propertyName!==t||d.targetTable!==l||d.relationType!==u.type||d.parentJoinId!==i)throw new Error(`Join registry collision for "${a}"`);return o==="inner"&&(d.joinType="inner"),d.purposes.includes(s)||d.purposes.push(s),a}let f={id:a,propertyName:t,parentTable:e,targetTable:l,relationType:u.type,parentJoinId:i,joinType:o,relationMeta:Xe(u),purposes:[s]};return this.map.set(a,f),a}}});function ti(n){let e=new Set(n),t={get size(){return e.size},has(r){return e.has(r)},forEach(r,o){for(let i of e)r.call(o,i,i,t)},entries(){return e.entries()},keys(){return e.keys()},values(){return e.values()},[Symbol.iterator](){return e[Symbol.iterator]()}};return Object.freeze(t)}function Qr(n){return Object.prototype.hasOwnProperty.call(ei,n)?ei[n]:null}var de,ro,ar,ei,wt=Q(()=>{"use strict";de=ti(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),ro=ti(["_and","_or","_not"]),ar=Object.freeze([...ro,...de]),ei=Object.assign(Object.create(null),{_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 w,re=Q(()=>{"use strict";w=class extends Error{constructor(t="Bad Request",r){let o=Array.isArray(t),i;if(o)i=t.join("; ")||"Bad Request";else if(typeof t=="string")i=t;else try{i=JSON.stringify(t)||"Bad Request"}catch{i="Bad Request"}super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=r,o&&(this.messages=[...t])}}});function ri(){let n=process.env.DB_URI||"";return n.startsWith("mongodb://")||n.startsWith("mongodb+srv://")}var ni=Q(()=>{"use strict"});function Ze(n,e,t){throw new w({message:`Unsupported filter operator "${n}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${ar.join(", ")}.`,error:"UnsupportedFilterOperator",operator:n,field:e,supportedOperators:ar})}function no(n,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let r=ri();for(let o of Object.keys(e))if(o.startsWith("_")&&!de.has(o)){if(r&&o==="_id")continue;Ze(o,n,t)}}function oi(n){if(n>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`)}function ii(n,e,t,r){if(!n||typeof n!="object")return;if(oi(e),t.has(n))throw new w("Filter contains a circular reference");let o=r.get(n);if(!(o!==void 0&&o>=e)){t.add(n);try{for(let i of Object.values(n))ii(i,e+1,t,r);r.set(n,Math.max(o??-1,e))}finally{t.delete(n)}}}function fa(n,e,t){let r=t.get(n);if(r)return r;let o=e?.tables?.get(n);if(!o)throw new w(`Filter validation requires metadata for table '${n}'`);let i=o?.columns??[],s={columnNames:new Set(i.map(a=>a.name)),relationMap:new Map((o?.relations??[]).map(a=>[a.propertyName,a])),acceptsIdAlias:i.some(a=>a.name==="_id"&&a.isPrimary)&&!i.some(a=>a.name==="id")};return t.set(n,s),s}function lr(n,e,t,r,o,i,s,a=!1){if(!n||typeof n!="object")return;if(oi(r),o.has(n))throw new w("Filter contains a circular reference");let c=`${e}:${a?"nested":"root"}`,u=s.get(n),l=u?.get(c);if(!(l!==void 0&&l>=r)){o.add(n);try{if(Array.isArray(n)){for(let y of n)lr(y,e,t,r+1,o,i,s,a);let h=u??new Map;h.set(c,Math.max(h.get(c)??-1,r)),s.set(n,h);return}let{columnNames:f,relationMap:d,acceptsIdAlias:p}=fa(e,t,i);for(let[h,y]of Object.entries(n)){if(a&&de.has(h)){if(h==="_is_null"||h==="_is_not_null"){if(typeof y!="boolean")throw new w(`Relation filter operator '${h}' requires a boolean value`)}else if((h==="_in"||h==="_not_in"||h==="_nin"||h==="_between")&&!Array.isArray(y))throw new w(`Relation filter operator '${h}' requires an array value`);continue}if(ua.has(h)){if(h==="_and"||h==="_or"){if(!Array.isArray(y)||y.some(S=>!S||typeof S!="object"||Array.isArray(S)))throw new w(`Filter '${h}' value must be an array of filter objects`)}else if(!y||typeof y!="object"||Array.isArray(y))throw new w("Filter '_not' value must be a filter object");lr(y,e,t,r+1,o,i,s,a);continue}let m=d.get(h);if(m){if(y===null)continue;if(typeof y!="object"||Array.isArray(y)){lr({id:{_eq:y}},m.targetTableName||m.targetTable,t,r+1,o,i,s,!0);continue}let S=m.targetTableName||m.targetTable;if(typeof S!="string"||!S||!t?.tables?.has(S))throw new w(`Filter relation '${h}' on '${e}' has no resolvable target table metadata`);lr(y,S,t,r+1,o,i,s,!0);continue}let b=p&&(h==="id"||h==="_id"),_=f.has("_id")&&h==="_id";if(h.startsWith("_")&&!f.has(h)&&!b&&Ze(h,h,e),!f.has(h)&&!b&&!_)throw new w(`Unknown filter field '${h}' on table '${e}'`);y&&typeof y=="object"&&no(h,y,e)}let g=u??new Map;g.set(c,Math.max(g.get(c)??-1,r)),s.set(n,g)}finally{o.delete(n)}}}function De(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))throw new w("Filter must be an object");ii(n,0,new Set,new WeakMap),lr(n,e,t,0,new Set,new Map,new WeakMap)}var ne,ua,Le=Q(()=>{"use strict";re();ni();wt();ne=64,ua=new Set(["_and","_or","_not"])});function Me(n,e,t,r){if(n===void 0)return{node:null,hasRelationFilters:!1};if(!n||typeof n!="object"||Array.isArray(n))throw new w("Filter must be an object");let o={tableName:e,metadata:t,registry:r,parentJoinId:null,currentJoinId:null,currentTable:e,depth:0,ancestors:new Set},i=r.createCheckpoint();try{return Jr(n,o)}catch(s){throw r.restoreCheckpoint(i),s}}function Jr(n,e){if(!n||typeof n!="object"||Array.isArray(n))throw new w("Logical filter operand must be a filter object");if(e.depth>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(e.ancestors.has(n))throw new w("Filter contains a circular reference");e.ancestors.add(n);let t=e.registry.createCheckpoint();try{let r=[],o=!1,i=!1;for(let[s,a]of Object.entries(n)){let c=da(s,a,e),u=c.node;if(u?.kind==="false")return e.registry.restoreCheckpoint(t),{node:u,hasRelationFilters:!1};if(u?.kind==="true"){i=!0;continue}c.hasRelationFilters&&(o=!0),u&&r.push(u)}return r.length===0?{node:i?{kind:"true"}:null,hasRelationFilters:o}:r.length===1?{node:r[0],hasRelationFilters:o}:{node:{kind:"and",children:r},hasRelationFilters:o}}finally{e.ancestors.delete(n)}}function ai(n){return{...n,depth:n.depth+1}}function da(n,e,t){if(n==="_and")return si("and",e,t);if(n==="_or")return si("or",e,t);if(n==="_not"){if(!e||typeof e!="object"||Array.isArray(e))throw new w("Filter '_not' value must be a filter object");let u=t.registry.createCheckpoint(),l=Jr(e,ai(t)),f=l.node??{kind:"true"};return f.kind==="true"||f.kind==="false"?(t.registry.restoreCheckpoint(u),{node:{kind:f.kind==="true"?"false":"true"},hasRelationFilters:!1}):{node:{kind:"not",child:f},hasRelationFilters:l.hasRelationFilters}}let r=t.metadata?.tables?.get(t.currentTable);if(!r)throw new w(`Filter parsing requires metadata for table '${t.currentTable}'`);let o=r.columns?.some(u=>u.name==="_id"&&u.isPrimary),i=r?.columns?.some(u=>u.name==="id"),a=n==="id"?o&&!i?"_id":"id":n,c=r?.relations?.find(u=>u.propertyName===a);if(c)return zr(a,e,c,t);if(r&&!r.columns?.find(l=>l.name===a))throw n.startsWith("_")&&n!=="_id"&&Ze(n,n,t.currentTable),new w(`Unknown field '${n}' on table '${t.currentTable}'`);return pa(a,e,t)}function si(n,e,t){if(!Array.isArray(e))throw new w(`Filter '${n}' value must be an array`);let r=t.registry.createCheckpoint(),o=[],i=!1;for(let a of e){if(!a||typeof a!="object"||Array.isArray(a))throw new w(`Filter '${n}' entries must be filter objects`);let c=t.registry.createCheckpoint(),u=Jr(a,ai(t)),l=u.node??{kind:"true"};n==="and"&&l.kind==="true"||n==="or"&&l.kind==="false"?t.registry.restoreCheckpoint(c):u.hasRelationFilters&&(i=!0),o.push(l)}if(o.length===0)return{node:{kind:n==="and"?"true":"false"},hasRelationFilters:i};if(n==="or"&&o.some(a=>a.kind==="true"))return t.registry.restoreCheckpoint(r),{node:{kind:"true"},hasRelationFilters:!1};if(n==="and"&&o.some(a=>a.kind==="false"))return t.registry.restoreCheckpoint(r),{node:{kind:"false"},hasRelationFilters:!1};let s=o.filter(a=>n==="and"?a.kind!=="true":a.kind!=="false");return s.length===0?{node:{kind:n==="and"?"true":"false"},hasRelationFilters:i}:s.length===1?{node:s[0],hasRelationFilters:i}:{node:{kind:n,children:s},hasRelationFilters:i}}function zr(n,e,t,r){if(typeof e!="object"||e===null||Array.isArray(e))return e===null?zr(n,{id:{_is_null:!0}},t,r):Array.isArray(e)?zr(n,{id:{_in:e}},t,r):zr(n,{id:{_eq:e}},t,r);let o=Object.keys(e);if(o.length===0)return{node:null,hasRelationFilters:!1};let i=r.registry.createCheckpoint(),s=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"),a=r.registry.registerWithParent(r.currentTable,n,r.metadata,"left",r.currentJoinId,"filter");if(s&&(o[0]==="_is_null"||o[0]==="_is_not_null")&&typeof e[o[0]]!="boolean")throw new w(`Relation null-check operator '${o[0]}' requires a boolean value`);if(!a)throw new w(`Unable to register filter join for relation '${n}'`);if(s&&o[0]==="_is_null")return{node:{kind:"relation_exists",joinId:a,negate:e._is_null===!0},hasRelationFilters:!0};if(s&&o[0]==="_is_not_null")return{node:{kind:"relation_exists",joinId:a,negate:e._is_not_null!==!0},hasRelationFilters:!0};if(s&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return{node:{kind:"relation_exists",joinId:a,negate:o[0]==="_eq"},hasRelationFilters:!0};let c=t.targetTableName||t.targetTable;if(!c)throw new w(`Relation '${n}' has no target table metadata`);let u={...r,parentJoinId:r.currentJoinId,currentJoinId:a,currentTable:c,depth:r.depth+1},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte","_between"]),d=o.length>0&&o.every(g=>l.has(g))?{id:e}:e,p=Jr(d,u);return!p.node||p.node.kind==="true"||p.node.kind==="false"?(r.registry.restoreCheckpoint(i),{node:p.node,hasRelationFilters:!1}):{node:p.node,hasRelationFilters:!0}}function oo(n,e,t){if(!(!n||typeof n!="object")){if(e>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(t.has(n))throw new w("Filter contains a circular reference");t.add(n);try{for(let r of Object.values(n))oo(r,e+1,t)}finally{t.delete(n)}}}function pa(n,e,t){let r={joinId:t.currentJoinId,fieldName:n,isUuid:ha(n,t)};if(e===null)return{node:{kind:"compare",field:r,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:r,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!de.has(s)&&Ze(s,n,t.tableName);let o=Object.entries(e).filter(([s])=>de.has(s));if(o.length>0&&o.length!==Object.keys(e).length)throw new w(`Field '${n}' has mixed filter operators and object properties`);if(o.length===0)return oo(e,t.depth+1,new Set),{node:{kind:"compare",field:r,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){if(oo(a,t.depth+1,new Set),(s==="_in"||s==="_not_in"||s==="_nin")&&!Array.isArray(a))throw new w(`Filter operator '${s}' requires an array value`);if(s==="_between"&&(!Array.isArray(a)||a.length!==2))throw new w("Filter operator '_between' requires an array with exactly two values");let c=ga(r,s,a);c&&i.push(c)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function ga(n,e,t){if(e==="_is_null"||e==="_is_not_null"){if(typeof t!="boolean")throw new w(`Filter operator '${e}' requires a boolean value`);return{kind:"compare",field:n,op:"is_null",value:e==="_is_null"?t:!t}}let r=Qr(e);return r?{kind:"compare",field:n,op:r,value:t}:null}function ha(n,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let r=n.includes(".")?n.split(".").pop():n,o=t.columns?.find(a=>a.name===r);if(!o)return!1;let s=(typeof o.type=="string"?o.type:typeof o.type?.name=="string"?o.type.name:"").toLowerCase();return s==="uuid"||s==="uuidv4"||s.includes("uuid")}var cr=Q(()=>{"use strict";wt();Le();re()});function ur(n){return Buffer.byteLength(n,"utf8")<=ba}function Xr(n){return n.map(e=>`${Buffer.byteLength(e,"utf8")}:${e}`).join("|")}function fr(n){return co.createHash("md5").update(n).digest("hex").substring(0,8)}function pi(n){let e=`${n}_pk`;return ur(e)?e:`j_${fr(n)}_pk`}function gi(n,e,t){let r=`${n}_${e}_foreign`;return ur(r)?r:`j_${fr(n)}_${t}_fk`}function dr(n,e,t){let r=[n,e,t],o=r.some(s=>s.includes(":"))?Xr(r):r.join(":");return`j_${co.createHash("sha1").update(o).digest("hex").slice(0,12)}`}function ie(n){let e=`${n}Id`;return ur(e)?e:`fk_${fr(Xr([n,"Id"]))}`}function pr(n,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function hi(n){return n.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function mi(n){return n.replace(/([A-Z])/g,"_$1").toLowerCase()}function yi(n,e,t){let r=`${n}_${e}_${t}_fk`;return ur(r)?r:`r_${fr(Xr([n,e,t]))}_${t}_fk`}function bi(n,e,t){let r=`${n}_${e}_${t}_idx`;return ur(r)?r:`r_${fr(Xr([n,e,t]))}_${t}_idx`}var co,ba,et=Q(()=>{"use strict";co=Je(require("crypto")),ba=63});var St,ae,hr,mr,$t=Q(()=>{"use strict";St=16,ae=5e3,hr=4,mr=10});var xa,nn,xi=Q(()=>{"use strict";re();$t();xa=new Set(["many-to-one","one-to-one","one-to-many","many-to-many"]),nn=class{constructor(e,t){this.adapter=e;this.metadataGetter=t}normalizeDeepFields(e,t){if(e===void 0)return t;if(!Array.isArray(e)&&typeof e!="string")throw new w("Deep relation fields must be a string or string array");let r=Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean);if(r.some(o=>typeof o!="string"))throw new w("Deep relation fields must be strings");return r.map(o=>o.trim()).filter(Boolean)}normalizeDeepSort(e){if(e!==void 0){if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new w("Deep relation sort entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new w("Deep relation sort must be a string or string array");return e}}normalizeDeepPagination(e,t){if(e===void 0)return;if(typeof e!="number"&&typeof e!="string")throw new w(`Deep relation ${t} must be an integer`);let r=String(e);if(!/^\d+$/.test(r))throw new w(`Deep relation ${t} must be an integer`);let o=Number(r),i=t==="limit"?0:1;if(!Number.isSafeInteger(o)||o<i)throw new w(`Deep relation ${t} must be a safe integer greater than or equal to ${i}`);return o}normalizeDescriptors(e){let t=new Set;for(let r of e){if(t.has(r.relationName))throw new w(`Duplicate deep relation '${r.relationName}'`);t.add(r.relationName)}return e.map(r=>{if(!xa.has(r.type))throw new w(`Unsupported relation type '${r.type}' for '${r.relationName}'`);return this.withDefaultToManyLimit({...r,fields:this.normalizeDeepFields(r.fields,[]),userSort:this.normalizeDeepSort(r.userSort),userLimit:this.normalizeDeepPagination(r.userLimit,"limit"),userPage:this.normalizeDeepPagination(r.userPage,"page")})})}entryValue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}enrichNestedDescs(e,t,r,o){if(t===void 0)return e;if(!t||typeof t!="object"||Array.isArray(t))throw new w("Nested deep options must be an object");if(Object.keys(t).length===0)return e;let i=e.map(a=>{if(!Object.prototype.hasOwnProperty.call(t,a.relationName))return a;let c=t[a.relationName];if(!c||typeof c!="object"||Array.isArray(c))throw new w(`Nested deep option for relation '${a.relationName}' must be an object`);let u=this.entryValue(c,"fields"),l=this.entryValue(c,"filter"),f=this.entryValue(c,"sort"),d=this.entryValue(c,"limit"),p=this.entryValue(c,"page"),g=this.entryValue(c,"deep");return{...a,fields:this.normalizeDeepFields(u,o?.has(a.relationName)&&a.fields.length>0?a.fields:["*"]),userFilter:l??a.userFilter,userSort:f!==void 0?this.normalizeDeepSort(f):a.userSort,userLimit:d!==void 0?this.normalizeDeepPagination(d,"limit"):a.userLimit,userPage:p!==void 0?this.normalizeDeepPagination(p,"page"):a.userPage,nestedDeep:g??a.nestedDeep}}),s=new Set(i.map(a=>a.relationName));for(let[a,c]of Object.entries(t)){if(s.has(a))continue;if(!c||typeof c!="object"||Array.isArray(c))throw new w(`Nested deep option for relation '${a}' must be an object`);let u=r?.relations?.find(m=>m.propertyName===a);if(!u)throw new w(`Unknown nested deep relation '${a}' on '${r?.name??"unknown"}'`);let l=this.entryValue(c,"fields"),f=this.entryValue(c,"filter"),d=this.entryValue(c,"sort"),p=this.entryValue(c,"limit"),g=this.entryValue(c,"page"),h=this.entryValue(c,"deep"),y=this.normalizeDeepFields(l,["*"]);i.push({relationName:a,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:y,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:f,userSort:this.normalizeDeepSort(d),userLimit:this.normalizeDeepPagination(p,"limit"),userPage:this.normalizeDeepPagination(g,"page"),nestedDeep:h})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:10}:e}projectedRelations(e){let t=new Set;for(let r of e)r==="*"||!r.includes(".")||t.add(r.split(".")[0]);return t}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let r=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))r.has(i)||o.push(i);return o}getMetadata(e,t){let r=t.metadataByTable.get(e);if(r)return r;let o=this.metadataGetter(e);return t.metadataByTable.set(e,o),o}async prepareDescriptor(e,t,r,o){let i=await this.getMetadata(e.targetTable,o);if(!i)throw new Error(`Metadata not found for target table: ${e.targetTable}`);this.assertLocalSortFields(e,i);let{nestedDescs:s,fetchSpec:a}=this.adapter.resolveFields(this.fieldsForNestedResolution(e.fields,e.nestedDeep),i);if(r+1>=t)return{desc:e,targetMeta:i,fetchSpec:a,children:[]};let c=await Promise.all(this.normalizeDescriptors(this.enrichNestedDescs(s,e.nestedDeep,i,this.projectedRelations(e.fields))).map(u=>this.prepareDescriptor(u,t,r+1,o)));return{desc:e,targetMeta:i,fetchSpec:a,children:c}}assertLocalSortFields(e,t){if(!e.userSort)return;let r=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of r){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new w(`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(c=>c.name===i),a=i==="id"&&t.columns?.some(c=>c.name==="_id");if(!s&&!a)throw new w(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}}});async function W(n,e,t=5e3){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(n.length===0)return[];if(n.length<=t)return e(n);let r=[];for(let f=0;f<n.length;f+=t)r.push(n.slice(f,f+t));let o=[],i=0,s=!1,a=!1,c;async function u(){for(;!s;){let f=i;if(f>=r.length)return;i+=1;try{o[f]=await e(r[f])}catch(d){a||(a=!0,c=d),s=!0}}}let l=Math.min(4,r.length);if(await Promise.all(Array.from({length:l},()=>u())),a)throw c;return o.flat()}function nt(n){let e=[],t=new Map;for(let r of n)if(r==="*"||!r.includes("."))e.push(r);else{let o=r.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 Ci=Q(()=>{"use strict";$t()});var qe,Ne=Q(()=>{"use strict";re();xi();$t();Ci();$t();qe=class{constructor(e,t,r){this.adapter=e;this.trace=r;this.plan=new nn(e,t)}uniqueValues(e){let t=new Set,r=[];for(let o of e){if(o==null)continue;let i=this.adapter.keyOf(o);t.has(i)||(t.add(i),r.push(o))}return r}setRelation(e,t,r){let o=Object.getOwnPropertyDescriptor(e,t);if(o&&!o.configurable){Object.defineProperty(e,t,{value:r});return}Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}assertCommitCanApply(e,t,r){for(let o of t){let i=o.desc;for(let s of e){let a=Object.getOwnPropertyDescriptor(s,i.relationName);if(!a&&!Object.isExtensible(s))throw new Error(`Cannot add relation '${i.relationName}' to a non-extensible result`);if(a&&!a.configurable&&(!("writable"in a)||!a.writable))throw new Error(`Cannot replace non-writable relation '${i.relationName}'`);for(let c of i.injectedParentFields??[]){if(r.has(c))continue;let u=Object.getOwnPropertyDescriptor(s,c);if(u&&!u.configurable)throw new Error(`Cannot remove injected relation field '${c}'`)}}}}createStagingParent(e){let t=Object.create(Object.getPrototypeOf(e));for(let r of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,r);"value"in o?Object.defineProperty(t,r,{value:o.value,enumerable:o.enumerable,writable:!0,configurable:!0}):Object.defineProperty(t,r,{get:o.get,set:o.set,enumerable:o.enumerable,configurable:!0})}return t}async execute(e,t,r=3,o=0,i){if(!Number.isSafeInteger(r)||r<0)throw new w("Maximum query depth must be a non-negative safe integer");if(!Number.isSafeInteger(o)||o<0)throw new w("Current query depth must be a non-negative safe integer");if(t.length===0||o>=r)return;let s={metadataByTable:new Map},a;if(i&&(a=await this.plan.getMetadata(i,s)??void 0,!a))throw new Error(`Metadata not found for parent table: ${i}`);let c=await Promise.all(this.plan.normalizeDescriptors(t).map(u=>this.plan.prepareDescriptor(u,r,o,s)));await this.executePrepared(e,c,r,o,a,s)}async executePrepared(e,t,r,o,i,s){if(e.length===0)return;let a=new Array(t.length),c=new Array(t.length),u=0,l=!1,f,d=async()=>{for(;!l&&u<t.length;){let g=u;u+=1;let h=t[g],y=h.desc,m=e.map(b=>this.createStagingParent(b));try{y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse?await this.fetchOwnerRelation(m,h,r,o,s):y.type==="one-to-many"||y.type==="one-to-one"&&y.isInverse?await this.fetchInverseRelation(m,h,r,o,i,s):y.type==="many-to-many"&&await this.fetchM2MRelation(m,h,r,o,i,s),a[g]=m.map(b=>b[y.relationName]),c[g]={status:"fulfilled",value:void 0}}catch(b){c[g]={status:"rejected",reason:b},l||(f=b),l=!0}}};if(await Promise.all(Array.from({length:Math.min(4,t.length)},()=>d())),l)throw f;let p=new Set(t.map(({desc:g})=>g.relationName));this.assertCommitCanApply(e,t,p);for(let g=0;g<t.length;g+=1){let h=t[g].desc,y=a[g];for(let m=0;m<e.length;m+=1){this.setRelation(e[m],h.relationName,y[m]);for(let b of h.injectedParentFields??[])p.has(b)||delete e[m][b]}}}async fetchOwnerRelation(e,t,r,o,i){let{desc:s,targetMeta:a,fetchSpec:c,children:u}=t,l=this.adapter.resolveOwnerFkKey(s),f=new Set,d=[];for(let _ of e){let S=_[l];if(S==null)continue;let E=this.adapter.keyOf(S);f.has(E)||(f.add(E),d.push(S))}if(d.length===0){for(let _ of e)this.setRelation(_,s.relationName,null),l!==s.relationName&&delete _[l],s.fkColumn&&s.fkColumn!==s.relationName&&delete _[s.fkColumn];return}let p=this.adapter.getTargetPkField(a),g=performance.now(),h=await this.adapter.fetchOwner(s.targetTable,d,c,s),y=Array.isArray(h)?h:h.docs,m=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${o}_${s.relationName}`,g,{relationType:s.type,targetTable:s.targetTable,strategy:m?.strategy??"batch-in",roundtrips:m?.roundtrips??(Math.ceil(d.length/5e3)||1),concurrencyWaves:m?.concurrencyWaves,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??y.length,rowsReturned:y.length,rowsDiscarded:0,userFilter:!!s.userFilter,userSort:!!s.userSort});let b=new Map;for(let _ of y)b.set(this.adapter.keyOf(_[p]),_);u.length>0&&await this.executePrepared(y,u,r,o+1,a,i);for(let _ of e){let S=_[l];this.setRelation(_,s.relationName,S!=null&&b.get(this.adapter.keyOf(S))||null),l!==s.relationName&&delete _[l],s.fkColumn&&s.fkColumn!==s.relationName&&delete _[s.fkColumn]}}async fetchInverseRelation(e,t,r,o,i,s){let{desc:a,targetMeta:c,fetchSpec:u,children:l}=t,f=this.adapter.resolveParentPk(i),d=this.uniqueValues(e.map(M=>M[f]));if(d.length===0){for(let M of e)this.setRelation(M,a.relationName,a.type==="one-to-one"?null:[]);return}let p=this.adapter.resolveInverseFkField(a),g=performance.now(),{docs:h,groupKeyField:y,stats:m}=await this.adapter.fetchInverse(a.targetTable,p,d,u,a),b=new Map,_=a.fields.includes("*")||a.fields.some(M=>M===p||M.startsWith(`${p}.`));for(let M of h){let N=M[y],j=this.adapter.keyOf(N);b.has(j)||b.set(j,[]),b.get(j).push(M)}let S=a.userLimit!==void 0&&a.userLimit>0,E=S?"per-parent-c16":"batch-in",C=S?d.length:Math.ceil(d.length/5e3)||1,x=S?Math.ceil(d.length/16):void 0,v=Array.from(b.values()).reduce((M,N)=>M+N.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${a.relationName}`,g,{relationType:a.type,targetTable:a.targetTable,strategy:m?.strategy??E,roundtrips:m?.roundtrips??C,concurrencyWaves:m?.concurrencyWaves??x,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??h.length,rowsReturned:v,rowsDiscarded:Math.max(0,(m?.rowsTransferred??h.length)-v),userLimit:a.userLimit,userFilter:!!a.userFilter,userSort:!!a.userSort}),l.length>0&&await this.executePrepared(h,l,r,o+1,c,s),this.adapter.postProcessInverseChild)for(let M of h)this.adapter.postProcessInverseChild(M,p,_);let R=a.type==="one-to-one";for(let M of e){let N=M[f];if(N==null){this.setRelation(M,a.relationName,R?null:[]);continue}let j=b.get(this.adapter.keyOf(N))||[];this.setRelation(M,a.relationName,R?j[0]||null:j)}}async fetchM2MRelation(e,t,r,o,i,s){let{desc:a,targetMeta:c,fetchSpec:u,children:l}=t,f=this.adapter.resolveParentPk(i),d=this.uniqueValues(e.map(x=>x[f]));if(d.length===0){for(let x of e)this.setRelation(x,a.relationName,[]);return}let p=e.filter(x=>x[f]!=null),g=performance.now(),{grouped:h,docs:y,stats:m}=await this.adapter.fetchM2M(p,a,i,c,u),b=a.userLimit!==void 0&&a.userLimit>0,_=b?"m2m-per-parent-c16":"m2m-batch",S=b?d.length:Math.ceil(d.length/5e3)||1,E=b?Math.ceil(d.length/16):void 0,C=Array.from(h.values()).reduce((x,v)=>x+v.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${a.relationName}`,g,{relationType:a.type,targetTable:a.targetTable,strategy:m?.strategy??_,roundtrips:m?.roundtrips??S,concurrencyWaves:m?.concurrencyWaves??E,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??y.length,rowsReturned:C,rowsDiscarded:m?.rowsDiscarded??Math.max(0,(m?.rowsTransferred??y.length)-C),userLimit:a.userLimit,userFilter:!!a.userFilter,userSort:!!a.userSort}),l.length>0){let x=Array.from(new Set(Array.from(h.values()).flat()));x.length>0&&await this.executePrepared(x,l,r,o+1,c,s)}for(let x of e){let v=x[f];if(v==null){this.setRelation(x,a.relationName,[]);continue}let R=this.adapter.keyOf(v);this.setRelation(x,a.relationName,h.get(R)||[])}}}});var Fi,We,on=Q(()=>{"use strict";Fi=2,We=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];this.waiterHead=0;this.failed=!1;if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{if(this.failed)throw this.failure;return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failed)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(!await new Promise(t=>this.waiters.push(t)))throw this.failure;if(this.failed)throw this.active-=1,this.failure}release(){if(this.active<1)throw new Error("Batch execution permit underflow");if(this.failed){this.active-=1;return}let e=this.waiters[this.waiterHead];if(e){this.waiters[this.waiterHead]=void 0,this.waiterHead+=1,this.waiterHead>1024&&this.waiterHead*2>this.waiters.length&&(this.waiters.splice(0,this.waiterHead),this.waiterHead=0),e(!0);return}this.active-=1}cancel(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t=this.waiterHead;t<this.waiters.length;t+=1)this.waiters[t]?.(!1);this.waiters.length=0,this.waiterHead=0}}}});function I(n,e){if(e==="mongodb")return n;let t=["postgres","pg","sqlite"].includes(e)?'"':"`";return t+n.split(t).join(t+t)+t}function ze(n,e){let t=[],r=0;for(;r<n.length;){let o=n[r];if(o==='"'||o==="`"){r++;let i="",s=!1;for(;r<n.length;){let a=n[r++];if(a!==o){i+=a;continue}if(n[r]===o){i+=o,r++;continue}s=!0;break}if(!s||r<n.length&&n[r]!==".")throw new Error("Invalid quoted SQL identifier");t.push(I(i,e))}else{let i=n.indexOf(".",r),s=n.slice(r,i===-1?void 0:i);if(!s)throw new Error("Invalid qualified SQL identifier");t.push(s==="*"?s:I(s,e)),r=i===-1?n.length:i}if(r<n.length&&(r++,r===n.length))throw new Error("Invalid qualified SQL identifier")}if(t.length===0)throw new Error("Invalid qualified SQL identifier");return t.join(".")}var Se=Q(()=>{"use strict"});function ee(n){return n.columns.find(e=>e.isPrimary)||null}var ft=Q(()=>{"use strict"});function ue(n,e,t){e&&Pt(n,e,t,"and")}function Pt(n,e,t,r){switch(e.kind){case"true":r==="or"?n.orWhereRaw("1 = 1"):n.whereRaw("1 = 1");return;case"false":r==="or"?n.orWhereRaw("1 = 0"):n.whereRaw("1 = 0");return;case"and":{if(e.children.length===0){Pt(n,{kind:"true"},t,r);return}let o=function(){for(let i of e.children)this.where(function(){Pt(this,i,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"or":{if(e.children.length===0){Pt(n,{kind:"false"},t,r);return}let o=function(){for(let i of e.children)this.orWhere(function(){Pt(this,i,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"not":{let o=function(){this.whereNot(function(){Pt(this,e.child,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"compare":cl(n,e,t,r);return;case"relation_exists":throw new Error(`SQL relation_exists node requires a materialized join: ${e.joinId}`)}}function cl(n,e,t,r){if(e.field.joinId!==null)throw new Error(`SQL comparison requires a materialized join target: ${e.field.joinId}`);let o=fl(e.field,t),i=ze(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",c=r==="or"?"orWhere":"where",u=r==="or"?"orWhereRaw":"whereRaw",l=r==="or"?"orWhereIn":"whereIn",f=r==="or"?"orWhereNotIn":"whereNotIn",d=r==="or"?"orWhereBetween":"whereBetween",p=r==="or"?"orWhereNull":"whereNull",g=r==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":e.value===null?n[p](o):s&&a&&typeof e.value=="string"?n[u](`${i} = ?::uuid`,[e.value]):n[c](o,"=",e.value);return;case"neq":e.value===null?n[g](o):s&&a&&typeof e.value=="string"?n[u](`${i} != ?::uuid`,[e.value]):n[c](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?n[u](`${i} > ?::uuid`,[e.value]):n[c](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?n[u](`${i} >= ?::uuid`,[e.value]):n[c](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?n[u](`${i} < ?::uuid`,[e.value]):n[c](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?n[u](`${i} <= ?::uuid`,[e.value]):n[c](o,"<=",e.value);return;case"in":{let h=ls(e.value);h.length===0?n[u]("1 = 0"):s&&a&&h.every(y=>typeof y=="string")?n[u](`${i} = ANY(?::uuid[])`,[h]):n[l](o,h);return}case"not_in":{let h=ls(e.value);h.length===0?n[u]("1 = 1"):s&&a&&h.every(y=>typeof y=="string")?n[u](`${i} != ALL(?::uuid[])`,[h]):n[f](o,h);return}case"contains":Co(n,i,e.value,"contains",t,r);return;case"starts_with":Co(n,i,e.value,"starts_with",t,r);return;case"ends_with":Co(n,i,e.value,"ends_with",t,r);return;case"between":if(!Array.isArray(e.value)||e.value.length!==2)throw new Error("Invalid between filter value");n[d](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?n[p](o):n[g](o);return}}function ul(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Co(n,e,t,r,o,i){let s=i==="or"?"orWhereRaw":"whereRaw",a=ul(t);if(o.dbType==="postgres"){let u=r==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%' ESCAPE '='`:r==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%' ESCAPE '='`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) ESCAPE '='`;n[s](u,[a]);return}if(o.dbType==="sqlite"){let u=r==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%' ESCAPE '='`:r==="starts_with"?`lower(${e}) LIKE lower(?) || '%' ESCAPE '='`:`lower(${e}) LIKE '%' || lower(?) ESCAPE '='`;n[s](u,[a]);return}let c=r==="contains"?`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(?) COLLATE utf8mb4_general_ci, '%') ESCAPE '='`:r==="starts_with"?`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(?) COLLATE utf8mb4_general_ci, '%') ESCAPE '='`:`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(?) COLLATE utf8mb4_general_ci) ESCAPE '='`;n[s](c,[a])}function fl(n,e){let t=n.fieldName.split(".");if(t.some(r=>!r))throw new Error("Invalid SQL filter field");if(t.length===1)return`${e.rootTable}.${t[0]}`;if(t.length!==2||t[0]!==e.rootTable)throw new Error("Invalid SQL filter field");return n.fieldName}function ls(n){return Array.isArray(n)?n:typeof n=="string"&&n.includes(",")?n.split(",").map(e=>e.trim()):[n]}var Rr=Q(()=>{"use strict";Se()});var fs={};Un(fs,{expandFieldsToJoinsAndSelect:()=>Ro});function us(n,e,t){if(n===void 0)return;let r=typeof n=="number",o=typeof n=="string"&&/^\d+$/.test(n.trim());if(!r&&!o)throw new Error(t);let i=Number(n);if(!Number.isSafeInteger(i)||i<e)throw new Error(t);return i}function dl(n){return us(n,0,"SQL relation limit must be a non-negative safe integer")}function pl(n){return us(n,1,"SQL relation page must be a positive safe integer")}function jt(n,e){return n&&Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0}function cs(n){if(typeof n!="string"&&!Array.isArray(n))throw new Error("SQL relation fields must be a string or string array");let e=typeof n=="string"?n.split(","):n;if(e.some(t=>typeof t!="string"))throw new Error("SQL relation fields must be strings");return e.map(t=>t.trim()).filter(Boolean)}async function Ro(n,e,t,r,o,i){if(o!==void 0&&(!Number.isSafeInteger(o)||o<0))throw new Error("SQL maximum query depth must be a non-negative safe integer");let s=[],a=[],c=await t(n);if(!c)throw new Error(`SQL field expansion requires metadata for '${n}'`);let u=new Map,l=new Set;for(let h of e){let y=h.split(".").map(b=>b.trim());if(y.some(b=>b.length===0))throw new Error(`Malformed SQL field path '${h}'`);let m=y.join(".");if(m==="*"||y.length===1)u.has("")||u.set("",[]),u.get("").push(m);else{let b=y[0],_=y.slice(1).join(".");u.has(b)||u.set(b,[]),u.get(b).push(_)}}if(i&&typeof i=="object")for(let[h,y]of Object.entries(i)){if(u.has(h))continue;let m=y&&typeof y=="object"&&y.fields!=null?cs(y.fields):["*"];u.set(h,m)}let f=u.get("")||[],d=new Set,p=new Set,g=h=>`${I(n,r)}.${I(h,r)}`;for(let h of f){if(h==="*"){let b=new Set;for(let S of c.relations||[])if(S.type==="many-to-one"||S.type==="one-to-one"&&!S.isInverse){let E=S.foreignKeyColumn||ie(S.propertyName);E&&b.add(E)}let _=new Set;for(let S of c.columns)b.has(S.name)||(s.push(g(S.name)),d.add(S.name),_.add(S.name));for(let S of c.relations||[])!u.has(S.propertyName)&&!_.has(S.propertyName)&&(u.set(S.propertyName,[]),l.add(S.propertyName));continue}if(h.includes(".")){s.push(g(h));continue}if(c.columns?.find(b=>b.name===h)){s.push(g(h)),d.add(h);continue}if(c.relations?.find(b=>b.propertyName===h)){u.has(h)||(u.set(h,[]),l.add(h));continue}}for(let[h,y]of u){if(h==="")continue;let m=c.relations?.find(v=>v.propertyName===h);if(!m)continue;if(o===0)throw new Error("SQL relation exceeds maximum query depth");if(m.type==="one-to-one"&&typeof m.isInverse!="boolean")throw new Error(`SQL one-to-one relation '${h}' requires ownership metadata`);let b=m.type==="many-to-one"||m.type==="one-to-one"&&m.isInverse===!1,_=[];if(d.has(h))throw new Error(`SQL relation '${h}' on '${n}' conflicts with a selected root column`);if(p.add(h),b){let v=m.foreignKeyColumn||ie(m.propertyName);if(!c.columns.some(j=>j.name===v))throw new Error(`SQL relation '${h}' foreign key '${v}' is missing from '${n}' metadata`);let R=I(n,r),M=I(v,r),N=I(h,r);s.push(`${R}.${M} as ${N}`),_.push(h)}else{let v=c.columns.filter(R=>R.isPrimary===!0);if(v.length===0)throw new Error(`SQL relation '${h}' on '${n}' requires parent primary key metadata`);for(let R of v){if(p.has(R.name))throw new Error(`SQL parent key '${R.name}' on '${n}' conflicts with a relation output`);d.has(R.name)||(s.push(g(R.name)),d.add(R.name),_.push(R.name))}}let S=m.targetTableName||m.targetTable,E=i&&Object.prototype.hasOwnProperty.call(i,h)?i[h]:void 0,C=jt(E,"fields"),x=C!=null?cs(C):y;if(C==null&&l.has(h)){let v=await t(S);if(!v)throw new Error(`SQL relation '${h}' requires target metadata for '${S}'`);if(x=v.columns.filter(R=>R.isPrimary===!0).map(R=>R.name),x.length===0)throw new Error(`SQL relation '${h}' requires target primary key metadata`)}a.push({relationName:h,type:m.type,targetTable:S,fields:x,isInverse:m.isInverse,fkColumn:b?m.foreignKeyColumn||ie(m.propertyName):m.foreignKeyColumn,injectedParentFields:_.length>0?_:void 0,mappedBy:m.mappedBy,junctionTableName:m.junctionTableName,junctionSourceColumn:m.junctionSourceColumn,junctionTargetColumn:m.junctionTargetColumn,userFilter:jt(E,"filter"),userSort:jt(E,"sort"),userLimit:dl(jt(E,"limit")),userPage:pl(jt(E,"page")),nestedDeep:jt(E,"deep")})}return{select:s,batchFetchDescriptors:a}}var Fo=Q(()=>{"use strict";et();Se()});var Mr,Dt,Bn,ds=Q(()=>{"use strict";Ne();cr();sr();et();ft();Se();Mr="__enfyra_row_number__",Dt="__enfyra_partitioned__",Bn=class{constructor(e,t,r){this.knex=e;this.dbType=t;this.metadata=r}getTableMetadata(e){let t=this.metadata?.tables??this.metadata;if(t)return typeof t.get=="function"?t.get(e):t[e]}sortAlias(e){return`__sort_${e.map(t=>`${t.length}_${t}`).join("_")}`}buildPartitionRowNumber(e,t,r){let o=[...t];o.some(s=>s.column===r)||o.push({column:r,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),Mr])}buildPartitionSlice(e,t,r,o){return this.knex.from(e.as(Dt)).select(`${Dt}.*`).where(`${Dt}.${Mr}`,">",r).andWhere(`${Dt}.${Mr}`,"<=",r+o).orderBy(`${Dt}.${t}`,"asc").orderBy(`${Dt}.${Mr}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Mr]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let r=new Te,o=this.metadata?.tables?this.metadata:{tables:this.metadata instanceof Map?this.metadata:new Map(Object.entries(this.metadata))},{node:i}=Me(e,t,o,r);return i}parseSortTokens(e,t,r){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),c=(s?i.slice(1):i).split(".");if(c.length===1)return{column:r?`${r}.${c[0]}`:`${t}.${c[0]}`,order:s?"desc":"asc"};let u=c[c.length-1];return{column:`${this.sortAlias(c.slice(0,-1))}.${u}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,r,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 u=(a.startsWith("-")?a.slice(1):a).split(".");if(u.length<=1)continue;let l=r,f=o||r;for(let d=0;d<u.length-1;d++){let p=u[d],g=this.getTableMetadata(l);if(!g)break;let h=g.relations?.find(b=>b.propertyName===p);if(!h)break;if(h.isInverse||h.type==="one-to-many"||h.type==="many-to-many")throw new Error(`Dotted sort through inverse or to-many relation '${p}' is not supported`);let y=h.targetTableName||h.targetTable,m=this.sortAlias(u.slice(0,d+1));if(!s.has(m)){s.add(m);let b=h.foreignKeyColumn||ie(h.propertyName),_=this.getTableMetadata(y),S=_&&ee(_)?.name||"id";e.leftJoin(`${y} as ${m}`,`${m}.${S}`,`${f}.${b}`)}l=y,f=m}}}toKnexSelect(e,t){let r=e.indexOf(" as ");if(r!==-1){let o=e.substring(0,r),i=e.substring(r+4),s=I(i,this.dbType),a=t?`${I(t,this.dbType)}.${I(o,this.dbType)}`:I(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${I(t,this.dbType)}.${I(e,this.dbType)} as ${I(e,this.dbType)}`):e}resolveFields(e,t){let{rootFields:r,subRelations:o}=nt(e),i=[];if(r.includes("*")){let u=new Set;for(let l of t.relations||[])if(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse){let f=l.foreignKeyColumn||ie(l.propertyName);f&&u.add(f)}for(let l of t.columns)u.has(l.name)||i.push(l.name);for(let l of t.relations||[])o.has(l.propertyName)||o.set(l.propertyName,["id"])}else for(let u of r){let l=t.columns.find(f=>f.name===u);l?i.push(l.name):t.relations?.find(d=>d.propertyName===u)&&!o.has(u)&&o.set(u,["id"])}let s=ee(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((u,l)=>{let f=t.relations?.find(d=>d.propertyName===l);if(f&&(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse)){let d=f.foreignKeyColumn||ie(f.propertyName);d&&i.push(`${d} as ${l}`)}});let a=[];return o.forEach((u,l)=>{let f=t.relations?.find(p=>p.propertyName===l);if(!f)return;let d=f.targetTableName||f.targetTable;d&&a.push({relationName:l,type:f.type,targetTable:d,fields:u,isInverse:f.isInverse,fkColumn:f.foreignKeyColumn,mappedBy:f.mappedBy,junctionTableName:f.junctionTableName,junctionSourceColumn:f.junctionSourceColumn,junctionTargetColumn:f.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}}});var Ar,Dn,hl,Lt,vo=Q(()=>{"use strict";on();Ne();et();ft();ds();Rr();Ar="__sourceId__",Dn="__targetId__",hl=5e4,Lt=class{constructor(e,t="postgres",r,o=new We){this.knex=e;this.dbType=t;this.metadata=r;this.executionBudget=o;this.pkField="id";this.batchQuery=new Bn(e,t,r)}resolveFields(e,t){return this.batchQuery.resolveFields(e,t)}chunkCount(e,t=5e3){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?hl:5e3}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)}keyOf(e){if(e===null)return"null:";if(e===void 0)return"undefined:";if(typeof e=="number")return Number.isNaN(e)?"number:nan":Object.is(e,-0)?"number:-0":`number:${e}`;if(typeof e=="bigint")return`bigint:${e}`;if(typeof e=="boolean")return`boolean:${e}`;if(typeof e=="string")return`string:${e.length}:${e}`;if(e instanceof Date)return`date:${e.toISOString()}`;throw new Error("SQL relation identity must be a scalar value")}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return ee(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;if(!t&&e.mappedBy&&(t=ie(e.mappedBy)),!t)throw new Error(`Missing inverse foreign key metadata for relation: ${e.relationName}`);return t}resolveParentPk(e){return e&&ee(e)?.name||"id"}async fetchOwner(e,t,r,o){let i=o?.userFilter?this.batchQuery.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.batchQuery.parseSortTokens(o.userSort,e):[],a=r.selectCols.map(l=>this.batchQuery.toKnexSelect(l,e)),c=this.uniqueValues(t),u=await W(c,l=>{let f=this.knex(e).select(a).whereIn(`${e}.${r.pkCol}`,l);if(i&&ue(f,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.batchQuery.applySortJoins(f,o.userSort,e);for(let d of s)f.orderBy(d.column,d.order)}return this.runQuery(f)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,r,o,i){let s=t,a=o.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let c=i?.userFilter?this.batchQuery.buildFilterTree(i.userFilter,e):null,u=i?.userSort?this.batchQuery.parseSortTokens(i.userSort,e):[],l=i?.userLimit,f=i?.userPage,d=this.uniqueValues(r);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,y=o.selectCols.map(b=>this.batchQuery.toKnexSelect(b,e)),m=await W(d,async b=>{let _=this.knex(e).select(y).select(this.batchQuery.buildPartitionRowNumber(`${e}.${t}`,u,`${e}.${o.pkCol}`)).whereIn(`${e}.${t}`,b);c&&ue(_,c,{dbType:this.dbType,rootTable:e}),this.batchQuery.applySortJoins(_,i.userSort,e);let S=await this.runQuery(this.batchQuery.buildPartitionSlice(_,s,h,l));return this.batchQuery.removePartitionFields(S),S});return{docs:m,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(d),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let p=o.selectCols.map(h=>this.batchQuery.toKnexSelect(h,e)),g=await W(d,h=>{let y=this.knex(e).select(p).whereIn(`${e}.${t}`,h);if(c&&ue(y,c,{dbType:this.dbType,rootTable:e}),this.batchQuery.applySortJoins(y,i?.userSort,e),u.length>0)for(let m of u)y.orderBy(m.column,m.order);else y.orderBy(`${e}.${o.pkCol}`,"asc");return this.runQuery(y)});return{docs:g,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(d),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}postProcessInverseChild(e,t,r){r||delete e[t]}async selectM2MEdges(e,t,r,o,i,s,a,c){let u=`t.${s}`,l=!!a||c.some(h=>h.column!==u),f=l?c:c.map(h=>({...h,column:`${r}.${i}`})),d=t.userLimit,p=t.userPage;if(d!==void 0&&d>0){let h=p?(p-1)*d:0;return(await W(e,async m=>{let b=this.knex(r).select({[Ar]:`${r}.${o}`,[Dn]:`${r}.${i}`}).whereIn(`${r}.${o}`,m);l&&(b=b.join(`${t.targetTable} as t`,`${r}.${i}`,`t.${s}`),a&&ue(b,a,{dbType:this.dbType,rootTable:"t"}),this.batchQuery.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.batchQuery.buildPartitionRowNumber(`${r}.${o}`,f,l?u:`${r}.${i}`));let _=await this.runQuery(this.batchQuery.buildPartitionSlice(b,Ar,h,d));return this.batchQuery.removePartitionFields(_),_})).map(m=>({sourceId:m[Ar],targetId:m[Dn]}))}return(await W(e,h=>{let y=this.knex(r).select({[Ar]:`${r}.${o}`,[Dn]:`${r}.${i}`}).whereIn(`${r}.${o}`,h);if(l&&(y=y.join(`${t.targetTable} as t`,`${r}.${i}`,`t.${s}`),a&&ue(y,a,{dbType:this.dbType,rootTable:"t"}),this.batchQuery.applySortJoins(y,t.userSort,t.targetTable,"t")),y.orderBy(`${r}.${o}`,"asc"),f.length>0){for(let m of f)y.orderBy(m.column,m.order);l&&!f.some(m=>m.column===u)&&y.orderBy(u,"asc")}else y.orderBy(`${r}.${i}`,"asc");return this.runQuery(y)})).map(h=>({sourceId:h[Ar],targetId:h[Dn]}))}async loadM2MTargets(e,t,r){if(t.length===0)return[];let o=r.selectCols.map(i=>this.batchQuery.toKnexSelect(i));return W(t,i=>this.runQuery(this.knex(e).select(o).whereIn(r.pkCol,i)),this.m2mTargetChunkSize())}async fetchM2M(e,t,r,o,i){let s=this.resolveParentPk(r),a=this.uniqueValues(e.map(x=>x[s]));if(a.length===0)return{grouped:new Map,docs:[]};let c=t.junctionTableName,u=t.junctionSourceColumn,l=t.junctionTargetColumn;if(!c||!u||!l)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let f=t.userFilter?this.batchQuery.buildFilterTree(t.userFilter,t.targetTable):null,d=t.userSort?this.batchQuery.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,c,u,l,i.pkCol,f,d),g=new Map;for(let x of a)g.set(this.keyOf(x),[]);let h=i.selectCols.length===1&&i.selectCols[0]===i.pkCol,y=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),b=`t.${i.pkCol}`,_=!f&&d.every(x=>x.column===b);if(h){let x=new Map;for(let v of p){let R=this.keyOf(v.targetId);x.has(R)||x.set(R,{[i.pkCol]:v.targetId}),g.get(this.keyOf(v.sourceId))?.push(x.get(R))}return{grouped:g,docs:[],stats:{strategy:_?y?"m2m-junction-partitioned-top-k":"m2m-junction-batch":y?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let S=this.uniqueValues(p.map(x=>x.targetId)),E=await this.loadM2MTargets(t.targetTable,S,i),C=new Map(E.map(x=>[this.keyOf(x[i.pkCol]),x]));for(let x of p){let v=C.get(this.keyOf(x.targetId));v&&g.get(this.keyOf(x.sourceId))?.push(v)}return{grouped:g,docs:E,stats:{strategy:y?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+(S.length>0?this.chunkCount(S,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+E.length,rowsDiscarded:0}}}}});var ps={};Un(ps,{executeBatchFetches:()=>Mo});async function Mo(n,e,t,r,o=3,i=0,s,a="postgres",c,u){let l=new Lt(n,a,c);await new qe(l,r,u).execute(e,t,o,i,s)}var Ao=Q(()=>{"use strict";Ne();vo()});var yl={};Un(yl,{ALL_SUPPORTED_OPERATORS:()=>ar,AuthenticationException:()=>zt,AuthorizationException:()=>Jt,BadRequestException:()=>w,BatchExecutionBudget:()=>We,BatchFetchEngine:()=>qe,BusinessLogicException:()=>Wt,CHUNKED_FETCH_CONCURRENCY:()=>hr,ConfigurationException:()=>Zt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>mr,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Fi,DEFAULT_TIMEOUT_MS:()=>Or,DOTTED_PATH_MAX_HOPS:()=>me,DatabaseException:()=>ht,DuplicateResourceException:()=>Qt,ErrorHandler:()=>Ve,ExecutorEngineService:()=>gt,ExternalServiceException:()=>Gt,FIELD_OPERATORS:()=>de,FileNotFoundException:()=>tr,FileSizeExceededException:()=>rr,FileUploadException:()=>er,HttpException:()=>Y,InvalidTokenException:()=>Vt,IsolatedExecutorService:()=>bt,JoinRegistry:()=>Te,LOGICAL_OPERATORS:()=>ro,MongoBatchAdapter:()=>Rt,MongoQueryExecutor:()=>lt,PER_PARENT_CONCURRENCY:()=>St,QueryBuilderService:()=>qt,QueryPlanner:()=>pe,ResourceNotFoundException:()=>Ut,SchemaException:()=>Xt,ScriptContractService:()=>Ur,ScriptExecutionException:()=>He,ScriptTimeoutException:()=>Be,ServiceUnavailableException:()=>Yt,SqlBatchAdapter:()=>Lt,SqlQueryExecutor:()=>pt,TokenExpiredException:()=>Ht,ValidationException:()=>Kt,WHERE_IN_CHUNK_SIZE:()=>ae,WorkerPool:()=>Ge,applyOperatorToMatch:()=>$r,applyRelationFilters:()=>Ot,applyWhereToKnex:()=>Bt,assertFieldOperatorValueIsClean:()=>no,buildMongoCharFoldMapJson:()=>ho,buildMongoFoldTextSearchJs:()=>fn,buildMongoSortSpec:()=>po,buildMongoSortSpecFromPlan:()=>gr,buildRelationSortSubquery:()=>On,buildRelationSubquery:()=>ss,buildSqlWherePartsFromFieldAst:()=>vr,buildWhereClause:()=>ut,camelToSnake:()=>mi,checkIfFilterContainsIsNull:()=>zi,chunkedFetch:()=>W,compileScriptSource:()=>ra,computeEngineTuning:()=>Gn,createEnfyraKernel:()=>ml,dslOpToCompareOp:()=>Qr,encodeMainThreadToIsolate:()=>ir,escapeSqlValue:()=>we,executeAggregationPipeline:()=>Fn,executeBatchFetches:()=>Mo,executeCountQueries:()=>Mn,executeMongoBatchFetches:()=>bn,expandFieldsMongo:()=>tt,expandFieldsToJoinsAndSelect:()=>Ro,expandFieldsToSelect:()=>Nn,getEffectiveCpuCount:()=>Vn,getEffectiveMemoryBytes:()=>or,getEngineTuning:()=>Br,getExecutableScript:()=>sa,getForeignKeyColumnName:()=>ie,getIoAbortSignal:()=>Xn,getJunctionColumnNames:()=>pr,getJunctionTableName:()=>dr,getMetadataGetter:()=>Fr,getMongoInverseRelationForeignField:()=>H,getMongoMetadataGetter:()=>ko,getMongoStoredRelationField:()=>X,getPrimaryKeyColumn:()=>ee,getScriptLegacyField:()=>Zs,getShortFkConstraintName:()=>gi,getShortFkName:()=>yi,getShortIndexName:()=>bi,getShortPkName:()=>pi,hasLogicalOperators:()=>ct,isExecutableJavaScript:()=>na,isMongoInverseRelation:()=>ge,isScriptTable:()=>ea,normalizeAggregateQuery:()=>At,normalizeFlowStepScriptConfig:()=>la,normalizeMongoDocument:()=>se,normalizeMongoResults:()=>Rn,normalizeScriptLanguage:()=>ta,normalizeScriptPatch:()=>ia,normalizeScriptRecord:()=>oa,parseBatchFields:()=>nt,parseFields:()=>Vr,parseFilter:()=>Me,parseSortInput:()=>gs,perParentRun:()=>bs,quoteIdentifier:()=>I,quoteQualifiedIdentifier:()=>ze,renderFilterToKnex:()=>ue,resolveExecutableScript:()=>aa,resolveMongoJunctionInfo:()=>he,rewriteFilterDenyingFields:()=>ms,rewriteSortDroppingDenied:()=>ys,runWithIoAbortSignal:()=>Zn,scriptContractService:()=>$e,separateFilters:()=>Ae,snakeToCamel:()=>hi,throwUnsupportedFieldOperator:()=>Ze,validateDeepOptions:()=>rt,validateFilterShape:()=>De,whereToMongoFilter:()=>It});module.exports=Es(yl);var Or=3e4,gt=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,r={}){let o=e.routeData.__codeBlocks||[];return o.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(o,e.routeData.context,t??Or,r)}async run(e,t,r=Or,o={}){return this.isolatedExecutorService.run(e,t,r,o)}};var Zo=Je(require("path"));var Be=class extends Error{constructor(t=0,r,o){let i=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${i}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={...o,timeoutMs:t,scriptId:r,outcome:o?.outcome??"timed_out",retryable:!1}}},He=class extends Error{constructor(t,r,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={...o,scriptId:r}}},z=class extends Error{constructor(t,r,o,i){if(!Number.isInteger(r)||r<400||r>599)throw new TypeError("Kernel exception statusCode must be an integer from 400 to 599");super(t);this.statusCode=r;this.errorCode=o;this.name=this.constructor.name,this.details=i}},Y=class extends z{constructor(e,t,r){super(e,t,`HTTP_${t}`,r)}},Wt=class extends z{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Kt=class extends z{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Ut=class extends z{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},Qt=class extends z{constructor(e,t,r){super(`${e} with ${t} '${r}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:r})}},zt=class extends z{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},Jt=class extends z{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},Ht=class extends z{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},Vt=class extends z{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},ht=class extends z{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},Gt=class extends z{constructor(e,t,r){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:r})}},Yt=class extends z{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},Xt=class extends z{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},Zt=class extends z{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},er=class extends z{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},tr=class extends z{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},rr=class extends z{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Pr=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!==void 0&&console.error(this.format(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;try{typeof e=="string"?t=e:e instanceof Error?t=e.stack??e.message:t=JSON.stringify(e,(o,i)=>typeof i=="bigint"?i.toString():i)??String(e)}catch{try{t=String(e)}catch{t="[Unserializable value]"}}return this.context?`[${this.context}] ${t}`:t}};var Qn=new Set(["__proto__","prototype","constructor","caller","callee","arguments"]);function oe(n,e,t=!1){if(Qn.has(e))throw new Error(`Host capability property is forbidden: ${e}`);if((typeof n!="object"||n===null)&&typeof n!="function")return;let r=n,o=new Set;for(;r&&r!==Object.prototype&&r!==Function.prototype;){if(o.size>=64)throw new Error("Host capability prototype traversal limit exceeded");if(o.has(r))throw new Error("Cyclic host capability prototype");if(o.add(r),Object.prototype.hasOwnProperty.call(r,e))return n[e];r=Object.getPrototypeOf(r)}if(t&&!Object.prototype.hasOwnProperty.call(Object.prototype,e)&&!Object.prototype.hasOwnProperty.call(Function.prototype,e)&&e in n)return n[e]}var Oo=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$streams","$debug"]);function Jn(n){let e={$body:n.$body,$query:n.$query,$params:n.$params,$user:n.$user,$share:n.$share,$data:n.$data,$api:{request:n.$api?.request},$uploadedFile:n.$uploadedFile,$req:zn(n.$req)};for(let r of Object.keys(n)){if(!r.startsWith("$")||r in e||Oo.has(r))continue;let o=zn(n[r]);o!==void 0&&(e[r]=o)}let t=n.$flow;if(t!=null)try{e.$flow=zn(t)??{}}catch{e.$flow={}}return e}function zn(n){if(typeof n!="function")try{return JSON.parse(JSON.stringify(n,(e,t)=>{if(typeof t=="bigint")return String(t);if(typeof t!="function")return t}))}catch{return}}function nr(n,e){if(e){for(let t of["$body","$query","$params","$data","$error","$statusCode","$share"])Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=e[t]);if(e.$api&&typeof e.$api=="object"&&n.$api&&typeof n.$api=="object"&&(Object.prototype.hasOwnProperty.call(e.$api,"error")&&(n.$api.error=e.$api.error),Object.prototype.hasOwnProperty.call(e.$api,"response")&&(n.$api.response=e.$api.response)),e.$flow!==void 0&&e.$flow!==null&&typeof e.$flow=="object"&&n.$flow!==null&&n.$flow!==void 0&&typeof n.$flow=="object")for(let[t,r]of Object.entries(e.$flow))Qn.has(t)||Object.defineProperty(n.$flow,t,{value:r,enumerable:!0,configurable:!0,writable:!0});for(let[t,r]of Object.entries(e))t.startsWith("$")&&(t==="$body"||t==="$query"||t==="$params"||t==="$data"||t==="$error"||t==="$statusCode"||t==="$share"||t==="$api"||t==="$flow"||Oo.has(t)||t==="$env"||(n[t]=r));delete n.$pkgs}}var yt=Je(require("os"));var jo=Je(require("fs")),jr=require("path");function mt(n){try{return jo.readFileSync(n,"utf8").trim()}catch{return""}}function Po(n){return n.replace(/\\([0-7]{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function Bo(n,e){let t=new Set([e?"/sys/fs/cgroup":`/sys/fs/cgroup/${n}`]),r=mt("/proc/self/cgroup").split(`
|
|
1
|
+
"use strict";var _s=Object.create;var Nr=Object.defineProperty;var Ss=Object.getOwnPropertyDescriptor;var $s=Object.getOwnPropertyNames;var Ts=Object.getPrototypeOf,ks=Object.prototype.hasOwnProperty;var Q=(n,e)=>()=>(n&&(e=n(n=0)),e);var Un=(n,e)=>{for(var t in e)Nr(n,t,{get:e[t],enumerable:!0})},No=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $s(e))!ks.call(n,o)&&o!==t&&Nr(n,o,{get:()=>e[o],enumerable:!(r=Ss(e,o))||r.enumerable});return n};var Je=(n,e,t)=>(t=n!=null?_s(Ts(n)):{},No(e||!n||!n.__esModule?Nr(t,"default",{value:n,enumerable:!0}):t,n)),Es=n=>No(Nr({},"__esModule",{value:!0}),n);function ca(n){return!!(typeof n._bsontype=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof RegExp)}function Xe(n,e=new WeakMap){if(!n||typeof n!="object")return n;let t=e.get(n);if(t)return t;if(Array.isArray(n)){let i=[];e.set(n,i);for(let s of n)i.push(Xe(s,e));return i}if(n instanceof Map){let i=new Map;e.set(n,i);for(let[s,a]of n)i.set(Xe(s,e),Xe(a,e));return i}if(n instanceof Set){let i=new Set;e.set(n,i);for(let s of n)i.add(Xe(s,e));return i}if(n instanceof Date)return new Date(n.getTime());if(ca(n))return n;let r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null)throw new TypeError("Join metadata must contain plain cloneable values");let o=Object.create(r);e.set(n,o);for(let[i,s]of Object.entries(n))Object.defineProperty(o,i,{value:Xe(s,e),enumerable:!0,configurable:!0,writable:!0});return o}function to(n){return{...n,relationMeta:Xe(n.relationMeta),purposes:[...n.purposes]}}var Te,sr=Q(()=>{"use strict";Te=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){let t=this.map.get(e);return t?to(t):void 0}getAll(){return Array.from(this.map.values(),to)}createCheckpoint(){return this.getAll()}restoreCheckpoint(e){let t=new Map;for(let r of e){let o=to(r);if(t.has(o.id))throw new Error(`Duplicate join registry checkpoint ID "${o.id}"`);t.set(o.id,o)}for(let r of t.values()){if(r.parentJoinId===null){if(r.id!==r.propertyName)throw new Error(`Invalid root join ID "${r.id}"`);continue}let o=t.get(r.parentJoinId);if(!o||o.targetTable!==r.parentTable||r.id!==`${r.parentJoinId}.${r.propertyName}`)throw new Error(`Invalid parent join for "${r.id}"`)}this.map.clear();for(let[r,o]of t)this.map.set(r,o)}registerWithParent(e,t,r,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t,c=r?.tables?.get(e);if(!c)return null;let u=c.relations?.find(d=>d.propertyName===t);if(!u)return null;let l=u.targetTableName||u.targetTable;if(!l)return null;if(i!==null){let d=this.map.get(i);if(!d||d.targetTable!==e)throw new Error(`Invalid parent join for "${a}"`)}if(this.map.has(a)){let d=this.map.get(a);if(d.parentTable!==e||d.propertyName!==t||d.targetTable!==l||d.relationType!==u.type||d.parentJoinId!==i)throw new Error(`Join registry collision for "${a}"`);return o==="inner"&&(d.joinType="inner"),d.purposes.includes(s)||d.purposes.push(s),a}let f={id:a,propertyName:t,parentTable:e,targetTable:l,relationType:u.type,parentJoinId:i,joinType:o,relationMeta:Xe(u),purposes:[s]};return this.map.set(a,f),a}}});function ti(n){let e=new Set(n),t={get size(){return e.size},has(r){return e.has(r)},forEach(r,o){for(let i of e)r.call(o,i,i,t)},entries(){return e.entries()},keys(){return e.keys()},values(){return e.values()},[Symbol.iterator](){return e[Symbol.iterator]()}};return Object.freeze(t)}function Qr(n){return Object.prototype.hasOwnProperty.call(ei,n)?ei[n]:null}var de,ro,ar,ei,wt=Q(()=>{"use strict";de=ti(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),ro=ti(["_and","_or","_not"]),ar=Object.freeze([...ro,...de]),ei=Object.assign(Object.create(null),{_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 b,ne=Q(()=>{"use strict";b=class extends Error{constructor(t="Bad Request",r){let o=Array.isArray(t),i;if(o)i=t.join("; ")||"Bad Request";else if(typeof t=="string")i=t;else try{i=JSON.stringify(t)||"Bad Request"}catch{i="Bad Request"}super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=r,o&&(this.messages=[...t])}}});function ri(){let n=process.env.DB_URI||"";return n.startsWith("mongodb://")||n.startsWith("mongodb+srv://")}var ni=Q(()=>{"use strict"});function Ze(n,e,t){throw new b({message:`Unsupported filter operator "${n}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${ar.join(", ")}.`,error:"UnsupportedFilterOperator",operator:n,field:e,supportedOperators:ar})}function no(n,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let r=ri();for(let o of Object.keys(e))if(o.startsWith("_")&&!de.has(o)){if(r&&o==="_id")continue;Ze(o,n,t)}}function oi(n){if(n>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`)}function ii(n,e,t,r){if(!n||typeof n!="object")return;if(oi(e),t.has(n))throw new b("Filter contains a circular reference");let o=r.get(n);if(!(o!==void 0&&o>=e)){t.add(n);try{for(let i of Object.values(n))ii(i,e+1,t,r);r.set(n,Math.max(o??-1,e))}finally{t.delete(n)}}}function fa(n,e,t){let r=t.get(n);if(r)return r;let o=e?.tables?.get(n);if(!o)throw new b(`Filter validation requires metadata for table '${n}'`);let i=o?.columns??[],s={columnNames:new Set(i.map(a=>a.name)),relationMap:new Map((o?.relations??[]).map(a=>[a.propertyName,a])),acceptsIdAlias:i.some(a=>a.name==="_id"&&a.isPrimary)&&!i.some(a=>a.name==="id")};return t.set(n,s),s}function lr(n,e,t,r,o,i,s,a=!1){if(!n||typeof n!="object")return;if(oi(r),o.has(n))throw new b("Filter contains a circular reference");let c=`${e}:${a?"nested":"root"}`,u=s.get(n),l=u?.get(c);if(!(l!==void 0&&l>=r)){o.add(n);try{if(Array.isArray(n)){for(let y of n)lr(y,e,t,r+1,o,i,s,a);let h=u??new Map;h.set(c,Math.max(h.get(c)??-1,r)),s.set(n,h);return}let{columnNames:f,relationMap:d,acceptsIdAlias:p}=fa(e,t,i);for(let[h,y]of Object.entries(n)){if(a&&de.has(h)){if(h==="_is_null"||h==="_is_not_null"){if(typeof y!="boolean")throw new b(`Relation filter operator '${h}' requires a boolean value`)}else if((h==="_in"||h==="_not_in"||h==="_nin"||h==="_between")&&!Array.isArray(y))throw new b(`Relation filter operator '${h}' requires an array value`);continue}if(ua.has(h)){if(h==="_and"||h==="_or"){if(!Array.isArray(y)||y.some($=>!$||typeof $!="object"||Array.isArray($)))throw new b(`Filter '${h}' value must be an array of filter objects`)}else if(!y||typeof y!="object"||Array.isArray(y))throw new b("Filter '_not' value must be a filter object");lr(y,e,t,r+1,o,i,s,a);continue}let m=d.get(h);if(m){if(y===null)continue;if(typeof y!="object"||Array.isArray(y)){lr({id:{_eq:y}},m.targetTableName||m.targetTable,t,r+1,o,i,s,!0);continue}let $=m.targetTableName||m.targetTable;if(typeof $!="string"||!$||!t?.tables?.has($))throw new b(`Filter relation '${h}' on '${e}' has no resolvable target table metadata`);lr(y,$,t,r+1,o,i,s,!0);continue}let w=p&&(h==="id"||h==="_id"),_=f.has("_id")&&h==="_id";if(h.startsWith("_")&&!f.has(h)&&!w&&Ze(h,h,e),!f.has(h)&&!w&&!_)throw new b(`Unknown filter field '${h}' on table '${e}'`);y&&typeof y=="object"&&no(h,y,e)}let g=u??new Map;g.set(c,Math.max(g.get(c)??-1,r)),s.set(n,g)}finally{o.delete(n)}}}function De(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))throw new b("Filter must be an object");ii(n,0,new Set,new WeakMap),lr(n,e,t,0,new Set,new Map,new WeakMap)}var oe,ua,Le=Q(()=>{"use strict";ne();ni();wt();oe=64,ua=new Set(["_and","_or","_not"])});function Me(n,e,t,r){if(n===void 0)return{node:null,hasRelationFilters:!1};if(!n||typeof n!="object"||Array.isArray(n))throw new b("Filter must be an object");let o={tableName:e,metadata:t,registry:r,parentJoinId:null,currentJoinId:null,currentTable:e,depth:0,ancestors:new Set},i=r.createCheckpoint();try{return Jr(n,o)}catch(s){throw r.restoreCheckpoint(i),s}}function Jr(n,e){if(!n||typeof n!="object"||Array.isArray(n))throw new b("Logical filter operand must be a filter object");if(e.depth>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`);if(e.ancestors.has(n))throw new b("Filter contains a circular reference");e.ancestors.add(n);let t=e.registry.createCheckpoint();try{let r=[],o=!1,i=!1;for(let[s,a]of Object.entries(n)){let c=da(s,a,e),u=c.node;if(u?.kind==="false")return e.registry.restoreCheckpoint(t),{node:u,hasRelationFilters:!1};if(u?.kind==="true"){i=!0;continue}c.hasRelationFilters&&(o=!0),u&&r.push(u)}return r.length===0?{node:i?{kind:"true"}:null,hasRelationFilters:o}:r.length===1?{node:r[0],hasRelationFilters:o}:{node:{kind:"and",children:r},hasRelationFilters:o}}finally{e.ancestors.delete(n)}}function ai(n){return{...n,depth:n.depth+1}}function da(n,e,t){if(n==="_and")return si("and",e,t);if(n==="_or")return si("or",e,t);if(n==="_not"){if(!e||typeof e!="object"||Array.isArray(e))throw new b("Filter '_not' value must be a filter object");let u=t.registry.createCheckpoint(),l=Jr(e,ai(t)),f=l.node??{kind:"true"};return f.kind==="true"||f.kind==="false"?(t.registry.restoreCheckpoint(u),{node:{kind:f.kind==="true"?"false":"true"},hasRelationFilters:!1}):{node:{kind:"not",child:f},hasRelationFilters:l.hasRelationFilters}}let r=t.metadata?.tables?.get(t.currentTable);if(!r)throw new b(`Filter parsing requires metadata for table '${t.currentTable}'`);let o=r.columns?.some(u=>u.name==="_id"&&u.isPrimary),i=r?.columns?.some(u=>u.name==="id"),a=n==="id"?o&&!i?"_id":"id":n,c=r?.relations?.find(u=>u.propertyName===a);if(c)return zr(a,e,c,t);if(r&&!r.columns?.find(l=>l.name===a))throw n.startsWith("_")&&n!=="_id"&&Ze(n,n,t.currentTable),new b(`Unknown field '${n}' on table '${t.currentTable}'`);return pa(a,e,t)}function si(n,e,t){if(!Array.isArray(e))throw new b(`Filter '${n}' value must be an array`);let r=t.registry.createCheckpoint(),o=[],i=!1;for(let a of e){if(!a||typeof a!="object"||Array.isArray(a))throw new b(`Filter '${n}' entries must be filter objects`);let c=t.registry.createCheckpoint(),u=Jr(a,ai(t)),l=u.node??{kind:"true"};n==="and"&&l.kind==="true"||n==="or"&&l.kind==="false"?t.registry.restoreCheckpoint(c):u.hasRelationFilters&&(i=!0),o.push(l)}if(o.length===0)return{node:{kind:n==="and"?"true":"false"},hasRelationFilters:i};if(n==="or"&&o.some(a=>a.kind==="true"))return t.registry.restoreCheckpoint(r),{node:{kind:"true"},hasRelationFilters:!1};if(n==="and"&&o.some(a=>a.kind==="false"))return t.registry.restoreCheckpoint(r),{node:{kind:"false"},hasRelationFilters:!1};let s=o.filter(a=>n==="and"?a.kind!=="true":a.kind!=="false");return s.length===0?{node:{kind:n==="and"?"true":"false"},hasRelationFilters:i}:s.length===1?{node:s[0],hasRelationFilters:i}:{node:{kind:n,children:s},hasRelationFilters:i}}function zr(n,e,t,r){if(typeof e!="object"||e===null||Array.isArray(e))return e===null?zr(n,{id:{_is_null:!0}},t,r):Array.isArray(e)?zr(n,{id:{_in:e}},t,r):zr(n,{id:{_eq:e}},t,r);let o=Object.keys(e);if(o.length===0)return{node:null,hasRelationFilters:!1};let i=r.registry.createCheckpoint(),s=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"),a=r.registry.registerWithParent(r.currentTable,n,r.metadata,"left",r.currentJoinId,"filter");if(s&&(o[0]==="_is_null"||o[0]==="_is_not_null")&&typeof e[o[0]]!="boolean")throw new b(`Relation null-check operator '${o[0]}' requires a boolean value`);if(!a)throw new b(`Unable to register filter join for relation '${n}'`);if(s&&o[0]==="_is_null")return{node:{kind:"relation_exists",joinId:a,negate:e._is_null===!0},hasRelationFilters:!0};if(s&&o[0]==="_is_not_null")return{node:{kind:"relation_exists",joinId:a,negate:e._is_not_null!==!0},hasRelationFilters:!0};if(s&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return{node:{kind:"relation_exists",joinId:a,negate:o[0]==="_eq"},hasRelationFilters:!0};let c=t.targetTableName||t.targetTable;if(!c)throw new b(`Relation '${n}' has no target table metadata`);let u={...r,parentJoinId:r.currentJoinId,currentJoinId:a,currentTable:c,depth:r.depth+1},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte","_between"]),d=o.length>0&&o.every(g=>l.has(g))?{id:e}:e,p=Jr(d,u);return!p.node||p.node.kind==="true"||p.node.kind==="false"?(r.registry.restoreCheckpoint(i),{node:p.node,hasRelationFilters:!1}):{node:p.node,hasRelationFilters:!0}}function oo(n,e,t){if(!(!n||typeof n!="object")){if(e>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`);if(t.has(n))throw new b("Filter contains a circular reference");t.add(n);try{for(let r of Object.values(n))oo(r,e+1,t)}finally{t.delete(n)}}}function pa(n,e,t){let r={joinId:t.currentJoinId,fieldName:n,isUuid:ha(n,t)};if(e===null)return{node:{kind:"compare",field:r,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:r,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!de.has(s)&&Ze(s,n,t.tableName);let o=Object.entries(e).filter(([s])=>de.has(s));if(o.length>0&&o.length!==Object.keys(e).length)throw new b(`Field '${n}' has mixed filter operators and object properties`);if(o.length===0)return oo(e,t.depth+1,new Set),{node:{kind:"compare",field:r,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){if(oo(a,t.depth+1,new Set),(s==="_in"||s==="_not_in"||s==="_nin")&&!Array.isArray(a))throw new b(`Filter operator '${s}' requires an array value`);if(s==="_between"&&(!Array.isArray(a)||a.length!==2))throw new b("Filter operator '_between' requires an array with exactly two values");let c=ga(r,s,a);c&&i.push(c)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function ga(n,e,t){if(e==="_is_null"||e==="_is_not_null"){if(typeof t!="boolean")throw new b(`Filter operator '${e}' requires a boolean value`);return{kind:"compare",field:n,op:"is_null",value:e==="_is_null"?t:!t}}let r=Qr(e);return r?{kind:"compare",field:n,op:r,value:t}:null}function ha(n,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let r=n.includes(".")?n.split(".").pop():n,o=t.columns?.find(a=>a.name===r);if(!o)return!1;let s=(typeof o.type=="string"?o.type:typeof o.type?.name=="string"?o.type.name:"").toLowerCase();return s==="uuid"||s==="uuidv4"||s.includes("uuid")}var cr=Q(()=>{"use strict";wt();Le();ne()});function ur(n){return Buffer.byteLength(n,"utf8")<=ba}function Xr(n){return n.map(e=>`${Buffer.byteLength(e,"utf8")}:${e}`).join("|")}function fr(n){return co.createHash("md5").update(n).digest("hex").substring(0,8)}function pi(n){let e=`${n}_pk`;return ur(e)?e:`j_${fr(n)}_pk`}function gi(n,e,t){let r=`${n}_${e}_foreign`;return ur(r)?r:`j_${fr(n)}_${t}_fk`}function dr(n,e,t){let r=[n,e,t],o=r.some(s=>s.includes(":"))?Xr(r):r.join(":");return`j_${co.createHash("sha1").update(o).digest("hex").slice(0,12)}`}function X(n){let e=`${n}Id`;return ur(e)?e:`fk_${fr(Xr([n,"Id"]))}`}function pr(n,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function hi(n){return n.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function mi(n){return n.replace(/([A-Z])/g,"_$1").toLowerCase()}function yi(n,e,t){let r=`${n}_${e}_${t}_fk`;return ur(r)?r:`r_${fr(Xr([n,e,t]))}_${t}_fk`}function bi(n,e,t){let r=`${n}_${e}_${t}_idx`;return ur(r)?r:`r_${fr(Xr([n,e,t]))}_${t}_idx`}var co,ba,et=Q(()=>{"use strict";co=Je(require("crypto")),ba=63});var St,ae,hr,mr,$t=Q(()=>{"use strict";St=16,ae=5e3,hr=4,mr=10});var xa,nn,xi=Q(()=>{"use strict";ne();$t();xa=new Set(["many-to-one","one-to-one","one-to-many","many-to-many"]),nn=class{constructor(e,t){this.adapter=e;this.metadataGetter=t}normalizeDeepFields(e,t){if(e===void 0)return t;if(!Array.isArray(e)&&typeof e!="string")throw new b("Deep relation fields must be a string or string array");let r=Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean);if(r.some(o=>typeof o!="string"))throw new b("Deep relation fields must be strings");return r.map(o=>o.trim()).filter(Boolean)}normalizeDeepSort(e){if(e!==void 0){if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new b("Deep relation sort entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new b("Deep relation sort must be a string or string array");return e}}normalizeDeepPagination(e,t){if(e===void 0)return;if(typeof e!="number"&&typeof e!="string")throw new b(`Deep relation ${t} must be an integer`);let r=String(e);if(!/^\d+$/.test(r))throw new b(`Deep relation ${t} must be an integer`);let o=Number(r),i=t==="limit"?0:1;if(!Number.isSafeInteger(o)||o<i)throw new b(`Deep relation ${t} must be a safe integer greater than or equal to ${i}`);return o}normalizeDescriptors(e){let t=new Set;for(let r of e){if(t.has(r.relationName))throw new b(`Duplicate deep relation '${r.relationName}'`);t.add(r.relationName)}return e.map(r=>{if(!xa.has(r.type))throw new b(`Unsupported relation type '${r.type}' for '${r.relationName}'`);return this.withDefaultToManyLimit({...r,fields:this.normalizeDeepFields(r.fields,[]),userSort:this.normalizeDeepSort(r.userSort),userLimit:this.normalizeDeepPagination(r.userLimit,"limit"),userPage:this.normalizeDeepPagination(r.userPage,"page")})})}entryValue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}enrichNestedDescs(e,t,r,o){if(t===void 0)return e;if(!t||typeof t!="object"||Array.isArray(t))throw new b("Nested deep options must be an object");if(Object.keys(t).length===0)return e;let i=e.map(a=>{if(!Object.prototype.hasOwnProperty.call(t,a.relationName))return a;let c=t[a.relationName];if(!c||typeof c!="object"||Array.isArray(c))throw new b(`Nested deep option for relation '${a.relationName}' must be an object`);let u=this.entryValue(c,"fields"),l=this.entryValue(c,"filter"),f=this.entryValue(c,"sort"),d=this.entryValue(c,"limit"),p=this.entryValue(c,"page"),g=this.entryValue(c,"deep");return{...a,fields:this.normalizeDeepFields(u,o?.has(a.relationName)&&a.fields.length>0?a.fields:["*"]),userFilter:l??a.userFilter,userSort:f!==void 0?this.normalizeDeepSort(f):a.userSort,userLimit:d!==void 0?this.normalizeDeepPagination(d,"limit"):a.userLimit,userPage:p!==void 0?this.normalizeDeepPagination(p,"page"):a.userPage,nestedDeep:g??a.nestedDeep}}),s=new Set(i.map(a=>a.relationName));for(let[a,c]of Object.entries(t)){if(s.has(a))continue;if(!c||typeof c!="object"||Array.isArray(c))throw new b(`Nested deep option for relation '${a}' must be an object`);let u=r?.relations?.find(m=>m.propertyName===a);if(!u)throw new b(`Unknown nested deep relation '${a}' on '${r?.name??"unknown"}'`);let l=this.entryValue(c,"fields"),f=this.entryValue(c,"filter"),d=this.entryValue(c,"sort"),p=this.entryValue(c,"limit"),g=this.entryValue(c,"page"),h=this.entryValue(c,"deep"),y=this.normalizeDeepFields(l,["*"]);i.push({relationName:a,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:y,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:f,userSort:this.normalizeDeepSort(d),userLimit:this.normalizeDeepPagination(p,"limit"),userPage:this.normalizeDeepPagination(g,"page"),nestedDeep:h})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:10}:e}projectedRelations(e){let t=new Set;for(let r of e)r==="*"||!r.includes(".")||t.add(r.split(".")[0]);return t}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let r=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))r.has(i)||o.push(i);return o}getMetadata(e,t){let r=t.metadataByTable.get(e);if(r)return r;let o=this.metadataGetter(e);return t.metadataByTable.set(e,o),o}async prepareDescriptor(e,t,r,o){let i=await this.getMetadata(e.targetTable,o);if(!i)throw new Error(`Metadata not found for target table: ${e.targetTable}`);this.assertLocalSortFields(e,i);let{nestedDescs:s,fetchSpec:a}=this.adapter.resolveFields(this.fieldsForNestedResolution(e.fields,e.nestedDeep),i);if(r+1>=t)return{desc:e,targetMeta:i,fetchSpec:a,children:[]};let c=await Promise.all(this.normalizeDescriptors(this.enrichNestedDescs(s,e.nestedDeep,i,this.projectedRelations(e.fields))).map(u=>this.prepareDescriptor(u,t,r+1,o)));return{desc:e,targetMeta:i,fetchSpec:a,children:c}}assertLocalSortFields(e,t){if(!e.userSort)return;let r=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of r){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new b(`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(c=>c.name===i),a=i==="id"&&t.columns?.some(c=>c.name==="_id");if(!s&&!a)throw new b(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}}});async function W(n,e,t=5e3){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(n.length===0)return[];if(n.length<=t)return e(n);let r=[];for(let f=0;f<n.length;f+=t)r.push(n.slice(f,f+t));let o=[],i=0,s=!1,a=!1,c;async function u(){for(;!s;){let f=i;if(f>=r.length)return;i+=1;try{o[f]=await e(r[f])}catch(d){a||(a=!0,c=d),s=!0}}}let l=Math.min(4,r.length);if(await Promise.all(Array.from({length:l},()=>u())),a)throw c;return o.flat()}function nt(n){let e=[],t=new Map;for(let r of n)if(r==="*"||!r.includes("."))e.push(r);else{let o=r.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 Ci=Q(()=>{"use strict";$t()});var qe,Ne=Q(()=>{"use strict";ne();xi();$t();Ci();$t();qe=class{constructor(e,t,r){this.adapter=e;this.trace=r;this.plan=new nn(e,t)}uniqueValues(e){let t=new Set,r=[];for(let o of e){if(o==null)continue;let i=this.adapter.keyOf(o);t.has(i)||(t.add(i),r.push(o))}return r}setRelation(e,t,r){let o=Object.getOwnPropertyDescriptor(e,t);if(o&&!o.configurable){Object.defineProperty(e,t,{value:r});return}Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}assertCommitCanApply(e,t,r){for(let o of t){let i=o.desc;for(let s of e){let a=Object.getOwnPropertyDescriptor(s,i.relationName);if(!a&&!Object.isExtensible(s))throw new Error(`Cannot add relation '${i.relationName}' to a non-extensible result`);if(a&&!a.configurable&&(!("writable"in a)||!a.writable))throw new Error(`Cannot replace non-writable relation '${i.relationName}'`);for(let c of i.injectedParentFields??[]){if(r.has(c))continue;let u=Object.getOwnPropertyDescriptor(s,c);if(u&&!u.configurable)throw new Error(`Cannot remove injected relation field '${c}'`)}}}}createStagingParent(e){let t=Object.create(Object.getPrototypeOf(e));for(let r of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,r);"value"in o?Object.defineProperty(t,r,{value:o.value,enumerable:o.enumerable,writable:!0,configurable:!0}):Object.defineProperty(t,r,{get:o.get,set:o.set,enumerable:o.enumerable,configurable:!0})}return t}async execute(e,t,r=3,o=0,i){if(!Number.isSafeInteger(r)||r<0)throw new b("Maximum query depth must be a non-negative safe integer");if(!Number.isSafeInteger(o)||o<0)throw new b("Current query depth must be a non-negative safe integer");if(t.length===0||o>=r)return;let s={metadataByTable:new Map},a;if(i&&(a=await this.plan.getMetadata(i,s)??void 0,!a))throw new Error(`Metadata not found for parent table: ${i}`);let c=await Promise.all(this.plan.normalizeDescriptors(t).map(u=>this.plan.prepareDescriptor(u,r,o,s)));await this.executePrepared(e,c,r,o,a,s)}async executePrepared(e,t,r,o,i,s){if(e.length===0)return;let a=new Array(t.length),c=new Array(t.length),u=0,l=!1,f,d=async()=>{for(;!l&&u<t.length;){let g=u;u+=1;let h=t[g],y=h.desc,m=e.map(w=>this.createStagingParent(w));try{y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse?await this.fetchOwnerRelation(m,h,r,o,s):y.type==="one-to-many"||y.type==="one-to-one"&&y.isInverse?await this.fetchInverseRelation(m,h,r,o,i,s):y.type==="many-to-many"&&await this.fetchM2MRelation(m,h,r,o,i,s),a[g]=m.map(w=>w[y.relationName]),c[g]={status:"fulfilled",value:void 0}}catch(w){c[g]={status:"rejected",reason:w},l||(f=w),l=!0}}};if(await Promise.all(Array.from({length:Math.min(4,t.length)},()=>d())),l)throw f;let p=new Set(t.map(({desc:g})=>g.relationName));this.assertCommitCanApply(e,t,p);for(let g=0;g<t.length;g+=1){let h=t[g].desc,y=a[g];for(let m=0;m<e.length;m+=1){this.setRelation(e[m],h.relationName,y[m]);for(let w of h.injectedParentFields??[])p.has(w)||delete e[m][w]}}}async fetchOwnerRelation(e,t,r,o,i){let{desc:s,targetMeta:a,fetchSpec:c,children:u}=t,l=this.adapter.resolveOwnerFkKey(s),f=new Set,d=[];for(let _ of e){let $=_[l];if($==null)continue;let k=this.adapter.keyOf($);f.has(k)||(f.add(k),d.push($))}if(d.length===0){for(let _ of e)this.setRelation(_,s.relationName,null),l!==s.relationName&&delete _[l],s.fkColumn&&s.fkColumn!==s.relationName&&delete _[s.fkColumn];return}let p=this.adapter.getTargetPkField(a),g=performance.now(),h=await this.adapter.fetchOwner(s.targetTable,d,c,s),y=Array.isArray(h)?h:h.docs,m=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${o}_${s.relationName}`,g,{relationType:s.type,targetTable:s.targetTable,strategy:m?.strategy??"batch-in",roundtrips:m?.roundtrips??(Math.ceil(d.length/5e3)||1),concurrencyWaves:m?.concurrencyWaves,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??y.length,rowsReturned:y.length,rowsDiscarded:0,userFilter:!!s.userFilter,userSort:!!s.userSort});let w=new Map;for(let _ of y)w.set(this.adapter.keyOf(_[p]),_);u.length>0&&await this.executePrepared(y,u,r,o+1,a,i);for(let _ of e){let $=_[l];this.setRelation(_,s.relationName,$!=null&&w.get(this.adapter.keyOf($))||null),l!==s.relationName&&delete _[l],s.fkColumn&&s.fkColumn!==s.relationName&&delete _[s.fkColumn]}}async fetchInverseRelation(e,t,r,o,i,s){let{desc:a,targetMeta:c,fetchSpec:u,children:l}=t,f=this.adapter.resolveParentPk(i),d=this.uniqueValues(e.map(M=>M[f]));if(d.length===0){for(let M of e)this.setRelation(M,a.relationName,a.type==="one-to-one"?null:[]);return}let p=this.adapter.resolveInverseFkField(a),g=performance.now(),{docs:h,groupKeyField:y,stats:m}=await this.adapter.fetchInverse(a.targetTable,p,d,u,a),w=new Map,_=a.fields.includes("*")||a.fields.some(M=>M===p||M.startsWith(`${p}.`));for(let M of h){let N=M[y],j=this.adapter.keyOf(N);w.has(j)||w.set(j,[]),w.get(j).push(M)}let $=a.userLimit!==void 0&&a.userLimit>0,k=$?"per-parent-c16":"batch-in",C=$?d.length:Math.ceil(d.length/5e3)||1,x=$?Math.ceil(d.length/16):void 0,v=Array.from(w.values()).reduce((M,N)=>M+N.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${a.relationName}`,g,{relationType:a.type,targetTable:a.targetTable,strategy:m?.strategy??k,roundtrips:m?.roundtrips??C,concurrencyWaves:m?.concurrencyWaves??x,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??h.length,rowsReturned:v,rowsDiscarded:Math.max(0,(m?.rowsTransferred??h.length)-v),userLimit:a.userLimit,userFilter:!!a.userFilter,userSort:!!a.userSort}),l.length>0&&await this.executePrepared(h,l,r,o+1,c,s),this.adapter.postProcessInverseChild)for(let M of h)this.adapter.postProcessInverseChild(M,p,_);let R=a.type==="one-to-one";for(let M of e){let N=M[f];if(N==null){this.setRelation(M,a.relationName,R?null:[]);continue}let j=w.get(this.adapter.keyOf(N))||[];this.setRelation(M,a.relationName,R?j[0]||null:j)}}async fetchM2MRelation(e,t,r,o,i,s){let{desc:a,targetMeta:c,fetchSpec:u,children:l}=t,f=this.adapter.resolveParentPk(i),d=this.uniqueValues(e.map(x=>x[f]));if(d.length===0){for(let x of e)this.setRelation(x,a.relationName,[]);return}let p=e.filter(x=>x[f]!=null),g=performance.now(),{grouped:h,docs:y,stats:m}=await this.adapter.fetchM2M(p,a,i,c,u),w=a.userLimit!==void 0&&a.userLimit>0,_=w?"m2m-per-parent-c16":"m2m-batch",$=w?d.length:Math.ceil(d.length/5e3)||1,k=w?Math.ceil(d.length/16):void 0,C=Array.from(h.values()).reduce((x,v)=>x+v.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${a.relationName}`,g,{relationType:a.type,targetTable:a.targetTable,strategy:m?.strategy??_,roundtrips:m?.roundtrips??$,concurrencyWaves:m?.concurrencyWaves??k,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??y.length,rowsReturned:C,rowsDiscarded:m?.rowsDiscarded??Math.max(0,(m?.rowsTransferred??y.length)-C),userLimit:a.userLimit,userFilter:!!a.userFilter,userSort:!!a.userSort}),l.length>0){let x=Array.from(new Set(Array.from(h.values()).flat()));x.length>0&&await this.executePrepared(x,l,r,o+1,c,s)}for(let x of e){let v=x[f];if(v==null){this.setRelation(x,a.relationName,[]);continue}let R=this.adapter.keyOf(v);this.setRelation(x,a.relationName,h.get(R)||[])}}}});var Fi,We,on=Q(()=>{"use strict";Fi=2,We=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];this.waiterHead=0;this.failed=!1;if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{if(this.failed)throw this.failure;return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failed)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(!await new Promise(t=>this.waiters.push(t)))throw this.failure;if(this.failed)throw this.active-=1,this.failure}release(){if(this.active<1)throw new Error("Batch execution permit underflow");if(this.failed){this.active-=1;return}let e=this.waiters[this.waiterHead];if(e){this.waiters[this.waiterHead]=void 0,this.waiterHead+=1,this.waiterHead>1024&&this.waiterHead*2>this.waiters.length&&(this.waiters.splice(0,this.waiterHead),this.waiterHead=0),e(!0);return}this.active-=1}cancel(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t=this.waiterHead;t<this.waiters.length;t+=1)this.waiters[t]?.(!1);this.waiters.length=0,this.waiterHead=0}}}});function I(n,e){if(e==="mongodb")return n;let t=["postgres","pg","sqlite"].includes(e)?'"':"`";return t+n.split(t).join(t+t)+t}function ze(n,e){let t=[],r=0;for(;r<n.length;){let o=n[r];if(o==='"'||o==="`"){r++;let i="",s=!1;for(;r<n.length;){let a=n[r++];if(a!==o){i+=a;continue}if(n[r]===o){i+=o,r++;continue}s=!0;break}if(!s||r<n.length&&n[r]!==".")throw new Error("Invalid quoted SQL identifier");t.push(I(i,e))}else{let i=n.indexOf(".",r),s=n.slice(r,i===-1?void 0:i);if(!s)throw new Error("Invalid qualified SQL identifier");t.push(s==="*"?s:I(s,e)),r=i===-1?n.length:i}if(r<n.length&&(r++,r===n.length))throw new Error("Invalid qualified SQL identifier")}if(t.length===0)throw new Error("Invalid qualified SQL identifier");return t.join(".")}var Se=Q(()=>{"use strict"});function te(n){return n.columns.find(e=>e.isPrimary)||null}var ft=Q(()=>{"use strict"});function ue(n,e,t){e&&Pt(n,e,t,"and")}function Pt(n,e,t,r){switch(e.kind){case"true":r==="or"?n.orWhereRaw("1 = 1"):n.whereRaw("1 = 1");return;case"false":r==="or"?n.orWhereRaw("1 = 0"):n.whereRaw("1 = 0");return;case"and":{if(e.children.length===0){Pt(n,{kind:"true"},t,r);return}let o=function(){for(let i of e.children)this.where(function(){Pt(this,i,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"or":{if(e.children.length===0){Pt(n,{kind:"false"},t,r);return}let o=function(){for(let i of e.children)this.orWhere(function(){Pt(this,i,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"not":{let o=function(){this.whereNot(function(){Pt(this,e.child,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"compare":cl(n,e,t,r);return;case"relation_exists":throw new Error(`SQL relation_exists node requires a materialized join: ${e.joinId}`)}}function cl(n,e,t,r){if(e.field.joinId!==null)throw new Error(`SQL comparison requires a materialized join target: ${e.field.joinId}`);let o=fl(e.field,t),i=ze(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",c=r==="or"?"orWhere":"where",u=r==="or"?"orWhereRaw":"whereRaw",l=r==="or"?"orWhereIn":"whereIn",f=r==="or"?"orWhereNotIn":"whereNotIn",d=r==="or"?"orWhereBetween":"whereBetween",p=r==="or"?"orWhereNull":"whereNull",g=r==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":e.value===null?n[p](o):s&&a&&typeof e.value=="string"?n[u](`${i} = ?::uuid`,[e.value]):n[c](o,"=",e.value);return;case"neq":e.value===null?n[g](o):s&&a&&typeof e.value=="string"?n[u](`${i} != ?::uuid`,[e.value]):n[c](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?n[u](`${i} > ?::uuid`,[e.value]):n[c](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?n[u](`${i} >= ?::uuid`,[e.value]):n[c](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?n[u](`${i} < ?::uuid`,[e.value]):n[c](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?n[u](`${i} <= ?::uuid`,[e.value]):n[c](o,"<=",e.value);return;case"in":{let h=ls(e.value);h.length===0?n[u]("1 = 0"):s&&a&&h.every(y=>typeof y=="string")?n[u](`${i} = ANY(?::uuid[])`,[h]):n[l](o,h);return}case"not_in":{let h=ls(e.value);h.length===0?n[u]("1 = 1"):s&&a&&h.every(y=>typeof y=="string")?n[u](`${i} != ALL(?::uuid[])`,[h]):n[f](o,h);return}case"contains":Co(n,i,e.value,"contains",t,r);return;case"starts_with":Co(n,i,e.value,"starts_with",t,r);return;case"ends_with":Co(n,i,e.value,"ends_with",t,r);return;case"between":if(!Array.isArray(e.value)||e.value.length!==2)throw new Error("Invalid between filter value");n[d](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?n[p](o):n[g](o);return}}function ul(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Co(n,e,t,r,o,i){let s=i==="or"?"orWhereRaw":"whereRaw",a=ul(t);if(o.dbType==="postgres"){let u=r==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%' ESCAPE '='`:r==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%' ESCAPE '='`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) ESCAPE '='`;n[s](u,[a]);return}if(o.dbType==="sqlite"){let u=r==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%' ESCAPE '='`:r==="starts_with"?`lower(${e}) LIKE lower(?) || '%' ESCAPE '='`:`lower(${e}) LIKE '%' || lower(?) ESCAPE '='`;n[s](u,[a]);return}let c=r==="contains"?`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(?) COLLATE utf8mb4_general_ci, '%') ESCAPE '='`:r==="starts_with"?`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(?) COLLATE utf8mb4_general_ci, '%') ESCAPE '='`:`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(?) COLLATE utf8mb4_general_ci) ESCAPE '='`;n[s](c,[a])}function fl(n,e){let t=n.fieldName.split(".");if(t.some(r=>!r))throw new Error("Invalid SQL filter field");if(t.length===1)return`${e.rootTable}.${t[0]}`;if(t.length!==2||t[0]!==e.rootTable)throw new Error("Invalid SQL filter field");return n.fieldName}function ls(n){return Array.isArray(n)?n:typeof n=="string"&&n.includes(",")?n.split(",").map(e=>e.trim()):[n]}var Rr=Q(()=>{"use strict";Se()});var fs={};Un(fs,{expandFieldsToJoinsAndSelect:()=>Ro});function us(n,e,t){if(n===void 0)return;let r=typeof n=="number",o=typeof n=="string"&&/^\d+$/.test(n.trim());if(!r&&!o)throw new Error(t);let i=Number(n);if(!Number.isSafeInteger(i)||i<e)throw new Error(t);return i}function dl(n){return us(n,0,"SQL relation limit must be a non-negative safe integer")}function pl(n){return us(n,1,"SQL relation page must be a positive safe integer")}function jt(n,e){return n&&Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0}function cs(n){if(typeof n!="string"&&!Array.isArray(n))throw new Error("SQL relation fields must be a string or string array");let e=typeof n=="string"?n.split(","):n;if(e.some(t=>typeof t!="string"))throw new Error("SQL relation fields must be strings");return e.map(t=>t.trim()).filter(Boolean)}async function Ro(n,e,t,r,o,i){if(o!==void 0&&(!Number.isSafeInteger(o)||o<0))throw new Error("SQL maximum query depth must be a non-negative safe integer");let s=[],a=[],c=await t(n);if(!c)throw new Error(`SQL field expansion requires metadata for '${n}'`);let u=new Map,l=new Set;for(let h of e){let y=h.split(".").map(w=>w.trim());if(y.some(w=>w.length===0))throw new Error(`Malformed SQL field path '${h}'`);let m=y.join(".");if(m==="*"||y.length===1)u.has("")||u.set("",[]),u.get("").push(m);else{let w=y[0],_=y.slice(1).join(".");u.has(w)||u.set(w,[]),u.get(w).push(_)}}if(i&&typeof i=="object")for(let[h,y]of Object.entries(i)){if(u.has(h))continue;let m=y&&typeof y=="object"&&y.fields!=null?cs(y.fields):["*"];u.set(h,m)}let f=u.get("")||[],d=new Set,p=new Set,g=h=>`${I(n,r)}.${I(h,r)}`;for(let h of f){if(h==="*"){let _=new Set;for(let k of c.relations||[])if(k.type==="many-to-one"||k.type==="one-to-one"&&!k.isInverse){let C=k.foreignKeyColumn||X(k.propertyName);C&&_.add(C)}let $=new Set;for(let k of c.columns)_.has(k.name)||(s.push(g(k.name)),d.add(k.name),$.add(k.name));for(let k of c.relations||[])!u.has(k.propertyName)&&!$.has(k.propertyName)&&(u.set(k.propertyName,[]),l.add(k.propertyName));continue}if(h.includes(".")){s.push(g(h));continue}let y=c.relations?.find(_=>(_.type==="many-to-one"||_.type==="one-to-one"&&!_.isInverse)&&(_.foreignKeyColumn||X(_.propertyName))===h);if(y){u.has(y.propertyName)||(u.set(y.propertyName,[]),l.add(y.propertyName));continue}if(c.columns?.find(_=>_.name===h)){s.push(g(h)),d.add(h);continue}if(c.relations?.find(_=>_.propertyName===h)){u.has(h)||(u.set(h,[]),l.add(h));continue}}for(let[h,y]of u){if(h==="")continue;let m=c.relations?.find(v=>v.propertyName===h);if(!m)continue;if(o===0)throw new Error("SQL relation exceeds maximum query depth");if(m.type==="one-to-one"&&typeof m.isInverse!="boolean")throw new Error(`SQL one-to-one relation '${h}' requires ownership metadata`);let w=m.type==="many-to-one"||m.type==="one-to-one"&&m.isInverse===!1,_=[];if(d.has(h))throw new Error(`SQL relation '${h}' on '${n}' conflicts with a selected root column`);if(p.add(h),w){let v=m.foreignKeyColumn||X(m.propertyName);if(!c.columns.some(j=>j.name===v))throw new Error(`SQL relation '${h}' foreign key '${v}' is missing from '${n}' metadata`);let R=I(n,r),M=I(v,r),N=I(h,r);s.push(`${R}.${M} as ${N}`),_.push(h)}else{let v=c.columns.filter(R=>R.isPrimary===!0);if(v.length===0)throw new Error(`SQL relation '${h}' on '${n}' requires parent primary key metadata`);for(let R of v){if(p.has(R.name))throw new Error(`SQL parent key '${R.name}' on '${n}' conflicts with a relation output`);d.has(R.name)||(s.push(g(R.name)),d.add(R.name),_.push(R.name))}}let $=m.targetTableName||m.targetTable,k=i&&Object.prototype.hasOwnProperty.call(i,h)?i[h]:void 0,C=jt(k,"fields"),x=C!=null?cs(C):y;if(C==null&&l.has(h)){let v=await t($);if(!v)throw new Error(`SQL relation '${h}' requires target metadata for '${$}'`);if(x=v.columns.filter(R=>R.isPrimary===!0).map(R=>R.name),x.length===0)throw new Error(`SQL relation '${h}' requires target primary key metadata`)}a.push({relationName:h,type:m.type,targetTable:$,fields:x,isInverse:m.isInverse,fkColumn:w?m.foreignKeyColumn||X(m.propertyName):m.foreignKeyColumn,injectedParentFields:_.length>0?_:void 0,mappedBy:m.mappedBy,junctionTableName:m.junctionTableName,junctionSourceColumn:m.junctionSourceColumn,junctionTargetColumn:m.junctionTargetColumn,userFilter:jt(k,"filter"),userSort:jt(k,"sort"),userLimit:dl(jt(k,"limit")),userPage:pl(jt(k,"page")),nestedDeep:jt(k,"deep")})}return{select:s,batchFetchDescriptors:a}}var Fo=Q(()=>{"use strict";et();Se()});var Mr,Dt,Bn,ds=Q(()=>{"use strict";Ne();cr();sr();et();ft();Se();Mr="__enfyra_row_number__",Dt="__enfyra_partitioned__",Bn=class{constructor(e,t,r){this.knex=e;this.dbType=t;this.metadata=r}getTableMetadata(e){let t=this.metadata?.tables??this.metadata;if(t)return typeof t.get=="function"?t.get(e):t[e]}sortAlias(e){return`__sort_${e.map(t=>`${t.length}_${t}`).join("_")}`}buildPartitionRowNumber(e,t,r){let o=[...t];o.some(s=>s.column===r)||o.push({column:r,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),Mr])}buildPartitionSlice(e,t,r,o){return this.knex.from(e.as(Dt)).select(`${Dt}.*`).where(`${Dt}.${Mr}`,">",r).andWhere(`${Dt}.${Mr}`,"<=",r+o).orderBy(`${Dt}.${t}`,"asc").orderBy(`${Dt}.${Mr}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Mr]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let r=new Te,o=this.metadata?.tables?this.metadata:{tables:this.metadata instanceof Map?this.metadata:new Map(Object.entries(this.metadata))},{node:i}=Me(e,t,o,r);return i}parseSortTokens(e,t,r){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),c=(s?i.slice(1):i).split(".");if(c.length===1)return{column:r?`${r}.${c[0]}`:`${t}.${c[0]}`,order:s?"desc":"asc"};let u=c[c.length-1];return{column:`${this.sortAlias(c.slice(0,-1))}.${u}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,r,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 u=(a.startsWith("-")?a.slice(1):a).split(".");if(u.length<=1)continue;let l=r,f=o||r;for(let d=0;d<u.length-1;d++){let p=u[d],g=this.getTableMetadata(l);if(!g)break;let h=g.relations?.find(w=>w.propertyName===p);if(!h)break;if(h.isInverse||h.type==="one-to-many"||h.type==="many-to-many")throw new Error(`Dotted sort through inverse or to-many relation '${p}' is not supported`);let y=h.targetTableName||h.targetTable,m=this.sortAlias(u.slice(0,d+1));if(!s.has(m)){s.add(m);let w=h.foreignKeyColumn||X(h.propertyName),_=this.getTableMetadata(y),$=_&&te(_)?.name||"id";e.leftJoin(`${y} as ${m}`,`${m}.${$}`,`${f}.${w}`)}l=y,f=m}}}toKnexSelect(e,t){let r=e.indexOf(" as ");if(r!==-1){let o=e.substring(0,r),i=e.substring(r+4),s=I(i,this.dbType),a=t?`${I(t,this.dbType)}.${I(o,this.dbType)}`:I(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${I(t,this.dbType)}.${I(e,this.dbType)} as ${I(e,this.dbType)}`):e}resolveFields(e,t){let{rootFields:r,subRelations:o}=nt(e),i=[];if(r.includes("*")){let u=new Set;for(let l of t.relations||[])if(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse){let f=l.foreignKeyColumn||X(l.propertyName);f&&u.add(f)}for(let l of t.columns)u.has(l.name)||i.push(l.name);for(let l of t.relations||[])o.has(l.propertyName)||o.set(l.propertyName,["id"])}else for(let u of r){let l=t.relations?.find(d=>(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse)&&(d.foreignKeyColumn||X(d.propertyName))===u);if(l){o.has(l.propertyName)||o.set(l.propertyName,["id"]);continue}let f=t.columns.find(d=>d.name===u);f?i.push(f.name):t.relations?.find(p=>p.propertyName===u)&&!o.has(u)&&o.set(u,["id"])}let s=te(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((u,l)=>{let f=t.relations?.find(d=>d.propertyName===l);if(f&&(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse)){let d=f.foreignKeyColumn||X(f.propertyName);d&&i.push(`${d} as ${l}`)}});let a=[];return o.forEach((u,l)=>{let f=t.relations?.find(p=>p.propertyName===l);if(!f)return;let d=f.targetTableName||f.targetTable;d&&a.push({relationName:l,type:f.type,targetTable:d,fields:u,isInverse:f.isInverse,fkColumn:f.foreignKeyColumn,mappedBy:f.mappedBy,junctionTableName:f.junctionTableName,junctionSourceColumn:f.junctionSourceColumn,junctionTargetColumn:f.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}}});var Ar,Dn,hl,Lt,vo=Q(()=>{"use strict";on();Ne();et();ft();ds();Rr();Ar="__sourceId__",Dn="__targetId__",hl=5e4,Lt=class{constructor(e,t="postgres",r,o=new We){this.knex=e;this.dbType=t;this.metadata=r;this.executionBudget=o;this.pkField="id";this.batchQuery=new Bn(e,t,r)}resolveFields(e,t){return this.batchQuery.resolveFields(e,t)}chunkCount(e,t=5e3){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?hl:5e3}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)}keyOf(e){if(e===null)return"null:";if(e===void 0)return"undefined:";if(typeof e=="number")return Number.isNaN(e)?"number:nan":Object.is(e,-0)?"number:-0":`number:${e}`;if(typeof e=="bigint")return`bigint:${e}`;if(typeof e=="boolean")return`boolean:${e}`;if(typeof e=="string")return`string:${e.length}:${e}`;if(e instanceof Date)return`date:${e.toISOString()}`;throw new Error("SQL relation identity must be a scalar value")}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return te(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;if(!t&&e.mappedBy&&(t=X(e.mappedBy)),!t)throw new Error(`Missing inverse foreign key metadata for relation: ${e.relationName}`);return t}resolveParentPk(e){return e&&te(e)?.name||"id"}async fetchOwner(e,t,r,o){let i=o?.userFilter?this.batchQuery.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.batchQuery.parseSortTokens(o.userSort,e):[],a=r.selectCols.map(l=>this.batchQuery.toKnexSelect(l,e)),c=this.uniqueValues(t),u=await W(c,l=>{let f=this.knex(e).select(a).whereIn(`${e}.${r.pkCol}`,l);if(i&&ue(f,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.batchQuery.applySortJoins(f,o.userSort,e);for(let d of s)f.orderBy(d.column,d.order)}return this.runQuery(f)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,r,o,i){let s=t,a=o.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let c=i?.userFilter?this.batchQuery.buildFilterTree(i.userFilter,e):null,u=i?.userSort?this.batchQuery.parseSortTokens(i.userSort,e):[],l=i?.userLimit,f=i?.userPage,d=this.uniqueValues(r);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,y=o.selectCols.map(w=>this.batchQuery.toKnexSelect(w,e)),m=await W(d,async w=>{let _=this.knex(e).select(y).select(this.batchQuery.buildPartitionRowNumber(`${e}.${t}`,u,`${e}.${o.pkCol}`)).whereIn(`${e}.${t}`,w);c&&ue(_,c,{dbType:this.dbType,rootTable:e}),this.batchQuery.applySortJoins(_,i.userSort,e);let $=await this.runQuery(this.batchQuery.buildPartitionSlice(_,s,h,l));return this.batchQuery.removePartitionFields($),$});return{docs:m,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(d),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let p=o.selectCols.map(h=>this.batchQuery.toKnexSelect(h,e)),g=await W(d,h=>{let y=this.knex(e).select(p).whereIn(`${e}.${t}`,h);if(c&&ue(y,c,{dbType:this.dbType,rootTable:e}),this.batchQuery.applySortJoins(y,i?.userSort,e),u.length>0)for(let m of u)y.orderBy(m.column,m.order);else y.orderBy(`${e}.${o.pkCol}`,"asc");return this.runQuery(y)});return{docs:g,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(d),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}postProcessInverseChild(e,t,r){r||delete e[t]}async selectM2MEdges(e,t,r,o,i,s,a,c){let u=`t.${s}`,l=!!a||c.some(h=>h.column!==u),f=l?c:c.map(h=>({...h,column:`${r}.${i}`})),d=t.userLimit,p=t.userPage;if(d!==void 0&&d>0){let h=p?(p-1)*d:0;return(await W(e,async m=>{let w=this.knex(r).select({[Ar]:`${r}.${o}`,[Dn]:`${r}.${i}`}).whereIn(`${r}.${o}`,m);l&&(w=w.join(`${t.targetTable} as t`,`${r}.${i}`,`t.${s}`),a&&ue(w,a,{dbType:this.dbType,rootTable:"t"}),this.batchQuery.applySortJoins(w,t.userSort,t.targetTable,"t")),w.select(this.batchQuery.buildPartitionRowNumber(`${r}.${o}`,f,l?u:`${r}.${i}`));let _=await this.runQuery(this.batchQuery.buildPartitionSlice(w,Ar,h,d));return this.batchQuery.removePartitionFields(_),_})).map(m=>({sourceId:m[Ar],targetId:m[Dn]}))}return(await W(e,h=>{let y=this.knex(r).select({[Ar]:`${r}.${o}`,[Dn]:`${r}.${i}`}).whereIn(`${r}.${o}`,h);if(l&&(y=y.join(`${t.targetTable} as t`,`${r}.${i}`,`t.${s}`),a&&ue(y,a,{dbType:this.dbType,rootTable:"t"}),this.batchQuery.applySortJoins(y,t.userSort,t.targetTable,"t")),y.orderBy(`${r}.${o}`,"asc"),f.length>0){for(let m of f)y.orderBy(m.column,m.order);l&&!f.some(m=>m.column===u)&&y.orderBy(u,"asc")}else y.orderBy(`${r}.${i}`,"asc");return this.runQuery(y)})).map(h=>({sourceId:h[Ar],targetId:h[Dn]}))}async loadM2MTargets(e,t,r){if(t.length===0)return[];let o=r.selectCols.map(i=>this.batchQuery.toKnexSelect(i));return W(t,i=>this.runQuery(this.knex(e).select(o).whereIn(r.pkCol,i)),this.m2mTargetChunkSize())}async fetchM2M(e,t,r,o,i){let s=this.resolveParentPk(r),a=this.uniqueValues(e.map(x=>x[s]));if(a.length===0)return{grouped:new Map,docs:[]};let c=t.junctionTableName,u=t.junctionSourceColumn,l=t.junctionTargetColumn;if(!c||!u||!l)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let f=t.userFilter?this.batchQuery.buildFilterTree(t.userFilter,t.targetTable):null,d=t.userSort?this.batchQuery.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,c,u,l,i.pkCol,f,d),g=new Map;for(let x of a)g.set(this.keyOf(x),[]);let h=i.selectCols.length===1&&i.selectCols[0]===i.pkCol,y=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),w=`t.${i.pkCol}`,_=!f&&d.every(x=>x.column===w);if(h){let x=new Map;for(let v of p){let R=this.keyOf(v.targetId);x.has(R)||x.set(R,{[i.pkCol]:v.targetId}),g.get(this.keyOf(v.sourceId))?.push(x.get(R))}return{grouped:g,docs:[],stats:{strategy:_?y?"m2m-junction-partitioned-top-k":"m2m-junction-batch":y?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let $=this.uniqueValues(p.map(x=>x.targetId)),k=await this.loadM2MTargets(t.targetTable,$,i),C=new Map(k.map(x=>[this.keyOf(x[i.pkCol]),x]));for(let x of p){let v=C.get(this.keyOf(x.targetId));v&&g.get(this.keyOf(x.sourceId))?.push(v)}return{grouped:g,docs:k,stats:{strategy:y?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+($.length>0?this.chunkCount($,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+k.length,rowsDiscarded:0}}}}});var ps={};Un(ps,{executeBatchFetches:()=>Mo});async function Mo(n,e,t,r,o=3,i=0,s,a="postgres",c,u){let l=new Lt(n,a,c);await new qe(l,r,u).execute(e,t,o,i,s)}var Ao=Q(()=>{"use strict";Ne();vo()});var yl={};Un(yl,{ALL_SUPPORTED_OPERATORS:()=>ar,AuthenticationException:()=>zt,AuthorizationException:()=>Jt,BadRequestException:()=>b,BatchExecutionBudget:()=>We,BatchFetchEngine:()=>qe,BusinessLogicException:()=>Wt,CHUNKED_FETCH_CONCURRENCY:()=>hr,ConfigurationException:()=>Zt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>mr,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Fi,DEFAULT_TIMEOUT_MS:()=>Or,DOTTED_PATH_MAX_HOPS:()=>me,DatabaseException:()=>ht,DuplicateResourceException:()=>Qt,ErrorHandler:()=>Ve,ExecutorEngineService:()=>gt,ExternalServiceException:()=>Gt,FIELD_OPERATORS:()=>de,FileNotFoundException:()=>tr,FileSizeExceededException:()=>rr,FileUploadException:()=>er,HttpException:()=>Y,InvalidTokenException:()=>Vt,IsolatedExecutorService:()=>bt,JoinRegistry:()=>Te,LOGICAL_OPERATORS:()=>ro,MongoBatchAdapter:()=>Rt,MongoQueryExecutor:()=>lt,PER_PARENT_CONCURRENCY:()=>St,QueryBuilderService:()=>qt,QueryPlanner:()=>pe,ResourceNotFoundException:()=>Ut,SchemaException:()=>Xt,ScriptContractService:()=>Ur,ScriptExecutionException:()=>He,ScriptTimeoutException:()=>Be,ServiceUnavailableException:()=>Yt,SqlBatchAdapter:()=>Lt,SqlQueryExecutor:()=>pt,TokenExpiredException:()=>Ht,ValidationException:()=>Kt,WHERE_IN_CHUNK_SIZE:()=>ae,WorkerPool:()=>Ge,applyOperatorToMatch:()=>$r,applyRelationFilters:()=>Ot,applyWhereToKnex:()=>Bt,assertFieldOperatorValueIsClean:()=>no,buildMongoCharFoldMapJson:()=>ho,buildMongoFoldTextSearchJs:()=>fn,buildMongoSortSpec:()=>po,buildMongoSortSpecFromPlan:()=>gr,buildRelationSortSubquery:()=>On,buildRelationSubquery:()=>ss,buildSqlWherePartsFromFieldAst:()=>vr,buildWhereClause:()=>ut,camelToSnake:()=>mi,checkIfFilterContainsIsNull:()=>zi,chunkedFetch:()=>W,compileScriptSource:()=>ra,computeEngineTuning:()=>Gn,createEnfyraKernel:()=>ml,dslOpToCompareOp:()=>Qr,encodeMainThreadToIsolate:()=>ir,escapeSqlValue:()=>we,executeAggregationPipeline:()=>Fn,executeBatchFetches:()=>Mo,executeCountQueries:()=>Mn,executeMongoBatchFetches:()=>bn,expandFieldsMongo:()=>tt,expandFieldsToJoinsAndSelect:()=>Ro,expandFieldsToSelect:()=>Nn,getEffectiveCpuCount:()=>Vn,getEffectiveMemoryBytes:()=>or,getEngineTuning:()=>Br,getExecutableScript:()=>sa,getForeignKeyColumnName:()=>X,getIoAbortSignal:()=>Xn,getJunctionColumnNames:()=>pr,getJunctionTableName:()=>dr,getMetadataGetter:()=>Fr,getMongoInverseRelationForeignField:()=>H,getMongoMetadataGetter:()=>ko,getMongoStoredRelationField:()=>Z,getPrimaryKeyColumn:()=>te,getScriptLegacyField:()=>Zs,getShortFkConstraintName:()=>gi,getShortFkName:()=>yi,getShortIndexName:()=>bi,getShortPkName:()=>pi,hasLogicalOperators:()=>ct,isExecutableJavaScript:()=>na,isMongoInverseRelation:()=>ge,isScriptTable:()=>ea,normalizeAggregateQuery:()=>At,normalizeFlowStepScriptConfig:()=>la,normalizeMongoDocument:()=>se,normalizeMongoResults:()=>Rn,normalizeScriptLanguage:()=>ta,normalizeScriptPatch:()=>ia,normalizeScriptRecord:()=>oa,parseBatchFields:()=>nt,parseFields:()=>Vr,parseFilter:()=>Me,parseSortInput:()=>gs,perParentRun:()=>bs,quoteIdentifier:()=>I,quoteQualifiedIdentifier:()=>ze,renderFilterToKnex:()=>ue,resolveExecutableScript:()=>aa,resolveMongoJunctionInfo:()=>he,rewriteFilterDenyingFields:()=>ms,rewriteSortDroppingDenied:()=>ys,runWithIoAbortSignal:()=>Zn,scriptContractService:()=>$e,separateFilters:()=>Ae,snakeToCamel:()=>hi,throwUnsupportedFieldOperator:()=>Ze,validateDeepOptions:()=>rt,validateFilterShape:()=>De,whereToMongoFilter:()=>It});module.exports=Es(yl);var Or=3e4,gt=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,r={}){let o=e.routeData.__codeBlocks||[];return o.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(o,e.routeData.context,t??Or,r)}async run(e,t,r=Or,o={}){return this.isolatedExecutorService.run(e,t,r,o)}};var Zo=Je(require("path"));var Be=class extends Error{constructor(t=0,r,o){let i=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${i}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={...o,timeoutMs:t,scriptId:r,outcome:o?.outcome??"timed_out",retryable:!1}}},He=class extends Error{constructor(t,r,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={...o,scriptId:r}}},z=class extends Error{constructor(t,r,o,i){if(!Number.isInteger(r)||r<400||r>599)throw new TypeError("Kernel exception statusCode must be an integer from 400 to 599");super(t);this.statusCode=r;this.errorCode=o;this.name=this.constructor.name,this.details=i}},Y=class extends z{constructor(e,t,r){super(e,t,`HTTP_${t}`,r)}},Wt=class extends z{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Kt=class extends z{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Ut=class extends z{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},Qt=class extends z{constructor(e,t,r){super(`${e} with ${t} '${r}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:r})}},zt=class extends z{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},Jt=class extends z{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},Ht=class extends z{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},Vt=class extends z{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},ht=class extends z{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},Gt=class extends z{constructor(e,t,r){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:r})}},Yt=class extends z{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},Xt=class extends z{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},Zt=class extends z{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},er=class extends z{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},tr=class extends z{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},rr=class extends z{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Pr=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!==void 0&&console.error(this.format(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;try{typeof e=="string"?t=e:e instanceof Error?t=e.stack??e.message:t=JSON.stringify(e,(o,i)=>typeof i=="bigint"?i.toString():i)??String(e)}catch{try{t=String(e)}catch{t="[Unserializable value]"}}return this.context?`[${this.context}] ${t}`:t}};var Qn=new Set(["__proto__","prototype","constructor","caller","callee","arguments"]);function ie(n,e,t=!1){if(Qn.has(e))throw new Error(`Host capability property is forbidden: ${e}`);if((typeof n!="object"||n===null)&&typeof n!="function")return;let r=n,o=new Set;for(;r&&r!==Object.prototype&&r!==Function.prototype;){if(o.size>=64)throw new Error("Host capability prototype traversal limit exceeded");if(o.has(r))throw new Error("Cyclic host capability prototype");if(o.add(r),Object.prototype.hasOwnProperty.call(r,e))return n[e];r=Object.getPrototypeOf(r)}if(t&&!Object.prototype.hasOwnProperty.call(Object.prototype,e)&&!Object.prototype.hasOwnProperty.call(Function.prototype,e)&&e in n)return n[e]}var Oo=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$streams","$debug"]);function Jn(n){let e={$body:n.$body,$query:n.$query,$params:n.$params,$user:n.$user,$share:n.$share,$data:n.$data,$api:{request:n.$api?.request},$uploadedFile:n.$uploadedFile,$req:zn(n.$req)};for(let r of Object.keys(n)){if(!r.startsWith("$")||r in e||Oo.has(r))continue;let o=zn(n[r]);o!==void 0&&(e[r]=o)}let t=n.$flow;if(t!=null)try{e.$flow=zn(t)??{}}catch{e.$flow={}}return e}function zn(n){if(typeof n!="function")try{return JSON.parse(JSON.stringify(n,(e,t)=>{if(typeof t=="bigint")return String(t);if(typeof t!="function")return t}))}catch{return}}function nr(n,e){if(e){for(let t of["$body","$query","$params","$data","$error","$statusCode","$share"])Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=e[t]);if(e.$api&&typeof e.$api=="object"&&n.$api&&typeof n.$api=="object"&&(Object.prototype.hasOwnProperty.call(e.$api,"error")&&(n.$api.error=e.$api.error),Object.prototype.hasOwnProperty.call(e.$api,"response")&&(n.$api.response=e.$api.response)),e.$flow!==void 0&&e.$flow!==null&&typeof e.$flow=="object"&&n.$flow!==null&&n.$flow!==void 0&&typeof n.$flow=="object")for(let[t,r]of Object.entries(e.$flow))Qn.has(t)||Object.defineProperty(n.$flow,t,{value:r,enumerable:!0,configurable:!0,writable:!0});for(let[t,r]of Object.entries(e))t.startsWith("$")&&(t==="$body"||t==="$query"||t==="$params"||t==="$data"||t==="$error"||t==="$statusCode"||t==="$share"||t==="$api"||t==="$flow"||Oo.has(t)||t==="$env"||(n[t]=r));delete n.$pkgs}}var yt=Je(require("os"));var jo=Je(require("fs")),jr=require("path");function mt(n){try{return jo.readFileSync(n,"utf8").trim()}catch{return""}}function Po(n){return n.replace(/\\([0-7]{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function Bo(n,e){let t=new Set([e?"/sys/fs/cgroup":`/sys/fs/cgroup/${n}`]),r=mt("/proc/self/cgroup").split(`
|
|
2
2
|
`);for(let o of mt("/proc/self/mountinfo").split(`
|
|
3
|
-
`)){let[i,s]=o.split(" - ");if(!s)continue;let a=s.split(" ");if(a[0]!==(e?"cgroup2":"cgroup")||!e&&!a[2]?.split(",").includes(n))continue;let c=i.split(" "),u=Po(c[3]??""),l=Po(c[4]??"");if(!(!u.startsWith("/")||!l.startsWith("/")))for(let f of r){let d=/^\d+:([^:]*):(\/.*)$/.exec(f);if(!d||(e?d[1]!=="":!d[1].split(",").includes(n)))continue;let p=jr.posix.normalize(d[2]);if(u!=="/"&&p!==u&&!p.startsWith(`${u}/`))continue;let g=u==="/"?p.slice(1):p.slice(u.length+1),h=jr.posix.join(l,g);for(;(h===l||h.startsWith(`${l}/`))&&(t.add(h),h!==l);)h=jr.posix.dirname(h)}}return t}function Do(n){let e=n;for(let t of[!0,!1])for(let r of Bo("memory",t)){let o=Number(mt(`${r}/${t?"memory.max":"memory.limit_in_bytes"}`));Number.isFinite(o)&&o>0&&(e=Math.min(e,o))}return e}function Lo(n){let e=n;for(let t of[!0,!1])for(let r of Bo("cpu",t)){let[o,i]=t?mt(`${r}/cpu.max`).split(/\s+/).map(Number):[Number(mt(`${r}/cpu.cfs_quota_us`)),Number(mt(`${r}/cpu.cfs_period_us`))];o>0&&i>0&&Number.isFinite(o)&&Number.isFinite(i)&&(e=Math.min(e,Math.max(1,Math.ceil(o/i))))}return e}function or(){return Do(yt.totalmem())}function Vn(){return Lo(yt.availableParallelism?.()||yt.cpus()?.length||1)}var xs=.25,Hn=128,Cs=2,Rs=4,Fs=6,Is=8,vs=2048,Ms=40,As=128,Ns=32;function Os(n){let e=Math.trunc(Number(n));if(!(!Number.isFinite(e)||e<1))return Math.min(Hn,e)}function Ps(n){let e=Math.trunc(Number(n));return!Number.isFinite(e)||e<1?Fs:Math.min(Is,e)}function qo(n){return 2**Math.ceil(Math.log2(Math.max(1,n)))}function Gn(n){let e=Math.max(1,Math.trunc(n.logicalCpuCount)||1),t=Math.max(1,n.totalMemoryBytes/(1024*1024)),r=Math.min(As,Math.max(Ms,Math.round(t/Ns))),o=t*xs,i=Math.max(1,Math.floor(o/r)),s=Math.max(1,Math.min(e,2,i)),a=Math.max(1,Math.floor(o/(s*r))),c=Math.min(Hn,qo(e*Cs)),u=Math.min(Hn,qo(e*Rs)),l=Math.max(c,Math.min(u,a)),f=Os(n.maxLanesPerRunner)??l,d=t<vs?1:f,p=Math.max(1,Math.min(d,a)),g=Ps(n.tasksPerIsolate),h=p*g;return{maxConcurrentWorkers:s,isolateMemoryLimitMb:r,tasksPerWorkerCap:h,isolatePoolSize:p,tasksPerIsolate:g}}function Br(){return Gn({logicalCpuCount:Vn(),totalMemoryBytes:or()})}var Wo={400:"Bad request",401:"Authentication required",403:"Insufficient permissions",404:"Not found",409:"Conflict",422:"Validation failed",429:"Rate limit exceeded",500:"Internal server error",503:"Service unavailable"},Ve=class{static createException(e,t,r,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new Y(r||"Error",t||500,i);case"$throw.businessLogic":return new Wt(r||"Bad request",i);case"$throw.validation":return new Kt(r||"Validation failed",i);case"$throw.notFound":return new Ut(i?.resource||r||"Resource",i?.identifier);case"$throw.duplicate":return new Qt(i?.resource||r||"Resource",i?.field||"field",i?.value??"value");case"$throw.unauthorized":return new zt(r||"Unauthorized");case"$throw.forbidden":return new Jt(r||"Forbidden");case"$throw.tokenExpired":return new Ht;case"$throw.invalidToken":return new Vt;case"$throw.database":return new ht(r||"Database error",i);case"$throw.dbQuery":return new ht(r||"Query error",i);case"$throw.externalService":return new Gt(r||"Service",r||"Error",i);case"$throw.serviceUnavailable":return new Yt(r||"Service");case"$throw.rateLimit":return new Y(r||"Rate limit exceeded",429,i);case"$throw.scriptError":return new He(r||"Script error",o,i);case"$throw.scriptTimeout":return new Be(i?.timeout||5e3,o);case"$throw.schema":return new Xt(r||"Schema error",i);case"$throw.config":return new Zt(r||"Configuration error",i);case"$throw.fileUpload":return new er(r||"File upload error",i);case"$throw.fileNotFound":return new tr(r||"File not found");case"$throw.fileSizeExceeded":return new rr(i?.maxSize??"unknown",i?.actualSize??"unknown");case"$throw.400":return new Y(r||"Bad request",400,i);case"$throw.401":return new Y(r||"Authentication required",401,i);case"$throw.403":return new Y(r||"Insufficient permissions",403,i);case"$throw.404":return new Y(r||"Not found",404,i);case"$throw.409":return new Y(r||"Conflict",409,i);case"$throw.422":return new Y(r||"Validation failed",422,i);case"$throw.429":return new Y(r||"Rate limit exceeded",429,i);case"$throw.500":return new Y(r||"Internal server error",500,i);case"$throw.503":return new Y(r||"Service unavailable",503,i);default:return Number.isInteger(t)&&t>=400&&t<=599?new Y(r||Wo[t]||"Request failed",t,i):new He(r||"Unknown error",o,i)}return Number.isInteger(t)&&t>=400&&t<=599?new Y(r||Wo[t]||"Request failed",t,i):new He(r||"Unknown error",o,i)}};function Ko(n){return Math.min(2147483647,n+Math.ceil(n*.15))}function Yn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0})}function Ie(n,e,t){if(!Object.prototype.hasOwnProperty.call(n,e))return!1;let r=new Set(t);return Object.keys(n).every(o=>r.has(o))}var Uo=Object.freeze({Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,...typeof globalThis.Float16Array>"u"?{}:{Float16Array:globalThis.Float16Array},...typeof BigInt64Array>"u"?{}:{BigInt64Array},...typeof BigUint64Array>"u"?{}:{BigUint64Array}});function fe(n,e){if(!n||typeof n!="object")return n;let t=n;if(Ie(t,"__plainObject",["__plainObject"])){let o={};for(let[i,s]of Object.entries(t.__plainObject||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__nullPrototype",["__nullPrototype"])){let o=Object.create(null);for(let[i,s]of Object.entries(t.__nullPrototype||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__e",["__e"])&&t.__e==="u")return;if(e&&Ie(t,"__fnRef",["__fnRef"])&&typeof t.__fnRef=="string")return e(t.__fnRef);if(Ie(t,"__number",["__number"])){if(t.__number==="nan")return Number.NaN;if(t.__number==="infinity")return Number.POSITIVE_INFINITY;if(t.__number==="-infinity")return Number.NEGATIVE_INFINITY;if(t.__number==="-0")return-0;throw new TypeError(`Unsupported executor number: ${t.__number}`)}if(Ie(t,"__bigint",["__bigint"]))return BigInt(t.__bigint);if(Ie(t,"__map",["__map"]))return new Map((t.__map||[]).map(([o,i])=>[fe(o,e),fe(i,e)]));if(Ie(t,"__arrayBuffer",["__arrayBuffer"]))return Uint8Array.from(t.__arrayBuffer||[]).buffer;if(Ie(t,"__typedArray",["__typedArray","bytes","data"])){let o=Uint8Array.from(t.bytes||t.data||[]);if(t.__typedArray==="DataView")return new DataView(o.buffer);let i=Uo[String(t.__typedArray)];if(!Object.prototype.hasOwnProperty.call(Uo,t.__typedArray)||typeof i!="function")throw new TypeError(`Unsupported executor typed array: ${t.__typedArray}`);return new i(o.buffer)}if(Array.isArray(n))return n.map(o=>fe(o,e));let r={};for(let[o,i]of Object.entries(t))Yn(r,o,fe(i,e));return r}function ve(n){try{if(n instanceof Error)return n}catch{}let e="Unknown error";try{n===void 0?e="Operation rejected with undefined":n===null?e="Operation rejected with null":e=String(n)}catch{}return new Error(e)}function Qo(n){let e=new WeakSet;try{return JSON.stringify(n,(t,r)=>{if(typeof r=="bigint")return r.toString();if(!(typeof r=="function"||typeof r=="symbol")){if(r&&typeof r=="object"){if(e.has(r))return"[Circular]";e.add(r)}return r}})}catch{let t="Host capability call failed",r;try{t=String(n.message||t)}catch{}try{typeof n.code=="string"&&(r=n.code)}catch{}return JSON.stringify({__userThrow:!0,message:t,code:r})}}function ir(n){if(n===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:n},(e,t)=>typeof t=="bigint"?{__bigint:t.toString()}:t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var zo=require("async_hooks"),Dr=new zo.AsyncLocalStorage;function Xn(){return Dr.getStore()}function Zn(n,e){return Dr.run(n,e)}var Lr=class{constructor(e,t){this.taskAbortSignals=e;this.taskDeadlines=t;this.runtimeCallbackCounter=0}postAbortedCallError(e,t){e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})}).catch(()=>{})}async handleIoCall(e,t,r,o){if(o?.aborted){this.postAbortedCallError(t,r);return}try{let i=await(o?Dr.run(o,e):e());if(o?.aborted){this.postAbortedCallError(t,r);return}await t.postMessage({type:"callResult",callId:r,result:ir(i)})}catch(i){if(o?.aborted){this.postAbortedCallError(t,r);return}let s=ve(i),a={__userThrow:!0,message:s.message,statusCode:s.statusCode,code:s.errorCode??s.code,errorPath:s.errorPath,details:s.details,messages:s.messages};await t.postMessage({type:"callError",callId:r,error:Qo(a)}).catch(()=>{})}}parseExecutorArgs(e,t,r){let o=JSON.parse(e||"[]");return fe(o,t&&r?s=>(...a)=>this.invokeRuntimeCallback(t,r,s,a):void 0)}async execRepoCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=e.access==="secure"?oe(t?.$repos,"secure",!0):t?.$repos,i=oe(o,String(e.table),!0),s=oe(i,String(e.method));if(!i||typeof s!="function"){let a=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${a}${e.table}.${e.method}`)}return s.apply(i,r)}async execTransactionCall(e,t,r){let i=this.parseExecutorArgs(e.argsJson,r,e.id)[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 r=this.parseExecutorArgs(e.argsJson),o=String(e.name).split("."),i=t?.$helpers,s=i;for(let a of o)i=s,s=oe(s,a);if(typeof s!="function")throw new Error(`Helper not found: ${e.name}`);return s.apply(i,r)}async execSocketCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$socket,i=oe(o,String(e.method));if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i.apply(o,r)}async execCacheCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$cache,i=oe(o,String(e.method));if(typeof i!="function")throw new Error(`Cache not found: ${e.method}`);return i.apply(o,r)}async execStorageCall(e,t,r){let o=this.parseStorageArgs(e.argsJson,r,e.id),i=t?.$storage,s=oe(i,String(e.method));if(typeof s!="function")throw new Error(`Storage method not found: ${e.method}`);return s.apply(i,o)}parseStorageArgs(e,t,r){return this.parseExecutorArgs(e,t,r)}invokeRuntimeCallback(e,t,r,o){let i=`rtcb_${++this.runtimeCallbackCounter}`,s=this.taskAbortSignals.get(t),a=this.taskDeadlines.get(t)??Date.now()+3e4,c=Math.max(1,a-Date.now())+500;return new Promise((u,l)=>{let f=!1,d=b=>{f||(f=!0,m(),b())},p=setTimeout(()=>{d(()=>l(new Error(`Runtime callback timed out: ${r}`)))},c),g=()=>{d(()=>l(new Error("Runtime callback was cancelled")))},h=()=>{d(()=>l(new Error("Runtime callback worker exited")))},y=b=>{if(!(b?.type!=="runtimeCallbackResult"||b.callId!==i)){if(b.error){let _=new Error(String(b.error));try{let S=JSON.parse(String(b.error));S?.__userThrow&&(_.message=String(S.message??_.message),_.statusCode=S.statusCode,_.code=S.code??(Number.isInteger(S.statusCode)?`HTTP_${S.statusCode}`:void 0),_.errorCode=_.code,_.errorPath=S.errorPath,_.details=S.details,_.messages=S.messages)}catch{}d(()=>l(_));return}d(()=>u(b.value))}},m=()=>{clearTimeout(p),e.off("message",y),e.off("exit",h),s?.removeEventListener("abort",g)};if(e.on("message",y),e.on("exit",h),s?.addEventListener("abort",g,{once:!0}),s?.aborted){g();return}try{e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:r,argsJson:JSON.stringify(o)}).catch(b=>d(()=>l(b)))}catch(b){d(()=>l(b))}})}async execDispatchCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=oe(t,"$trigger");if(typeof o!="function")throw new Error("$trigger is not available");return o.apply(t,r)}};var Ho=require("stream");var eo=32*1024*1024,Jo=Math.ceil(eo/3)*4,qr=class{constructor(e,t){this.cancelTask=e;this.parseExecutorArgs=t;this.responseStreams=new Map}async execResCall(e,t){if(e.method==="json"){let s=oe(t?.$res,"__enfyraJson");if(typeof s!="function")throw new Error("Native JSON response is not available");return await s.call(t.$res,String(e.jsonText),e.options||{})}if(e.method==="bytes"){let s=oe(t?.$res,"__enfyraBytes");if(typeof s!="function")throw new Error("Native binary response is not available");let a=String(e.bytes||"");if(a.length>Jo)throw new Error("Native binary response exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Native binary response exceeded 32 MiB");return await s.call(t.$res,c,e.options||{})}if(e.method==="streamStart"){if(this.responseStreams.has(e.id))throw new Error(`Response stream already exists: ${e.id}`);let a=JSON.parse(e.argsJson||"[]")[1]||{},c=oe(t?.$res,"stream");if(typeof c!="function")throw new Error("Response method not found: stream");let u=new Ho.PassThrough;u.on("error",()=>{});let l={stream:u};this.responseStreams.set(e.id,l);let f=t?.$res;if(f&&typeof f.once=="function"){let d=()=>{f.writableEnded!==!0&&this.cancelTask(e.id)};f.once("close",d),l.closeCleanup=()=>{typeof f.off=="function"?f.off("close",d):typeof f.removeListener=="function"&&f.removeListener("close",d)}}try{let d=c.call(t.$res,u,a);return d&&typeof d.then=="function"&&(l.completion=Promise.resolve(d).then(()=>{},p=>{let g=ve(p);throw this.responseStreams.get(e.id)===l&&(this.cleanupResponseStream(e.id,g),this.cancelTask(e.id)),g}),l.completion.catch(()=>{})),!0}catch(d){let p=ve(d);throw this.cleanupResponseStream(e.id,p),p}}if(e.method==="streamChunk"){let s=this.responseStreams.get(e.id);if(!s)throw new Error(`Response stream not found: ${e.id}`);let a=String(e.chunk||"");if(a.length>Jo)throw new Error("Response stream chunk exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Response stream chunk exceeded 32 MiB");if(s.stream.destroyed)throw new Error("Response stream closed before drain");return s.stream.write(c)||await new Promise((u,l)=>{let f=()=>{g(),u()},d=h=>{g(),l(h)},p=()=>{g(),l(new Error("Response stream closed before drain"))},g=()=>{s.stream.off("drain",f),s.stream.off("error",d),s.stream.off("close",p)};s.stream.once("drain",f),s.stream.once("error",d),s.stream.once("close",p)}),!0}if(e.method==="streamEnd"){let s=this.responseStreams.get(e.id);if(s){s.stream.end();try{await s.completion}finally{this.responseStreams.get(e.id)===s&&(s.closeCleanup?.(),this.responseStreams.delete(e.id))}}return!0}if(e.method==="streamError"){let s=this.responseStreams.get(e.id);if(s){s.closeCleanup?.();let a=e.error?.message||"Response stream failed";s.stream.destroy(new Error(a)),this.responseStreams.delete(e.id)}return!0}let r=this.parseExecutorArgs(e.argsJson),o=t?.$res,i=oe(o,String(e.method));if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(o,r)}cleanupResponseStream(e,t){let r=this.responseStreams.get(e);r&&(this.responseStreams.delete(e),r.closeCleanup?.(),t?r.stream.destroy(t):r.stream.end())}};var Vo=require("child_process"),Go=require("string_decoder"),Bs=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function Ds(){let n={};for(let e of Bs){let t=process.env[e];t!==void 0&&(n[e]=t)}return n}var Wr=class{constructor(e){this.terminated=!1;this.stderrTail="";this.stderrDecoder=new Go.StringDecoder("utf8");this.child=(0,Vo.fork)(e,[],{stdio:["ignore","ignore","pipe","ipc"],env:Ds(),execArgv:[],serialization:"advanced"}),this.child.on("error",t=>{this.stderrTail=(this.stderrTail+t.message).slice(-8192)}),this.child.stderr?.on("data",t=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.write(t)).slice(-8192)}),this.child.stderr?.on("end",()=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.end()).slice(-8192)})}get stderr(){return this.stderrTail}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){return this.child.connected?new Promise((t,r)=>{try{this.child.send(e,o=>{o?r(o):t()})}catch(o){r(o)}}):Promise.reject(new Error("Executor runner IPC is closed"))}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var Ge=class{constructor(e,t,r,o,i,s,a,c=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=r,this.tasksCap=o,this.drainTimeoutMs=c;for(let u=0;u<e;u++)this.spawnEntry()}getEntries(){return this.entries}clearDrainTimeout(e){e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0)}reportObserverError(e,t){let r=t instanceof Error?t.message:String(t);console.error(`[executor-pool] ${e}: ${r}`)}spawnEntry(){let e=new Wr(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",r=>{let o=t.tasks.get(r.id);if(o)if(r.type==="taskReleased")o.onRelease?.();else if(r.type==="taskLane")o.onLane?.(r.laneKey);else if(r.type==="taskFailure")o.onFailure?.(r.error);else if(r.type==="result"||r.type==="taskCancelled"){typeof r.heapRatio=="number"&&(t.lastHeapRatio=r.heapRatio),typeof r.runnerRssBytes=="number"&&(t.lastRssBytes=r.runnerRssBytes),r.contextStats&&(t.contextStats=r.contextStats);let i=r;r.type==="taskCancelled"&&(i={type:"result",id:r.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}});try{o.onResult(i)}catch(s){this.reportObserverError("task result callback failed",s)}!t.draining&&typeof r.heapRatio=="number"&&r.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(r.heapRatio*100)}%`)}else o.onIoCall(r)}),e.on("exit",(r,o)=>{let i=t.draining,s=this.destroying;t.draining=!0;let a={entryId:t.id,pid:t.worker.pid,exitCode:r,exitSignal:o??null,lastError:t.lastError||t.worker.stderr||void 0,terminationReason:t.terminationReason,lastHeapRatio:t.lastHeapRatio,lastRssBytes:t.lastRssBytes,activeTasks:[...t.tasks.values()].map(l=>l.diagnostics)};this.clearDrainTimeout(t);let c="Worker crashed";s?c="Worker terminated":t.lastError&&(c=`Worker crashed: ${t.lastError}`);for(let[,l]of t.tasks){l.abortController.abort();try{l.onResult({type:"result",success:!1,error:{message:c,code:s?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:s?void 0:{outcome:"unknown_outcome",retryable:!1}}})}catch(f){this.reportObserverError("worker-exit task callback failed",f)}}t.tasks.clear();let u=this.entries.indexOf(t);if(u!==-1&&this.entries.splice(u,1),(!i||t.replaceOnExit)&&!s){try{this.onCrash?.(a)}catch(f){this.reportObserverError("worker crash observer failed",f)}this.entries.filter(f=>!f.draining).length<this.max&&this.spawnEntry()}this.drainWaiting()}),e.on("error",r=>{t.lastError=r.message}),this.entries.push(t),t}rotateEntry(e,t){if(this.destroying||e.draining)return;e.draining=!0;let r=Date.now()-e.spawnedAt;try{this.onRotate?.({reason:t,ageMs:r})}catch(o){this.reportObserverError("worker rotation observer failed",o)}if(this.spawnEntry(),this.drainWaiting(),e.tasks.size===0&&e.reservations===0){this.clearDrainTimeout(e),e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,this.abortEntryTasks(e),e.worker.terminate()},this.drainTimeoutMs)}abortEntryTasks(e){for(let t of e.tasks.values())t.abortController.abort()}isMemoryAvailable(){let e=Date.now();if(e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs){let t=this.entries.reduce((r,o)=>r+(o.lastRssBytes??0),0);this.cachedMemoryOk=(process.memoryUsage().rss+t)/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e}return this.cachedMemoryOk}hasActiveWork(){return this.entries.some(e=>e.tasks.size>0||e.reservations>0)}canDispatch(){return!this.hasActiveWork()||this.isMemoryAvailable()}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let r=t.tasks.size+t.reservations;r<this.tasksCap&&(!e||r<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(e){if(this.destroying)return Promise.reject(new Error("Executor worker pool is shutting down"));if(e?.aborted)return Promise.reject(new Error("Execution aborted before dispatch"));let t=this.findLeastBusy();return t&&this.canDispatch()?(t.reservations++,Promise.resolve(t)):new Promise((r,o)=>{let i={resolve:r,reject:o,signal:e};e&&(i.onAbort=()=>{let s=this.waiting.indexOf(i);s!==-1&&this.waiting.splice(s,1),o(new Error("Execution aborted before dispatch"))},e.addEventListener("abort",i.onAbort,{once:!0})),this.waiting.push(i)})}registerTask(e,t,r){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,r)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(!e||!this.canDispatch())break;let t=this.waiting.shift();if(t.signal?.aborted){t.reject(new Error("Execution aborted before dispatch"));continue}t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),e.reservations++,t.resolve(e)}}terminateEntry(e,t="host_requested"){e.draining&&e.terminationReason||(e.draining=!0,e.replaceOnExit=!0,e.terminationReason=t,this.clearDrainTimeout(e),this.abortEntryTasks(e),e.worker.terminate())}resize(e){this.max=Math.max(1,e);let t=this.entries.filter(i=>!i.draining);for(;t.length<this.max;)t.push(this.spawnEntry());let r=t.length-this.max;if(r<=0){this.drainWaiting();return}let o=t.sort((i,s)=>i.tasks.size+i.reservations-(s.tasks.size+s.reservations)).slice(0,r);for(let i of o)i.draining=!0;this.drainWaiting();for(let i of o)i.tasks.size===0&&i.reservations===0?(this.clearDrainTimeout(i),i.worker.terminate()):(this.clearDrainTimeout(i),i.drainTimeout=setTimeout(()=>{i.drainTimeout=void 0,this.abortEntryTasks(i),i.worker.terminate()},this.drainTimeoutMs))}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,lastRssBytes:e.lastRssBytes??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;let e=new Error("Executor worker pool was destroyed");for(let t of this.waiting.splice(0))t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),t.reject(e);for(let t of this.entries)t.draining=!0,t.terminationReason="pool_destroyed",this.clearDrainTimeout(t),this.abortEntryTasks(t),t.worker.terminate();this.entries.length=0}};var Gs=Zo.join(__dirname,"execution/worker.js"),Ys=3e4,Xs=2147483647;function Xo(n){let e=Number(n);return Number.isFinite(e)?Math.max(1,Math.min(Xs,Math.trunc(e))):Ys}var bt=class n{constructor(e){this.logger=new Pr(n.name);this.effectiveMemory=or();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.taskCancellers=new Map;this.taskAbortSignals=new Map;this.taskDeadlines=new Map;this.taskDurationsMs=[];this.queueWaitDurationsMs=[];this.hostIo=new Lr(this.taskAbortSignals,this.taskDeadlines);this.responseBridge=new qr(e=>this.cancelTask(e),e=>this.hostIo.parseExecutorArgs(e));this.packageCacheService=e.packageCacheService,this.onExecutionFinished=e.onExecutionFinished,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??Br(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Ge(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Gs,t=>{this.crashesTotal++;let r={event:"executor_worker_crashed",occurredAt:new Date().toISOString(),...t};this.logger.warn(r);try{e.onExecutorWorkerCrash?.(r)}catch(o){this.logger.warn({event:"executor_worker_crash_report_failed",error:o instanceof Error?o.message:String(o)})}},({reason:t,ageMs:r})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(r/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerIsolate} tasks/isolate, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let e=this.pool.getEntries().reduce((g,h)=>g+(h.lastRssBytes??0),0),r=(process.memoryUsage().rss+e)/this.effectiveMemory,o=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),s=Number(o-this.prevCpuTime)/1e3,a=s>0?(i.user+i.system)/s:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=o;let c=this.pool.getMax(),u=this.pool.getWaitingCount(),l=r>.85||a>.7,f=r<.7&&a<.5,d=u>0,p=c;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,c-1))):f&&d?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,c+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==c&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${c} -> ${p} (rss=${Math.round(r*100)}% cpu=${Math.round(a*100)}% queue=${u})`))}spawnAndExecute(e,t,r,o,i){return(async()=>{let s=Date.now(),a;try{a=await this.pool.dispatch(i)}catch(l){if(i?.aborted){let f=new Error("Execution aborted before dispatch");throw f.code="ERR_EXECUTION_ABORTED",f.isAbort=!0,f}throw l}if(this.recordQueueWait(Date.now()-s),i?.aborted){this.pool.releaseReservation(a);let l=new Error("Execution aborted after client disconnect");return l.code="ERR_EXECUTION_ABORTED",l.isAbort=!0,Promise.reject(l)}let c=`t_${++this.taskCounter}`,u=Date.now();return new Promise((l,f)=>{let d=!1,p=new AbortController;this.taskAbortSignals.set(c,p.signal);let g=Ko(o);this.taskDeadlines.set(c,u+g);let h=!1,y,m,b=()=>{let k=new Error("Execution aborted after client disconnect");return k.code="ERR_EXECUTION_ABORTED",k.isAbort=!0,k},_=()=>{let k=new Error(`Script execution timed out after ${o}ms`);return k.code="ERR_SCRIPT_EXECUTION_TIMEOUT",k.isTimeout=!0,k},S,E,C=!1,x=k=>{if(!(d||h)){h=!0,y=k,p.abort(),this.responseBridge.cleanupResponseStream(c,k);try{a.worker.postMessage({type:"cancelTask",id:c}).catch(()=>{})}catch{}S=setTimeout(()=>{d||(d=!0,E&&clearTimeout(E),M(),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),this.recordTaskDuration(Date.now()-u),this.pool.terminateEntry(a,k.isTimeout?"timeout_cancel_grace":k.isAbort?"client_abort_cancel_grace":"failure_cancel_grace"),this.pool.unregisterTask(a,c),this.taskErrorTotal++,k.details={...k.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},f(k))},1e4),S.unref?.()}},v=()=>x(b());this.taskCancellers.set(c,v);let R=()=>v(),M=()=>{i?.removeEventListener("abort",R)};i&&(i.addEventListener("abort",R,{once:!0}),i.aborted&&v());let N=()=>{E&&clearTimeout(E),S&&clearTimeout(S),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),M(),this.responseBridge.cleanupResponseStream(c),this.recordTaskDuration(Date.now()-u)},j=()=>{N(),this.pool.unregisterTask(a,c)},O=25,P=()=>{d||(this.taskTimeoutTotal++,x(_()))},G=u+g+[...a.tasks.keys()].reduce((k,$)=>{if($===c)return k;let T=this.taskDeadlines.get($);return k+(T===void 0?0:Math.max(0,T-u))},0),te=()=>{if(!(d||h)){if(!C&&Date.now()>=G){this.taskTimeoutTotal++,x(_());return}if(!C){E=setTimeout(te,O),E.unref?.();return}this.taskDeadlines.set(c,Date.now()+g),E=setTimeout(P,g),E.unref?.()}};E=setTimeout(te,O),E.unref?.(),this.pool.registerTask(a,c,{abortController:p,onLane:()=>{d||h||C||(C=!0,E&&clearTimeout(E),te())},diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),onFailure:k=>{if(d||h)return;m=k;let $=new Error(k.message);$.code=k.code,$.errorCode=k.code,$.statusCode=k.statusCode,$.errorPath=k.errorPath,$.details=k.details,k.stack&&($.stack=k.stack),$.isTimeout=k.code==="ERR_SCRIPT_EXECUTION_TIMEOUT",$.isTimeout&&!h&&!d&&this.taskTimeoutTotal++,x($)},onResult:k=>{if(!d){d=!0;try{this.onExecutionFinished?.({diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),logs:Array.isArray(k.diagnosticLogs?.logs)?k.diagnosticLogs.logs:Array.isArray(k.ctxChanges?.$share?.$logs)?k.ctxChanges.$share.$logs:[],logsTruncated:k.diagnosticLogs?.truncated===!0||k.ctxChanges?.$share?.$logsTruncated===!0,statusCode:k.error?.statusCode??k.ctxChanges?.$statusCode,error:m??(k.success||h?void 0:k.error)})}catch($){this.logger.error("Executor diagnostic callback failed",$)}if(k.taskCancelled===!0&&this.pool.unregisterTask(a,c),N(),h){this.taskErrorTotal++;try{k.ctxChanges&&y&&(y.ctxChanges=fe(k.ctxChanges)),f(y??b())}catch($){f(ve($))}return}if(k.success)try{let $={value:fe(k.value),valueAbsent:k.valueAbsent===!0,ctxChanges:fe(k.ctxChanges)};k.shortCircuit&&($.shortCircuit=!0),this.taskDoneTotal++,l($)}catch($){p.abort();let T=ve($);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}else try{let $=new Error(k.error?.message||"Handler execution failed");$.statusCode=k.error?.statusCode,$.code=k.error?.code,$.errorCode=k.error?.code,$.details=k.error?.details,k.error?.stack&&($.stack=k.error.stack),k.ctxChanges&&($.ctxChanges=fe(k.ctxChanges)),this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,$),f($)}catch($){p.abort();let T=ve($);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}}},onRelease:()=>{this.pool.unregisterTask(a,c)},onIoCall:k=>{if(d||k.type==="executionError")return;let $=p.signal;k.type==="repoCall"?this.hostIo.handleIoCall(()=>this.hostIo.execRepoCall(k,r),a.worker,k.callId,$):k.type==="transactionCall"?this.hostIo.handleIoCall(()=>this.hostIo.execTransactionCall(k,r,a.worker),a.worker,k.callId,$):k.type==="helpersCall"?this.hostIo.handleIoCall(()=>this.hostIo.execHelpersCall(k,r),a.worker,k.callId,$):k.type==="socketCall"?this.hostIo.handleIoCall(()=>this.hostIo.execSocketCall(k,r),a.worker,k.callId,$):k.type==="cacheCall"?this.hostIo.handleIoCall(()=>this.hostIo.execCacheCall(k,r),a.worker,k.callId,$):k.type==="storageCall"?this.hostIo.handleIoCall(()=>this.hostIo.execStorageCall(k,r,a.worker),a.worker,k.callId,$):k.type==="dispatchCall"?this.hostIo.handleIoCall(()=>this.hostIo.execDispatchCall(k,r),a.worker,k.callId,$):k.type==="resCall"&&this.hostIo.handleIoCall(()=>this.responseBridge.execResCall(k,r),a.worker,k.callId,$)}}),a.worker.postMessage({type:e,id:c,...t}).then(()=>{i?.aborted&&v()}).catch(k=>{d||(d=!0,p.abort(),j(),this.taskErrorTotal++,f(k))})})})()}cancelTask(e){this.taskCancellers.get(e)?.()}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,scriptId:e.scriptId,type:e.type}}createWorkerTaskDiagnostics(e,t,r,o){let i=r?.$api?.request?.correlationId,s=Array.isArray(t.codeBlocks)?t.codeBlocks.map(a=>({type:a?.type==="preHook"||a?.type==="postHook"||a?.type==="handler"?a.type:"run",...a?.scriptId!==void 0&&a?.scriptId!==null?{scriptId:String(a.scriptId)}:{}})):[{type:typeof t.sourceKind=="string"?t.sourceKind:"run",...t.scriptId==null?{}:{scriptId:String(t.scriptId)}}];return{...typeof i=="string"&&i?{correlationId:i}:{},timeoutMs:o,isolateMemoryLimitMb:Number(t.memoryLimitMb||0),isolatePoolSize:Number(t.isolatePoolSize||0),tasksPerIsolate:Number(t.tasksPerIsolate||0),scriptBlocks:s}}async run(e,t,r,o={}){let i=Xo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let l={code:e,scriptId:o.scriptId,sourceKind:o.sourceKind,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("execute",l,t,i)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,e,f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error",e,f.details||{})}return nr(t,u.ctxChanges||{}),u.valueAbsent?void 0:u.value}async runBatch(e,t,r,o={}){let i=Xo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let f={codeBlocks:e.map(d=>this.toWorkerCodeBlock(d)),pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("executeBatch",f,t,i,o.signal)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,"(batch execution)",f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error","(batch execution)",f.details||{})}return nr(t,u.ctxChanges||{}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((i,s)=>i-s),o=Math.min(r.length-1,Math.max(0,Math.ceil(t/100*r.length)-1));return r[o]}resetLatencyMetrics(){this.taskDurationsMs.length=0,this.queueWaitDurationsMs.length=0}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,r=t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,o=this.queueWaitDurationsMs,i=o.length===0?0:o.reduce((s,a)=>s+a,0)/o.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:r,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),avgQueueWaitMs:i,p95QueueWaitMs:this.percentile(o,95),p99QueueWaitMs:this.percentile(o,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var Ye=Je(require("typescript")),Kr={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 Zs(n){return $e.getLegacyField(n)}function ea(n){return $e.isScriptTable(n)}function ta(n){return $e.normalizeLanguage(n)}var Ur=class{getLegacyField(e){return Object.prototype.hasOwnProperty.call(Kr,e)?Kr[e]:void 0}isScriptTable(e){return Object.prototype.hasOwnProperty.call(Kr,e)}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let r=String(e),i=this.normalizeLanguage(t)==="javascript"?r:this.transpileTypeScript(r);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 r={...t},o=this.getLegacyField(e);return o&&(r.sourceCode===void 0||r.sourceCode===null||r.sourceCode==="")&&r[o]!==void 0&&(r.sourceCode=r[o]),r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage),o&&o in r&&delete r[o],r}normalizePatch(e,t,r){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode"),s=o?Object.prototype.hasOwnProperty.call(t,o):!1,a=i||s,c=Object.prototype.hasOwnProperty.call(t,"scriptLanguage"),u={...t};if(!a&&!c)return delete u.compiledCode,u;if(!a&&!r)throw new Error("Existing script data is required when changing scriptLanguage.");let l;i?l=t.sourceCode:s&&o?l=t[o]:(l=r?.sourceCode,l===void 0&&o&&r&&(l=r[o]));let f=c?t.scriptLanguage:r?.scriptLanguage;return a&&(u.sourceCode=l??null),u.scriptLanguage=this.normalizeLanguage(f),u.compiledCode=this.compileSource(l,u.scriptLanguage),o&&o in u&&delete u[o],u}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 r=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==e.compiledCode}}let t=Object.values(Kr).filter(r=>r!=="").map(r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:void 0).find(r=>typeof r=="string"&&r!=="");if(typeof t=="string"){let r=this.compileSource(t,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==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 r={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};r.sourceCode=r.sourceCode??i.sourceCode??i.code??null,r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage??i.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...r,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),r=e?.sourceCode??null,o=this.compileSource(r,t);return{sourceCode:r,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Ye.default.transpileModule(e,{compilerOptions:{target:Ye.default.ScriptTarget.ES2022,module:Ye.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ye.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),r=t.diagnostics?.find(o=>o.category===Ye.default.DiagnosticCategory.Error);if(r)throw new Error(Ye.default.flattenDiagnosticMessageText(r.messageText,`
|
|
3
|
+
`)){let[i,s]=o.split(" - ");if(!s)continue;let a=s.split(" ");if(a[0]!==(e?"cgroup2":"cgroup")||!e&&!a[2]?.split(",").includes(n))continue;let c=i.split(" "),u=Po(c[3]??""),l=Po(c[4]??"");if(!(!u.startsWith("/")||!l.startsWith("/")))for(let f of r){let d=/^\d+:([^:]*):(\/.*)$/.exec(f);if(!d||(e?d[1]!=="":!d[1].split(",").includes(n)))continue;let p=jr.posix.normalize(d[2]);if(u!=="/"&&p!==u&&!p.startsWith(`${u}/`))continue;let g=u==="/"?p.slice(1):p.slice(u.length+1),h=jr.posix.join(l,g);for(;(h===l||h.startsWith(`${l}/`))&&(t.add(h),h!==l);)h=jr.posix.dirname(h)}}return t}function Do(n){let e=n;for(let t of[!0,!1])for(let r of Bo("memory",t)){let o=Number(mt(`${r}/${t?"memory.max":"memory.limit_in_bytes"}`));Number.isFinite(o)&&o>0&&(e=Math.min(e,o))}return e}function Lo(n){let e=n;for(let t of[!0,!1])for(let r of Bo("cpu",t)){let[o,i]=t?mt(`${r}/cpu.max`).split(/\s+/).map(Number):[Number(mt(`${r}/cpu.cfs_quota_us`)),Number(mt(`${r}/cpu.cfs_period_us`))];o>0&&i>0&&Number.isFinite(o)&&Number.isFinite(i)&&(e=Math.min(e,Math.max(1,Math.ceil(o/i))))}return e}function or(){return Do(yt.totalmem())}function Vn(){return Lo(yt.availableParallelism?.()||yt.cpus()?.length||1)}var xs=.25,Hn=128,Cs=2,Rs=4,Fs=6,Is=8,vs=2048,Ms=40,As=128,Ns=32;function Os(n){let e=Math.trunc(Number(n));if(!(!Number.isFinite(e)||e<1))return Math.min(Hn,e)}function Ps(n){let e=Math.trunc(Number(n));return!Number.isFinite(e)||e<1?Fs:Math.min(Is,e)}function qo(n){return 2**Math.ceil(Math.log2(Math.max(1,n)))}function Gn(n){let e=Math.max(1,Math.trunc(n.logicalCpuCount)||1),t=Math.max(1,n.totalMemoryBytes/(1024*1024)),r=Math.min(As,Math.max(Ms,Math.round(t/Ns))),o=t*xs,i=Math.max(1,Math.floor(o/r)),s=Math.max(1,Math.min(e,2,i)),a=Math.max(1,Math.floor(o/(s*r))),c=Math.min(Hn,qo(e*Cs)),u=Math.min(Hn,qo(e*Rs)),l=Math.max(c,Math.min(u,a)),f=Os(n.maxLanesPerRunner)??l,d=t<vs?1:f,p=Math.max(1,Math.min(d,a)),g=Ps(n.tasksPerIsolate),h=p*g;return{maxConcurrentWorkers:s,isolateMemoryLimitMb:r,tasksPerWorkerCap:h,isolatePoolSize:p,tasksPerIsolate:g}}function Br(){return Gn({logicalCpuCount:Vn(),totalMemoryBytes:or()})}var Wo={400:"Bad request",401:"Authentication required",403:"Insufficient permissions",404:"Not found",409:"Conflict",422:"Validation failed",429:"Rate limit exceeded",500:"Internal server error",503:"Service unavailable"},Ve=class{static createException(e,t,r,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new Y(r||"Error",t||500,i);case"$throw.businessLogic":return new Wt(r||"Bad request",i);case"$throw.validation":return new Kt(r||"Validation failed",i);case"$throw.notFound":return new Ut(i?.resource||r||"Resource",i?.identifier);case"$throw.duplicate":return new Qt(i?.resource||r||"Resource",i?.field||"field",i?.value??"value");case"$throw.unauthorized":return new zt(r||"Unauthorized");case"$throw.forbidden":return new Jt(r||"Forbidden");case"$throw.tokenExpired":return new Ht;case"$throw.invalidToken":return new Vt;case"$throw.database":return new ht(r||"Database error",i);case"$throw.dbQuery":return new ht(r||"Query error",i);case"$throw.externalService":return new Gt(r||"Service",r||"Error",i);case"$throw.serviceUnavailable":return new Yt(r||"Service");case"$throw.rateLimit":return new Y(r||"Rate limit exceeded",429,i);case"$throw.scriptError":return new He(r||"Script error",o,i);case"$throw.scriptTimeout":return new Be(i?.timeout||5e3,o);case"$throw.schema":return new Xt(r||"Schema error",i);case"$throw.config":return new Zt(r||"Configuration error",i);case"$throw.fileUpload":return new er(r||"File upload error",i);case"$throw.fileNotFound":return new tr(r||"File not found");case"$throw.fileSizeExceeded":return new rr(i?.maxSize??"unknown",i?.actualSize??"unknown");case"$throw.400":return new Y(r||"Bad request",400,i);case"$throw.401":return new Y(r||"Authentication required",401,i);case"$throw.403":return new Y(r||"Insufficient permissions",403,i);case"$throw.404":return new Y(r||"Not found",404,i);case"$throw.409":return new Y(r||"Conflict",409,i);case"$throw.422":return new Y(r||"Validation failed",422,i);case"$throw.429":return new Y(r||"Rate limit exceeded",429,i);case"$throw.500":return new Y(r||"Internal server error",500,i);case"$throw.503":return new Y(r||"Service unavailable",503,i);default:return Number.isInteger(t)&&t>=400&&t<=599?new Y(r||Wo[t]||"Request failed",t,i):new He(r||"Unknown error",o,i)}return Number.isInteger(t)&&t>=400&&t<=599?new Y(r||Wo[t]||"Request failed",t,i):new He(r||"Unknown error",o,i)}};function Ko(n){return Math.min(2147483647,n+Math.ceil(n*.15))}function Yn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0})}function Ie(n,e,t){if(!Object.prototype.hasOwnProperty.call(n,e))return!1;let r=new Set(t);return Object.keys(n).every(o=>r.has(o))}var Uo=Object.freeze({Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,...typeof globalThis.Float16Array>"u"?{}:{Float16Array:globalThis.Float16Array},...typeof BigInt64Array>"u"?{}:{BigInt64Array},...typeof BigUint64Array>"u"?{}:{BigUint64Array}});function fe(n,e){if(!n||typeof n!="object")return n;let t=n;if(Ie(t,"__plainObject",["__plainObject"])){let o={};for(let[i,s]of Object.entries(t.__plainObject||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__nullPrototype",["__nullPrototype"])){let o=Object.create(null);for(let[i,s]of Object.entries(t.__nullPrototype||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__e",["__e"])&&t.__e==="u")return;if(e&&Ie(t,"__fnRef",["__fnRef"])&&typeof t.__fnRef=="string")return e(t.__fnRef);if(Ie(t,"__number",["__number"])){if(t.__number==="nan")return Number.NaN;if(t.__number==="infinity")return Number.POSITIVE_INFINITY;if(t.__number==="-infinity")return Number.NEGATIVE_INFINITY;if(t.__number==="-0")return-0;throw new TypeError(`Unsupported executor number: ${t.__number}`)}if(Ie(t,"__bigint",["__bigint"]))return BigInt(t.__bigint);if(Ie(t,"__map",["__map"]))return new Map((t.__map||[]).map(([o,i])=>[fe(o,e),fe(i,e)]));if(Ie(t,"__arrayBuffer",["__arrayBuffer"]))return Uint8Array.from(t.__arrayBuffer||[]).buffer;if(Ie(t,"__typedArray",["__typedArray","bytes","data"])){let o=Uint8Array.from(t.bytes||t.data||[]);if(t.__typedArray==="DataView")return new DataView(o.buffer);let i=Uo[String(t.__typedArray)];if(!Object.prototype.hasOwnProperty.call(Uo,t.__typedArray)||typeof i!="function")throw new TypeError(`Unsupported executor typed array: ${t.__typedArray}`);return new i(o.buffer)}if(Array.isArray(n))return n.map(o=>fe(o,e));let r={};for(let[o,i]of Object.entries(t))Yn(r,o,fe(i,e));return r}function ve(n){try{if(n instanceof Error)return n}catch{}let e="Unknown error";try{n===void 0?e="Operation rejected with undefined":n===null?e="Operation rejected with null":e=String(n)}catch{}return new Error(e)}function Qo(n){let e=new WeakSet;try{return JSON.stringify(n,(t,r)=>{if(typeof r=="bigint")return r.toString();if(!(typeof r=="function"||typeof r=="symbol")){if(r&&typeof r=="object"){if(e.has(r))return"[Circular]";e.add(r)}return r}})}catch{let t="Host capability call failed",r;try{t=String(n.message||t)}catch{}try{typeof n.code=="string"&&(r=n.code)}catch{}return JSON.stringify({__userThrow:!0,message:t,code:r})}}function ir(n){if(n===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:n},(e,t)=>typeof t=="bigint"?{__bigint:t.toString()}:t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var zo=require("async_hooks"),Dr=new zo.AsyncLocalStorage;function Xn(){return Dr.getStore()}function Zn(n,e){return Dr.run(n,e)}var Lr=class{constructor(e,t){this.taskAbortSignals=e;this.taskDeadlines=t;this.runtimeCallbackCounter=0}postAbortedCallError(e,t){e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})}).catch(()=>{})}async handleIoCall(e,t,r,o){if(o?.aborted){this.postAbortedCallError(t,r);return}try{let i=await(o?Dr.run(o,e):e());if(o?.aborted){this.postAbortedCallError(t,r);return}await t.postMessage({type:"callResult",callId:r,result:ir(i)})}catch(i){if(o?.aborted){this.postAbortedCallError(t,r);return}let s=ve(i),a={__userThrow:!0,message:s.message,statusCode:s.statusCode,code:s.errorCode??s.code,errorPath:s.errorPath,details:s.details,messages:s.messages};await t.postMessage({type:"callError",callId:r,error:Qo(a)}).catch(()=>{})}}parseExecutorArgs(e,t,r){let o=JSON.parse(e||"[]");return fe(o,t&&r?s=>(...a)=>this.invokeRuntimeCallback(t,r,s,a):void 0)}async execRepoCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=e.access==="secure"?ie(t?.$repos,"secure",!0):t?.$repos,i=ie(o,String(e.table),!0),s=ie(i,String(e.method));if(!i||typeof s!="function"){let a=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${a}${e.table}.${e.method}`)}return s.apply(i,r)}async execTransactionCall(e,t,r){let i=this.parseExecutorArgs(e.argsJson,r,e.id)[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 r=this.parseExecutorArgs(e.argsJson),o=String(e.name).split("."),i=t?.$helpers,s=i;for(let a of o)i=s,s=ie(s,a);if(typeof s!="function")throw new Error(`Helper not found: ${e.name}`);return s.apply(i,r)}async execSocketCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$socket,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i.apply(o,r)}async execCacheCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$cache,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Cache not found: ${e.method}`);return i.apply(o,r)}async execStorageCall(e,t,r){let o=this.parseStorageArgs(e.argsJson,r,e.id),i=t?.$storage,s=ie(i,String(e.method));if(typeof s!="function")throw new Error(`Storage method not found: ${e.method}`);return s.apply(i,o)}parseStorageArgs(e,t,r){return this.parseExecutorArgs(e,t,r)}invokeRuntimeCallback(e,t,r,o){let i=`rtcb_${++this.runtimeCallbackCounter}`,s=this.taskAbortSignals.get(t),a=this.taskDeadlines.get(t)??Date.now()+3e4,c=Math.max(1,a-Date.now())+500;return new Promise((u,l)=>{let f=!1,d=w=>{f||(f=!0,m(),w())},p=setTimeout(()=>{d(()=>l(new Error(`Runtime callback timed out: ${r}`)))},c),g=()=>{d(()=>l(new Error("Runtime callback was cancelled")))},h=()=>{d(()=>l(new Error("Runtime callback worker exited")))},y=w=>{if(!(w?.type!=="runtimeCallbackResult"||w.callId!==i)){if(w.error){let _=new Error(String(w.error));try{let $=JSON.parse(String(w.error));$?.__userThrow&&(_.message=String($.message??_.message),_.statusCode=$.statusCode,_.code=$.code??(Number.isInteger($.statusCode)?`HTTP_${$.statusCode}`:void 0),_.errorCode=_.code,_.errorPath=$.errorPath,_.details=$.details,_.messages=$.messages)}catch{}d(()=>l(_));return}d(()=>u(w.value))}},m=()=>{clearTimeout(p),e.off("message",y),e.off("exit",h),s?.removeEventListener("abort",g)};if(e.on("message",y),e.on("exit",h),s?.addEventListener("abort",g,{once:!0}),s?.aborted){g();return}try{e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:r,argsJson:JSON.stringify(o)}).catch(w=>d(()=>l(w)))}catch(w){d(()=>l(w))}})}async execDispatchCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=ie(t,"$trigger");if(typeof o!="function")throw new Error("$trigger is not available");return o.apply(t,r)}};var Ho=require("stream");var eo=32*1024*1024,Jo=Math.ceil(eo/3)*4,qr=class{constructor(e,t){this.cancelTask=e;this.parseExecutorArgs=t;this.responseStreams=new Map}async execResCall(e,t){if(e.method==="json"){let s=ie(t?.$res,"__enfyraJson");if(typeof s!="function")throw new Error("Native JSON response is not available");return await s.call(t.$res,String(e.jsonText),e.options||{})}if(e.method==="bytes"){let s=ie(t?.$res,"__enfyraBytes");if(typeof s!="function")throw new Error("Native binary response is not available");let a=String(e.bytes||"");if(a.length>Jo)throw new Error("Native binary response exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Native binary response exceeded 32 MiB");return await s.call(t.$res,c,e.options||{})}if(e.method==="streamStart"){if(this.responseStreams.has(e.id))throw new Error(`Response stream already exists: ${e.id}`);let a=JSON.parse(e.argsJson||"[]")[1]||{},c=ie(t?.$res,"stream");if(typeof c!="function")throw new Error("Response method not found: stream");let u=new Ho.PassThrough;u.on("error",()=>{});let l={stream:u};this.responseStreams.set(e.id,l);let f=t?.$res;if(f&&typeof f.once=="function"){let d=()=>{f.writableEnded!==!0&&this.cancelTask(e.id)};f.once("close",d),l.closeCleanup=()=>{typeof f.off=="function"?f.off("close",d):typeof f.removeListener=="function"&&f.removeListener("close",d)}}try{let d=c.call(t.$res,u,a);return d&&typeof d.then=="function"&&(l.completion=Promise.resolve(d).then(()=>{},p=>{let g=ve(p);throw this.responseStreams.get(e.id)===l&&(this.cleanupResponseStream(e.id,g),this.cancelTask(e.id)),g}),l.completion.catch(()=>{})),!0}catch(d){let p=ve(d);throw this.cleanupResponseStream(e.id,p),p}}if(e.method==="streamChunk"){let s=this.responseStreams.get(e.id);if(!s)throw new Error(`Response stream not found: ${e.id}`);let a=String(e.chunk||"");if(a.length>Jo)throw new Error("Response stream chunk exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Response stream chunk exceeded 32 MiB");if(s.stream.destroyed)throw new Error("Response stream closed before drain");return s.stream.write(c)||await new Promise((u,l)=>{let f=()=>{g(),u()},d=h=>{g(),l(h)},p=()=>{g(),l(new Error("Response stream closed before drain"))},g=()=>{s.stream.off("drain",f),s.stream.off("error",d),s.stream.off("close",p)};s.stream.once("drain",f),s.stream.once("error",d),s.stream.once("close",p)}),!0}if(e.method==="streamEnd"){let s=this.responseStreams.get(e.id);if(s){s.stream.end();try{await s.completion}finally{this.responseStreams.get(e.id)===s&&(s.closeCleanup?.(),this.responseStreams.delete(e.id))}}return!0}if(e.method==="streamError"){let s=this.responseStreams.get(e.id);if(s){s.closeCleanup?.();let a=e.error?.message||"Response stream failed";s.stream.destroy(new Error(a)),this.responseStreams.delete(e.id)}return!0}let r=this.parseExecutorArgs(e.argsJson),o=t?.$res,i=ie(o,String(e.method));if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(o,r)}cleanupResponseStream(e,t){let r=this.responseStreams.get(e);r&&(this.responseStreams.delete(e),r.closeCleanup?.(),t?r.stream.destroy(t):r.stream.end())}};var Vo=require("child_process"),Go=require("string_decoder"),Bs=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function Ds(){let n={};for(let e of Bs){let t=process.env[e];t!==void 0&&(n[e]=t)}return n}var Wr=class{constructor(e){this.terminated=!1;this.stderrTail="";this.stderrDecoder=new Go.StringDecoder("utf8");this.child=(0,Vo.fork)(e,[],{stdio:["ignore","ignore","pipe","ipc"],env:Ds(),execArgv:[],serialization:"advanced"}),this.child.on("error",t=>{this.stderrTail=(this.stderrTail+t.message).slice(-8192)}),this.child.stderr?.on("data",t=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.write(t)).slice(-8192)}),this.child.stderr?.on("end",()=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.end()).slice(-8192)})}get stderr(){return this.stderrTail}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){return this.child.connected?new Promise((t,r)=>{try{this.child.send(e,o=>{o?r(o):t()})}catch(o){r(o)}}):Promise.reject(new Error("Executor runner IPC is closed"))}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var Ge=class{constructor(e,t,r,o,i,s,a,c=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=r,this.tasksCap=o,this.drainTimeoutMs=c;for(let u=0;u<e;u++)this.spawnEntry()}getEntries(){return this.entries}clearDrainTimeout(e){e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0)}reportObserverError(e,t){let r=t instanceof Error?t.message:String(t);console.error(`[executor-pool] ${e}: ${r}`)}spawnEntry(){let e=new Wr(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",r=>{let o=t.tasks.get(r.id);if(o)if(r.type==="taskReleased")o.onRelease?.();else if(r.type==="taskLane")o.onLane?.(r.laneKey);else if(r.type==="taskFailure")o.onFailure?.(r.error);else if(r.type==="result"||r.type==="taskCancelled"){typeof r.heapRatio=="number"&&(t.lastHeapRatio=r.heapRatio),typeof r.runnerRssBytes=="number"&&(t.lastRssBytes=r.runnerRssBytes),r.contextStats&&(t.contextStats=r.contextStats);let i=r;r.type==="taskCancelled"&&(i={type:"result",id:r.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}});try{o.onResult(i)}catch(s){this.reportObserverError("task result callback failed",s)}!t.draining&&typeof r.heapRatio=="number"&&r.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(r.heapRatio*100)}%`)}else o.onIoCall(r)}),e.on("exit",(r,o)=>{let i=t.draining,s=this.destroying;t.draining=!0;let a={entryId:t.id,pid:t.worker.pid,exitCode:r,exitSignal:o??null,lastError:t.lastError||t.worker.stderr||void 0,terminationReason:t.terminationReason,lastHeapRatio:t.lastHeapRatio,lastRssBytes:t.lastRssBytes,activeTasks:[...t.tasks.values()].map(l=>l.diagnostics)};this.clearDrainTimeout(t);let c="Worker crashed";s?c="Worker terminated":t.lastError&&(c=`Worker crashed: ${t.lastError}`);for(let[,l]of t.tasks){l.abortController.abort();try{l.onResult({type:"result",success:!1,error:{message:c,code:s?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:s?void 0:{outcome:"unknown_outcome",retryable:!1}}})}catch(f){this.reportObserverError("worker-exit task callback failed",f)}}t.tasks.clear();let u=this.entries.indexOf(t);if(u!==-1&&this.entries.splice(u,1),(!i||t.replaceOnExit)&&!s){try{this.onCrash?.(a)}catch(f){this.reportObserverError("worker crash observer failed",f)}this.entries.filter(f=>!f.draining).length<this.max&&this.spawnEntry()}this.drainWaiting()}),e.on("error",r=>{t.lastError=r.message}),this.entries.push(t),t}rotateEntry(e,t){if(this.destroying||e.draining)return;e.draining=!0;let r=Date.now()-e.spawnedAt;try{this.onRotate?.({reason:t,ageMs:r})}catch(o){this.reportObserverError("worker rotation observer failed",o)}if(this.spawnEntry(),this.drainWaiting(),e.tasks.size===0&&e.reservations===0){this.clearDrainTimeout(e),e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,this.abortEntryTasks(e),e.worker.terminate()},this.drainTimeoutMs)}abortEntryTasks(e){for(let t of e.tasks.values())t.abortController.abort()}isMemoryAvailable(){let e=Date.now();if(e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs){let t=this.entries.reduce((r,o)=>r+(o.lastRssBytes??0),0);this.cachedMemoryOk=(process.memoryUsage().rss+t)/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e}return this.cachedMemoryOk}hasActiveWork(){return this.entries.some(e=>e.tasks.size>0||e.reservations>0)}canDispatch(){return!this.hasActiveWork()||this.isMemoryAvailable()}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let r=t.tasks.size+t.reservations;r<this.tasksCap&&(!e||r<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(e){if(this.destroying)return Promise.reject(new Error("Executor worker pool is shutting down"));if(e?.aborted)return Promise.reject(new Error("Execution aborted before dispatch"));let t=this.findLeastBusy();return t&&this.canDispatch()?(t.reservations++,Promise.resolve(t)):new Promise((r,o)=>{let i={resolve:r,reject:o,signal:e};e&&(i.onAbort=()=>{let s=this.waiting.indexOf(i);s!==-1&&this.waiting.splice(s,1),o(new Error("Execution aborted before dispatch"))},e.addEventListener("abort",i.onAbort,{once:!0})),this.waiting.push(i)})}registerTask(e,t,r){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,r)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(!e||!this.canDispatch())break;let t=this.waiting.shift();if(t.signal?.aborted){t.reject(new Error("Execution aborted before dispatch"));continue}t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),e.reservations++,t.resolve(e)}}terminateEntry(e,t="host_requested"){e.draining&&e.terminationReason||(e.draining=!0,e.replaceOnExit=!0,e.terminationReason=t,this.clearDrainTimeout(e),this.abortEntryTasks(e),e.worker.terminate())}resize(e){this.max=Math.max(1,e);let t=this.entries.filter(i=>!i.draining);for(;t.length<this.max;)t.push(this.spawnEntry());let r=t.length-this.max;if(r<=0){this.drainWaiting();return}let o=t.sort((i,s)=>i.tasks.size+i.reservations-(s.tasks.size+s.reservations)).slice(0,r);for(let i of o)i.draining=!0;this.drainWaiting();for(let i of o)i.tasks.size===0&&i.reservations===0?(this.clearDrainTimeout(i),i.worker.terminate()):(this.clearDrainTimeout(i),i.drainTimeout=setTimeout(()=>{i.drainTimeout=void 0,this.abortEntryTasks(i),i.worker.terminate()},this.drainTimeoutMs))}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,lastRssBytes:e.lastRssBytes??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;let e=new Error("Executor worker pool was destroyed");for(let t of this.waiting.splice(0))t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),t.reject(e);for(let t of this.entries)t.draining=!0,t.terminationReason="pool_destroyed",this.clearDrainTimeout(t),this.abortEntryTasks(t),t.worker.terminate();this.entries.length=0}};var Gs=Zo.join(__dirname,"execution/worker.js"),Ys=3e4,Xs=2147483647;function Xo(n){let e=Number(n);return Number.isFinite(e)?Math.max(1,Math.min(Xs,Math.trunc(e))):Ys}var bt=class n{constructor(e){this.logger=new Pr(n.name);this.effectiveMemory=or();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.taskCancellers=new Map;this.taskAbortSignals=new Map;this.taskDeadlines=new Map;this.taskDurationsMs=[];this.queueWaitDurationsMs=[];this.hostIo=new Lr(this.taskAbortSignals,this.taskDeadlines);this.responseBridge=new qr(e=>this.cancelTask(e),e=>this.hostIo.parseExecutorArgs(e));this.packageCacheService=e.packageCacheService,this.onExecutionFinished=e.onExecutionFinished,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??Br(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Ge(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Gs,t=>{this.crashesTotal++;let r={event:"executor_worker_crashed",occurredAt:new Date().toISOString(),...t};this.logger.warn(r);try{e.onExecutorWorkerCrash?.(r)}catch(o){this.logger.warn({event:"executor_worker_crash_report_failed",error:o instanceof Error?o.message:String(o)})}},({reason:t,ageMs:r})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(r/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerIsolate} tasks/isolate, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let e=this.pool.getEntries().reduce((g,h)=>g+(h.lastRssBytes??0),0),r=(process.memoryUsage().rss+e)/this.effectiveMemory,o=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),s=Number(o-this.prevCpuTime)/1e3,a=s>0?(i.user+i.system)/s:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=o;let c=this.pool.getMax(),u=this.pool.getWaitingCount(),l=r>.85||a>.7,f=r<.7&&a<.5,d=u>0,p=c;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,c-1))):f&&d?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,c+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==c&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${c} -> ${p} (rss=${Math.round(r*100)}% cpu=${Math.round(a*100)}% queue=${u})`))}spawnAndExecute(e,t,r,o,i){return(async()=>{let s=Date.now(),a;try{a=await this.pool.dispatch(i)}catch(l){if(i?.aborted){let f=new Error("Execution aborted before dispatch");throw f.code="ERR_EXECUTION_ABORTED",f.isAbort=!0,f}throw l}if(this.recordQueueWait(Date.now()-s),i?.aborted){this.pool.releaseReservation(a);let l=new Error("Execution aborted after client disconnect");return l.code="ERR_EXECUTION_ABORTED",l.isAbort=!0,Promise.reject(l)}let c=`t_${++this.taskCounter}`,u=Date.now();return new Promise((l,f)=>{let d=!1,p=new AbortController;this.taskAbortSignals.set(c,p.signal);let g=Ko(o);this.taskDeadlines.set(c,u+g);let h=!1,y,m,w=()=>{let E=new Error("Execution aborted after client disconnect");return E.code="ERR_EXECUTION_ABORTED",E.isAbort=!0,E},_=()=>{let E=new Error(`Script execution timed out after ${o}ms`);return E.code="ERR_SCRIPT_EXECUTION_TIMEOUT",E.isTimeout=!0,E},$,k,C=!1,x=E=>{if(!(d||h)){h=!0,y=E,p.abort(),this.responseBridge.cleanupResponseStream(c,E);try{a.worker.postMessage({type:"cancelTask",id:c}).catch(()=>{})}catch{}$=setTimeout(()=>{d||(d=!0,k&&clearTimeout(k),M(),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),this.recordTaskDuration(Date.now()-u),this.pool.terminateEntry(a,E.isTimeout?"timeout_cancel_grace":E.isAbort?"client_abort_cancel_grace":"failure_cancel_grace"),this.pool.unregisterTask(a,c),this.taskErrorTotal++,E.details={...E.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},f(E))},1e4),$.unref?.()}},v=()=>x(w());this.taskCancellers.set(c,v);let R=()=>v(),M=()=>{i?.removeEventListener("abort",R)};i&&(i.addEventListener("abort",R,{once:!0}),i.aborted&&v());let N=()=>{k&&clearTimeout(k),$&&clearTimeout($),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),M(),this.responseBridge.cleanupResponseStream(c),this.recordTaskDuration(Date.now()-u)},j=()=>{N(),this.pool.unregisterTask(a,c)},O=25,P=()=>{d||(this.taskTimeoutTotal++,x(_()))},G=u+g+[...a.tasks.keys()].reduce((E,S)=>{if(S===c)return E;let T=this.taskDeadlines.get(S);return E+(T===void 0?0:Math.max(0,T-u))},0),re=()=>{if(!(d||h)){if(!C&&Date.now()>=G){this.taskTimeoutTotal++,x(_());return}if(!C){k=setTimeout(re,O),k.unref?.();return}this.taskDeadlines.set(c,Date.now()+g),k=setTimeout(P,g),k.unref?.()}};k=setTimeout(re,O),k.unref?.(),this.pool.registerTask(a,c,{abortController:p,onLane:()=>{d||h||C||(C=!0,k&&clearTimeout(k),re())},diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),onFailure:E=>{if(d||h)return;m=E;let S=new Error(E.message);S.code=E.code,S.errorCode=E.code,S.statusCode=E.statusCode,S.errorPath=E.errorPath,S.details=E.details,E.stack&&(S.stack=E.stack),S.isTimeout=E.code==="ERR_SCRIPT_EXECUTION_TIMEOUT",S.isTimeout&&!h&&!d&&this.taskTimeoutTotal++,x(S)},onResult:E=>{if(!d){d=!0;try{this.onExecutionFinished?.({diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),logs:Array.isArray(E.diagnosticLogs?.logs)?E.diagnosticLogs.logs:Array.isArray(E.ctxChanges?.$share?.$logs)?E.ctxChanges.$share.$logs:[],logsTruncated:E.diagnosticLogs?.truncated===!0||E.ctxChanges?.$share?.$logsTruncated===!0,statusCode:E.error?.statusCode??E.ctxChanges?.$statusCode,error:m??(E.success||h?void 0:E.error)})}catch(S){this.logger.error("Executor diagnostic callback failed",S)}if(E.taskCancelled===!0&&this.pool.unregisterTask(a,c),N(),h){this.taskErrorTotal++;try{E.ctxChanges&&y&&(y.ctxChanges=fe(E.ctxChanges)),f(y??w())}catch(S){f(ve(S))}return}if(E.success)try{let S={value:fe(E.value),valueAbsent:E.valueAbsent===!0,ctxChanges:fe(E.ctxChanges)};E.shortCircuit&&(S.shortCircuit=!0),this.taskDoneTotal++,l(S)}catch(S){p.abort();let T=ve(S);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}else try{let S=new Error(E.error?.message||"Handler execution failed");S.statusCode=E.error?.statusCode,S.code=E.error?.code,S.errorCode=E.error?.code,S.details=E.error?.details,E.error?.stack&&(S.stack=E.error.stack),E.ctxChanges&&(S.ctxChanges=fe(E.ctxChanges)),this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,S),f(S)}catch(S){p.abort();let T=ve(S);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}}},onRelease:()=>{this.pool.unregisterTask(a,c)},onIoCall:E=>{if(d||E.type==="executionError")return;let S=p.signal;E.type==="repoCall"?this.hostIo.handleIoCall(()=>this.hostIo.execRepoCall(E,r),a.worker,E.callId,S):E.type==="transactionCall"?this.hostIo.handleIoCall(()=>this.hostIo.execTransactionCall(E,r,a.worker),a.worker,E.callId,S):E.type==="helpersCall"?this.hostIo.handleIoCall(()=>this.hostIo.execHelpersCall(E,r),a.worker,E.callId,S):E.type==="socketCall"?this.hostIo.handleIoCall(()=>this.hostIo.execSocketCall(E,r),a.worker,E.callId,S):E.type==="cacheCall"?this.hostIo.handleIoCall(()=>this.hostIo.execCacheCall(E,r),a.worker,E.callId,S):E.type==="storageCall"?this.hostIo.handleIoCall(()=>this.hostIo.execStorageCall(E,r,a.worker),a.worker,E.callId,S):E.type==="dispatchCall"?this.hostIo.handleIoCall(()=>this.hostIo.execDispatchCall(E,r),a.worker,E.callId,S):E.type==="resCall"&&this.hostIo.handleIoCall(()=>this.responseBridge.execResCall(E,r),a.worker,E.callId,S)}}),a.worker.postMessage({type:e,id:c,...t}).then(()=>{i?.aborted&&v()}).catch(E=>{d||(d=!0,p.abort(),j(),this.taskErrorTotal++,f(E))})})})()}cancelTask(e){this.taskCancellers.get(e)?.()}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,scriptId:e.scriptId,type:e.type}}createWorkerTaskDiagnostics(e,t,r,o){let i=r?.$api?.request?.correlationId,s=Array.isArray(t.codeBlocks)?t.codeBlocks.map(a=>({type:a?.type==="preHook"||a?.type==="postHook"||a?.type==="handler"?a.type:"run",...a?.scriptId!==void 0&&a?.scriptId!==null?{scriptId:String(a.scriptId)}:{}})):[{type:typeof t.sourceKind=="string"?t.sourceKind:"run",...t.scriptId==null?{}:{scriptId:String(t.scriptId)}}];return{...typeof i=="string"&&i?{correlationId:i}:{},timeoutMs:o,isolateMemoryLimitMb:Number(t.memoryLimitMb||0),isolatePoolSize:Number(t.isolatePoolSize||0),tasksPerIsolate:Number(t.tasksPerIsolate||0),scriptBlocks:s}}async run(e,t,r,o={}){let i=Xo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let l={code:e,scriptId:o.scriptId,sourceKind:o.sourceKind,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("execute",l,t,i)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,e,f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error",e,f.details||{})}return nr(t,u.ctxChanges||{}),u.valueAbsent?void 0:u.value}async runBatch(e,t,r,o={}){let i=Xo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let f={codeBlocks:e.map(d=>this.toWorkerCodeBlock(d)),pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("executeBatch",f,t,i,o.signal)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,"(batch execution)",f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error","(batch execution)",f.details||{})}return nr(t,u.ctxChanges||{}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((i,s)=>i-s),o=Math.min(r.length-1,Math.max(0,Math.ceil(t/100*r.length)-1));return r[o]}resetLatencyMetrics(){this.taskDurationsMs.length=0,this.queueWaitDurationsMs.length=0}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,r=t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,o=this.queueWaitDurationsMs,i=o.length===0?0:o.reduce((s,a)=>s+a,0)/o.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:r,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),avgQueueWaitMs:i,p95QueueWaitMs:this.percentile(o,95),p99QueueWaitMs:this.percentile(o,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var Ye=Je(require("typescript")),Kr={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 Zs(n){return $e.getLegacyField(n)}function ea(n){return $e.isScriptTable(n)}function ta(n){return $e.normalizeLanguage(n)}var Ur=class{getLegacyField(e){return Object.prototype.hasOwnProperty.call(Kr,e)?Kr[e]:void 0}isScriptTable(e){return Object.prototype.hasOwnProperty.call(Kr,e)}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let r=String(e),i=this.normalizeLanguage(t)==="javascript"?r:this.transpileTypeScript(r);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 r={...t},o=this.getLegacyField(e);return o&&(r.sourceCode===void 0||r.sourceCode===null||r.sourceCode==="")&&r[o]!==void 0&&(r.sourceCode=r[o]),r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage),o&&o in r&&delete r[o],r}normalizePatch(e,t,r){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode"),s=o?Object.prototype.hasOwnProperty.call(t,o):!1,a=i||s,c=Object.prototype.hasOwnProperty.call(t,"scriptLanguage"),u={...t};if(!a&&!c)return delete u.compiledCode,u;if(!a&&!r)throw new Error("Existing script data is required when changing scriptLanguage.");let l;i?l=t.sourceCode:s&&o?l=t[o]:(l=r?.sourceCode,l===void 0&&o&&r&&(l=r[o]));let f=c?t.scriptLanguage:r?.scriptLanguage;return a&&(u.sourceCode=l??null),u.scriptLanguage=this.normalizeLanguage(f),u.compiledCode=this.compileSource(l,u.scriptLanguage),o&&o in u&&delete u[o],u}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 r=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==e.compiledCode}}let t=Object.values(Kr).filter(r=>r!=="").map(r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:void 0).find(r=>typeof r=="string"&&r!=="");if(typeof t=="string"){let r=this.compileSource(t,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==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 r={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};r.sourceCode=r.sourceCode??i.sourceCode??i.code??null,r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage??i.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...r,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),r=e?.sourceCode??null,o=this.compileSource(r,t);return{sourceCode:r,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Ye.default.transpileModule(e,{compilerOptions:{target:Ye.default.ScriptTarget.ES2022,module:Ye.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ye.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),r=t.diagnostics?.find(o=>o.category===Ye.default.DiagnosticCategory.Error);if(r)throw new Error(Ye.default.flattenDiagnosticMessageText(r.messageText,`
|
|
4
4
|
`));return t.outputText.trimEnd()}assertExecutableJavaScript(e){if(!e)return;let t=Object.getPrototypeOf(async function(){}).constructor;new t(`"use strict";
|
|
5
|
-
${e}`)}},$e=new Ur;function ra(n,e){return $e.compileSource(n,e)}function na(n){return $e.isExecutableJavaScript(n)}function oa(n,e){return $e.normalizeRecord(n,e)}function ia(n,e,t){return $e.normalizePatch(n,e,t)}function sa(n){return $e.getExecutableScript(n)}function aa(n){return $e.resolveExecutableScript(n)}function la(n){return $e.normalizeFlowStepScriptConfig(n)}sr();cr();re();var li=64;function ci(n){let e=(n?.columns??[]).filter(t=>t.isPrimary===!0).map(t=>t.name);return e.length>0?e:n?.columns?.some(t=>t.name==="id")?["id"]:n?.columns?.some(t=>t.name==="_id")?["_id"]:[]}function ui(n,e){if(n!=="id")return n;if(e.columns?.some(r=>r.name==="id"))return"id";let t=ci(e);return t.length===1?t[0]:n}function Hr(n,e){let t=n.targetTableName||n.targetTable,r=e?.tables?.get(t);if(!r)throw new w(`Field relation '${n.propertyName}' has no target table metadata`);let o=ci(r);if(o.length===0)throw new w(`Field relation '${n.propertyName}' target '${t}' has no primary key metadata`);return o}function Vr(n,e,t,r){let o={rootTable:e,nodes:[]};if(n===void 0)return o;if(!Array.isArray(n))throw new w("Query fields must be an array");if(n.some(a=>typeof a!="string"))throw new w("Query field entries must be strings");if(n.length===0)return o;let i=t?.tables?.get(e);if(!i)throw new w(`Field parsing requires metadata for table '${e}'`);let s=r.createCheckpoint();try{let a=new Map,c=[],u=new Set(n.map(l=>ui(l,i)));for(let l of u)if(l==="*")c.push("*");else if(l.includes(".")){let f=l.indexOf("."),d=l.substring(0,f),p=l.substring(f+1);if(!d||!p)throw new w(`Invalid field path '${l}'`);if(!i.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(p)}else if(i.relations?.some(d=>d.propertyName===l)){a.has(l)||a.set(l,[]);let d=i.relations.find(p=>p.propertyName===l);for(let p of Hr(d,t))a.get(l).includes(p)||a.get(l).push(p)}else{if(!i.columns?.some(p=>p.name===l))continue;c.push(l)}if(c.includes("*")){o.nodes.push({kind:"wildcard"});for(let l of i.relations||[])a.has(l.propertyName)||a.set(l.propertyName,Hr(l,t))}else for(let l of c)o.nodes.push({kind:"scalar",name:l});for(let[l,f]of a.entries()){let d=i.relations?.find(y=>y.propertyName===l);if(!d)continue;let p=d.targetTableName||d.targetTable;if(typeof p!="string"||!p||!t?.tables?.has(p))throw new w(`Field relation '${l}' on '${e}' has no resolvable target table metadata`);let g=fi(f,p,t,1);if(g.length===0)continue;let h={kind:"relation",propertyName:l,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:p,children:g};if(d.type==="many-to-one"||d.type==="one-to-one"){let y=r.registerWithParent(e,l,t,"left",null,"data");h.joinId=y}o.nodes.push(h)}return o}catch(a){throw r.restoreCheckpoint(s),a}}function fi(n,e,t,r){if(r>li)throw new w(`Field nesting depth exceeds maximum of ${li}`);let o=t?.tables?.get(e);if(!o)throw new w(`Field parsing requires metadata for table '${e}'`);let i=new Map,s=[],a=new Set(n.map(u=>ui(u,o)));for(let u of a)if(u==="*")s.push("*");else if(u.includes(".")){let l=u.indexOf("."),f=u.substring(0,l),d=u.substring(l+1);if(!f||!d)throw new w(`Invalid field path '${u}'`);if(!o.relations?.some(g=>g.propertyName===f))continue;i.has(f)||i.set(f,[]),i.get(f).push(d)}else if(o.relations?.some(f=>f.propertyName===u)){i.has(u)||i.set(u,[]);let f=o.relations.find(d=>d.propertyName===u);for(let d of Hr(f,t))i.get(u).includes(d)||i.get(u).push(d)}else{if(!o.columns?.some(d=>d.name===u))continue;s.push(u)}let c=[];if(s.includes("*")){c.push({kind:"wildcard"});for(let u of o.relations||[])i.has(u.propertyName)||i.set(u.propertyName,Hr(u,t))}else for(let u of s)c.push({kind:"scalar",name:u});for(let[u,l]of i.entries()){let f=o.relations?.find(g=>g.propertyName===u);if(!f)continue;let d=f.targetTableName||f.targetTable;if(typeof d!="string"||!d||!t?.tables?.has(d))throw new w(`Field relation '${u}' on '${e}' has no resolvable target table metadata`);let p=fi(l,d,t,r+1);p.length!==0&&c.push({kind:"relation",propertyName:u,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:d,children:p})}return c}re();function di(n,e,t){return n.filter(r=>{let o=r.split(".");if(o.some(s=>!s))throw new w(`Invalid field path '${r}'`);let i=e;for(let s=0;s<o.length;s++){let a=t?.tables?.get(i);if(!a)throw new w(`Field parsing requires metadata for table '${i}'`);let c=o[s],u=s===o.length-1;if(u&&c==="*"||u&&a.columns?.some(f=>f.name===c||c==="id"&&f.name==="_id"))return!0;let l=a.relations?.find(f=>f.propertyName===c);if(!l)return!1;if(u)return!0;i=l.targetTableName||l.targetTable}return!1})}re();re();Le();var ma=new Set(["_and","_or","_not"]);function lo(n,e){return n?.tables?.get(e)??null}function io(n,e,t){return lo(n,e)?.columns?.find(r=>r.name===t)}function so(n,e,t){return lo(n,e)?.relations?.find(r=>r.propertyName===t)}function ya(n){let e=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],r=e[2].trim();if(t==="count")return{functionName:t,relationName:r};let o=r.indexOf(".");return o<=0||o!==r.lastIndexOf(".")?null:{functionName:t,relationName:r.slice(0,o).trim(),fieldName:r.slice(o+1).trim()}}function ao(n,e,t,r){if(!lo(n,e))throw new w(`${r==="filter"?"Filter":"Sort"} validation requires metadata for table '${e}'`);let i=io(n,e,t)??(t==="id"?io(n,e,"_id"):void 0);if(!i)throw new w(`${r==="filter"?"Filter":"Sort"} field '${t}' does not exist on '${e}'`);if(i.isEncrypted===!0)throw new w(`Encrypted field '${t}' on '${e}' cannot be used for ${r}.`)}function Gr(n,e,t,r,o){if(!(!n||typeof n!="object")){if(r>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(o.has(n))throw new w("Filter contains a circular reference");o.add(n);try{if(Array.isArray(n)){for(let i of n)Gr(i,e,t,r+1,o);return}for(let[i,s]of Object.entries(n)){if(ma.has(i)){Gr(s,e,t,r+1,o);continue}let a=so(t,e,i),c=a?null:io(t,e,i);if(c?.isEncrypted===!0)throw new w(`Encrypted field '${i}' on '${e}' cannot be used for filter.`);if(!(i.startsWith("_")&&!c&&!a)){if(a){let u=a.targetTableName||a.targetTable;if(typeof u!="string"||!u)throw new w(`Filter relation '${i}' on '${e}' has no target table metadata`);Gr(s,u,t,r+1,o);continue}ao(t,e,i,"filter")}}}finally{o.delete(n)}}}function Yr(n,e,t){Gr(n,e,t,0,new Set)}function _t(n,e,t){if(n===void 0)return;if(typeof n!="string"&&!Array.isArray(n))throw new w("Sort must be a string or string array");let r=Array.isArray(n)?n:n.split(",");if(r.some(i=>typeof i!="string"))throw new w("Sort entries must be strings");let o=r.map(i=>i.trim()).filter(Boolean);for(let i of o){let s=i.startsWith("-")?i.slice(1):i;if(!s)continue;let a=ya(s);if(a){let l=so(t,e,a.relationName);if(!l)throw new w(`Sort relation '${a.relationName}' does not exist on '${e}'`);if(a.functionName==="count")continue;let f=l.targetTableName||l.targetTable;if(typeof f!="string"||!f)throw new w(`Sort relation '${a.relationName}' on '${e}' has no target table metadata`);ao(t,f,a.fieldName,"sort");continue}let c=s.split("."),u=e;for(let l=0;l<c.length;l++){let f=c[l];if(l===c.length-1){ao(t,u,f,"sort");break}let p=so(t,u,f);if(!p)throw new w(`Sort path '${s}' references unknown relation '${f}' on '${u}'`);let g=p.targetTableName||p.targetTable;if(typeof g!="string"||!g)throw new w(`Sort relation '${f}' on '${u}' has no target table metadata`);u=g}}}var pe=class{plan(e){let{tableName:t,fields:r,filter:o,sort:i,page:s,limit:a,meta:c,metadata:u,dbType:l}=e,f=u?.tables?.get(t);if(!f)throw new w(`Query planning requires metadata for table '${t}'`);let d=new Te,p=this.parseFields(r),g=p===void 0?void 0:di(p,t,u),h=null;g&&f&&(h=Vr(g,t,u,d));let y=!1,m=null;if(o!=null){Yr(o,t,u);let O=Me(o,t,u,d);m=O.node,y=O.hasRelationFilters}let b=this.parseLimit(a),_=this.parsePage(s),S=this.parseSort(i);f&&_t(S,t,u);let E=[],C=!1;for(let O of S){let P=O.startsWith("-"),G=P?O.substring(1):O,te=P?"desc":"asc";if(f){let k=this.parseRelationAggregateSort(t,f,G,u,l);if(k){C=!0,E.push({joinId:null,field:G,direction:te,fullPath:G,function:k.functionName,relationName:k.relationName,aggregateField:k.aggregateField,relationMeta:k.relationMeta});continue}let $=this.resolveLocalSortField(t,f,G,l);E.push({joinId:null,field:$,direction:te,fullPath:$});continue}E.push({joinId:null,field:G,direction:te,fullPath:G})}if(_!==void 0&&b===void 0)throw new w("Query page requires limit to be present");let x=(f?.columns??[]).filter(O=>O.isPrimary===!0).map(O=>O.name);if(x.length===0&&l==="mongodb"&&f?.columns?.some(O=>O.name==="_id")&&x.push("_id"),E.length===0)for(let O of x)_t([O],t,u),E.push({joinId:null,field:O,direction:"asc",fullPath:O});else if(_!==void 0&&b!==void 0)for(let O of x)E.some(P=>P.joinId===null&&P.field===O)||(_t([O],t,u),E.push({joinId:null,field:O,direction:"asc",fullPath:O}));if(_!==void 0&&b!==void 0&&x.length===0)throw new w(`Query pagination requires a deterministic primary key on '${t}'`);let v=_!==void 0&&b!==void 0?(_-1)*b:void 0;if(v!==void 0&&!Number.isSafeInteger(v))throw new w("Query pagination offset exceeds safe integer range");let R=this.parseMeta(c),M=R.includes("totalCount")||R.includes("*"),N=R.includes("filterCount")||R.includes("*"),j=d.getAll();return{table:t,dbType:l,rawFields:g,rawFilter:o??null,joins:j,sortItems:E,limit:b,offset:v,needsTotalCount:M,needsFilterCount:N,hasRelationFilters:y,hasRelationSort:C,filterTree:m,fieldTree:h}}parseFields(e){if(e!=null){if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new w("Query field entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new w("Query fields must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}}parseSort(e){if(e==null)return[];if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new w("Query sort entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new w("Query sort must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}parseLimit(e){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))throw new w("Query limit must be a non-negative integer");let r=Number(t);if(!Number.isSafeInteger(r))throw new w("Query limit must be a safe integer");return r}parsePage(e){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))throw new w("Query page must be a positive integer");let r=Number(t);if(!Number.isSafeInteger(r)||r<1)throw new w("Query page must be a positive safe integer");return r}parseMeta(e){if(e==null)return[];if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new w("Query meta entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new w("Query meta must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}resolveLocalSortField(e,t,r,o){if(r.includes("."))throw new w(`Sort field '${r}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(a=>a.name===r),s=!i&&o==="mongodb"&&r==="id"&&t.columns?.some(a=>a.name==="_id");if(!i&&!s)throw new w(`Sort field '${r}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`);return s?"_id":r}parseRelationAggregateSort(e,t,r,o,i){let s=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!s){if(/^_(count|max|min)\(/.test(r))throw new w(`Sort function '${r}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let a=s[1],c=s[2].trim();if(a==="count"){let y=c;if(!y||y.includes("."))throw new w(`Sort function '${r}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===y);if(!m)throw new w(`Sort relation '${y}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new w(`Sort function '_count(${y})' is only supported for list relations on '${e}'.`);return{functionName:a,relationName:y,relationMeta:m}}let u=c.indexOf(".");if(u<=0||u!==c.lastIndexOf("."))throw new w(`Sort function '${r}' is not supported on '${e}'. Use _${a}(relationName.fieldName).`);let l=c.slice(0,u).trim(),f=c.slice(u+1).trim();if(!l||!f)throw new w(`Sort function '${r}' is not supported on '${e}'. Use _${a}(relationName.fieldName).`);let d=t.relations?.find(y=>y.propertyName===l);if(!d)throw new w(`Sort relation '${l}' does not exist on '${e}'.`);if(d.type!=="one-to-many"&&d.type!=="many-to-many")throw new w(`Sort function '_${a}(${l}.${f})' is only supported for list relations on '${e}'.`);let p=d.targetTableName||d.targetTable,g=o?.tables?.get(p);if(!g)throw new w(`Sort function '${r}' references unknown target table '${p}' on '${e}'.`);let h=g.columns?.find(y=>y.name===f)??(i==="mongodb"&&f==="id"?g.columns?.find(y=>y.name==="_id"):void 0);if(!h)throw new w(`Sort field '${f}' does not exist on '${p}' for function '_${a}(${l}.${f})'.`);if(h?.isEncrypted===!0)throw new w(`Encrypted field '${f}' on '${p}' cannot be used for sort.`);return{functionName:a,relationName:l,aggregateField:h.name,relationMeta:d}}};var Zr=require("mongodb");et();function ge(n){return n.type==="one-to-many"||n.isInverse===!0||n.type==="one-to-one"&&!!n.mappedBy}function X(n){return(n.type==="many-to-one"||n.type==="one-to-one")&&!ge(n)&&(n.foreignKeyColumn||n.propertyName)||null}function H(n){return n.foreignKeyColumn||n.mappedBy||n.propertyName||null}function wa(n){return n instanceof Zr.ObjectId?!0:n==null||typeof n!="object"?!1:n._bsontype==="ObjectId"||n._bsontype==="ObjectID"?typeof n.toHexString=="function"||n.id instanceof Uint8Array:!1}function _a(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let e=Object.keys(n);if(e.length!==1||e[0]!=="buffer")return!1;let t=n.buffer;return!!t&&typeof t=="object"&&Object.keys(t).length===12}function se(n){if(!n||typeof n!="object")return n;if(wa(n))return typeof n.toHexString=="function"?n.toHexString():new Zr.ObjectId(Buffer.from(n.id??n.buffer)).toString();if(n instanceof Date)return n.toISOString();if(Buffer.isBuffer(n))return n;if(Array.isArray(n))return n.map(t=>se(t));if(_a(n))try{let t=n.buffer,r=Object.keys(t).sort((o,i)=>parseInt(o,10)-parseInt(i,10)).map(o=>t[o]);return new Zr.ObjectId(Buffer.from(r)).toString()}catch{}let e={};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{value:se(r),enumerable:!0,configurable:!0,writable:!0});return e}function he(n,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,c=e.mappedBy,u=n,l=e.junctionTableName||dr(a,c,u);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:l,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:u};let f=pr(a,c,u);return{junctionName:l,selfColumn:f.targetColumn,otherColumn:f.sourceColumn,owningTable:a,inverseTable:u}}let r=n,o=t,i=e.junctionTableName||dr(r,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:r,inverseTable:o};let s=pr(r,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:r,inverseTable:o}}var tn=require("node:fs"),wi=require("node:path"),en=class{constructor(e,t,r,o){this.dbType=e;this.knexService=t;this.mongoService=r;this.runMongoMutationInSaga=o;this.batchInserts={items:[],flushing:!1};if(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)try{(0,tn.mkdirSync)((0,wi.dirname)(this.batchInsertTraceFile),{recursive:!0})}catch{}}async flush(){let e=this.batchInserts.failure;for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)try{await this.flushBatchInsertBuffer()}catch(t){e??={reason:t}}if(e??=this.batchInserts.failure,this.batchInserts.failure=void 0,e)throw e.reason}async enqueue(e,t){let r=Array.isArray(t)?t:[t],o=r.map(i=>({table:e,data:this.cloneBatchInsertRow(i)}));for(let i of o)this.batchInserts.items.push(i);return this.traceBatchInsert("enqueue",{tableName:e,count:r.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:r.length}}cloneBatchInsertRow(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async flushBatchInsertBuffer(){for(;this.batchInserts.flushing;)if(await this.batchInserts.flushPromise,this.batchInserts.items.length===0)return;let e=this.batchInserts.items.splice(0,this.batchInsertMaxSize);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 r=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...r.entries()].map(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...r.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}catch(r){throw this.batchInserts.failure??={reason:r},r}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(r=>this.logBatchInsertError("QueryBuilder batch insert flush failed",r))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let r=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-r})}async runBatchInsertWithIsolation(e,t){if(t.length===0)return;if(!(this.dbType==="mongodb"?typeof this.mongoService?.insertManyWithCascade=="function":typeof this.knexService?.insertManyWithCascade=="function")){let o=async()=>{await this.runLimited(t,async i=>{this.dbType==="mongodb"?await this.mongoService.insertOne(e,i.data):await this.knexService.insertWithCascade(e,i.data)})};this.dbType==="mongodb"?await this.runMongoMutationInSaga(o):await o();return}try{this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.insertManyWithCascade(e,t.map(o=>o.data))):await this.knexService.insertManyWithCascade(e,t.map(o=>o.data))}catch(o){if(t.length===1)throw this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,o),o;let i=Math.ceil(t.length/2),s;for(let a of[t.slice(0,i),t.slice(i)])try{await this.runBatchInsertWithIsolation(e,a)}catch(c){s??={reason:c}}if(s)throw s.reason}}groupBatchInsertsByTable(e){let t=new Map;for(let r of e){let o=t.get(r.table);o?o.push(r):t.set(r.table,[r])}return t}async runLimited(e,t){let r=0,o,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;r<e.length;){let s=e[r++];try{await t(s)}catch(a){o??={reason:a}}}});if(await Promise.all(i),o)throw o.reason}readPositiveEnv(e,t){let r=Number(process.env[e]);return!Number.isSafeInteger(r)||r<=0?t:r}traceBatchInsert(e,t){if(this.batchInsertTraceFile)try{(0,tn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
6
|
-
`)}catch{}}logBatchInsertError(e,t){let r=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:r,code:t?.code,detail:t?.detail}),console.error(`${e}: ${r}`)}};async function tt(n,e,t,r){if(!n)return{scalarFields:[],relations:[]};let o=n.tables?.get(e);if(!o)return{scalarFields:[],relations:[]};let i=new Map;for(let u of t)if(u==="*")i.has("")||i.set("",[]),i.get("").push(u);else if(u.includes(".")&&o.relations?.some(l=>l.propertyName===u.split(".")[0])){let l=u.split("."),f=l[0],d=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(d)}else if(o.relations?.some(f=>f.propertyName===u)){let f=i.get(u)??[];f.includes("_id")||f.push("_id"),i.set(u,f)}else i.has("")||i.set("",[]),i.get("").push(u);if(r&&typeof r=="object")for(let[u,l]of Object.entries(r)){if(i.has(u))continue;let f=l&&typeof l=="object"&&l.fields!=null?Array.isArray(l.fields)?l.fields:String(l.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.set(u,f)}let s=[],a=[],c=i.get("")||[];for(let u of c)if(u==="*"){if(o.columns)for(let l of o.columns)s.includes(l.name)||s.push(l.name);if(o.relations)for(let l of o.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else o.columns?.some(f=>f.name===u)&&!s.includes(u)&&s.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=o.relations?.find(y=>y.propertyName===u);if(!f)continue;let d="",p="",g=!1;f.type==="many-to-one"||f.type==="one-to-one"?ge(f)?(d="_id",p=H(f)||f.propertyName,g=!0):(d=X(f)||f.propertyName,p="_id",g=!1):f.type==="one-to-many"?(d="_id",p=H(f)||f.propertyName,g=!0):f.type==="many-to-many"&&(f.mappedBy?(d="_id",p=f.mappedBy,g=!0):(d=f.propertyName,p="_id",g=!1));let h=f.type==="one-to-many"||f.type==="many-to-many";a.push({propertyName:u,targetTable:f.targetTableName,localField:d,foreignField:p,type:h?"many":"one",isInverse:g,nestedFields:l})}return{scalarFields:s,relations:a}}re();Le();var _i=new Set(["fields","filter","sort","limit","page","deep"]),me=3;function Sa(n,e,t,r,o){let i=Array.isArray(n)?n:typeof n=="string"?n.split(","):null;if(!i||i.some(s=>typeof s!="string"))throw new w(`Deep fields for relation '${r}' on '${o}' must be strings`);for(let s of i){let a=s.trim();if(!a||a==="*")continue;let c=a.split(".");if(c.some(l=>!l))throw new w(`Invalid deep field path '${a}'`);let u=e;for(let l=0;l<c.length;l+=1){let f=c[l],d=t?.tables?.get(u);if(!d)throw new w(`Deep fields require metadata for target table '${u}'`);let p=l===c.length-1,g=d.columns?.find(b=>b.name===f),h=f==="id"&&d.columns?.some(b=>b.name==="_id");if(p&&(g||h))break;let y=d.relations?.find(b=>b.propertyName===f);if(!y)break;if(l+1>me)throw new w(`Deep field path exceeds max relation hops of ${me} at '${f}'`);let m=y.targetTableName||y.targetTable;if(typeof m!="string"||!m||!t?.tables?.has(m))throw new w(`Deep field relation '${f}' on '${u}' has no resolvable target table metadata`);if(p)break;u=m}}}function Si(n,e,t,r){if(!Number.isSafeInteger(n)||(e==="limit"?Number(n)<0:Number(n)<1))throw new w(`Deep ${e} for relation '${t}' on '${r}' must be a ${e==="limit"?"non-negative":"positive"} safe integer`);return n}function rt(n,e,t,r=0,o=3){if(!e||typeof e!="object"||Array.isArray(e))throw new w("deep option must be an object");if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(o)||o<1||o>64)throw new w("Deep option recursion bounds must be safe integers within 0..64");if(r>=o)throw new w(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(n),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,c]of Object.entries(e)){let u=s.get(a);if(!u)throw new w(`Unknown relation '${a}' on '${n}'`);if(!c||typeof c!="object"||Array.isArray(c))throw new w(`Deep option for relation '${a}' must be an object`);for(let d of Object.keys(c))if(!_i.has(d))throw new w(`Unknown deep option key '${d}' for relation '${a}'. Allowed: ${[..._i].join(", ")}`);let l=u.type;if(c.limit!==void 0&&(l==="many-to-one"||l==="one-to-one"))throw new w(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${n}')`);if(c.limit!==void 0&&Si(c.limit,"limit",a,n),c.page!==void 0&&Si(c.page,"page",a,n),c.page!==void 0&&c.limit===void 0)throw new w(`'page' requires 'limit' to be present (relation '${a}' on '${n}')`);let f=u.targetTableName||u.targetTable;if(typeof f!="string"||!f||!t?.tables?.has(f))throw new w(`Relation '${a}' on '${n}' has no resolvable target table metadata`);if(c.fields!==void 0&&Sa(c.fields,f,t,a,n),c.filter!==void 0){if(!c.filter||typeof c.filter!="object"||Array.isArray(c.filter))throw new w(`Deep filter for relation '${a}' on '${n}' must be an object`);rn(c.filter,0,a,n,f,t,0,new Set),De(c.filter,f,t),Yr(c.filter,f,t)}if(c.sort!==void 0){if(typeof c.sort!="string"&&!Array.isArray(c.sort))throw new w(`Deep sort for relation '${a}' on '${n}' must be a string or string array`);let d=Array.isArray(c.sort)?c.sort:c.sort.split(",").map(p=>p.trim()).filter(Boolean);if(d.some(p=>typeof p!="string"))throw new w(`Sort entries must be strings (relation '${a}' on '${n}')`);_t(d,f,t);for(let p of d){let g=p.startsWith("-")?p.slice(1):p;$a(g,f,t,a,n)}}c.deep!==void 0&&rt(f,c.deep,t,r+1,o)}}function $a(n,e,t,r,o){if(n.includes("."))throw new w(`Sort field '${n}' is not supported for relation '${r}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new w(`Sort field '${n}' references unknown table '${e}' (relation '${r}' on '${o}')`);let s=i.columns?.some(c=>c.name===n),a=n==="id"&&i.columns?.some(c=>c.name==="_id");if(!s&&!a)throw new w(`Sort field '${n}' does not exist on '${e}' (relation '${r}' on '${o}')`)}var Ta=new Set(["_and","_or","_not"]);function ka(n,e,t,r,o,i){let s=n.split(".");if(s.some(p=>!p))throw new w(`Invalid dotted filter path '${n}'`);let a=e,c=r;for(let p of s.slice(0,-1)){let g=t?.tables?.get(a);if(!g)throw new w(`Filter path '${n}' references unknown table '${a}'`);let h=g.relations?.find(m=>m.propertyName===p);if(!h)throw new w(`Filter path '${n}' references unknown relation '${p}' on '${a}'`);if(c+=1,c>me)throw new w(`Filter path exceeds max dotted hops of ${me} at '${p}' (relation '${o}' on '${i}')`);let y=h.targetTableName||h.targetTable;if(!y)throw new w(`Filter relation '${p}' on '${a}' has no target table`);a=y}let u=s[s.length-1],l=t?.tables?.get(a);if(!l)throw new w(`Filter path '${n}' references unknown table '${a}'`);let f=l.columns?.some(p=>p.name===u),d=u==="id"&&l.columns?.some(p=>p.name==="_id");if(!f&&!d)throw new w(`Filter path '${n}' references unknown field '${u}' on '${a}'`);return{tableName:a,relationDepth:c}}function rn(n,e,t,r,o,i,s,a){if(!(!n||typeof n!="object")){if(s>64)throw new w("Filter nesting depth exceeds maximum of 64");if(a.has(n))throw new w("Filter contains a circular reference");a.add(n);try{if(Array.isArray(n)){for(let l of n)rn(l,e,t,r,o,i,s+1,a);return}let c=i?.tables?.get(o);if(!c)throw new w(`Filter validation requires metadata for table '${o}'`);let u=new Map((c?.relations??[]).map(l=>[l.propertyName,l]));for(let[l,f]of Object.entries(n)){if(Ta.has(l)){rn(f,e,t,r,o,i,s+1,a);continue}if(l.includes(".")){if(ka(l,o,i,e,t,r).relationDepth>me)throw new w(`Filter path exceeds max dotted hops of ${me} at '${l}' (relation '${t}' on '${r}')`);continue}let d=u.get(l);if(!d){if(l.startsWith("_"))continue;continue}let p=e+1;if(p>me)throw new w(`Filter path exceeds max dotted hops of ${me} at '${l}' (relation '${t}' on '${r}')`);let g=d.targetTableName||d.targetTable;g&&rn(f,p,t,r,g,i,s+1,a)}}finally{a.delete(n)}}}function ye(n,e){if(!n||typeof n!="object")return!1;for(let[t,r]of Object.entries(n))if(t==="_and"||t==="_or"){if(Array.isArray(r)){for(let o of r)if(ye(o,e))return!0}}else if(t==="_not"){if(ye(r,e))return!0}else if(e.has(t))return!0;return!1}function Ae(n,e){if(!n||typeof n!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},r={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(n)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let c=Object.keys(a);if(c.some(l=>l.startsWith("_"))){let l=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];c.length>0&&c.every(f=>l.includes(f))?r[s]={id:a}:r[s]=a}else r[s]=a}else r[s]=a;else t[s]=a}let i=ye(n,o);return{fieldFilters:t,relationFilters:r,hasRelations:i}}function uo(n){return`__sort_count_${n.relationName||n.field}`}function fo(n){let e=n.relationName||n.field,t=n.aggregateField||"value";return`__sort_${n.function}_${e.length}_${e}_${t.length}_${t}`}function $i(n){return n.filter(e=>e.function==="count").map(uo)}function Ti(n){return n.filter(e=>(e.function==="max"||e.function==="min")&&e.aggregateField).map(fo)}function ki(n,e,t,r){for(let i of t){if(i.function!=="count")continue;let s=i.relationMeta,a=i.relationName||i.field,c=s?.targetTableName||s?.targetTable,u=uo(i);if(!(!s||!c)){if(s.type==="one-to-many"){let l=H(s)||a;n.push({$lookup:{from:c,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:u}}),n.push({$addFields:{[u]:{$ifNull:[{$arrayElemAt:[`$${u}.value`,0]},0]}}});continue}if(s.type==="many-to-many"){let l=he(e,s);if(!l)continue;n.push({$lookup:{from:l.junctionName,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:u}}),n.push({$addFields:{[u]:{$ifNull:[{$arrayElemAt:[`$${u}.value`,0]},0]}}})}}}}function Ei(n,e,t,r){for(let i of t){if(i.function!=="max"&&i.function!=="min")continue;let s=i.relationMeta,a=i.relationName||i.field,c=s?.targetTableName||s?.targetTable,u=i.aggregateField;if(!s||!c||!u)continue;let l="_id",f=u,d=fo(i),p=i.function==="min"?"$min":"$max";if(s.type==="one-to-many"){let g=H(s)||a;n.push({$lookup:{from:c,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${g}`,"$$localId"]}}},{$group:{_id:null,value:{[p]:`$${f}`}}}],as:d}}),n.push({$addFields:{[d]:{$arrayElemAt:[`$${d}.value`,0]}}});continue}if(s.type==="many-to-many"){let g=he(e,s);if(!g)continue;let h="__enfyra_relation_aggregate_target__";n.push({$lookup:{from:g.junctionName,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${g.selfColumn}`,"$$localId"]}}},{$lookup:{from:c,localField:g.otherColumn,foreignField:l,as:h}},{$unwind:`$${h}`},{$group:{_id:null,value:{[p]:`$${h}.${f}`}}}],as:d}}),n.push({$addFields:{[d]:{$arrayElemAt:[`$${d}.value`,0]}}})}}}function Ea(n){let e=n.split(".");return e[e.length-1]==="id"&&(e[e.length-1]="_id"),e.join(".")}function po(n){let e=Object.create(null);for(let t of n){let r=Ea(t.field);Object.defineProperty(e,r,{value:t.direction==="asc"?1:-1,enumerable:!0,configurable:!0,writable:!0})}return e}function gr(n){let e=Object.create(null);for(let t of n){if((t.function==="max"||t.function==="min")&&!t.aggregateField)continue;let r=t.function==="count"?uo(t):t.function==="max"||t.function==="min"?fo(t):t.joinId!==null?t.fullPath:t.field;Object.defineProperty(e,r,{value:t.direction==="asc"?1:-1,enumerable:!0,configurable:!0,writable:!0})}return e}Ne();var Di=require("mongodb");on();Ne();Ne();function Ii(n,e,t){let{rootFields:r,subRelations:o}=nt(n),i={},s=!1;if(r.includes("*")){s=!0;for(let d of e.relations||[])o.has(d.propertyName)||o.set(d.propertyName,["_id"])}else for(let d of r){let p=e.columns.find(g=>g.name===d);p?i[p.name]=1:e.relations?.find(h=>h.propertyName===d)&&!o.has(d)&&o.set(d,["_id"])}o.forEach((d,p)=>{let g=e.relations?.find(h=>h.propertyName===p);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[X(g)||g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((d,p)=>{let g=e.relations?.find(b=>b.propertyName===p);if(!g)return;let h=g.targetTableName||g.targetTable;if(!h)return;let y,m;g.type==="many-to-one"||g.type==="one-to-one"?ge(g)?(y="_id",m=H(g)||g.propertyName):(y=X(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(y="_id",m=H(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(y="_id",m=g.mappedBy):(y=g.propertyName,m="_id")),a.push({relationName:p,type:g.type,targetTable:h,fields:d,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:y,foreignField:m})});let c=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,u=t?.get(e.name)??[],l=[];if(!s&&u.length>0)for(let d of u)i[d.newName]===1&&i[d.oldName]!==1&&(i[d.oldName]=1,l.push(d.oldName));return{isPkOnly:c,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:u,hiddenFields:l}}}function Oe(n,e){let t=e.pendingRenames??[];if(n.length===0||t.length===0)return n;let r=new Set(e.hiddenFields??[]);for(let o of n){let i=Object.getOwnPropertyDescriptors(o),s=[],a=new Set;for(let c of t){let u=Object.prototype.hasOwnProperty.call(i,c.newName),l=Object.prototype.hasOwnProperty.call(i,c.oldName)?i[c.oldName]:void 0;!u&&l&&s.push({name:c.newName,value:l.value}),(r.has(c.oldName)||u||l)&&a.add(c.oldName)}for(let c of s)Object.defineProperty(o,c.name,{value:c.value,enumerable:!0,configurable:!0,writable:!0});for(let c of a)delete o[c]}return n}Ne();var sn=require("mongodb");function vi(n){return`__sort_${n.map(e=>`${e.length}_${e}`).join("_")}`}function Ke(n){let e={};for(let t of ke(n)){let r=t.field.split("."),o=r[r.length-1]==="id"?"_id":r[r.length-1];if(r.length===1)Object.defineProperty(e,o,{value:t.order,enumerable:!0,writable:!0,configurable:!0});else{let i=vi(r.slice(0,-1));e[`${i}.${o}`]=t.order}}return Object.keys(e).length>0?e:void 0}function ke(n){return n?(Array.isArray(n)?n:n.split(",")).map(t=>String(t).trim()).filter(Boolean).map(t=>{let r=t.startsWith("-"),o=r?t.slice(1):t;return{field:o==="id"?"_id":o,order:r?-1:1}}):[]}function yr(n){return ke(n).some(e=>e.field.includes("."))}function an(n,e,t,r=!1,o){let i=ke(t).map(p=>`${p.order===-1?"-":""}${p.field}`),s=[{$match:e}],a=new Set,c=new Map,u=new Set((o?.tables?.get(n)?.columns??[]).map(p=>p.name)),l=p=>{let g=p.join("."),h=c.get(g);if(h)return h;let y=vi(p),m=y,b=1;for(;u.has(m);)m=`${y}_${b++}`;return u.add(m),c.set(g,m),m};for(let p of i){let h=(p.startsWith("-")?p.slice(1):p).split(".");if(h.length<=1)continue;let y=n;for(let m=0;m<h.length-1;m++){let b=h[m],_=o?.tables?.get(y);if(!_)throw new Error(`MongoDB sort metadata not found for table '${y}'`);let S=_.relations?.find(x=>x.propertyName===b);if(!S)throw new Error(`MongoDB dotted sort relation '${y}.${b}' was not found`);let E=S.targetTableName||S.targetTable,C=l(h.slice(0,m+1));if(ge(S)||S.type==="one-to-many"||S.type==="many-to-many")throw new Error(`Dotted sort through inverse or to-many relation '${b}' is not supported`);if(!a.has(C)){a.add(C);let x=X(S)||S.propertyName,v=m===0?null:l(h.slice(0,m)),R=v?`${v}.${x}`:x;s.push({$lookup:{from:E,localField:R,foreignField:"_id",as:C}},{$unwind:{path:`$${C}`,preserveNullAndEmptyArrays:!0}})}y=E}}let f={};for(let p of ke(t)){let g=p.field.split(".");if(g.length===1)Object.defineProperty(f,g[0],{value:p.order,enumerable:!0,writable:!0,configurable:!0});else{let h=g[g.length-1]==="id"?"_id":g[g.length-1];f[`${l(g.slice(0,-1))}.${h}`]=p.order}}f._id===void 0&&(f._id=1),s.push({$sort:f});let d={};for(let p of a)d[p]=0;return!r&&Object.keys(d).length>0&&s.push({$project:d}),s}function ot(n,e){let t=i=>i==null?1:typeof i=="number"?2:typeof i=="string"?3:i instanceof sn.ObjectId?7:typeof i=="boolean"?8:i instanceof Date?9:typeof i=="object"&&!Array.isArray(i)?4:Array.isArray(i)?5:100,r=t(n),o=t(e);if(r!==o)return r<o?-1:1;if(n==null&&e==null)return 0;if(typeof n=="number"&&typeof e=="number")return n===e||Number.isNaN(n)&&Number.isNaN(e)?0:Number.isNaN(n)?-1:Number.isNaN(e)?1:n<e?-1:1;if(n instanceof Date&&e instanceof Date){let i=n.getTime(),s=e.getTime();return Number.isNaN(i)&&Number.isNaN(s)?0:Number.isNaN(i)?-1:Number.isNaN(s)?1:i===s?0:i<s?-1:1}if(n instanceof sn.ObjectId&&e instanceof sn.ObjectId)return Buffer.compare(n.id,e.id);if(typeof n=="string"&&typeof e=="string")return Buffer.compare(Buffer.from(n),Buffer.from(e));if(typeof n=="boolean"&&typeof e=="boolean")return n===e?0:n?1:-1;throw new Error("MongoDB in-memory merge does not support object sort keys")}function Mi(n,e){let t=ke(e).filter(r=>!r.field.includes("."));t.length!==0&&n.sort((r,o)=>{for(let i of t){let s=ot(r[i.field],o[i.field]);if(s!==0)return s*i.order}return ot(r._id,o._id)})}function Ai(n){n.sort((e,t)=>ot(e._id,t._id))}var Ca=new Set(["__proto__","constructor","prototype"]);function le(n){return n===0||n===!1}function go(n){let e=Object.entries(n??{});return e.length===0?!1:e.every(([t])=>t==="_id")?e.some(([,t])=>le(t)):e.some(([t,r])=>t!=="_id"&&le(r))}function it(n,e){if(!n||Object.keys(n).length===0)return;let t={...n},r=go(t);for(let o of e){let i=Object.keys(t).filter(s=>s===o||o.startsWith(s+".")||s.startsWith(o+"."));if(r)for(let s of i)le(t[s])&&delete t[s];else if(!i.some(s=>!le(t[s])&&(s===o||o.startsWith(s+".")))){for(let s of i)delete t[s];Object.defineProperty(t,o,{value:1,enumerable:!0,configurable:!0,writable:!0})}}return Object.keys(t).length>0?t:void 0}function Ni(n,e,t){let r=it(e,t);r&&n.push({$project:r})}function ln(n,e){if(!n||Object.keys(n).length===0)return{projection:void 0,hiddenFields:[]};let t=[],r=go(n),o=[...ke(e).map(a=>a.field),"_id"],i=[...new Set(o)],s=it(n,i.filter(a=>!(a==="_id"&&n._id===void 0)));for(let a of i)if(r)for(let[c,u]of Object.entries(n))le(u)&&(c===a||a.startsWith(c+".")||c.startsWith(a+"."))&&t.push(c);else!(a==="_id"&&n._id===void 0)&&!Object.keys(n).some(c=>!le(n[c])&&(c===a||a.startsWith(c+".")))&&t.push(a);return{projection:s,hiddenFields:[...new Set(t)]}}function cn(n,e){if(e)for(let t of n)delete t._id}function un(n,e,t=[]){if(e&&Object.keys(e).length===0&&(e=void 0),!e&&t.length===0)return;let r=e?go(e):!1,o=e?Object.entries(e):[],i=u=>{if(u.some(l=>Ca.has(l)))throw new Error("Unsafe MongoDB projection path")},s=(u,l)=>{if(u==null)return;if(l.length===0)return u;if(Array.isArray(u))return u.map(h=>s(h,l));let[f,...d]=l;if(!Object.prototype.hasOwnProperty.call(u,f))return;let p=s(u[f],d);if(p===void 0)return;let g=Object.create(null);return Object.defineProperty(g,f,{value:p,enumerable:!0,configurable:!0,writable:!0}),g},a=(u,l)=>{if(l===void 0)return u;if(Array.isArray(l)){let p=Array.isArray(u)?u:[];return l.forEach((g,h)=>{p[h]=a(p[h],g)}),p}if(!l||typeof l!="object")return l;let f=Object.getPrototypeOf(l);if(f!==null&&f!==Object.prototype)return l;let d=u&&typeof u=="object"&&!Array.isArray(u)?u:Object.create(null);for(let[p,g]of Object.entries(l))Object.defineProperty(d,p,{value:a(d[p],g),enumerable:!0,configurable:!0,writable:!0});return d},c=(u,l)=>{if(u==null||l.length===0)return;if(Array.isArray(u)){for(let p of u)c(p,l);return}let[f,...d]=l;if(Object.prototype.hasOwnProperty.call(u,f)){if(d.length===0){delete u[f];return}c(u[f],d)}};for(let u of n){if(e)if(r)for(let[l,f]of o){let d=l.split(".");i(d),le(f)&&c(u,d)}else{let l=Object.create(null);for(let[f,d]of o){if(le(d))continue;let p=f.split(".");i(p),l=a(l,s(u,p))}!le(e._id)&&u._id!==void 0&&Object.defineProperty(l,"_id",{value:u._id,enumerable:!0,configurable:!0,writable:!0});for(let f of Object.keys(u))delete u[f];for(let[f,d]of Object.entries(l))Object.defineProperty(u,f,{value:d,enumerable:!0,configurable:!0,writable:!0})}for(let l of Object.keys(u))t.some(f=>l.startsWith(f))&&delete u[l]}}var wr=require("mongodb");$t();var br="__enfyra_top_n_documents__";function Z(n){return Math.ceil(n.length/5e3)||1}function st(n){return Array.from(new Map(n.filter(e=>e!=null).map(e=>[B(e),e])).values())}function Tt(n,e="_id"){let t=Ke(n)||{};return t[e]===void 0&&(t[e]=1),t}function Pe(n,e){return!e||Object.keys(e).length===0?n:{$and:[n,e]}}function _r(n,e,t,r,o){n.push({$group:{_id:`$${e}`,[br]:{$topN:{sortBy:t,output:"$$ROOT",n:r+o}}}},{$project:{[br]:{$slice:[`$${br}`,r,o]}}},{$unwind:`$${br}`},{$replaceRoot:{newRoot:`$${br}`}})}function B(n){return n instanceof wr.ObjectId?`objectId:${n.toHexString()}`:typeof n=="object"&&typeof n?.toHexString=="function"?`objectId:${n.toHexString()}`:n===void 0?"undefined:":typeof n=="object"&&n!==null?`bson:${Buffer.from(wr.BSON.serialize({value:n})).toString("base64")}`:`${typeof n}:${wr.BSON.EJSON.stringify(n,{relaxed:!1})}`}var dn=Je(require("fs")),mo=Je(require("path"));var Ra=new RegExp("\\p{Mark}","gu");function Oi(n){return n==null?"":String(n).normalize("NFKD").replace(Ra,"").toLowerCase()}function ho(){let n={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),r=Oi(t);r!==t&&(n[t]=r)}catch{}return JSON.stringify(n)}function fn(){return`function() {
|
|
5
|
+
${e}`)}},$e=new Ur;function ra(n,e){return $e.compileSource(n,e)}function na(n){return $e.isExecutableJavaScript(n)}function oa(n,e){return $e.normalizeRecord(n,e)}function ia(n,e,t){return $e.normalizePatch(n,e,t)}function sa(n){return $e.getExecutableScript(n)}function aa(n){return $e.resolveExecutableScript(n)}function la(n){return $e.normalizeFlowStepScriptConfig(n)}sr();cr();ne();var li=64;function ci(n){let e=(n?.columns??[]).filter(t=>t.isPrimary===!0).map(t=>t.name);return e.length>0?e:n?.columns?.some(t=>t.name==="id")?["id"]:n?.columns?.some(t=>t.name==="_id")?["_id"]:[]}function ui(n,e){if(n!=="id")return n;if(e.columns?.some(r=>r.name==="id"))return"id";let t=ci(e);return t.length===1?t[0]:n}function Hr(n,e){let t=n.targetTableName||n.targetTable,r=e?.tables?.get(t);if(!r)throw new b(`Field relation '${n.propertyName}' has no target table metadata`);let o=ci(r);if(o.length===0)throw new b(`Field relation '${n.propertyName}' target '${t}' has no primary key metadata`);return o}function Vr(n,e,t,r){let o={rootTable:e,nodes:[]};if(n===void 0)return o;if(!Array.isArray(n))throw new b("Query fields must be an array");if(n.some(a=>typeof a!="string"))throw new b("Query field entries must be strings");if(n.length===0)return o;let i=t?.tables?.get(e);if(!i)throw new b(`Field parsing requires metadata for table '${e}'`);let s=r.createCheckpoint();try{let a=new Map,c=[],u=new Set(n.map(l=>ui(l,i)));for(let l of u)if(l==="*")c.push("*");else if(l.includes(".")){let f=l.indexOf("."),d=l.substring(0,f),p=l.substring(f+1);if(!d||!p)throw new b(`Invalid field path '${l}'`);if(!i.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(p)}else if(i.relations?.some(d=>d.propertyName===l)){a.has(l)||a.set(l,[]);let d=i.relations.find(p=>p.propertyName===l);for(let p of Hr(d,t))a.get(l).includes(p)||a.get(l).push(p)}else{if(!i.columns?.some(p=>p.name===l))continue;c.push(l)}if(c.includes("*")){o.nodes.push({kind:"wildcard"});for(let l of i.relations||[])a.has(l.propertyName)||a.set(l.propertyName,Hr(l,t))}else for(let l of c)o.nodes.push({kind:"scalar",name:l});for(let[l,f]of a.entries()){let d=i.relations?.find(y=>y.propertyName===l);if(!d)continue;let p=d.targetTableName||d.targetTable;if(typeof p!="string"||!p||!t?.tables?.has(p))throw new b(`Field relation '${l}' on '${e}' has no resolvable target table metadata`);let g=fi(f,p,t,1);if(g.length===0)continue;let h={kind:"relation",propertyName:l,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:p,children:g};if(d.type==="many-to-one"||d.type==="one-to-one"){let y=r.registerWithParent(e,l,t,"left",null,"data");h.joinId=y}o.nodes.push(h)}return o}catch(a){throw r.restoreCheckpoint(s),a}}function fi(n,e,t,r){if(r>li)throw new b(`Field nesting depth exceeds maximum of ${li}`);let o=t?.tables?.get(e);if(!o)throw new b(`Field parsing requires metadata for table '${e}'`);let i=new Map,s=[],a=new Set(n.map(u=>ui(u,o)));for(let u of a)if(u==="*")s.push("*");else if(u.includes(".")){let l=u.indexOf("."),f=u.substring(0,l),d=u.substring(l+1);if(!f||!d)throw new b(`Invalid field path '${u}'`);if(!o.relations?.some(g=>g.propertyName===f))continue;i.has(f)||i.set(f,[]),i.get(f).push(d)}else if(o.relations?.some(f=>f.propertyName===u)){i.has(u)||i.set(u,[]);let f=o.relations.find(d=>d.propertyName===u);for(let d of Hr(f,t))i.get(u).includes(d)||i.get(u).push(d)}else{if(!o.columns?.some(d=>d.name===u))continue;s.push(u)}let c=[];if(s.includes("*")){c.push({kind:"wildcard"});for(let u of o.relations||[])i.has(u.propertyName)||i.set(u.propertyName,Hr(u,t))}else for(let u of s)c.push({kind:"scalar",name:u});for(let[u,l]of i.entries()){let f=o.relations?.find(g=>g.propertyName===u);if(!f)continue;let d=f.targetTableName||f.targetTable;if(typeof d!="string"||!d||!t?.tables?.has(d))throw new b(`Field relation '${u}' on '${e}' has no resolvable target table metadata`);let p=fi(l,d,t,r+1);p.length!==0&&c.push({kind:"relation",propertyName:u,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:d,children:p})}return c}ne();function di(n,e,t){return n.filter(r=>{let o=r.split(".");if(o.some(s=>!s))throw new b(`Invalid field path '${r}'`);let i=e;for(let s=0;s<o.length;s++){let a=t?.tables?.get(i);if(!a)throw new b(`Field parsing requires metadata for table '${i}'`);let c=o[s],u=s===o.length-1;if(u&&c==="*"||u&&a.columns?.some(f=>f.name===c||c==="id"&&f.name==="_id"))return!0;let l=a.relations?.find(f=>f.propertyName===c);if(!l)return!1;if(u)return!0;i=l.targetTableName||l.targetTable}return!1})}ne();ne();Le();var ma=new Set(["_and","_or","_not"]);function lo(n,e){return n?.tables?.get(e)??null}function io(n,e,t){return lo(n,e)?.columns?.find(r=>r.name===t)}function so(n,e,t){return lo(n,e)?.relations?.find(r=>r.propertyName===t)}function ya(n){let e=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],r=e[2].trim();if(t==="count")return{functionName:t,relationName:r};let o=r.indexOf(".");return o<=0||o!==r.lastIndexOf(".")?null:{functionName:t,relationName:r.slice(0,o).trim(),fieldName:r.slice(o+1).trim()}}function ao(n,e,t,r){if(!lo(n,e))throw new b(`${r==="filter"?"Filter":"Sort"} validation requires metadata for table '${e}'`);let i=io(n,e,t)??(t==="id"?io(n,e,"_id"):void 0);if(!i)throw new b(`${r==="filter"?"Filter":"Sort"} field '${t}' does not exist on '${e}'`);if(i.isEncrypted===!0)throw new b(`Encrypted field '${t}' on '${e}' cannot be used for ${r}.`)}function Gr(n,e,t,r,o){if(!(!n||typeof n!="object")){if(r>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`);if(o.has(n))throw new b("Filter contains a circular reference");o.add(n);try{if(Array.isArray(n)){for(let i of n)Gr(i,e,t,r+1,o);return}for(let[i,s]of Object.entries(n)){if(ma.has(i)){Gr(s,e,t,r+1,o);continue}let a=so(t,e,i),c=a?null:io(t,e,i);if(c?.isEncrypted===!0)throw new b(`Encrypted field '${i}' on '${e}' cannot be used for filter.`);if(!(i.startsWith("_")&&!c&&!a)){if(a){let u=a.targetTableName||a.targetTable;if(typeof u!="string"||!u)throw new b(`Filter relation '${i}' on '${e}' has no target table metadata`);Gr(s,u,t,r+1,o);continue}ao(t,e,i,"filter")}}}finally{o.delete(n)}}}function Yr(n,e,t){Gr(n,e,t,0,new Set)}function _t(n,e,t){if(n===void 0)return;if(typeof n!="string"&&!Array.isArray(n))throw new b("Sort must be a string or string array");let r=Array.isArray(n)?n:n.split(",");if(r.some(i=>typeof i!="string"))throw new b("Sort entries must be strings");let o=r.map(i=>i.trim()).filter(Boolean);for(let i of o){let s=i.startsWith("-")?i.slice(1):i;if(!s)continue;let a=ya(s);if(a){let l=so(t,e,a.relationName);if(!l)throw new b(`Sort relation '${a.relationName}' does not exist on '${e}'`);if(a.functionName==="count")continue;let f=l.targetTableName||l.targetTable;if(typeof f!="string"||!f)throw new b(`Sort relation '${a.relationName}' on '${e}' has no target table metadata`);ao(t,f,a.fieldName,"sort");continue}let c=s.split("."),u=e;for(let l=0;l<c.length;l++){let f=c[l];if(l===c.length-1){ao(t,u,f,"sort");break}let p=so(t,u,f);if(!p)throw new b(`Sort path '${s}' references unknown relation '${f}' on '${u}'`);let g=p.targetTableName||p.targetTable;if(typeof g!="string"||!g)throw new b(`Sort relation '${f}' on '${u}' has no target table metadata`);u=g}}}var pe=class{plan(e){let{tableName:t,fields:r,filter:o,sort:i,page:s,limit:a,meta:c,metadata:u,dbType:l}=e,f=u?.tables?.get(t);if(!f)throw new b(`Query planning requires metadata for table '${t}'`);let d=new Te,p=this.parseFields(r),g=p===void 0?void 0:di(p,t,u),h=null;g&&f&&(h=Vr(g,t,u,d));let y=!1,m=null;if(o!=null){Yr(o,t,u);let O=Me(o,t,u,d);m=O.node,y=O.hasRelationFilters}let w=this.parseLimit(a),_=this.parsePage(s),$=this.parseSort(i);f&&_t($,t,u);let k=[],C=!1;for(let O of $){let P=O.startsWith("-"),G=P?O.substring(1):O,re=P?"desc":"asc";if(f){let E=this.parseRelationAggregateSort(t,f,G,u,l);if(E){C=!0,k.push({joinId:null,field:G,direction:re,fullPath:G,function:E.functionName,relationName:E.relationName,aggregateField:E.aggregateField,relationMeta:E.relationMeta});continue}let S=this.resolveLocalSortField(t,f,G,l);k.push({joinId:null,field:S,direction:re,fullPath:S});continue}k.push({joinId:null,field:G,direction:re,fullPath:G})}if(_!==void 0&&w===void 0)throw new b("Query page requires limit to be present");let x=(f?.columns??[]).filter(O=>O.isPrimary===!0).map(O=>O.name);if(x.length===0&&l==="mongodb"&&f?.columns?.some(O=>O.name==="_id")&&x.push("_id"),k.length===0)for(let O of x)_t([O],t,u),k.push({joinId:null,field:O,direction:"asc",fullPath:O});else if(_!==void 0&&w!==void 0)for(let O of x)k.some(P=>P.joinId===null&&P.field===O)||(_t([O],t,u),k.push({joinId:null,field:O,direction:"asc",fullPath:O}));if(_!==void 0&&w!==void 0&&x.length===0)throw new b(`Query pagination requires a deterministic primary key on '${t}'`);let v=_!==void 0&&w!==void 0?(_-1)*w:void 0;if(v!==void 0&&!Number.isSafeInteger(v))throw new b("Query pagination offset exceeds safe integer range");let R=this.parseMeta(c),M=R.includes("totalCount")||R.includes("*"),N=R.includes("filterCount")||R.includes("*"),j=d.getAll();return{table:t,dbType:l,rawFields:g,rawFilter:o??null,joins:j,sortItems:k,limit:w,offset:v,needsTotalCount:M,needsFilterCount:N,hasRelationFilters:y,hasRelationSort:C,filterTree:m,fieldTree:h}}parseFields(e){if(e!=null){if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new b("Query field entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new b("Query fields must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}}parseSort(e){if(e==null)return[];if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new b("Query sort entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new b("Query sort must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}parseLimit(e){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))throw new b("Query limit must be a non-negative integer");let r=Number(t);if(!Number.isSafeInteger(r))throw new b("Query limit must be a safe integer");return r}parsePage(e){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))throw new b("Query page must be a positive integer");let r=Number(t);if(!Number.isSafeInteger(r)||r<1)throw new b("Query page must be a positive safe integer");return r}parseMeta(e){if(e==null)return[];if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new b("Query meta entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new b("Query meta must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}resolveLocalSortField(e,t,r,o){if(r.includes("."))throw new b(`Sort field '${r}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(a=>a.name===r),s=!i&&o==="mongodb"&&r==="id"&&t.columns?.some(a=>a.name==="_id");if(!i&&!s)throw new b(`Sort field '${r}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`);return s?"_id":r}parseRelationAggregateSort(e,t,r,o,i){let s=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!s){if(/^_(count|max|min)\(/.test(r))throw new b(`Sort function '${r}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let a=s[1],c=s[2].trim();if(a==="count"){let y=c;if(!y||y.includes("."))throw new b(`Sort function '${r}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(w=>w.propertyName===y);if(!m)throw new b(`Sort relation '${y}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new b(`Sort function '_count(${y})' is only supported for list relations on '${e}'.`);return{functionName:a,relationName:y,relationMeta:m}}let u=c.indexOf(".");if(u<=0||u!==c.lastIndexOf("."))throw new b(`Sort function '${r}' is not supported on '${e}'. Use _${a}(relationName.fieldName).`);let l=c.slice(0,u).trim(),f=c.slice(u+1).trim();if(!l||!f)throw new b(`Sort function '${r}' is not supported on '${e}'. Use _${a}(relationName.fieldName).`);let d=t.relations?.find(y=>y.propertyName===l);if(!d)throw new b(`Sort relation '${l}' does not exist on '${e}'.`);if(d.type!=="one-to-many"&&d.type!=="many-to-many")throw new b(`Sort function '_${a}(${l}.${f})' is only supported for list relations on '${e}'.`);let p=d.targetTableName||d.targetTable,g=o?.tables?.get(p);if(!g)throw new b(`Sort function '${r}' references unknown target table '${p}' on '${e}'.`);let h=g.columns?.find(y=>y.name===f)??(i==="mongodb"&&f==="id"?g.columns?.find(y=>y.name==="_id"):void 0);if(!h)throw new b(`Sort field '${f}' does not exist on '${p}' for function '_${a}(${l}.${f})'.`);if(h?.isEncrypted===!0)throw new b(`Encrypted field '${f}' on '${p}' cannot be used for sort.`);return{functionName:a,relationName:l,aggregateField:h.name,relationMeta:d}}};var Zr=require("mongodb");et();function ge(n){return n.type==="one-to-many"||n.isInverse===!0||n.type==="one-to-one"&&!!n.mappedBy}function Z(n){return(n.type==="many-to-one"||n.type==="one-to-one")&&!ge(n)&&(n.foreignKeyColumn||n.propertyName)||null}function H(n){return n.foreignKeyColumn||n.mappedBy||n.propertyName||null}function wa(n){return n instanceof Zr.ObjectId?!0:n==null||typeof n!="object"?!1:n._bsontype==="ObjectId"||n._bsontype==="ObjectID"?typeof n.toHexString=="function"||n.id instanceof Uint8Array:!1}function _a(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let e=Object.keys(n);if(e.length!==1||e[0]!=="buffer")return!1;let t=n.buffer;return!!t&&typeof t=="object"&&Object.keys(t).length===12}function se(n){if(!n||typeof n!="object")return n;if(wa(n))return typeof n.toHexString=="function"?n.toHexString():new Zr.ObjectId(Buffer.from(n.id??n.buffer)).toString();if(n instanceof Date)return n.toISOString();if(Buffer.isBuffer(n))return n;if(Array.isArray(n))return n.map(t=>se(t));if(_a(n))try{let t=n.buffer,r=Object.keys(t).sort((o,i)=>parseInt(o,10)-parseInt(i,10)).map(o=>t[o]);return new Zr.ObjectId(Buffer.from(r)).toString()}catch{}let e={};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{value:se(r),enumerable:!0,configurable:!0,writable:!0});return e}function he(n,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,c=e.mappedBy,u=n,l=e.junctionTableName||dr(a,c,u);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:l,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:u};let f=pr(a,c,u);return{junctionName:l,selfColumn:f.targetColumn,otherColumn:f.sourceColumn,owningTable:a,inverseTable:u}}let r=n,o=t,i=e.junctionTableName||dr(r,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:r,inverseTable:o};let s=pr(r,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:r,inverseTable:o}}var tn=require("node:fs"),wi=require("node:path"),en=class{constructor(e,t,r,o){this.dbType=e;this.knexService=t;this.mongoService=r;this.runMongoMutationInSaga=o;this.batchInserts={items:[],flushing:!1};if(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)try{(0,tn.mkdirSync)((0,wi.dirname)(this.batchInsertTraceFile),{recursive:!0})}catch{}}async flush(){let e=this.batchInserts.failure;for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)try{await this.flushBatchInsertBuffer()}catch(t){e??={reason:t}}if(e??=this.batchInserts.failure,this.batchInserts.failure=void 0,e)throw e.reason}async enqueue(e,t){let r=Array.isArray(t)?t:[t],o=r.map(i=>({table:e,data:this.cloneBatchInsertRow(i)}));for(let i of o)this.batchInserts.items.push(i);return this.traceBatchInsert("enqueue",{tableName:e,count:r.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:r.length}}cloneBatchInsertRow(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async flushBatchInsertBuffer(){for(;this.batchInserts.flushing;)if(await this.batchInserts.flushPromise,this.batchInserts.items.length===0)return;let e=this.batchInserts.items.splice(0,this.batchInsertMaxSize);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 r=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...r.entries()].map(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...r.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}catch(r){throw this.batchInserts.failure??={reason:r},r}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(r=>this.logBatchInsertError("QueryBuilder batch insert flush failed",r))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let r=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-r})}async runBatchInsertWithIsolation(e,t){if(t.length===0)return;if(!(this.dbType==="mongodb"?typeof this.mongoService?.insertManyWithCascade=="function":typeof this.knexService?.insertManyWithCascade=="function")){let o=async()=>{await this.runLimited(t,async i=>{this.dbType==="mongodb"?await this.mongoService.insertOne(e,i.data):await this.knexService.insertWithCascade(e,i.data)})};this.dbType==="mongodb"?await this.runMongoMutationInSaga(o):await o();return}try{this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.insertManyWithCascade(e,t.map(o=>o.data))):await this.knexService.insertManyWithCascade(e,t.map(o=>o.data))}catch(o){if(t.length===1)throw this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,o),o;let i=Math.ceil(t.length/2),s;for(let a of[t.slice(0,i),t.slice(i)])try{await this.runBatchInsertWithIsolation(e,a)}catch(c){s??={reason:c}}if(s)throw s.reason}}groupBatchInsertsByTable(e){let t=new Map;for(let r of e){let o=t.get(r.table);o?o.push(r):t.set(r.table,[r])}return t}async runLimited(e,t){let r=0,o,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;r<e.length;){let s=e[r++];try{await t(s)}catch(a){o??={reason:a}}}});if(await Promise.all(i),o)throw o.reason}readPositiveEnv(e,t){let r=Number(process.env[e]);return!Number.isSafeInteger(r)||r<=0?t:r}traceBatchInsert(e,t){if(this.batchInsertTraceFile)try{(0,tn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
6
|
+
`)}catch{}}logBatchInsertError(e,t){let r=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:r,code:t?.code,detail:t?.detail}),console.error(`${e}: ${r}`)}};async function tt(n,e,t,r){if(!n)return{scalarFields:[],relations:[]};let o=n.tables?.get(e);if(!o)return{scalarFields:[],relations:[]};let i=new Map;for(let u of t)if(u==="*")i.has("")||i.set("",[]),i.get("").push(u);else if(u.includes(".")&&o.relations?.some(l=>l.propertyName===u.split(".")[0])){let l=u.split("."),f=l[0],d=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(d)}else if(o.relations?.some(f=>f.propertyName===u)){let f=i.get(u)??[];f.includes("_id")||f.push("_id"),i.set(u,f)}else i.has("")||i.set("",[]),i.get("").push(u);if(r&&typeof r=="object")for(let[u,l]of Object.entries(r)){if(i.has(u))continue;let f=l&&typeof l=="object"&&l.fields!=null?Array.isArray(l.fields)?l.fields:String(l.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.set(u,f)}let s=[],a=[],c=i.get("")||[];for(let u of c)if(u==="*"){if(o.columns)for(let l of o.columns)s.includes(l.name)||s.push(l.name);if(o.relations)for(let l of o.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else o.columns?.some(f=>f.name===u)&&!s.includes(u)&&s.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=o.relations?.find(y=>y.propertyName===u);if(!f)continue;let d="",p="",g=!1;f.type==="many-to-one"||f.type==="one-to-one"?ge(f)?(d="_id",p=H(f)||f.propertyName,g=!0):(d=Z(f)||f.propertyName,p="_id",g=!1):f.type==="one-to-many"?(d="_id",p=H(f)||f.propertyName,g=!0):f.type==="many-to-many"&&(f.mappedBy?(d="_id",p=f.mappedBy,g=!0):(d=f.propertyName,p="_id",g=!1));let h=f.type==="one-to-many"||f.type==="many-to-many";a.push({propertyName:u,targetTable:f.targetTableName,localField:d,foreignField:p,type:h?"many":"one",isInverse:g,nestedFields:l})}return{scalarFields:s,relations:a}}ne();Le();var _i=new Set(["fields","filter","sort","limit","page","deep"]),me=3;function Sa(n,e,t,r,o){let i=Array.isArray(n)?n:typeof n=="string"?n.split(","):null;if(!i||i.some(s=>typeof s!="string"))throw new b(`Deep fields for relation '${r}' on '${o}' must be strings`);for(let s of i){let a=s.trim();if(!a||a==="*")continue;let c=a.split(".");if(c.some(l=>!l))throw new b(`Invalid deep field path '${a}'`);let u=e;for(let l=0;l<c.length;l+=1){let f=c[l],d=t?.tables?.get(u);if(!d)throw new b(`Deep fields require metadata for target table '${u}'`);let p=l===c.length-1,g=d.columns?.find(w=>w.name===f),h=f==="id"&&d.columns?.some(w=>w.name==="_id");if(p&&(g||h))break;let y=d.relations?.find(w=>w.propertyName===f);if(!y)break;if(l+1>me)throw new b(`Deep field path exceeds max relation hops of ${me} at '${f}'`);let m=y.targetTableName||y.targetTable;if(typeof m!="string"||!m||!t?.tables?.has(m))throw new b(`Deep field relation '${f}' on '${u}' has no resolvable target table metadata`);if(p)break;u=m}}}function Si(n,e,t,r){if(!Number.isSafeInteger(n)||(e==="limit"?Number(n)<0:Number(n)<1))throw new b(`Deep ${e} for relation '${t}' on '${r}' must be a ${e==="limit"?"non-negative":"positive"} safe integer`);return n}function rt(n,e,t,r=0,o=3){if(!e||typeof e!="object"||Array.isArray(e))throw new b("deep option must be an object");if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(o)||o<1||o>64)throw new b("Deep option recursion bounds must be safe integers within 0..64");if(r>=o)throw new b(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(n),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,c]of Object.entries(e)){let u=s.get(a);if(!u)throw new b(`Unknown relation '${a}' on '${n}'`);if(!c||typeof c!="object"||Array.isArray(c))throw new b(`Deep option for relation '${a}' must be an object`);for(let d of Object.keys(c))if(!_i.has(d))throw new b(`Unknown deep option key '${d}' for relation '${a}'. Allowed: ${[..._i].join(", ")}`);let l=u.type;if(c.limit!==void 0&&(l==="many-to-one"||l==="one-to-one"))throw new b(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${n}')`);if(c.limit!==void 0&&Si(c.limit,"limit",a,n),c.page!==void 0&&Si(c.page,"page",a,n),c.page!==void 0&&c.limit===void 0)throw new b(`'page' requires 'limit' to be present (relation '${a}' on '${n}')`);let f=u.targetTableName||u.targetTable;if(typeof f!="string"||!f||!t?.tables?.has(f))throw new b(`Relation '${a}' on '${n}' has no resolvable target table metadata`);if(c.fields!==void 0&&Sa(c.fields,f,t,a,n),c.filter!==void 0){if(!c.filter||typeof c.filter!="object"||Array.isArray(c.filter))throw new b(`Deep filter for relation '${a}' on '${n}' must be an object`);rn(c.filter,0,a,n,f,t,0,new Set),De(c.filter,f,t),Yr(c.filter,f,t)}if(c.sort!==void 0){if(typeof c.sort!="string"&&!Array.isArray(c.sort))throw new b(`Deep sort for relation '${a}' on '${n}' must be a string or string array`);let d=Array.isArray(c.sort)?c.sort:c.sort.split(",").map(p=>p.trim()).filter(Boolean);if(d.some(p=>typeof p!="string"))throw new b(`Sort entries must be strings (relation '${a}' on '${n}')`);_t(d,f,t);for(let p of d){let g=p.startsWith("-")?p.slice(1):p;$a(g,f,t,a,n)}}c.deep!==void 0&&rt(f,c.deep,t,r+1,o)}}function $a(n,e,t,r,o){if(n.includes("."))throw new b(`Sort field '${n}' is not supported for relation '${r}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new b(`Sort field '${n}' references unknown table '${e}' (relation '${r}' on '${o}')`);let s=i.columns?.some(c=>c.name===n),a=n==="id"&&i.columns?.some(c=>c.name==="_id");if(!s&&!a)throw new b(`Sort field '${n}' does not exist on '${e}' (relation '${r}' on '${o}')`)}var Ta=new Set(["_and","_or","_not"]);function ka(n,e,t,r,o,i){let s=n.split(".");if(s.some(p=>!p))throw new b(`Invalid dotted filter path '${n}'`);let a=e,c=r;for(let p of s.slice(0,-1)){let g=t?.tables?.get(a);if(!g)throw new b(`Filter path '${n}' references unknown table '${a}'`);let h=g.relations?.find(m=>m.propertyName===p);if(!h)throw new b(`Filter path '${n}' references unknown relation '${p}' on '${a}'`);if(c+=1,c>me)throw new b(`Filter path exceeds max dotted hops of ${me} at '${p}' (relation '${o}' on '${i}')`);let y=h.targetTableName||h.targetTable;if(!y)throw new b(`Filter relation '${p}' on '${a}' has no target table`);a=y}let u=s[s.length-1],l=t?.tables?.get(a);if(!l)throw new b(`Filter path '${n}' references unknown table '${a}'`);let f=l.columns?.some(p=>p.name===u),d=u==="id"&&l.columns?.some(p=>p.name==="_id");if(!f&&!d)throw new b(`Filter path '${n}' references unknown field '${u}' on '${a}'`);return{tableName:a,relationDepth:c}}function rn(n,e,t,r,o,i,s,a){if(!(!n||typeof n!="object")){if(s>64)throw new b("Filter nesting depth exceeds maximum of 64");if(a.has(n))throw new b("Filter contains a circular reference");a.add(n);try{if(Array.isArray(n)){for(let l of n)rn(l,e,t,r,o,i,s+1,a);return}let c=i?.tables?.get(o);if(!c)throw new b(`Filter validation requires metadata for table '${o}'`);let u=new Map((c?.relations??[]).map(l=>[l.propertyName,l]));for(let[l,f]of Object.entries(n)){if(Ta.has(l)){rn(f,e,t,r,o,i,s+1,a);continue}if(l.includes(".")){if(ka(l,o,i,e,t,r).relationDepth>me)throw new b(`Filter path exceeds max dotted hops of ${me} at '${l}' (relation '${t}' on '${r}')`);continue}let d=u.get(l);if(!d){if(l.startsWith("_"))continue;continue}let p=e+1;if(p>me)throw new b(`Filter path exceeds max dotted hops of ${me} at '${l}' (relation '${t}' on '${r}')`);let g=d.targetTableName||d.targetTable;g&&rn(f,p,t,r,g,i,s+1,a)}}finally{a.delete(n)}}}function ye(n,e){if(!n||typeof n!="object")return!1;for(let[t,r]of Object.entries(n))if(t==="_and"||t==="_or"){if(Array.isArray(r)){for(let o of r)if(ye(o,e))return!0}}else if(t==="_not"){if(ye(r,e))return!0}else if(e.has(t))return!0;return!1}function Ae(n,e){if(!n||typeof n!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},r={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(n)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let c=Object.keys(a);if(c.some(l=>l.startsWith("_"))){let l=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];c.length>0&&c.every(f=>l.includes(f))?r[s]={id:a}:r[s]=a}else r[s]=a}else r[s]=a;else t[s]=a}let i=ye(n,o);return{fieldFilters:t,relationFilters:r,hasRelations:i}}function uo(n){return`__sort_count_${n.relationName||n.field}`}function fo(n){let e=n.relationName||n.field,t=n.aggregateField||"value";return`__sort_${n.function}_${e.length}_${e}_${t.length}_${t}`}function $i(n){return n.filter(e=>e.function==="count").map(uo)}function Ti(n){return n.filter(e=>(e.function==="max"||e.function==="min")&&e.aggregateField).map(fo)}function ki(n,e,t,r){for(let i of t){if(i.function!=="count")continue;let s=i.relationMeta,a=i.relationName||i.field,c=s?.targetTableName||s?.targetTable,u=uo(i);if(!(!s||!c)){if(s.type==="one-to-many"){let l=H(s)||a;n.push({$lookup:{from:c,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:u}}),n.push({$addFields:{[u]:{$ifNull:[{$arrayElemAt:[`$${u}.value`,0]},0]}}});continue}if(s.type==="many-to-many"){let l=he(e,s);if(!l)continue;n.push({$lookup:{from:l.junctionName,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:u}}),n.push({$addFields:{[u]:{$ifNull:[{$arrayElemAt:[`$${u}.value`,0]},0]}}})}}}}function Ei(n,e,t,r){for(let i of t){if(i.function!=="max"&&i.function!=="min")continue;let s=i.relationMeta,a=i.relationName||i.field,c=s?.targetTableName||s?.targetTable,u=i.aggregateField;if(!s||!c||!u)continue;let l="_id",f=u,d=fo(i),p=i.function==="min"?"$min":"$max";if(s.type==="one-to-many"){let g=H(s)||a;n.push({$lookup:{from:c,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${g}`,"$$localId"]}}},{$group:{_id:null,value:{[p]:`$${f}`}}}],as:d}}),n.push({$addFields:{[d]:{$arrayElemAt:[`$${d}.value`,0]}}});continue}if(s.type==="many-to-many"){let g=he(e,s);if(!g)continue;let h="__enfyra_relation_aggregate_target__";n.push({$lookup:{from:g.junctionName,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${g.selfColumn}`,"$$localId"]}}},{$lookup:{from:c,localField:g.otherColumn,foreignField:l,as:h}},{$unwind:`$${h}`},{$group:{_id:null,value:{[p]:`$${h}.${f}`}}}],as:d}}),n.push({$addFields:{[d]:{$arrayElemAt:[`$${d}.value`,0]}}})}}}function Ea(n){let e=n.split(".");return e[e.length-1]==="id"&&(e[e.length-1]="_id"),e.join(".")}function po(n){let e=Object.create(null);for(let t of n){let r=Ea(t.field);Object.defineProperty(e,r,{value:t.direction==="asc"?1:-1,enumerable:!0,configurable:!0,writable:!0})}return e}function gr(n){let e=Object.create(null);for(let t of n){if((t.function==="max"||t.function==="min")&&!t.aggregateField)continue;let r=t.function==="count"?uo(t):t.function==="max"||t.function==="min"?fo(t):t.joinId!==null?t.fullPath:t.field;Object.defineProperty(e,r,{value:t.direction==="asc"?1:-1,enumerable:!0,configurable:!0,writable:!0})}return e}Ne();var Di=require("mongodb");on();Ne();Ne();function Ii(n,e,t){let{rootFields:r,subRelations:o}=nt(n),i={},s=!1;if(r.includes("*")){s=!0;for(let d of e.relations||[])o.has(d.propertyName)||o.set(d.propertyName,["_id"])}else for(let d of r){let p=e.columns.find(g=>g.name===d);p?i[p.name]=1:e.relations?.find(h=>h.propertyName===d)&&!o.has(d)&&o.set(d,["_id"])}o.forEach((d,p)=>{let g=e.relations?.find(h=>h.propertyName===p);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[Z(g)||g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((d,p)=>{let g=e.relations?.find(w=>w.propertyName===p);if(!g)return;let h=g.targetTableName||g.targetTable;if(!h)return;let y,m;g.type==="many-to-one"||g.type==="one-to-one"?ge(g)?(y="_id",m=H(g)||g.propertyName):(y=Z(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(y="_id",m=H(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(y="_id",m=g.mappedBy):(y=g.propertyName,m="_id")),a.push({relationName:p,type:g.type,targetTable:h,fields:d,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:y,foreignField:m})});let c=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,u=t?.get(e.name)??[],l=[];if(!s&&u.length>0)for(let d of u)i[d.newName]===1&&i[d.oldName]!==1&&(i[d.oldName]=1,l.push(d.oldName));return{isPkOnly:c,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:u,hiddenFields:l}}}function Oe(n,e){let t=e.pendingRenames??[];if(n.length===0||t.length===0)return n;let r=new Set(e.hiddenFields??[]);for(let o of n){let i=Object.getOwnPropertyDescriptors(o),s=[],a=new Set;for(let c of t){let u=Object.prototype.hasOwnProperty.call(i,c.newName),l=Object.prototype.hasOwnProperty.call(i,c.oldName)?i[c.oldName]:void 0;!u&&l&&s.push({name:c.newName,value:l.value}),(r.has(c.oldName)||u||l)&&a.add(c.oldName)}for(let c of s)Object.defineProperty(o,c.name,{value:c.value,enumerable:!0,configurable:!0,writable:!0});for(let c of a)delete o[c]}return n}Ne();var sn=require("mongodb");function vi(n){return`__sort_${n.map(e=>`${e.length}_${e}`).join("_")}`}function Ke(n){let e={};for(let t of ke(n)){let r=t.field.split("."),o=r[r.length-1]==="id"?"_id":r[r.length-1];if(r.length===1)Object.defineProperty(e,o,{value:t.order,enumerable:!0,writable:!0,configurable:!0});else{let i=vi(r.slice(0,-1));e[`${i}.${o}`]=t.order}}return Object.keys(e).length>0?e:void 0}function ke(n){return n?(Array.isArray(n)?n:n.split(",")).map(t=>String(t).trim()).filter(Boolean).map(t=>{let r=t.startsWith("-"),o=r?t.slice(1):t;return{field:o==="id"?"_id":o,order:r?-1:1}}):[]}function yr(n){return ke(n).some(e=>e.field.includes("."))}function an(n,e,t,r=!1,o){let i=ke(t).map(p=>`${p.order===-1?"-":""}${p.field}`),s=[{$match:e}],a=new Set,c=new Map,u=new Set((o?.tables?.get(n)?.columns??[]).map(p=>p.name)),l=p=>{let g=p.join("."),h=c.get(g);if(h)return h;let y=vi(p),m=y,w=1;for(;u.has(m);)m=`${y}_${w++}`;return u.add(m),c.set(g,m),m};for(let p of i){let h=(p.startsWith("-")?p.slice(1):p).split(".");if(h.length<=1)continue;let y=n;for(let m=0;m<h.length-1;m++){let w=h[m],_=o?.tables?.get(y);if(!_)throw new Error(`MongoDB sort metadata not found for table '${y}'`);let $=_.relations?.find(x=>x.propertyName===w);if(!$)throw new Error(`MongoDB dotted sort relation '${y}.${w}' was not found`);let k=$.targetTableName||$.targetTable,C=l(h.slice(0,m+1));if(ge($)||$.type==="one-to-many"||$.type==="many-to-many")throw new Error(`Dotted sort through inverse or to-many relation '${w}' is not supported`);if(!a.has(C)){a.add(C);let x=Z($)||$.propertyName,v=m===0?null:l(h.slice(0,m)),R=v?`${v}.${x}`:x;s.push({$lookup:{from:k,localField:R,foreignField:"_id",as:C}},{$unwind:{path:`$${C}`,preserveNullAndEmptyArrays:!0}})}y=k}}let f={};for(let p of ke(t)){let g=p.field.split(".");if(g.length===1)Object.defineProperty(f,g[0],{value:p.order,enumerable:!0,writable:!0,configurable:!0});else{let h=g[g.length-1]==="id"?"_id":g[g.length-1];f[`${l(g.slice(0,-1))}.${h}`]=p.order}}f._id===void 0&&(f._id=1),s.push({$sort:f});let d={};for(let p of a)d[p]=0;return!r&&Object.keys(d).length>0&&s.push({$project:d}),s}function ot(n,e){let t=i=>i==null?1:typeof i=="number"?2:typeof i=="string"?3:i instanceof sn.ObjectId?7:typeof i=="boolean"?8:i instanceof Date?9:typeof i=="object"&&!Array.isArray(i)?4:Array.isArray(i)?5:100,r=t(n),o=t(e);if(r!==o)return r<o?-1:1;if(n==null&&e==null)return 0;if(typeof n=="number"&&typeof e=="number")return n===e||Number.isNaN(n)&&Number.isNaN(e)?0:Number.isNaN(n)?-1:Number.isNaN(e)?1:n<e?-1:1;if(n instanceof Date&&e instanceof Date){let i=n.getTime(),s=e.getTime();return Number.isNaN(i)&&Number.isNaN(s)?0:Number.isNaN(i)?-1:Number.isNaN(s)?1:i===s?0:i<s?-1:1}if(n instanceof sn.ObjectId&&e instanceof sn.ObjectId)return Buffer.compare(n.id,e.id);if(typeof n=="string"&&typeof e=="string")return Buffer.compare(Buffer.from(n),Buffer.from(e));if(typeof n=="boolean"&&typeof e=="boolean")return n===e?0:n?1:-1;throw new Error("MongoDB in-memory merge does not support object sort keys")}function Mi(n,e){let t=ke(e).filter(r=>!r.field.includes("."));t.length!==0&&n.sort((r,o)=>{for(let i of t){let s=ot(r[i.field],o[i.field]);if(s!==0)return s*i.order}return ot(r._id,o._id)})}function Ai(n){n.sort((e,t)=>ot(e._id,t._id))}var Ca=new Set(["__proto__","constructor","prototype"]);function le(n){return n===0||n===!1}function go(n){let e=Object.entries(n??{});return e.length===0?!1:e.every(([t])=>t==="_id")?e.some(([,t])=>le(t)):e.some(([t,r])=>t!=="_id"&&le(r))}function it(n,e){if(!n||Object.keys(n).length===0)return;let t={...n},r=go(t);for(let o of e){let i=Object.keys(t).filter(s=>s===o||o.startsWith(s+".")||s.startsWith(o+"."));if(r)for(let s of i)le(t[s])&&delete t[s];else if(!i.some(s=>!le(t[s])&&(s===o||o.startsWith(s+".")))){for(let s of i)delete t[s];Object.defineProperty(t,o,{value:1,enumerable:!0,configurable:!0,writable:!0})}}return Object.keys(t).length>0?t:void 0}function Ni(n,e,t){let r=it(e,t);r&&n.push({$project:r})}function ln(n,e){if(!n||Object.keys(n).length===0)return{projection:void 0,hiddenFields:[]};let t=[],r=go(n),o=[...ke(e).map(a=>a.field),"_id"],i=[...new Set(o)],s=it(n,i.filter(a=>!(a==="_id"&&n._id===void 0)));for(let a of i)if(r)for(let[c,u]of Object.entries(n))le(u)&&(c===a||a.startsWith(c+".")||c.startsWith(a+"."))&&t.push(c);else!(a==="_id"&&n._id===void 0)&&!Object.keys(n).some(c=>!le(n[c])&&(c===a||a.startsWith(c+".")))&&t.push(a);return{projection:s,hiddenFields:[...new Set(t)]}}function cn(n,e){if(e)for(let t of n)delete t._id}function un(n,e,t=[]){if(e&&Object.keys(e).length===0&&(e=void 0),!e&&t.length===0)return;let r=e?go(e):!1,o=e?Object.entries(e):[],i=u=>{if(u.some(l=>Ca.has(l)))throw new Error("Unsafe MongoDB projection path")},s=(u,l)=>{if(u==null)return;if(l.length===0)return u;if(Array.isArray(u))return u.map(h=>s(h,l));let[f,...d]=l;if(!Object.prototype.hasOwnProperty.call(u,f))return;let p=s(u[f],d);if(p===void 0)return;let g=Object.create(null);return Object.defineProperty(g,f,{value:p,enumerable:!0,configurable:!0,writable:!0}),g},a=(u,l)=>{if(l===void 0)return u;if(Array.isArray(l)){let p=Array.isArray(u)?u:[];return l.forEach((g,h)=>{p[h]=a(p[h],g)}),p}if(!l||typeof l!="object")return l;let f=Object.getPrototypeOf(l);if(f!==null&&f!==Object.prototype)return l;let d=u&&typeof u=="object"&&!Array.isArray(u)?u:Object.create(null);for(let[p,g]of Object.entries(l))Object.defineProperty(d,p,{value:a(d[p],g),enumerable:!0,configurable:!0,writable:!0});return d},c=(u,l)=>{if(u==null||l.length===0)return;if(Array.isArray(u)){for(let p of u)c(p,l);return}let[f,...d]=l;if(Object.prototype.hasOwnProperty.call(u,f)){if(d.length===0){delete u[f];return}c(u[f],d)}};for(let u of n){if(e)if(r)for(let[l,f]of o){let d=l.split(".");i(d),le(f)&&c(u,d)}else{let l=Object.create(null);for(let[f,d]of o){if(le(d))continue;let p=f.split(".");i(p),l=a(l,s(u,p))}!le(e._id)&&u._id!==void 0&&Object.defineProperty(l,"_id",{value:u._id,enumerable:!0,configurable:!0,writable:!0});for(let f of Object.keys(u))delete u[f];for(let[f,d]of Object.entries(l))Object.defineProperty(u,f,{value:d,enumerable:!0,configurable:!0,writable:!0})}for(let l of Object.keys(u))t.some(f=>l.startsWith(f))&&delete u[l]}}var wr=require("mongodb");$t();var br="__enfyra_top_n_documents__";function ee(n){return Math.ceil(n.length/5e3)||1}function st(n){return Array.from(new Map(n.filter(e=>e!=null).map(e=>[B(e),e])).values())}function Tt(n,e="_id"){let t=Ke(n)||{};return t[e]===void 0&&(t[e]=1),t}function Pe(n,e){return!e||Object.keys(e).length===0?n:{$and:[n,e]}}function _r(n,e,t,r,o){n.push({$group:{_id:`$${e}`,[br]:{$topN:{sortBy:t,output:"$$ROOT",n:r+o}}}},{$project:{[br]:{$slice:[`$${br}`,r,o]}}},{$unwind:`$${br}`},{$replaceRoot:{newRoot:`$${br}`}})}function B(n){return n instanceof wr.ObjectId?`objectId:${n.toHexString()}`:typeof n=="object"&&typeof n?.toHexString=="function"?`objectId:${n.toHexString()}`:n===void 0?"undefined:":typeof n=="object"&&n!==null?`bson:${Buffer.from(wr.BSON.serialize({value:n})).toString("base64")}`:`${typeof n}:${wr.BSON.EJSON.stringify(n,{relaxed:!1})}`}var dn=Je(require("fs")),mo=Je(require("path"));var Ra=new RegExp("\\p{Mark}","gu");function Oi(n){return n==null?"":String(n).normalize("NFKD").replace(Ra,"").toLowerCase()}function ho(){let n={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),r=Oi(t);r!==t&&(n[t]=r)}catch{}return JSON.stringify(n)}function fn(){return`function() {
|
|
7
7
|
var M = ${ho()};
|
|
8
8
|
function foldStr(s) {
|
|
9
9
|
if (s == null) return '';
|
|
@@ -49,4 +49,4 @@ ${e}`)}},$e=new Ur;function ra(n,e){return $e.compileSource(n,e)}function na(n){
|
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
51
|
return true;
|
|
52
|
-
}`}var Pi="mongo-fold-text-search.body.txt",kt=null;function Fa(){let n=[mo.join(__dirname,Pi),mo.join(process.cwd(),"dist","kernel","query","utils",Pi)];for(let e of n)try{if(dn.existsSync(e))return dn.readFileSync(e,"utf8")}catch{}return null}function pn(){if(kt!==null)return kt;let n=Fa();return n?(kt=n,kt):(kt=fn(),kt)}var be=require("mongodb");function V(n,e,t,r){if(t==="_id"){if(r instanceof be.ObjectId)return r;if(typeof r=="string")try{return new be.ObjectId(r)}catch{return r}return r}let o=n?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}if(r==null)return r;switch(i.type){case"long":case"bigint":{if(be.Long.isLong(r)&&!r.unsigned)return r;if(typeof r=="number"&&!Number.isSafeInteger(r))throw new TypeError("MongoDB bigint requires an exact integer");if(!["string","number","bigint"].includes(typeof r)&&!be.Long.isLong(r))throw new TypeError("MongoDB bigint requires an integer");let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new TypeError("MongoDB bigint requires an integer");let a=BigInt(s);if(a<-(1n<<63n)||a>=1n<<63n)throw new RangeError("MongoDB bigint exceeds signed 64-bit range");return be.Long.fromBigInt(a)}case"int":case"integer":case"smallint":case"tinyint":return typeof r=="string"?parseInt(r,10):Number(r);case"float":case"double":case"decimal":case"numeric":case"real":return typeof r=="string"?parseFloat(r):Number(r);case"boolean":case"bool":return typeof r=="string"?r==="true"||r==="1":!!r;case"date":case"datetime":case"timestamp":return typeof r=="string"?new Date(r):r;case"objectId":case"ObjectId":if(r instanceof be.ObjectId)return r;if(typeof r=="string")try{return new be.ObjectId(r)}catch{return r}return r;case"uuid":return r;default:return r}}cr();sr();var gn="__mongoFoldTextTriples";function xt(n,e){if(!n)return{};let t={};return Et(n,t,e),at(t),t}function Ia(n,e){if(!n)return{};let t={};return hn(n,t,e),at(t),t}function ce(n,e,t){if(!e)return{};let r=new Te,{node:o}=Me(e,t,n,r);return xt(o,{metadata:n,rootTable:t})}function mn(n,e,t){if(!e)return{};let r=new Te,{node:o}=Me(e,t,n,r);return Ia(o,{metadata:n,rootTable:t})}function Et(n,e,t){switch(n.kind){case"true":return;case"false":Ee(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=n.children.map(i=>{let s={};return Et(i,s,t),at(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}Ee(e,...o);return}case"or":{let r=n.children.map(o=>{let i={};return Et(o,i,t),at(i),i});if(r.some(o=>Object.keys(o).length===0))return;if(r.length===0){Et({kind:"false"},e,t);return}Ee(e,{$or:r});return}case"not":hn(n.child,e,t);return;case"compare":Bi(n,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${n.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Bi(n,e,t){let r=n.field.fieldName;if(n.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${n.field.joinId} (field=${n.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let o=i=>V(t.metadata,t.rootTable,r,i);switch(n.op){case"eq":_e(e,r,o(n.value));return;case"neq":{let i=o(n.value);bo(t,r)?Ee(e,{[r]:{$ne:null}},{[r]:{$ne:i}}):_e(e,r,{$ne:i});return}case"gt":_e(e,r,{$gt:o(n.value)});return;case"gte":_e(e,r,{$gte:o(n.value)});return;case"lt":_e(e,r,{$lt:o(n.value)});return;case"lte":_e(e,r,{$lte:o(n.value)});return;case"in":{let i=ji(n.value).map(o);_e(e,r,{$in:i});return}case"not_in":{let i=ji(n.value).map(o);bo(t,r)?Ee(e,{[r]:{$ne:null}},{[r]:{$nin:i}}):_e(e,r,{$nin:i});return}case"between":{let i=Array.isArray(n.value)?n.value:typeof n.value=="string"?n.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&_e(e,r,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":_e(e,r,n.value===!0?{$eq:null}:{$ne:null});return;case"contains":yo(e,r,String(n.value),"contains");return;case"starts_with":yo(e,r,String(n.value),"starts");return;case"ends_with":yo(e,r,String(n.value),"ends");return}}function hn(n,e,t){switch(n.kind){case"true":Ee(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let r=n.children.map(o=>{let i={};return hn(o,i,t),at(i),i});if(r.some(o=>Object.keys(o).length===0))return;if(r.length===0){Et({kind:"false"},e,t);return}Ee(e,{$or:r});return}case"or":{let o=n.children.map(i=>{let s={};return hn(i,s,t),at(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}Ee(e,...o);return}case"not":Et(n.child,e,t);return;case"compare":va(n,e,t);return;case"relation_exists":{_e(e,n.joinId,n.negate?{$ne:null}:{$eq:null});return}}}function va(n,e,t){let r=n.field.fieldName;if(n.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${n.field.joinId} (field=${n.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(n.op==="is_null"){_e(e,r,n.value===!0?{$ne:null}:{$eq:null});return}let o={};Bi(n,o,t),at(o);let i={$nor:[o]};bo(t,r)?Ee(e,i,{[r]:{$ne:null}}):Ee(e,i)}function _e(n,e,t){n[e]===void 0?n[e]=t:(Ee(n,{[e]:n[e]},{[e]:t}),delete n[e])}function Ee(n,...e){if(e.length===0)return;let t=n.$and;n.$and=t?[...t,...e]:e}function bo(n,e){let r=n.metadata?.tables?.get?.(n.rootTable)?.columns?.find(o=>o.name===e);return r?r.isNullable!==!1:!0}function ji(n){return Array.isArray(n)?n:typeof n=="string"&&n.includes(",")?n.split(",").map(e=>e.trim()):[n]}function Ma(n){return n==="_id"?"$_id":`$${n}`}function yo(n,e,t,r){let o=Ma(e),i=n[gn]??[];i.push({ref:o,needle:t,mode:r}),n[gn]=i}function at(n){let e=n[gn];if(delete n[gn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,{$literal:i.needle},i.mode);let r={$eq:[{$function:{body:pn(),args:t,lang:"js"}},!0]},o=n.$expr;Object.prototype.hasOwnProperty.call(n,"$expr")?n.$expr={$and:[o,r]}:n.$expr=r}var xe="__sourceId__",Ue="__targetId__",Ct="__enfyra_target__",yn=class{constructor(e,t,r){this.db=e;this.metadata=t;this.executionBudget=r}runQuery(e){return this.executionBudget.run(e)}normalizeMetadata(){return this.metadata?this.metadata.tables instanceof Map?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}m2mSortCanUseJunction(e){return ke(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,r){if(t.length===0)return{docs:[],hideId:!1};let o=le(r.projection?._id),i=it(r.projection,["_id"]),s=i?{projection:i}:void 0,a=await W(t,c=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:c}},s).toArray()));return{docs:Oe(a,r),hideId:o}}async fetchM2MTopK(e,t,r,o,i,s,a){if(yr(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let c=new Map;for(let _ of e)c.set(B(_),[]);let u=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,l=!i&&this.m2mSortCanUseJunction(t.userSort),f=ke(t.userSort).find(_=>_.field==="_id")?.order??1,d=Tt(t.userSort),p=await W(e,async _=>{if(l&&!u){let C=[{$match:{[r.selfColumn]:{$in:_}}}];return _r(C,r.selfColumn,{[r.otherColumn]:f},s,a),C.push({$sort:{[r.selfColumn]:1,[r.otherColumn]:f}},{$project:{_id:0,[xe]:`$${r.selfColumn}`,[Ue]:`$${r.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate(C).toArray())).map(v=>({sourceId:v[xe],targetId:v[Ue]}))}let S=[{$match:{[r.selfColumn]:{$in:_}}},{$lookup:{from:t.targetTable,localField:r.otherColumn,foreignField:"_id",as:Ct}},{$unwind:`$${Ct}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ct}`,{[xe]:`$${r.selfColumn}`,[Ue]:`$${r.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&S.push({$match:i}),_r(S,xe,d,s,a),S.push({$sort:{[xe]:1,...d}}),S.push({$project:{_id:0,[xe]:1,[Ue]:1}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate(S).toArray())).map(C=>({sourceId:C[xe],targetId:C[Ue]}))});if(u){let _=new Map;for(let S of p){let E=B(S.targetId);_.has(E)||_.set(E,{_id:S.targetId}),c.get(B(S.sourceId))?.push(_.get(E))}return{grouped:c,docs:[],stats:{strategy:l?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:Z(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let g=st(p.map(_=>_.targetId)),h=await this.loadM2MTargets(t.targetTable,g,o),{docs:y}=h,m=new Map(y.map(_=>[B(_._id),_])),b=0;for(let _ of p){let S=m.get(B(_.targetId)),E=c.get(B(_.sourceId));S&&E&&(E.push(S),b+=1)}return cn(y,h.hideId),{grouped:c,docs:y,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:Z(e)+(g.length>0?Z(g):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+y.length,rowsDiscarded:p.length-b}}}async fetchM2MEdgeBatch(e,t,r,o,i){let s=new Map;for(let m of e)s.set(B(m),[]);let a=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,c=!i&&this.m2mSortCanUseJunction(t.userSort),u=ke(t.userSort).find(m=>m.field==="_id")?.order??1,l=Tt(t.userSort),f=await W(e,async m=>{if(c&&!a)return(await this.runQuery(()=>this.db.collection(r.junctionName).find({[r.selfColumn]:{$in:m}},{projection:{_id:0,[r.selfColumn]:1,[r.otherColumn]:1},sort:{[r.selfColumn]:1,[r.otherColumn]:u}}).toArray())).map(E=>({sourceId:E[r.selfColumn],targetId:E[r.otherColumn]}));let b=[{$match:{[r.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:r.otherColumn,foreignField:"_id",as:Ct}},{$unwind:`$${Ct}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ct}`,{[xe]:`$${r.selfColumn}`,[Ue]:`$${r.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&b.push({$match:i}),b.push({$sort:{[xe]:1,...l}},{$project:{_id:0,[xe]:1,[Ue]:1}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate(b).toArray())).map(S=>({sourceId:S[xe],targetId:S[Ue]}))});if(a){let m=new Map;for(let b of f){let _=B(b.targetId);m.has(_)||m.set(_,{_id:b.targetId}),s.get(B(b.sourceId))?.push(m.get(_))}return{grouped:s,docs:[],stats:{strategy:c?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:Z(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length,rowsDiscarded:0}}}let d=st(f.map(m=>m.targetId)),p=await this.loadM2MTargets(t.targetTable,d,o),{docs:g}=p,h=new Map(g.map(m=>[B(m._id),m])),y=0;for(let m of f){let b=h.get(B(m.targetId)),_=s.get(B(m.sourceId));b&&_&&(_.push(b),y+=1)}return cn(g,p.hideId),{grouped:s,docs:g,stats:{strategy:"m2m-edge-loader",roundtrips:Z(e)+(d.length>0?Z(d):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length+g.length,rowsDiscarded:f.length-y}}}async fetchM2M(e,t,r,o,i){let s=r?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=he(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 c=st(e.map(R=>R._id)),u=new Map;for(let R of e)u.set(B(R._id),[]);if(c.length===0)return{grouped:u,docs:[]};let l=t.userFilter?ce(this.normalizeMetadata(),t.userFilter,t.targetTable):null,f=t.userLimit,d=t.userPage;if(f!==void 0&&(!Number.isSafeInteger(f)||f<0))throw new Error("MongoDB relation limit must be a non-negative safe integer");if(d!==void 0&&(!Number.isSafeInteger(d)||d<1))throw new Error("MongoDB relation page must be a positive safe integer");if(f!==void 0&&f>0){let R=d?(d-1)*f:0;if(!Number.isSafeInteger(R))throw new Error("MongoDB relation pagination offset is too large");return this.fetchM2MTopK(c,t,a,i,l,R,f)}let p=yr(t.userSort);if(!p)return this.fetchM2MEdgeBatch(c,t,a,i,l);let g=await W(c,R=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:R}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:u,docs:[],stats:{strategy:"m2m-batch",roundtrips:Z(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,y=[];for(let R of g){let M=R[a.otherColumn];if(M==null)continue;let N=B(M);h.has(N)||(h.add(N),y.push(M))}if(y.length===0)return{grouped:u,docs:[],stats:{strategy:"m2m-batch",roundtrips:Z(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}};let m=[],b=new Map,_=le(i.projection?._id),S=Pe({_id:{$in:y}},l),E;if(p){E=await W(y,async M=>{let N=Pe({_id:{$in:M}},l),j=an(t.targetTable,N,t.userSort,!0,this.normalizeMetadata());return this.runQuery(()=>this.db.collection(t.targetTable).aggregate(j).toArray())});let R=Tt(t.userSort);E.sort((M,N)=>{for(let[j,O]of Object.entries(R)){let P=(te,k)=>k.split(".").reduce(($,T)=>$?.[T],te),G=ot(P(M,j),P(N,j));if(G!==0)return G*O}return 0})}else{let R=Ke(t.userSort)||{_id:1},M=ln(i.projection,t.userSort),N={sort:R};M.projection&&(N.projection=M.projection),E=await W(y,j=>this.runQuery(()=>this.db.collection(t.targetTable).find(Pe({_id:{$in:j}},l),N).toArray())),Oe(E,i),t.userSort?Mi(E,t.userSort):Ai(E)}let C=new WeakMap;for(let R of E)C.set(R,B(R._id));m=p?Oe(E,i):E;for(let R of m)b.set(C.get(R),R);let x=new Map;for(let R of g){let M=B(R[a.selfColumn]),N=B(R[a.otherColumn]);b.has(N)&&(x.has(N)||x.set(N,[]),x.get(N).push(M))}for(let R of m){let M=x.get(C.get(R))||[];for(let N of M)u.get(N)?.push(R)}un(m,i.projection,p?["__sort_"]:[]),cn(m,_);let v=y.length===0?0:Z(y);return{grouped:u,docs:m,stats:{strategy:"m2m-batch",roundtrips:Z(c)+v,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+m.length}}}};var Rt=class{constructor(e,t,r,o=new We){this.db=e;this.metadata=t;this.fieldRenamesByTable=r;this.executionBudget=o;this.hiddenInverseIds=new WeakSet;this.pkField="_id"}buildSortFromTokens(e){return Ke(e)}compareSortValues(e,t){return ot(e,t)}projectionWithSortFields(e,t){return ln(e,t)}keyOf(e){return B(e)}async fetchM2M(e,t,r,o,i){return new yn(this.db,this.metadata,this.executionBudget).fetchM2M(e,t,r,o,i)}runQuery(e){return this.executionBudget.run(e)}inverseKeyFields(e,t){return[e,...(t.pendingRenames??[]).filter(r=>r.newName===e).map(r=>r.oldName)]}inverseScope(e,t){return e.length===1?{[e[0]]:t}:{$or:e.map(r=>({[r]:t}))}}normalizeInverseKey(e,t,r){for(let o of e){if(o[t]!==void 0)continue;let i=r.find(s=>s!==t&&o[s]!==void 0);i&&(o[t]=o[i])}}normalizeMetadata(){return this.metadata?this.metadata.tables instanceof Map?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortAggregatePipeline(e,t,r,o=!1){return an(e,t,r,o,this.normalizeMetadata())}toObjectId(e){try{return typeof e=="string"?new Di.ObjectId(e):e}catch{return e}}applyPublicProjection(e,t,r=[]){return un(e,t,r)}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){return Ii(e,t,this.fieldRenamesByTable)}async fetchOwner(e,t,r,o){let i=o?.userFilter?ce(this.normalizeMetadata(),o.userFilter,e):null,s=Ke(o?.userSort),a=it(r.projection,["_id"]),c=st(t),u=await W(c,f=>{let d=Pe({_id:{$in:f}},i),p={projection:a};return s&&(p.sort=s),this.runQuery(()=>this.db.collection(e).find(d,p).toArray())}),l=Oe(u,r);return{docs:l,stats:{strategy:"batch-in",roundtrips:Z(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:l.length}}}async fetchInverse(e,t,r,o,i){let s=this.inverseKeyFields(t,o),a=it(o.projection,[...s,"_id"]),c=S=>{if(le(o.projection?._id))for(let E of S)this.hiddenInverseIds.add(E);return S},u=st(r.map(S=>this.toObjectId(S))),l=i?.userFilter?ce(this.normalizeMetadata(),i.userFilter,e):null,f=i?.userLimit,d=i?.userPage,p=yr(i?.userSort);if(f!==void 0&&f>0){let S=d?(d-1)*f:0;if(p)throw new Error(`Dotted sort is not supported for batch relation '${i?.relationName}'`);let E=Tt(i?.userSort),C=await W(u,async x=>{let R=[{$match:Pe(this.inverseScope(s,{$in:x}),l)}];s.length>1&&R.push({$set:{[t]:{$ifNull:s.map(N=>`$${N}`)}}},{$match:{[t]:{$in:x}}}),_r(R,t,E,S,f),R.push({$sort:{[t]:1,...E}}),Ni(R,a,[t]);let M=await this.runQuery(()=>this.db.collection(e).aggregate(R).toArray());return Oe(M,o)});return{docs:c(C),groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:Z(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:C.length}}}if(p){let S=await W(u,async C=>{let x=Pe(this.inverseScope(s,{$in:C}),l),v=this.buildSortAggregatePipeline(e,x,i.userSort);s.length>1&&v.splice(1,0,{$set:{[t]:{$ifNull:s.map(M=>`$${M}`)}}},{$match:{[t]:{$in:C}}});let R=v.find(M=>M.$sort);return R&&(R.$sort={[t]:1,...R.$sort}),a&&v.push({$project:a}),this.runQuery(()=>this.db.collection(e).aggregate(v).toArray())});this.normalizeInverseKey(S,t,s);let E=Oe(S,o);return{docs:c(E),groupKeyField:t,stats:{strategy:"batch-dotted-sort",roundtrips:Z(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:E.length}}}let g=Ke(i?.userSort)||{_id:1},h={projection:a,sort:g},y=await W(u,async S=>{let E=await this.runQuery(()=>this.db.collection(e).find(Pe(this.inverseScope(s,{$in:S}),l),h).toArray());this.normalizeInverseKey(E,t,s);let C=new Set(S.map(x=>B(x)));return E.filter(x=>C.has(B(x[t])))});this.normalizeInverseKey(y,t,s);let m=new Set(u.map(S=>B(S))),b=Array.from(new Map(y.filter(S=>m.has(B(S[t]))).map(S=>[`${B(S[t])}:${B(S._id)}`,S])).values()),_=Oe(b,o);return{docs:c(_),groupKeyField:t,stats:{strategy:"batch-in",roundtrips:Z(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:_.length}}}postProcessInverseChild(e,t,r){this.hiddenInverseIds.delete(e)&&delete e._id,r||delete e[t]}};async function bn(n,e,t,r,o=3,i=0,s,a,c,u){let l=await u?.getActiveFieldRenamesByTable?.(),f=new Rt(n,a,l);await new qe(f,r,c).execute(e,t,o,i,s)}var _n=new WeakMap,Aa=new Set(["__proto__","constructor","prototype"]);function Sr(n){if(n.split(".").some(t=>t.length===0||t.startsWith("$")||Aa.has(t)))throw new Error(`Invalid MongoDB field: ${n}`)}function Ce(n,e){let t=n.$and;if(t===void 0){n.$and=[e];return}if(!Array.isArray(t))throw new Error("Invalid MongoDB $and predicate");t.push(e)}function Li(n){Ce(n,{_id:{$exists:!1,$type:"null"}})}function q(n,e,t){if(Sr(e),!Object.prototype.hasOwnProperty.call(n,e)){n[e]=t;return}let r=n[e];delete n[e],Ce(n,{[e]:r}),Ce(n,{[e]:t})}function Na(n){let e="^";for(let t of String(n))t==="%"?e+="[\\s\\S]*":t==="_"?e+="[\\s\\S]":e+=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&");return`${e}(?![\\s\\S])`}function Oa(n){return Sr(n),n==="_id"?"$_id":`$${n}`}function Ft(n,e,t,r){let o=Oa(e),i=_n.get(n)??[];i.push({ref:o,needle:t,mode:r}),_n.set(n,i)}function wn(n){let e=_n.get(n);if(_n.delete(n),!e?.length)return;let t=[];for(let i of e)t.push(i.ref,{$literal:i.needle},i.mode);let r={$eq:[{$function:{body:pn(),args:t,lang:"js"}},!0]},o=n.$expr;Object.prototype.hasOwnProperty.call(n,"$expr")?n.$expr={$and:[o,r]}:n.$expr=r}function It(n,e,t,r){let o={},i=r==="mongodb"||!r;for(let s of e){Sr(s.field);let a=i&&t&&s.field.startsWith(`${t}.`)?s.field.slice(t.length+1):i||!s.field.includes(".")?s.field:s.field.split(".").pop()??s.field,c=t??"";i&&a==="id"&&(a="_id");let u=V(n,c,a,s.value);switch(Sr(a),s.operator){case"=":q(o,a,u!==null&&typeof u=="object"?{$eq:u}:u);break;case"!=":Sn(n,c,a)?(Ce(o,{[a]:{$ne:null}}),Ce(o,{[a]:{$ne:u}})):q(o,a,{$ne:u});break;case">":q(o,a,{$gt:u});break;case"<":q(o,a,{$lt:u});break;case">=":q(o,a,{$gte:u});break;case"<=":q(o,a,{$lte:u});break;case"like":q(o,a,{$regex:Na(u),$options:"i"});break;case"in":let l=s.value;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(m=>m.trim()):[l]);let f=l.map(m=>V(n,c,a,m)).filter(m=>m!==null);q(o,a,{$in:f});break;case"not in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let p=d.map(m=>V(n,c,a,m));if(p.some(m=>m===null)){Li(o);break}Sn(n,c,a)?(Ce(o,{[a]:{$ne:null}}),Ce(o,{[a]:{$nin:p}})):q(o,a,{$nin:p});break;case"is null":q(o,a,null);break;case"is not null":q(o,a,{$ne:null});break;case"_contains":Ft(o,a,String(u),"contains");break;case"_starts_with":Ft(o,a,String(u),"starts");break;case"_ends_with":Ft(o,a,String(u),"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=V(n,c,a,g[0]),b=V(n,c,a,g[1]);q(o,a,{$gte:m,$lte:b})}break;case"_is_null":let h=s.value===!0||s.value==="true";q(o,a,h?{$eq:null}:{$ne:null});break;case"_is_not_null":let y=s.value===!0||s.value==="true";q(o,a,y?{$ne:null}:{$eq:null});break}}return wn(o),o}function Sn(n,e,t){let o=n?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function $r(n,e,t,r,o,i){switch(Sr(r),o){case"_contains":Ft(e,r,String(i),"contains"),wn(e);break;case"_starts_with":Ft(e,r,String(i),"starts"),wn(e);break;case"_ends_with":Ft(e,r,String(i),"ends"),wn(e);break;case"_eq":{let f=V(n,t,r,i);q(e,r,f!==null&&typeof f=="object"?{$eq:f}:f);break}case"_neq":{let f=V(n,t,r,i);Sn(n,t,r)?(Ce(e,{[r]:{$ne:null}}),Ce(e,{[r]:{$ne:f}})):q(e,r,{$ne:f});break}case"_in":{let f=i;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]);let d=f.map(p=>V(n,t,r,p)).filter(p=>p!==null);q(e,r,{$in:d});break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(f=>f.trim()):[s]);let a=s.map(f=>V(n,t,r,f));if(a.some(f=>f===null)){Li(e);break}Sn(n,t,r)?(Ce(e,{[r]:{$ne:null}}),Ce(e,{[r]:{$nin:a}})):q(e,r,{$nin:a});break;case"_gt":q(e,r,{$gt:V(n,t,r,i)});break;case"_gte":q(e,r,{$gte:V(n,t,r,i)});break;case"_lt":q(e,r,{$lt:V(n,t,r,i)});break;case"_lte":q(e,r,{$lte:V(n,t,r,i)});break;case"_is_null":q(e,r,i===!0||i==="true"?{$eq:null}:{$ne:null});break;case"_is_not_null":q(e,r,i===!0||i==="true"?{$ne:null}:{$eq:null});break;case"_between":let l=i;if(typeof l=="string"&&(l=l.split(",").map(f=>f.trim())),Array.isArray(l)&&l.length===2){let f=V(n,t,r,l[0]),d=V(n,t,r,l[1]);q(e,r,{$gte:f,$lte:d})}break}}var _o=require("mongodb");function vt(n,e){if(e)return n.some(r=>r&&Object.keys(r).length===0)?{}:n.length===0?{_id:{$in:[]}}:n.length===1?n[0]:{$or:n};let t=n.filter(r=>r&&Object.keys(r).length>0);return t.length===0?{}:t.length===1?t[0]:{$and:t}}async function je(n,e,t,r){if(!n||typeof n!="object")return{};let o=t?.tables?.get(e);if(!o)return ce(t,n,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!ye(n,i))return ce(t,n,e);let s=Object.entries(n);if(s.length>1){let l=await Promise.all(s.map(([f,d])=>je({[f]:d},e,t,r)));return vt(l,!1)}if(Array.isArray(n._and)){let l=await Promise.all(n._and.map(f=>je(f,e,t,r)));return vt(l,!1)}if(Array.isArray(n._or)){let l=await Promise.all(n._or.map(f=>je(f,e,t,r)));return vt(l,!0)}if(Object.prototype.hasOwnProperty.call(n,"_not"))return $n(n._not,e,t,r);let{fieldFilters:a,relationFilters:c}=Ae(n,o),u=[];if(a&&Object.keys(a).length>0){let l=ce(t,a,e);l&&Object.keys(l).length>0&&u.push(l)}if(c&&Object.keys(c).length>0)for(let[l,f]of Object.entries(c)){let d=await Pa(l,f,e,o,t,r);d&&Object.keys(d).length>0&&u.push(d)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function $n(n,e,t,r){if(!n||typeof n!="object")return{};let o=t?.tables?.get(e);if(!o)return mn(t,n,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!ye(n,i))return mn(t,n,e);let s=Object.entries(n);if(s.length>1){let l=await Promise.all(s.map(([f,d])=>$n({[f]:d},e,t,r)));return vt(l,!0)}if(Array.isArray(n._and)){let l=await Promise.all(n._and.map(f=>$n(f,e,t,r)));return vt(l,!0)}if(Array.isArray(n._or)){let l=await Promise.all(n._or.map(f=>$n(f,e,t,r)));return vt(l,!1)}if(Object.prototype.hasOwnProperty.call(n,"_not"))return je(n._not,e,t,r);let{fieldFilters:a,relationFilters:c}=Ae(n,o),u=[];if(a&&Object.keys(a).length>0){let l=mn(t,a,e);l&&Object.keys(l).length>0&&u.push(l)}if(c&&Object.keys(c).length>0)for(let[l,f]of Object.entries(c)){let d=await Ba(l,f,e,o,t,r);d&&Object.keys(d).length>0&&u.push(d)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function Pa(n,e,t,r,o,i){let s=(r.relations||[]).find(u=>u.propertyName===n);if(!s)return{};let a=s.targetTableName||s.targetTable,c=o?.tables?.get(a);return!a||!c?{}:s.type==="many-to-one"||s.type==="one-to-one"?ja(e,s,n,a,c,o,i):s.type==="one-to-many"?Ki(e,s,t,a,c,o,i):s.type==="many-to-many"?Ui(e,s,t,a,c,o,i):{}}async function ja(n,e,t,r,o,i,s){let a=X(e)||t,c=kn(n),u=En(c);if(u!==null)return u?{[a]:null}:{[a]:{$ne:null}};let l=So(c);if(l!==null){let g=xn(l.value);if(l.op==="eq")return{[a]:g};if(l.op==="neq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(l.op==="in")return{[a]:{$in:g}};if(l.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(g=>g!=null);return p.length===0?Qe():{[a]:{$in:p}}}async function Ba(n,e,t,r,o,i){let s=(r.relations||[]).find(u=>u.propertyName===n);if(!s)return{};let a=s.targetTableName||s.targetTable,c=o?.tables?.get(a);if(!a||!c)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return Da(e,s,n,a,c,o,i);if(s.type==="one-to-many"){let u=await Ki(e,s,t,a,c,o,i);return Wi(u)}if(s.type==="many-to-many"){let u=await Ui(e,s,t,a,c,o,i);return Wi(u)}return{}}async function Da(n,e,t,r,o,i,s){let a=X(e)||t,c=kn(n),u=En(c);if(u!==null)return u?{[a]:{$ne:null}}:{[a]:null};let l=So(c);if(l!==null){let g=xn(l.value);if(l.op==="eq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(l.op==="neq")return{[a]:g};if(l.op==="in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]};if(l.op==="not_in")return{[a]:{$in:g}}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{[a]:null};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(g=>g!=null);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function Ki(n,e,t,r,o,i,s){let a=H(e)||t,c=kn(n),u=En(c);if(u!==null){let d=await qi(s,r,a,{});return u?d.length===0?{}:{_id:{$nin:d}}:d.length===0?Qe():{_id:{$in:d}}}let l=await Tn(c,r,o,i,s);if(!l||Object.keys(l).length===0)return{};let f=await qi(s,r,a,l);return f.length===0?Qe():{_id:{$in:f}}}async function Ui(n,e,t,r,o,i,s){let a=he(t,e);if(!a)return{};let c=kn(n),u=En(c);if(u!==null){let h=await wo(s,a,r,null);return u?h.length===0?{}:{_id:{$nin:h}}:h.length===0?Qe():{_id:{$in:h}}}let l=So(c);if(l!==null){let h=xn(l.value),y=Array.isArray(h)?h:[h],m=await wo(s,a,r,{_id:l.op==="neq"||l.op==="not_in"?{$nin:y,$ne:null}:{$in:y}});return m.length===0?Qe():{_id:{$in:m}}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(h=>h!=null);if(p.length===0)return Qe();let g=await wo(s,a,r,{_id:{$in:p}});return g.length===0?Qe():{_id:{$in:g}}}async function Tn(n,e,t,r,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return ye(n,i)?je(n,e,r,o):ce(r,n,e)}async function qi(n,e,t,r){let o=await n.collection(e).find(r,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let c=a[t];if(c==null)continue;let u=String(c);i.has(u)||(i.add(u),s.push(c))}return s}function Qe(){return{_id:{$in:[]}}}function La(n){if(!n||typeof n!="object")return!1;let e=Object.keys(n);if(e.length!==1||e[0]!=="_id")return!1;let t=n._id;return!!t&&typeof t=="object"&&Array.isArray(t.$in)&&t.$in.length===0}function Wi(n){if(!n||Object.keys(n).length===0)return Qe();if(La(n))return{};let e=n._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:[n]}}async function wo(n,e,t,r){let o=null;r&&t&&(o=(await n.collection(t).find(r,{projection:{_id:1}}).toArray()).map(l=>l._id).filter(l=>l!=null));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await n.collection(e.junctionName).find(i,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,c=[];for(let u of s){let l=u[e.selfColumn];if(l==null)continue;let f=String(l);a.has(f)||(a.add(f),c.push(l))}return c}function kn(n){return n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===1&&n.id&&typeof n.id=="object"?n.id:n}function En(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=Object.keys(n);if(e.length!==1)return null;let t=e[0],r=n[t];return t==="_is_null"?r===!0:t==="_is_not_null"?r!==!0:t==="_eq"?r===null?!0:null:t==="_neq"&&r===null?!1:null}function xn(n){if(Array.isArray(n))return n.map(e=>xn(e));if(typeof n!="string")return n;try{return new _o.ObjectId(n)}catch{return n}}function So(n){if(Array.isArray(n))return{op:"in",value:n};if(n instanceof _o.ObjectId)return{op:"eq",value:n};if(n==null)return null;if(typeof n!="object")return{op:"eq",value:n};if(!n||typeof n!="object"||Array.isArray(n))return null;let e=Object.keys(n);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:n._eq}:t==="_neq"?{op:"neq",value:n._neq}:t==="_in"&&Array.isArray(n._in)?{op:"in",value:n._in}:t==="_not_in"&&Array.isArray(n._not_in)?{op:"not_in",value:n._not_in}:null}function Tr(n){let{targetTable:e,localField:t,foreignField:r,alias:o,pipeline:i,junction:s}=n,a=u=>({$match:{$expr:{$and:[{$ne:[{$ifNull:["$$localId",null]},null]},{$ne:[{$ifNull:[`$${u}`,null]},null]},{$eq:[`$${u}`,"$$localId"]}]}}});if(!s)return{$lookup:{from:e,let:{localId:`$${t}`},pipeline:[a(r),...i],as:o}};let c="__enfyra_sorted_relation_target__";return{$lookup:{from:s.junctionName,let:{localId:`$${t}`},pipeline:[a(s.selfColumn),Tr({targetTable:e,localField:s.otherColumn,foreignField:r,alias:c,pipeline:[]}),{$unwind:`$${c}`},{$replaceRoot:{newRoot:`$${c}`}},...i],as:o}}}wt();async function $o(n,e,t,r,o=1){if(o>me)throw new Error(`MongoDB lookup exceeds maximum relation depth of ${me}`);let i=n?.tables?.get(e);if(!i)throw new Error(`Metadata not found for lookup table '${e}'`);let s=i.relations??[],a=t.map(g=>g==="id"&&!i.columns?.some(h=>h.name==="id")?"_id":g),c=await tt(n,e,a),u=[],l=new Map;if(r&&["_and","_or","_not"].some(g=>Object.prototype.hasOwnProperty.call(r,g))){if(ye(r,new Set(s.map(h=>h.propertyName))))throw new Error(`Logical relation filter is not supported inside nested lookup '${e}'`);let g=ce(n,r,e);Object.keys(g).length>0&&u.push({$match:g})}else if(r){let g={};for(let[h,y]of Object.entries(r)){let m=s.find(_=>_.propertyName===h),b=y&&typeof y=="object"&&Object.keys(y).every(_=>de.has(_));if(m&&y&&typeof y=="object"&&!b)l.set(h,y);else if(y&&typeof y=="object")for(let[_,S]of Object.entries(y))$r(n,g,e,h,_,S);else $r(n,g,e,h,"_eq",y)}Object.keys(g).length>0&&u.push({$match:g})}let d=[...c.relations];for(let g of l.keys()){if(d.some(m=>m.propertyName===g))continue;let h=s.find(m=>m.propertyName===g),y=h.type==="one-to-many"||ge(h);d.push({propertyName:g,targetTable:h.targetTableName||h.targetTable,localField:y||h.type==="many-to-many"?"_id":X(h)||g,foreignField:y&&h.type!=="many-to-many"?H(h)||g:"_id",type:h.type==="one-to-many"||h.type==="many-to-many"?"many":"one",nestedFields:["_id"]})}for(let g of d){let h=s.find(b=>b.propertyName===g.propertyName),y=l.get(g.propertyName),m=await $o(n,g.targetTable,g.nestedFields.length?g.nestedFields:["_id"],y,o+1);g.type==="one"&&m.push({$limit:1}),u.push(Tr({targetTable:g.targetTable,localField:h?.type==="many-to-many"?"_id":g.localField,foreignField:g.foreignField,alias:g.propertyName,pipeline:m,junction:h?.type==="many-to-many"?he(e,h):null})),g.type==="one"&&u.push({$unwind:{path:`$${g.propertyName}`,preserveNullAndEmptyArrays:!0}}),y&&u.push({$match:g.type==="one"?{[g.propertyName]:{$ne:null}}:{[`${g.propertyName}.0`]:{$exists:!0}}})}let p={_id:1};for(let g of c.scalarFields)p[g]=1;for(let g of c.relations)p[g.propertyName]=1;return u.push({$project:p}),u}async function Qi(n,e,t,r,o){let i={_id:1};for(let s of r)i[s]=1;for(let s of o)s.type==="one"&&s.localField&&(i[s.localField]=1);e.push({$project:i})}function To(n,e){if(!n||typeof n!="object"||Array.isArray(n))return!1;let t=Object.entries(n);return t.length>0&&t.every(([r,o])=>r===e?!0:r==="_not"?To(o,e):r==="_and"||r==="_or"?Array.isArray(o)&&o.length>0&&o.every(i=>To(i,e)):!1)}function Cn(n,e){if(!n||typeof n!="object"||Array.isArray(n))return;let t=[];if(Object.prototype.hasOwnProperty.call(n,e)&&t.push(n[e]),Array.isArray(n._and)){let r=n._and.map(o=>Cn(o,e)).filter(o=>o!==void 0);t.push(...r)}if(Array.isArray(n._or)&&n._or.length>0){let r=n._or.map(o=>Cn(o,e));r.every(o=>o!==void 0)&&t.push({_or:r})}if(To(n._not,e)){let r=Cn(n._not,e);r!==void 0&&t.push({_not:r})}if(t.length!==0)return t.length===1?t[0]:{_and:t}}async function Fn(n,e,t){let r=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,c=t.execute!==!1;e.deep!==void 0&&rt(e.table,e.deep,i);let u=e.offset??0,l=e.limit===0?void 0:e.limit;if(!Number.isSafeInteger(u)||u<0)throw new Error("MongoDB offset must be a non-negative safe integer");if(l!=null&&(!Number.isSafeInteger(l)||l<0))throw new Error("MongoDB limit must be a non-negative safe integer");!e.mongoRawFilter&&e.plan?.rawFilter&&(e={...e,mongoRawFilter:e.plan.rawFilter});let f=i?.tables?.get(e.table),d=new Set((f?.relations??[]).map(T=>T.propertyName)),p=!!e.mongoRawFilter&&!!i&&ye(e.mongoRawFilter,d),g=e.plan,h=g?.filterTree&&!g.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&p){let T=await je(e.mongoRawFilter,e.table,i,o);T&&Object.keys(T).length>0&&r.push({$match:T})}else if(h){let T=xt(g.filterTree,{metadata:i,rootTable:e.table});Object.keys(T).length>0&&r.push({$match:T})}else if(e.mongoRawFilter){let T=ce(i,e.mongoRawFilter,e.table);Object.keys(T).length>0&&r.push({$match:T})}else if(e.where){let T=It(i,e.where,e.table,s);r.push({$match:T})}let y=e.plan,b=y?y.hasRelationSort:e.sort?.some(T=>{if(!T.field.includes("."))return!1;let F=T.field.split(".")[0];return d.has(F)||(e.mongoFieldsExpanded?.relations?.some(L=>L.propertyName===F)??!1)})??!1,_=(T,F=e.table)=>{let L=T.split("."),A=F;for(let J of L.slice(0,-1)){let K=i?.tables?.get(A)?.relations?.find(Fe=>Fe.propertyName===J);if(!K)return T;A=K.targetTableName||K.targetTable}let Re=i?.tables?.get(A);return L.at(-1)==="id"&&!Re?.columns?.some(J=>J.name==="id")&&(L[L.length-1]="_id"),L.join(".")},S=()=>{let T=y?.sortItems?.length?gr(y.sortItems):e.sort?.length?Object.fromEntries(e.sort.map(F=>[_(F.field),F.direction==="desc"?-1:1])):null;return T&&Object.keys(T).length>0?T:null},E=y?.sortItems?$i(y.sortItems):[],C=y?.sortItems?Ti(y.sortItems):[],x=new Set((i?.tables?.get(e.table)?.columns??[]).map(T=>T.name));for(let T of e.mongoCountOnly?[]:[...E,...C])if(x.has(T))throw new Error(`MongoDB relation sort alias conflicts with a root field: ${T}`);let v=()=>{!y||E.length===0||ki(r,e.table,y.sortItems,i)},R=()=>{!y||C.length===0||Ei(r,e.table,y.sortItems,i)},M=()=>{let T=[...E,...C];T.length===0||e.mongoCountOnly||r.push({$project:Object.fromEntries(T.map(F=>[F,0]))})};if(!e.mongoFieldsExpanded){if(b&&!e.mongoCountOnly&&(y?.sortItems.some(F=>!F.function&&F.joinId!==null)??!0))throw new Error("MongoDB relation sort requires expanded relation fields");if(!e.mongoCountOnly){v(),R();let F=S();F&&r.push({$sort:F})}if(e.mongoCountOnly?r.push({$count:"count"}):(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l})),M(),!e.mongoCountOnly&&e.select?.length){let F={_id:0};for(let L of e.select)F[_(L)]=1;r.push({$project:F})}if(a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:[...r]}),!c)return{results:[],pipeline:r};let T=await n.aggregate(r).toArray();return e.mongoCountOnly?{results:T,pipeline:r}:{results:Rn(T),pipeline:r}}let{scalarFields:N,relations:j}=e.mongoFieldsExpanded;if(!b){if(!e.mongoCountOnly){v(),R();let T=S();T&&r.push({$sort:T})}e.mongoCountOnly||(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l}))}let O=new Set(e.mongoCountOnly?[]:y?.sortItems.filter(T=>T.joinId!==null&&!T.function).map(T=>T.fullPath.split(".")[0])??e.sort?.filter(T=>T.field.includes(".")&&(d.has(T.field.split(".")[0])||j.some(F=>F.propertyName===T.field.split(".")[0]))).map(T=>T.field.split(".")[0])??[]);for(let T of O)if(!j.some(F=>F.propertyName===T))throw new Error(`MongoDB relation sort expansion is missing for '${T}'`);let P=j,G=new Map,te=new Set([...x,...j.map(T=>T.propertyName)]);for(let T of j){if(!O.has(T.propertyName))continue;let F=`__enfyra_relation_sort_${G.size}`;for(;te.has(F);)F+="_";te.add(F),G.set(T.propertyName,F);let L=(y?.sortItems??e.sort?.map(K=>({fullPath:K.field,direction:K.direction,function:void 0}))??[]).filter(K=>!K.function&&K.fullPath.startsWith(`${T.propertyName}.`)),A=L.map(K=>K.fullPath.slice(T.propertyName.length+1)),Re=await $o(i,T.targetTable,A.length?A:["_id"],Cn(e.mongoRawFilter,T.propertyName)),J=Object.create(null);for(let K of L){let Fe=K.fullPath.slice(T.propertyName.length+1);J[y?Fe:_(Fe,T.targetTable)]=K.direction==="desc"?-1:1}J._id===void 0&&(J._id=1),Re.push({$sort:J},{$limit:1});let U=i?.tables?.get(e.table)?.relations?.find(K=>K.propertyName===T.propertyName);r.push(Tr({targetTable:T.targetTable,localField:U?.type==="many-to-many"?"_id":T.localField,foreignField:T.foreignField,alias:F,pipeline:Re,junction:U?.type==="many-to-many"?he(e.table,U):null})),r.push({$unwind:{path:`$${F}`,preserveNullAndEmptyArrays:!0}})}if(b){if(!e.mongoCountOnly){v(),R();let T=S();if(T){let F=Object.create(null);for(let[L,A]of Object.entries(T)){let[Re,...J]=L.split("."),U=G.get(Re);F[U&&J.length?`${U}.${J.join(".")}`:L]=A}r.push({$sort:F})}}e.mongoCountOnly||(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l}))}if(e.mongoCountOnly?r.push({$count:"count"}):(M(),await Qi(i,r,e.table,N,[...j])),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:[...r]}),!c)return{results:[],pipeline:r};let k=performance.now(),$=await n.aggregate(r).toArray();if(e.debugTrace?.dur("db_execute",k,{table:e.table}),e.mongoCountOnly)return{results:$,pipeline:r};if(P.length>0&&$.length>0){let T=e.deep||{},F=P.map(A=>{let J=i?.tables?.get(e.table)?.relations?.find(Kn=>Kn.propertyName===A.propertyName),U=T[A.propertyName],K=U?.limit===void 0?void 0:Number(U.limit),Fe=U?.page===void 0?void 0:Number(U.page);if(K!==void 0&&(!Number.isSafeInteger(K)||K<0))throw new Error("MongoDB relation limit must be a non-negative safe integer");if(Fe!==void 0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new Error("MongoDB relation page must be a positive safe integer");let ws=U?.fields!=null?Array.isArray(U.fields)?U.fields:String(U.fields).split(",").map(Kn=>Kn.trim()).filter(Boolean):A.nestedFields&&A.nestedFields.length>0?A.nestedFields:["_id"];return{relationName:A.propertyName,type:J?.type,targetTable:A.targetTable,fields:ws,isInverse:J?.isInverse,mappedBy:J?.mappedBy,junctionTableName:J?.junctionTableName,junctionSourceColumn:J?.junctionSourceColumn,junctionTargetColumn:J?.junctionTargetColumn,localField:A.localField,foreignField:A.foreignField,injectedParentFields:A.type==="one"&&A.localField&&A.localField!==A.propertyName&&!N.includes(A.localField)?[A.localField]:void 0,userFilter:U?.filter,userSort:U?.sort,userLimit:K,userPage:Fe,nestedDeep:U?.deep}}),L=ko(i);if(!L)throw new Error("MongoDB relation hydration requires metadata");await bn(o,$,F,L,3,0,e.table,i,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Rn($),pipeline:r}}function ko(n){let e=n;return e?async t=>{let r=e.tables?.get(t);return r?{name:r.name,columns:(r.columns||[]).map(o=>({name:o.name,type:o.type})),relations:r.relations||[]}:null}:null}function zi(n){if(n===null||typeof n!="object")return!1;let e=new WeakSet,t=[n];for(;t.length>0;){let r=t.pop();if(!e.has(r)){if(e.add(r),Array.isArray(r)){for(let o of r)o&&typeof o=="object"&&t.push(o);continue}for(let[o,i]of Object.entries(r)){if(i===null){if(o==="_eq"||o==="$eq")return!0;continue}if(!(!i||typeof i!="object")){if(Object.prototype.hasOwnProperty.call(i,"_is_null")&&(i._is_null===!0||i._is_null==="true")||Object.prototype.hasOwnProperty.call(i,"_eq")&&i._eq===null||Object.prototype.hasOwnProperty.call(i,"$eq")&&i.$eq===null)return!0;t.push(i)}}}}return!1}function Rn(n){return n.map(se)}function Ji(n,e){let t=[],r=[],o=e?.tables?.get(n.rootTable);if(!o)return{scalarFields:t,relations:r};for(let i of n.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"&&r.push(qa(i,o,e));return{scalarFields:t,relations:r}}function qa(n,e,t){let r=e.relations?.find(u=>u.propertyName===n.propertyName),o,i,s=!1;n.relationType==="many-to-one"||n.relationType==="one-to-one"?r&&ge(r)?(o="_id",i=H(r)||n.propertyName,s=!0):(o=r&&X(r)||n.propertyName,i="_id",s=!1):n.relationType==="one-to-many"?(o="_id",i=r&&H(r)||n.propertyName,s=!0):r?.mappedBy?(o="_id",i=r.mappedBy,s=!0):(o=n.propertyName,i="_id",s=!1);let a=n.relationType==="one-to-many"||n.relationType==="many-to-many",c=Hi(n.children);return{propertyName:n.propertyName,targetTable:n.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:c}}function Hi(n){let e=[];for(let t of n)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let r=Hi(t.children);if(r.length===0)e.push(`${t.propertyName}.id`);else for(let o of r)e.push(`${t.propertyName}.${o}`)}return e}Le();re();var Wa=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Ka=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),Ua=new Set(["hour","day","week","month","year"]),Qa=new Set(["count","countDistinct","sum","avg","min","max"]);function D(n,e){throw new w(e,{path:n})}function Mt(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function za(n,e){let t=n?.tables?.get(e);return t||D("aggregate",`Table "${e}" metadata is not available`),t}function Vi(n,e,t){let r=n.columns?.find(o=>o.name===e);return r||D(t,`Unknown aggregate field "${e}"`),r.isEncrypted===!0&&D(t,`Encrypted field "${e}" cannot be used in aggregate queries`),r}function Ja(n,e){let t=n===void 0?"UTC":n;(typeof t!="string"||t.length===0)&&D(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{D(e,`Invalid aggregate timezone "${t}"`)}return t}function Ha(n,e){return n==null?{}:(Mt(n)||D(e,"Aggregate filter must be an object"),n)}function Gi(n,e,t){let r;return typeof n=="number"?r=n:typeof n=="string"&&/^\d+$/.test(n)?r=Number(n):D(e,t),Number.isSafeInteger(r)||D(e,t),r}function At(n,e,t){Mt(n)||D("aggregate","Aggregate options must be an object");let r=za(t,e),o=n.dimensions===void 0?[]:n.dimensions,i=n.measures;Array.isArray(o)||D("aggregate.dimensions","Aggregate dimensions must be an array"),(!Mt(i)||Object.keys(i).length===0)&&D("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=o.map((m,b)=>{let _=`aggregate.dimensions[${b}]`;(!Mt(m)||typeof m.field!="string"||m.field.length===0)&&D(_,"Aggregate dimension requires a field");let S=Vi(r,m.field,`${_}.field`);return s.has(m.field)&&D(`${_}.field`,`Duplicate aggregate dimension "${m.field}"`),s.add(m.field),m.bucket===void 0?(m.timezone!==void 0&&D(`${_}.timezone`,"Aggregate timezone requires a bucket"),{field:m.field,outputKey:m.field,column:S}):((typeof m.bucket!="string"||!Ua.has(m.bucket))&&D(`${_}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Ka.has(String(S.type).toLowerCase())||D(`${_}.bucket`,`Aggregate bucket requires a date field, but "${m.field}" is "${S.type}"`),{field:m.field,outputKey:m.field,bucket:m.bucket,timezone:Ja(m.timezone,`${_}.timezone`),column:S})}),c=new Set,u=Object.entries(i).map(([m,b])=>{let _=`aggregate.measures.${m}`;(!m||!Mt(b))&&D(_,"Aggregate measure must be an object");let S=Object.entries(b);S.length!==1&&D(_,"Aggregate measure must define exactly one operation");let[E,C]=S[0];Qa.has(E)||D(_,`Unsupported aggregate measure "${E}"`),(typeof C!="string"||C.length===0)&&D(_,"Aggregate measure field must be a non-empty string");let x=Vi(r,C,`${_}.${E}`);return(c.has(m)||s.has(m))&&D(_,`Aggregate output key "${m}" is duplicated`),c.add(m),["sum","avg","min","max"].includes(E)&&!Wa.has(String(x.type).toLowerCase())&&D(_,`Aggregate ${E} requires a numeric field, but "${C}" is "${x.type}"`),{outputKey:m,operation:E,field:C,column:x}}),l=n.sort===void 0?[]:n.sort;Array.isArray(l)||D("aggregate.sort","Aggregate sort must be an array");let f=new Set([...s,...c]),d=l.map((m,b)=>{let _=`aggregate.sort[${b}]`;return(!Mt(m)||typeof m.field!="string"||!f.has(m.field))&&D(_,"Aggregate sort field must reference a dimension or measure output"),m.direction!=="asc"&&m.direction!=="desc"&&D(`${_}.direction`,"Aggregate sort direction must be asc or desc"),{field:m.field,direction:m.direction}}),p="Aggregate limit must be an integer between 1 and 10000",g="Aggregate page must be a positive integer",h=n.limit===void 0?void 0:Gi(n.limit,"aggregate.limit",p),y=n.page===void 0?1:Gi(n.page,"aggregate.page",g);return h!==void 0&&(h<=0||h>1e4)&&D("aggregate.limit",p),y<=0&&D("aggregate.page",g),{tableName:e,filter:Ha(n.filter,"aggregate.filter"),dimensions:a,measures:u,sort:d,page:y,limit:h}}var lt=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.db=e.getDb()}async execute(e){let t={metadata:e.metadata,dbType:e.dbType||"mongodb",debugLog:e.debugLog,execute:!e.debugMode};if(!e.plan){let m=new pe;e={...e,plan:m.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"})}}e={...e,fields:e.plan.rawFields};let r=e.plan.rawFields!==void 0&&e.plan.rawFields.length===0&&!Object.keys(e.deep??{}).length;e.deep!==void 0&&rt(e.tableName,e.deep,e.metadata);let o={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};e.pipeline&&(o.pipeline=e.pipeline),r?(o.fields=["_id"],o.mongoFieldsExpanded={scalarFields:["_id"],relations:[]}):e.fields&&(Array.isArray(e.fields)?o.fields=e.fields:typeof e.fields=="string"&&(o.fields=e.fields.split(",").map(m=>m.trim())));let i=e.filter??e.plan?.rawFilter;if(i&&(De(i,e.tableName,e.metadata),o.mongoRawFilter=i),e.sort){let m=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(b=>b.trim());o.sort=m.map(b=>{let _=b.trim();return _.startsWith("-")?{field:_.substring(1),direction:"desc"}:{field:_,direction:"asc"}})}else o.sort=[{field:"id",direction:"asc"}];let s=this.normalizePaginationValue(e.page,"page",1),a=this.normalizePaginationValue(e.limit,"limit",0);if(s!==void 0&&a===void 0)throw new Error("limit is required when page is provided");s!==void 0&&a!==void 0?(o.offset=(s-1)*a,o.limit=a):a!==void 0&&(o.limit=a);let c=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(m=>m.trim()).filter(Boolean),u=0,l=0;(c.includes("totalCount")||c.includes("*"))&&(u=await this.mongoService.collection(e.tableName).countDocuments({}));let f=t.metadata?.tables?.get(e.tableName),d=new Set((f?.relations??[]).map(m=>m.propertyName)),p=!!o.mongoRawFilter&&ye(o.mongoRawFilter,d);if((c.includes("filterCount")||c.includes("*"))&&!p){let m=this.mongoService.collection(e.tableName),b=e.plan?.filterTree?xt(e.plan.filterTree,{metadata:t.metadata,rootTable:e.tableName}):{};l=await m.countDocuments(b)}o.plan=e.plan,o.deep=e.deep;let g=await this.selectLegacy(o,t),h=r?g.results.map(()=>({})):g.results,y=typeof this.mongoService?.parseResult=="function"?await this.mongoService.parseResult(h,e.tableName):h;if(e.debugMode){let m;try{m=await this.db.collection(e.tableName).aggregate(g.pipeline).explain()}catch(b){m={error:String(b)}}return{pipeline:g.pipeline,explain:m}}if(p&&(c.includes("filterCount")||c.includes("*"))){let m={...o,pipeline:void 0,mongoCountOnly:!0},b=await this.selectLegacy(m,t);l=b.results.length>0?b.results[0].count:0}return{data:y,...c.length>0&&{meta:{...c.includes("totalCount")||c.includes("*")?{totalCount:u}:{},...c.includes("filterCount")||c.includes("*")?{filterCount:l}:{}}}}}async aggregate(e){let t=At(e.aggregate,e.tableName,e.metadata),r=this.db.collection(e.tableName),o=new pe().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),i=o.hasRelationFilters?await je(t.filter,e.tableName,e.metadata,this.db):o.filterTree?xt(o.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(i).length>0&&s.push({$match:i});let a={_id:{}},c={};for(let l of t.dimensions){let f=`$${l.field}`,d=l.bucket?{$dateTrunc:{date:f,unit:l.bucket,timezone:l.timezone}}:f;a._id[l.outputKey]=d,c[l.outputKey]=`$_id.${l.outputKey}`}for(let l of t.measures){let f=`$${l.field}`;a[l.outputKey]=l.operation==="count"?{$sum:{$cond:[{$ne:[{$ifNull:[f,null]},null]},1,0]}}:l.operation==="countDistinct"?{$addToSet:f}:{[`$${l.operation}`]:f},c[l.outputKey]=l.operation==="countDistinct"?{$size:{$setDifference:[`$${l.outputKey}`,[null]]}}:`$${l.outputKey}`}return s.push({$group:a},{$project:{_id:0,...c}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(l=>[l.field,l.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),e.debugMode?{pipeline:s,explain:await r.aggregate(s).explain()}:{data:(await r.aggregate(s).toArray()).map(se)}}normalizePaginationValue(e,t,r){if(e==null)return;let o;if(typeof e=="number")o=e;else if(typeof e=="string"&&/^\d+$/.test(e))o=Number(e);else throw new Error(`${t} must be a ${r===1?"positive":"non-negative"} integer`);if(!Number.isSafeInteger(o)||o<r)throw new Error(`${t} must be a ${r===1?"positive":"non-negative"} integer`);return o}async selectLegacy(e,t){let r=[],o=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=t.metadata?.tables?.get(e.table),s=i?.relations&&i.relations.length>0;if(!e.mongoFieldsExpanded&&(e.fields&&e.fields.length>0||o||s)){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=Ji(l.fieldTree,t.metadata),o){let d=await tt(t.metadata,e.table,[],e.deep),p=new Set(e.mongoFieldsExpanded.relations.map(g=>g.propertyName));e.mongoFieldsExpanded.relations.push(...d.relations.filter(g=>!p.has(g.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await tt(t.metadata,e.table,f,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let d=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:d.scalarFields},r=d.hiddenFields}}e.where&&(e.where=e.where.map(l=>l.field.includes(".")?l:{...l,field:`${e.table}.${l.field}`}));let a=this.db.collection(e.table);if(e.pipeline)return t.debugLog?.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),t.execute?{results:(await a.aggregate(e.pipeline).toArray()).map(se),pipeline:e.pipeline}:{results:[],pipeline:e.pipeline};let{results:c,pipeline:u}=await Fn(a,e,{db:this.db,metadata:t.metadata,dbType:t.dbType,debugLog:t.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService,execute:t.execute});return this.mongoPhysicalMigrationService&&t.execute?{results:await this.mongoPhysicalMigrationService.applyReadFallback(e.table,c,r),pipeline:u}:{results:c,pipeline:u}}};Le();var Yi=require("util"),In=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;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{try{t=(0,Yi.inspect)(e,{depth:4,maxArrayLength:100,maxStringLength:4e3,customInspect:!1,getters:!1})}catch{t="[Unserializable]"}}return this.context?`[${this.context}] ${t}`:t}};Se();Se();var Va=new Set(["_and","_or","_not"]),Ga=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]);function ct(n){if(!n||typeof n!="object")return!1;let e=new WeakSet,t=[n];try{for(;t.length>0;){let r=t.pop();if(e.has(r))continue;e.add(r);let o=Object.getOwnPropertyDescriptors(r);for(let[i,s]of Object.entries(o)){if(!s.enumerable)continue;if(s.get||s.set||Va.has(i))return!0;if(Ga.has(i))continue;let a=s.value;a&&typeof a=="object"&&t.push(a)}}}catch{return!0}return!1}var Eo=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"],Ya=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kr(n){if(typeof n!="string"||!Ya.test(n))throw new Error("Invalid UUID filter value")}function Xa(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Za(n){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[n]||n}function vn(n,e,t){if(!t)return!1;let r=n;if(n.includes(".")){let s=n.split(".");r=s[s.length-1]}let o=t.columns.find(s=>s.name===r);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function el(n,e,t,r,o){return r!=="postgres"||typeof e!="string"||vn(n,t,o)&&kr(e),e}function Xi(n,e,t,r,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,c=ze(a,i??"postgres"),u=vn(e,o,s),l=["_eq","_neq","_gt","_gte","_lt","_lte"].includes(t)?el(e,r,o,i,s):r;switch(t){case"_eq":r===null?n.whereNull(a):u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} = ?::uuid`,[r]):n.where(a,"=",l);break;case"_neq":r===null?n.whereNotNull(a):u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} != ?::uuid`,[r]):n.where(a,"!=",l);break;case"_gt":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} > ?::uuid`,[r]):n.where(a,">",l);break;case"_gte":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} >= ?::uuid`,[r]):n.where(a,">=",l);break;case"_lt":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} < ?::uuid`,[r]):n.where(a,"<",l);break;case"_lte":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} <= ?::uuid`,[r]):n.where(a,"<=",l);break;case"_in":let f=r;if(Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&i==="postgres"){for(let p of f)kr(p);n.whereRaw(`${c} = ANY(?::uuid[])`,[f])}else n.whereIn(a,f);break;case"_not_in":case"_nin":let d=r;if(Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(p=>p.trim()):[d]),u&&i==="postgres"){for(let p of d)kr(p);n.whereRaw(`${c} != ALL(?::uuid[])`,[d])}else n.whereNotIn(a,d);break;case"_contains":case"_starts_with":case"_ends_with":{let p=Xa(r),g=t==="_contains"?`%${p}%`:t==="_starts_with"?`${p}%`:`%${p}`;i==="postgres"?n.whereRaw(`lower(unaccent(${c})) ILIKE lower(unaccent(?)) ESCAPE '='`,[g]):i==="sqlite"?n.whereRaw(`lower(${c}) LIKE lower(?) ESCAPE '='`,[g]):n.whereRaw(`lower(${c}) COLLATE utf8mb4_general_ci LIKE lower(?) COLLATE utf8mb4_general_ci ESCAPE '='`,[g]);break}case"_between":if(!Array.isArray(r)||r.length!==2)throw new Error("Invalid SQL _between filter");n.whereBetween(a,[r[0],r[1]]);break;case"_is_null":r===!0?n.whereNull(a):n.whereNotNull(a);break;case"_is_not_null":r===!0?n.whereNotNull(a):n.whereNull(a);break;default:n.where(a,Za(t),r)}}function tl(n,e,t){if(n==="_and"||n==="_or"||n==="_not"||!t)return!0;let r=n.split(".");if(r.length>1&&(!e||r[0]!==e))return!1;let o=r[r.length-1],i=t.columns?.some(a=>a.name===o),s=t.relations?.some(a=>a.propertyName===o);return i||s}function Nt(n,e,t,r="and",o,i){if(!(!e||typeof e!="object")){if(Object.keys(e).length===0){n.whereRaw("1 = 1");return}if(Array.isArray(e)){for(let s of e)r==="and"?n.where(function(){Nt(this,s,t,"and",o,i)}):n.orWhere(function(){Nt(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e)){if(!tl(s,t,i))throw new Error(`Invalid SQL filter field: ${s}`);if(s==="_and"){if(Array.isArray(a)){if(a.length===0){n.whereRaw("1 = 1");continue}n.where(function(){for(let c of a)this.where(function(){Nt(this,c,t,"and",o,i)})})}continue}if(s==="_or"){if(Array.isArray(a)){if(a.length===0){n.whereRaw("1 = 0");continue}n.where(function(){for(let c of a)this.orWhere(function(){Nt(this,c,t,"and",o,i)})})}continue}if(s==="_not"){let c=function(){Nt(this,a,t,"and",o,i)};r==="or"?n.orWhereNot(c):n.whereNot(c);continue}if(typeof a=="object"&&a!==null){let c=Object.keys(a),u=c.some(l=>Eo.includes(l));if(u&&c.some(l=>!Eo.includes(l)))throw new Error(`Invalid SQL filter operator for field: ${s}`);if(u)for(let[l,f]of Object.entries(a))Eo.includes(l)&&(r==="and"?n.where(function(){Xi(this,s,l,f,t,o,i)}):n.orWhere(function(){Xi(this,s,l,f,t,o,i)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s,f=ze(l,o??"postgres");vn(s,t,i)&&o==="postgres"&&typeof a=="string"?(kr(a),r==="and"?n.whereRaw(`${f} = ?::uuid`,[a]):n.orWhereRaw(`${f} = ?::uuid`,[a])):r==="and"?n.where(l,"=",a):n.orWhere(l,"=",a)}}else{let c=t&&!s.includes(".")?`${t}.${s}`:s,u=ze(c,o??"postgres"),l=vn(s,t,i);a===null?r==="and"?n.whereNull(c):n.orWhereNull(c):l&&o==="postgres"&&typeof a=="string"?(kr(a),r==="and"?n.whereRaw(`${u} = ?::uuid`,[a]):n.orWhereRaw(`${u} = ?::uuid`,[a])):r==="and"?n.where(c,"=",a):n.orWhere(c,"=",a)}}}}function ut(n,e,t,r,o){return!e||typeof e!="object"||Nt(n,e,t,"and",r,o),n}function Zi(n){let e=String(n??0);if(!/^\d+$/.test(e))throw new Error("Database count is not a non-negative integer");let t=Number(e);if(!Number.isSafeInteger(t))throw new Error("Database count exceeds JavaScript safe integer range");return t}async function Mn(n,e,t,r,o){let i={};if(r.includes("totalCount")||r.includes("*")){let s=await n(t).count("* as count").first();i.totalCount=Zi(s?.count)}if(r.includes("filterCount")||r.includes("*")){let s=e.clone().clearOrder().clear("limit").clear("offset"),a=await n.from(s.as("enfyra_count_source")).count("* as count").first();i.filterCount=Zi(a?.count)}return i}function Er(n,e,t){if(!n||!t)return n;let r=t.tables?.get(e);if(!r)return n;if(Array.isArray(n))return n.map(i=>Er(i,e,t));if(typeof n!="object"||Buffer.isBuffer(n))return n;let o={...n};for(let i of r.columns)if(i.type==="simple-json"&&o[i.name]&&typeof o[i.name]=="string")try{o[i.name]=JSON.parse(o[i.name])}catch{}for(let i of r.relations??[]){let s=i.propertyName;if(!Object.prototype.hasOwnProperty.call(o,s))continue;let a=i.targetTableName||i.targetTable;a&&(o[s]=Er(o[s],a,t))}return o}var os=require("crypto");ft();Se();var rl=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);function es(n,e){if(!e)return!1;let t=e.columns.find(o=>o.name===n);if(!t)return!1;let r=t.type?.toLowerCase()||"";return r==="uuid"||r==="uuidv4"||r.includes("uuid")}function ts(n){return n===!0||n==="true"?!0:n===!1||n==="false"?!1:null}function rs(n){return n&&ee(n)?.name||"id"}function An(n,e,t,r,o,i,s){let a=es(e,o),c=es(r,i),u=`${I(n,s)}.${I(e,s)}`,l=`${I(t,s)}.${I(r,s)}`;if(s==="postgres"){if(a&&!c)return`${u} = ${l}::uuid`;if(!a&&c)return`${u}::uuid = ${l}`}return`${u} = ${l}`}function nl(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return Object.keys(e).length!==1||!e.id||typeof e.id!="object"||Array.isArray(e.id)?!1:Object.keys(e.id).every(t=>rl.has(t))}function ol(n,e,t){return`__enfyra_relation_${(0,os.createHash)("sha256").update(JSON.stringify([t,n,e])).digest("hex").slice(0,16)}`}function ns(n,e,t){return n(e===t?e:{[t]:e})}async function is(n,e,t,r,o,i,s){let a=o.relations.find(g=>g.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${o.name}"`);let c=a.targetTableName||a.targetTable;if(!c)throw new Error(`Relation "${t}" in table "${o.name}" is missing target metadata`);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn&&nl(r))return null;let u=s?await s(c):null,l=ol(t,c,e),f=rs(o),d=rs(u),p;switch(a.type){case"one-to-many":{if(!a.foreignKeyColumn)throw new Error(`Relation "${t}" is missing a foreign key`);p=ns(n,c,l).select(n.raw("1")).whereRaw(An(l,a.foreignKeyColumn,e,f,u,o,i));break}case"many-to-many":{if(!a.junctionTableName||!a.junctionSourceColumn||!a.junctionTargetColumn)throw new Error(`Relation "${t}" is missing junction metadata`);let g=s?await s(a.junctionTableName):null;p=n(a.junctionTableName).select(n.raw("1")).join({[l]:c},n.raw(An(a.junctionTableName,a.junctionTargetColumn,l,d,g,u,i))).whereRaw(An(a.junctionTableName,a.junctionSourceColumn,e,f,g,o,i));break}case"many-to-one":case"one-to-one":{if(!a.foreignKeyColumn)throw new Error(`Relation "${t}" is missing a foreign key`);p=ns(n,c,l).select(n.raw("1")).whereRaw(An(l,d,e,a.foreignKeyColumn,u,o,i));break}default:throw new Error(`Unsupported relation type: ${a.type}`)}return u?await as(n,p,r,l,u,i,s,c):ut(p,r,l,i),{query:p}}async function ss(n,e,t,r,o,i,s){let a=await is(n,e,t,r,o,i,s);return a?a.query.toString():null}function il(n,e,t){for(let[r,o]of Object.entries(t))switch(r){case"_is_null":{let i=ts(o);i===!0?n.whereNull(e):i===!1&&n.whereNotNull(e);break}case"_is_not_null":{let i=ts(o);i===!0?n.whereNotNull(e):i===!1&&n.whereNull(e);break}case"_eq":o===null?n.whereNull(e):n.where(e,"=",o);break;case"_neq":o===null?n.whereNotNull(e):n.where(e,"!=",o);break;case"_in":{let i=(Array.isArray(o)?o:[o]).filter(s=>s!==null);i.length===0?n.whereRaw("1 = 0"):n.whereIn(e,i);break}case"_not_in":case"_nin":{let i=Array.isArray(o)?o:[o];i.some(s=>s===null)?n.whereRaw("1 = 0"):i.length===0?n.whereRaw("1 = 1"):n.whereNotIn(e,i);break}case"_gt":n.where(e,">",o);break;case"_gte":n.where(e,">=",o);break;case"_lt":n.where(e,"<",o);break;case"_lte":n.where(e,"<=",o);break;default:throw new Error(`Unsupported direct relation operator: ${r}`)}}function dt(n){return{constant:n,apply(e){e.whereRaw(n?"1 = 1":"1 = 0")}}}function xo(n){if(n.some(t=>t.constant===!1))return dt(!1);let e=n.filter(t=>t.constant!==!0);return e.length===0?dt(!0):{apply(t){for(let r of e)r.apply(t)}}}function sl(n){if(n.some(t=>t.constant===!0))return dt(!0);let e=n.filter(t=>t.constant!==!1);return e.length===0?dt(!1):{apply(t){t.where(function(){e.forEach((r,o)=>{let i=function(){r.apply(this)};o===0?this.where(i):this.orWhere(i)})})}}}function al(n){return n.constant!==void 0?dt(!n.constant):{apply(e){e.whereNot(function(){n.apply(this)})}}}async function ll(n,e,t,r,o,i){let{fieldFilters:s,relationFilters:a}=Ae(e,r),c=[];for(let[u,l]of Object.entries(a)){let f=r.relations.find(g=>g.propertyName===u),d=await is(n,t,u,l,r,o,i);if(d){c.push(d);continue}if(!f?.foreignKeyColumn)throw new Error(`Relation "${u}" has no direct foreign key`);let p=l?.id;if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`Relation "${u}" has an invalid ID filter`);c.push({field:`${t}.${f.foreignKeyColumn}`,idFilter:p})}return Object.keys(s).length===0&&c.length===0?dt(!0):{apply(u){Object.keys(s).length>0&&ut(u,s,t,o,r);for(let l of c)"query"in l?u.whereExists(l.query):il(u,l.field,l.idFilter)}}}async function xr(n,e,t,r,o,i){if(!e||typeof e!="object")return dt(!0);if(Array.isArray(e))return xo(await Promise.all(e.map(c=>xr(n,c,t,r,o,i))));let s=[],a=Object.entries(e).filter(([c])=>c!=="_and"&&c!=="_or"&&c!=="_not");return a.length>0&&s.push(await ll(n,Object.fromEntries(a),t,r,o,i)),Array.isArray(e._and)&&s.push(xo(await Promise.all(e._and.map(c=>xr(n,c,t,r,o,i))))),Array.isArray(e._or)&&s.push(sl(await Promise.all(e._or.map(c=>xr(n,c,t,r,o,i))))),Object.prototype.hasOwnProperty.call(e,"_not")&&s.push(al(await xr(n,e._not,t,r,o,i))),xo(s)}async function as(n,e,t,r,o,i,s,a=r){(await xr(n,t,r,o,i,s)).apply(e)}async function Ot(n,e,t,r,o,i,s){await as(n,e,t,r,o,i,s)}re();ft();Se();var Cr=class{constructor(e,t){this.metadata=e;this.dbType=t}buildRelationCountSortSubquery(e,t){let r=t.relationMeta,o=t.relationName||t.field,i=r?.targetTableName||r?.targetTable,s=this.metadata?.tables?.get(e),a=ee(s)?.name||"id",c=I(e,this.dbType),u=I(a,this.dbType);if(!r||!i)throw new w(`Sort relation '${o}' does not exist on '${e}'.`);if(r.type==="one-to-many"){let l=r.foreignKeyColumn||r.mappedBy;if(!l)throw new w(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let f=I(i,this.dbType),d=I(l,this.dbType),p=i===e?I(e==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target",this.dbType):f;return`(SELECT COUNT(*) FROM ${p===f?f:`${f} AS ${p}`} WHERE ${p}.${d} = ${c}.${u})`}if(r.type==="many-to-many"){let l=this.resolveManyToManyContract(r,o,e),f=I(l.tableName,this.dbType),d=I(l.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${f} WHERE ${f}.${d} = ${c}.${u})`}throw new w(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let r=t.relationMeta,o=t.relationName||t.field,i=t.aggregateField,s=r?.targetTableName||r?.targetTable,a=this.metadata?.tables?.get(e),c=this.metadata?.tables?.get(s),u=ee(a)?.name||"id",l=ee(c)?.name||"id",f=I(e,this.dbType),d=I(u,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!r||!s||!i)throw new w(`Sort function '${t.field}' is not supported on '${e}'.`);let g=I(s,this.dbType),h=I(i,this.dbType),y=s===e?I(e==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target",this.dbType):g,m=y===g?g:`${g} AS ${y}`;if(r.type==="one-to-many"){let b=r.foreignKeyColumn||r.mappedBy;if(!b)throw new w(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let _=I(b,this.dbType);return`(SELECT ${p}(${y}.${h}) FROM ${m} WHERE ${y}.${_} = ${f}.${d})`}if(r.type==="many-to-many"){let b=this.resolveManyToManyContract(r,o,e),_=I(b.tableName,this.dbType),S=I(b.sourceColumn,this.dbType),E=I(b.targetColumn,this.dbType),C=I(l,this.dbType);return`(SELECT ${p}(${y}.${h}) FROM ${_} JOIN ${m} ON ${y}.${C} = ${_}.${E} WHERE ${_}.${S} = ${f}.${d})`}throw new w(`Sort function '_${t.function}(${o}.${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,r){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new w(`Relation '${t}' on '${r}' is missing physical many-to-many metadata.`)}};Rr();Se();ft();et();async function Nn(n,e,t,r,o,i,s){if(!r)return{select:t};let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Fo(),fs)),c=await a(e,t,r,o,i,s);return{select:c.select,batchFetchDescriptors:c.batchFetchDescriptors}}function Fr(n){let e=n;return e?async t=>{let r=e.tables?.get(t);return r?{name:r.name,columns:(r.columns||[]).map(o=>({name:o.name,type:o.type,isPrimary:o.isPrimary})),relations:r.relations||[]}:null}:null}function On(n,e,t,r,o){let i=n.targetTableName||n.targetTable;if(!i)return null;if(!(n.type==="many-to-one"||n.type==="one-to-one"&&n.isInverse===!1))throw new Error("Relation sorting requires an explicitly parent-owned to-one relation");let a=n.foreignKeyColumn||(n.propertyName?ie(n.propertyName):null);if(!a)throw new Error("Relation sorting requires a parent foreign-key column");let c=p=>I(p,o),u=r?.tables?.get(i);if(!u)throw new Error(`SQL relation sort requires target metadata for '${i}'`);let l=ee(u)?.name;if(!l)throw new Error(`SQL relation sort requires a primary key for '${i}'`);if(!u.columns?.some(p=>p.name===e))throw new Error(`SQL relation sort requires target column '${e}' on '${i}'`);let f=r?.tables?.get(t);if(!f)throw new Error(`SQL relation sort requires parent metadata for '${t}'`);if(!f.columns?.some(p=>p.name===a))throw new Error(`SQL relation sort requires foreign-key column '${a}' on '${t}'`);let d=t==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target";return`(SELECT ${c(d)}.${c(e)} FROM ${c(i)} AS ${c(d)} WHERE ${c(d)}.${c(l)} = ${c(t)}.${c(a)})`}Se();var gl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Io(n){if(typeof n!="string"||!gl.test(n))throw new Error("Invalid UUID filter value")}function Pn(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Bt(n,e,t,r,o){for(let i of e){let s=i.field.split("."),a=s.length>1?s[0]:t,c=s[s.length-1],l=["=","!=",">","<",">=","<=","like"].includes(i.operator)?Ir(r,a,c,i.value):i.value;switch(i.operator){case"=":n=n.where(i.field,"=",l);break;case"!=":n=n.where(i.field,"!=",l);break;case">":n=n.where(i.field,">",l);break;case"<":n=n.where(i.field,"<",l);break;case">=":n=n.where(i.field,">=",l);break;case"<=":n=n.where(i.field,"<=",l);break;case"like":n=n.where(i.field,"like",l);break;case"in":let f=Array.isArray(i.value)?i.value.map(b=>Ir(r,a,c,b)):[l];n=n.whereIn(i.field,f);break;case"not in":let d=Array.isArray(i.value)?i.value.map(b=>Ir(r,a,c,b)):[l];n=n.whereNotIn(i.field,d);break;case"is null":n=n.whereNull(i.field);break;case"is not null":n=n.whereNotNull(i.field);break;case"_contains":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`%${Pn(i.value)}%`]);break;case"_starts_with":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`${Pn(i.value)}%`]);break;case"_ends_with":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`%${Pn(i.value)}`]);break;case"_between":let p=i.value;if(typeof p=="string"&&(p=p.split(",").map(b=>b.trim())),!Array.isArray(p)||p.length!==2)throw new Error("Invalid _between filter value");let g=Ir(r,a,c,p[0]),h=Ir(r,a,c,p[1]);n=n.whereBetween(i.field,[g,h]);break;case"_is_null":n=l===!0||l==="true"?n.whereNull(i.field):n.whereNotNull(i.field);break;case"_is_not_null":n=l===!0||l==="true"?n.whereNotNull(i.field):n.whereNull(i.field);break}}return n}function vr(n,e,t,r){let o=[],i=t;if(!n||typeof n!="object")return o;for(let[s,a]of Object.entries(n))if(s==="_and"&&Array.isArray(a)){let c=a.map(u=>{let l=vr(u,e,t,r);return l.length>0?`(${l.join(" AND ")})`:null}).filter(u=>u!==null);c.length>0&&o.push(`(${c.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let c=a.map(u=>{let l=vr(u,e,t,r);return l.length>0?`(${l.join(" AND ")})`:null}).filter(u=>u!==null);c.length>0&&o.push(`(${c.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let c=vr(a,e,t,r);c.length>0&&o.push(`NOT (${c.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[c,u]of Object.entries(a)){let l=`${I(e,r)}.${I(s,r)}`,f=i.columns?.find(h=>h.name===s),d=f&&(f.type?.toLowerCase()==="uuid"||f.type?.toLowerCase().includes("uuid")),p=["_eq","_neq","_gt","_gte","_lt","_lte"].includes(c);d&&r==="postgres"&&u!==null&&p&&Io(u);let g=d&&r==="postgres"&&u!==null&&p?`${we(u,r)}::uuid`:we(u,r);if(c==="_eq")o.push(u===null?`${l} IS NULL`:`${l} = ${g}`);else if(c==="_neq")o.push(u===null?`${l} IS NOT NULL`:`${l} != ${g}`);else if(c==="_gt")o.push(`${l} > ${g}`);else if(c==="_gte")o.push(`${l} >= ${g}`);else if(c==="_lt")o.push(`${l} < ${g}`);else if(c==="_lte")o.push(`${l} <= ${g}`);else if(c==="_is_null")o.push(`${l} IS ${u===!0||u==="true"?"":"NOT "}NULL`);else if(c==="_is_not_null")o.push(`${l} IS ${u===!0||u==="true"?"NOT ":""}NULL`);else if(c==="_in"){let h=Array.isArray(u)?u:[u];if(h.length===0)o.push("FALSE");else{let y=h.map(m=>{d&&r==="postgres"&&m!==null&&Io(m);let b=we(m,r);return d&&r==="postgres"?`${b}::uuid`:b}).join(", ");o.push(`${l} IN (${y})`)}}else if(c==="_not_in"||c==="_nin"){let h=Array.isArray(u)?u:[u];if(h.length===0)o.push("TRUE");else{let y=h.map(m=>{d&&r==="postgres"&&m!==null&&Io(m);let b=we(m,r);return d&&r==="postgres"?`${b}::uuid`:b}).join(", ");o.push(`${l} NOT IN (${y})`)}}else if(c==="_contains"||c==="_starts_with"||c==="_ends_with"){let h=Pn(u).toLowerCase(),y=we(h,r),m=c==="_contains"?r==="mysql"?`CONCAT('%', lower(${y}), '%')`:`'%' || lower(${y}) || '%'`:c==="_starts_with"?r==="mysql"?`CONCAT(lower(${y}), '%')`:`lower(${y}) || '%'`:r==="mysql"?`CONCAT('%', lower(${y}))`:`'%' || lower(${y})`;r==="postgres"?o.push(`lower(unaccent(${l})) ILIKE unaccent(${m}) ESCAPE '='`):r==="mysql"?o.push(`lower(${l}) COLLATE utf8mb4_general_ci LIKE ${m} ESCAPE '='`):o.push(`lower(${l}) LIKE ${m} ESCAPE '='`)}else if(c==="_between"){if(!Array.isArray(u)||u.length!==2)throw new Error("Invalid _between filter value");o.push(`${l} BETWEEN ${we(u[0],r)} AND ${we(u[1],r)}`)}}else{let c=`${I(e,r)}.${I(s,r)}`;o.push(a===null?`${c} IS NULL`:`${c} = ${we(a,r)}`)}return o}function we(n,e="postgres"){if(n==null)return"NULL";if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("Invalid numeric SQL value");return String(n)}if(typeof n=="bigint")return n.toString();let t=Buffer.from(String(n),"utf8").toString("hex");return e==="mysql"?`CONVERT(X'${t}' USING utf8mb4)`:e==="sqlite"?`CAST(X'${t}' AS TEXT)`:`E'${String(n).replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}function Ir(n,e,t,r){if(r==null)return r;let o=n?.tables?.get(e);if(!o?.columns)return r;let i=o.columns.find(s=>s.name===t);if(!i)return r;switch(i.type){case"bigint":{let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new Error("Invalid bigint value");return s}case"int":case"integer":case"smallint":case"tinyint":{let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new Error("Invalid integer value");let a=Number(s);if(!Number.isSafeInteger(a))throw new Error("Integer value exceeds JavaScript safe range");return a}case"decimal":case"numeric":{let s=String(r);if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(s))throw new Error("Invalid decimal value");return s}case"float":case"double":case"real":{let s=Number(r);if(!Number.isFinite(s))throw new Error("Invalid float value");return s}case"boolean":case"bool":if(r===!0||r===!1)return r;if(r==="true"||r==="1"||r===1)return!0;if(r==="false"||r==="0"||r===0)return!1;throw new Error("Invalid boolean value");case"date":case"datetime":case"timestamp":if(typeof r=="string"){let s=new Date(r);if(Number.isNaN(s.getTime()))throw new Error("Invalid date value");return s}return r;default:return r}}re();Se();Rr();var jn=class{constructor(e,t){this.knex=e;this.dbType=t}async aggregate(e){let t=At(e.aggregate,e.tableName,e.metadata),r=this.knex(e.tableName),o=I(e.tableName,this.dbType),i=[],s=[];for(let f of t.dimensions){let d=`${o}.${I(f.field,this.dbType)}`,p=f.bucket?this.buildSqlBucketExpression(d,f.bucket,f.timezone,f.column.type):d;s.push(this.knex.raw(`${p} as ${I(f.outputKey,this.dbType)}`)),i.push(p)}for(let f of t.measures){let d=`${o}.${I(f.field,this.dbType)}`,p=f.operation==="count"?`COUNT(${d})`:f.operation==="countDistinct"?`COUNT(DISTINCT ${d})`:`${f.operation.toUpperCase()}(${d})`;s.push(this.knex.raw(`${p} as ${I(f.outputKey,this.dbType)}`))}let c=new pe().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});c.hasRelationFilters?await Ot(this.knex,r,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,f=>e.metadata?.tables?.get(f)):c.filterTree&&ue(r,c.filterTree,{dbType:this.dbType,rootTable:e.tableName}),r.select(s),i.length>0&&r.groupByRaw(i.join(", "));for(let f of t.sort)r.orderByRaw(`${I(f.field,this.dbType)} ${f.direction.toUpperCase()}`);return t.limit!==void 0&&r.limit(t.limit).offset((t.page-1)*t.limit),{data:(await r).map(f=>{let d={...f};for(let p of t.measures){let g=d[p.outputKey];if(typeof g=="string"&&/^-?\d+$/.test(g)){let h=Number(g);Number.isSafeInteger(h)&&(d[p.outputKey]=h)}}return d})}}buildSqlBucketExpression(e,t,r,o){let i=we(r,this.dbType);if(this.dbType==="postgres"){let c=`(${["timestamp without time zone","date"].includes(o.toLowerCase())?`(${e}::timestamp AT TIME ZONE 'UTC')`:e} AT TIME ZONE ${i})`;return`DATE_TRUNC(${we(t,this.dbType)}, ${c})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${i})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`DATE_SUB(DATE(${s}), INTERVAL WEEKDAY(${s}) DAY)`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new w(`Aggregate time bucket is not supported on ${this.dbType}`)}};var pt=class n{constructor(e,t,r,o){this.knex=e;this.dbType=t;this.knexService=r;this.maxQueryDepth=o;this.logger=new In(n.name)}async execute(e){let t=performance.now(),r=e.debugLog||[],o=e.debugTrace;if(e.filter&&De(e.filter,e.tableName,e.metadata),!e.plan){let $=new pe;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;e={...e,fields:i.rawFields};let s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,c=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,u=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!c&&!a&&u){o&&o.setQueryPath("simple");let $=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),$}let f={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?f.fields=e.fields:typeof e.fields=="string"&&(f.fields=e.fields.split(",").map($=>$.trim())));let d=e.filter;if(e.filter&&!ct(e.filter)){f.where=[];for(let[$,T]of Object.entries(e.filter))if(typeof T=="object"&&T!==null)for(let[F,L]of Object.entries(T)){let A;if(F==="_eq")A="=";else if(F==="_neq")A="!=";else if(F==="_in")A="in";else if(F==="_not_in"||F==="_nin")A="not in";else if(F==="_gt")A=">";else if(F==="_gte")A=">=";else if(F==="_lt")A="<";else if(F==="_lte")A="<=";else if(F==="_contains")A="_contains";else if(F==="_starts_with")A="_starts_with";else if(F==="_ends_with")A="_ends_with";else if(F==="_between")A="_between";else if(F==="_is_null")A="_is_null";else if(F==="_is_not_null")A="_is_not_null";else if(F==="_like")A="like";else if(F==="_ilike")A="ilike";else continue;f.where.push({field:$,operator:A,value:L})}else f.where.push({field:$,operator:"=",value:T})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(T=>T.trim());f.sort=$.map(T=>{let F=T.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else f.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,h=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,y=h===void 0||Number.isNaN(h)?void 0:h;y&&g!==void 0?(f.offset=(y-1)*g,f.limit=g):g!==void 0&&(f.limit=g);let m=e.plan?.sortItems??(f.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),b=[],_=[];for(let $ of m){if($.function==="count"){let T={sql:this.buildRelationCountSortSubquery(f.table,$,e.metadata),direction:$.direction};_.push(T);continue}if($.function==="max"||$.function==="min"){let T={sql:this.buildRelationAggregateSortSubquery(f.table,$,e.metadata),direction:$.direction};_.push(T);continue}if($.joinId===null){if($.field.includes(".")&&!e.plan){let F=$.field.split(".")[0];if(e.metadata?.tables?.get(f.table)?.relations?.some(Re=>Re.propertyName===F))continue}let T={field:$.field.includes(".")?$.field:`${f.table}.${$.field}`,direction:$.direction};b.push(T),_.push(T)}else{let T=e.plan?.joins.find(F=>F.id===$.joinId);if(T&&(T.relationType==="many-to-one"||T.relationType==="one-to-one")){let F=On(T.relationMeta,$.field,f.table,e.metadata,this.dbType);if(F){let L={sql:F,direction:$.direction};_.push(L)}}}}let S=[],E=[];if(f.fields&&f.fields.length>0||c||a){let $=Fr(e.metadata),T=f.fields??["*"],F=await Nn(this.knex,f.table,T,$,this.dbType,this.maxQueryDepth,e.deep);E=F.select.map(L=>$?this.knex.raw(L):L),S=F.batchFetchDescriptors||[]}f.where&&(f.where=f.where.map($=>$.field.includes(".")?$:{...$,field:`${f.table}.${$.field}`})),f.sort=b;let C=this.knex(f.table),x=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),v=x.includes("filterCount")||x.includes("*"),R=x.includes("totalCount")||x.includes("*");if(f.select||E.length>0){let $=(f.select??[]).map(T=>typeof T=="string"&&T.trim().startsWith("(")?this.knex.raw(T):typeof T=="string"&&/ as /i.test(T)?this.knex.raw(T):T);C=C.select([...$,...E])}let M=i.rawFields!==void 0&&i.rawFields.length===0&&!c;if(M&&C.select(this.knex.raw("1 as ??",["__enfyra_empty_selection"])),!M&&!f.select&&E.length===0&&(v||R)&&C.select(`${f.table}.*`),v&&C.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),R){let $=I(f.table,this.dbType);C.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let N=["table_definition","column_definition","relation_definition","method_definition"].includes(f.table);if(d&&(ct(d)||Object.keys(d).length>0)){let $=e.metadata?.tables?.get(f.table);(!N&&$&&$.relations&&$.relations.length>0?Ae(d,$).hasRelations:!1)?await Ot(this.knex,C,d,f.table,$,this.dbType,F=>e.metadata?.tables?.get(F)):e.plan?.filterTree?ue(C,e.plan.filterTree,{dbType:this.dbType,rootTable:f.table}):(this.logger.debug(`buildWhereClause fallback for table=${f.table}`),C=ut(C,d,f.table,this.dbType,$))}else e.plan?.filterTree?ue(C,e.plan.filterTree,{dbType:this.dbType,rootTable:f.table}):f.where&&f.where.length>0&&(C=Bt(C,f.where,f.table,e.metadata,this.dbType));for(let $ of _)if($.field){let T=$.field.includes(".")?$.field:`${f.table}.${$.field}`;C=C.orderBy(T,$.direction)}else $.sql&&(C=C.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`));f.groupBy&&(C=C.groupBy(f.groupBy)),f.offset&&(C=C.offset(f.offset)),f.limit!==void 0&&f.limit>0&&(C=C.limit(f.limit));let j=0;r&&r.push({type:"SQL Query",table:f.table,sql:C.toSQL().toNative()});let O;if(e.debugMode&&(O=C.toSQL().toNative().sql),e.debugMode&&o){let $=C.toSQL().toNative();o.setSql($.sql);try{let T=$.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${T}`,$.bindings);o.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(T){o.setExplain({error:String(T)})}}let P,G=performance.now();P=await C,o&&o.dur("db_execute",G,{table:e.tableName});let te=await this.resolveEmptyPageMeta(C,f.table,x,P.length),k=te.filterCount??0;if(j=te.totalCount??0,v&&P.length>0&&(k=Number(P[0].__filter_count__||0),P.forEach($=>{delete $.__filter_count__})),R&&P.length>0&&P[0].__total_count__!==void 0&&(j=Number(P[0].__total_count__||0),P.forEach($=>{delete $.__total_count__})),S&&S.length>0&&P.length>0){let $=Fr(e.metadata);if($){let{executeBatchFetches:T}=await Promise.resolve().then(()=>(Ao(),ps));await T(this.knex,P,S,$,this.maxQueryDepth??3,0,f.table,this.dbType,e.metadata,o)}}if(this.knexService){let $=performance.now();P=await this.knexService.parseResult(P,f.table),o&&o.dur("db_parseResult",$,{table:e.tableName})}else P=Er(P,f.table,e.metadata);return M&&(P=P.map(()=>({}))),o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName})),{data:P,...x.length>0&&{meta:{...x.includes("totalCount")||x.includes("*")?{totalCount:j}:{},...x.includes("filterCount")||x.includes("*")?{filterCount:k}:{}}},...O!==void 0&&{sql:O}}}buildRelationCountSortSubquery(e,t,r){return new Cr(r,this.dbType).buildRelationCountSortSubquery(e,t)}buildRelationAggregateSortSubquery(e,t,r){return new Cr(r,this.dbType).buildRelationAggregateSortSubquery(e,t)}async resolveEmptyPageMeta(e,t,r,o){return o>0||r.length===0?{}:Mn(this.knex,e,t,r,!1)}async executeSimple(e,t){let r=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(r).select(o);t.filterTree&&ue(i,t.filterTree,{dbType:this.dbType,rootTable:r});for(let y of t.sortItems){let m=y.field.includes(".")?y.field:`${r}.${y.field}`;i=i.orderBy(m,y.direction)}t.limit!==void 0&&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(y=>y.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),c=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),c){let y=I(r,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${y}) as __total_count__`))}let u=e.debugTrace,l;if(e.debugMode){let y=i.toSQL().toNative();if(l=y.sql,u){u.setSql(y.sql);try{let m=y.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,y.bindings);u.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){u.setExplain({error:String(m)})}}}let f=performance.now(),d;d=await i,u&&u.dur("db_execute",f,{table:r}),this.knexService?d=await this.knexService.parseResult(d,r):d=Er(d,r,e.metadata);let p=await this.resolveEmptyPageMeta(i,r,s,d.length),g=p.filterCount??0,h=p.totalCount??0;return a&&d.length>0&&(g=Number(d[0].__filter_count__||0),d.forEach(y=>delete y.__filter_count__)),c&&d.length>0&&(h=Number(d[0].__total_count__||0),d.forEach(y=>delete y.__total_count__)),{data:d,...s.length>0&&{meta:{...c?{totalCount:h}:{},...a?{filterCount:g}:{}}},...l!==void 0&&{sql:l}}}async aggregate(e){return new jn(this.knex,this.dbType).aggregate(e)}};var Ln=require("mongodb"),qn=class{constructor(e){this.databaseConfigService=e}safeObjectId(e){if(!Ln.ObjectId)return e;if(typeof e=="string")try{return new Ln.ObjectId(e)}catch{return e}return e}whereToFilter(e){let t={},r=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?r?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 Ln.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[r,o]of Object.entries(e))t[r]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[r,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o))for(let[i,s]of Object.entries(o))t.push({field:r,operator:this.mapFilterOperatorToSql(i),value:s});return t}mapFilterOperatorToSql(e){let t={_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"_contains",_starts_with:"_starts_with",_ends_with:"_ends_with",_is_null:"is null",_is_not_null:"is not null"},r=t[e];if(!Object.prototype.hasOwnProperty.call(t,e))throw new Error(`Unsupported filter operator: ${e}`);return r}};var qt=class{constructor(e){this.debugLog=[];this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.conditions=new qn(this.databaseConfigService),this.batchInsertBuffer=new en(this.dbType,this.knexService,this.mongoService,t=>this.runMongoMutationInSaga(t))}async runWithPolicy(e,t){if(this.dbType==="mongodb"){if(typeof this.mongoService?.runWithPolicy!="function")throw new Error("MongoDB policy context is not available");return this.mongoService.runWithPolicy(e,t)}if(typeof this.knexService?.runWithPolicy!="function")throw new Error("SQL policy context is not available");return this.knexService.runWithPolicy(e,t)}async runWithFieldPermissionCheck(e,t){if(this.dbType==="mongodb"){if(typeof this.mongoService?.runWithFieldPermissionCheck!="function")throw new Error("MongoDB field-permission context is not available");return this.mongoService.runWithFieldPermissionCheck(e,t)}if(typeof this.knexService?.runWithFieldPermissionCheck!="function")throw new Error("SQL field-permission context is not available");return this.knexService.runWithFieldPermissionCheck(e,t)}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}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 r=await this.getMetadataForQuery(),o=It(r,e,t,this.dbType);return o._id!==void 0&&(o._id=this.conditions.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,r){let o=await this.getMetadataForQuery();return{query:Bt(e,t,r??"",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.batchInsertBuffer.enqueue(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let r of e.data){let o=await this.mongoService.insertOne(e.table,r);t.push(se(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let r of e.data){let o=await this.knexService.insertWithCascade(e.table,r);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),r=await this.getMetadataForQuery(),o=performance.now(),s=new pe().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:r,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 f=await new lt(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:r,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),f}let u=await new pt(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:r,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),u}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},c=await s.find(i,a).toArray(),u=[];for(let l of c){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),r=t(e.table);e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table));let o=await r;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);return e.returning?o.length===0?[]:await t(e.table).whereIn("id",o.map(i=>i.id)).select(e.returning):{affected:o.length}}async deleteWithOptions(e){if(!Array.isArray(e.where))throw new TypeError("Delete conditions must be an array");if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),i=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await i.find(o,s).toArray(),c=0;for(let u of a)await this.mongoService.deleteOne(e.table,u._id)&&c++;return c});let r=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table)),await r.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 r=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table));let o=await r.count("* as count").first();return Number(o?.count||0)}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.conditions.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new lt(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new pt(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,r){return r?.batch?await this.batchInsertBuffer.enqueue(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return se(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 createMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService.insertManyWithCascade=="function")return this.mongoService.insertManyWithCascade(e,t);let o=[];for(let i of t)o.push(await this.mongoService.insertOne(e,i));return o})).map(o=>se(o)):this.knexService.insertManyWithCascade(e,t))}async insertMany(e,t){return this.createMany(e,t)}async flushBatchInserts(){await this.batchInsertBuffer.flush()}async update(e,t,r){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:r});if(this.dbType==="mongodb"){let i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,r));return se(i)}return await this.knexService.updateWithCascade(e,t,r),await this.knexService.getKnex()(e).where("id",t).first()})}async updateMany(e,t,r,o=this.getPkField()){return t.length===0?0:this.trackQueryMetric("update_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let a=this.mongoService.collection(e),c=this.mongoService.ioSignalPublic?.()??{},u=o==="_id"?t.map(f=>this.conditions.safeObjectId(f)):t;return(await a.updateMany({[o]:{$in:u}},{$set:r},c)).modifiedCount});let s=await this.knexService.getKnex()(e).whereIn(o,t).update(r);return typeof s=="number"?s:0})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async deleteMany(e,t,r=this.getPkField()){return t.length===0?0:this.trackQueryMetric("delete_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let s=this.mongoService.collection(e),a=this.mongoService.ioSignalPublic?.()??{},c=r==="_id"?t.map(f=>this.conditions.safeObjectId(f)):t,u=await s.find({[r]:{$in:c}},a).toArray(),l=0;for(let f of u)await this.mongoService.deleteOne(e,f._id)&&l++;return l});let i=await this.knexService.getKnex()(e).whereIn(r,t).delete();return typeof i=="number"?i: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.conditions.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.conditions.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.conditions.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[c,u]of Object.entries(t))c==="id"||c==="_id"?o._id=this.conditions.safeObjectId(u):o[c]=u;let i=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await i.find(o,s).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let r=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=r||t.id;return await o(e).where("id",i).first()}async updateById(e,t,r){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,r)):(await this.knexService.updateWithCascade(e,t,r),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 r=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",r,async()=>{if(this.dbType==="mongodb"){let i=this.mongoService.getDb();if(typeof e=="string"){if(/^\s*select\s+1\s*;?\s*$/i.test(e))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,r){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},r):await r()}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}};Ao();vo();Fo();function gs(n){return n?(Array.isArray(n)?n:n.split(",")).flatMap(t=>{let r=typeof t=="string"?t.trim():"",o=r.startsWith("-"),i=o?r.substring(1).trim():r;return i?[{field:i,direction:o?"DESC":"ASC"}]:[]}):[]}Rr();Se();ft();Ne();on();re();Le();wt();function hs(n,e,t){if(!(!n||typeof n!="object")){if(e>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(t.has(n))throw new w("Filter contains a circular reference");t.add(n);try{for(let r of Object.values(n))hs(r,e+1,t)}finally{t.delete(n)}}}function ms(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new w("Filter must be an object");return Wn(n,e,t,r,0,new Set)}function Wn(n,e,t,r,o,i){if(!n||typeof n!="object"||Array.isArray(n))throw new w("Filter operand must be an object");if(o>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(i.has(n))throw new w("Filter contains a circular reference");let s=t?.tables?.get(e);if(!s)throw new w(`Filter validation requires metadata for table '${e}'`);i.add(n);let a=Object.create(null);try{for(let[c,u]of Object.entries(n)){if(de.has(c))throw new w(`Filter operator '${c}' is not valid at table scope`);if(c==="_and"||c==="_or"){if(!Array.isArray(u))throw new w(`Filter '${c}' value must be an array`);a[c]=u.map(d=>Wn(d,e,t,r,o+1,i));continue}if(c==="_not"){a[c]=Wn(u,e,t,r,o+1,i);continue}let l=s.relations?.find(d=>d.propertyName===c);if(l){if(!r(e,c,"relation"))throw new w(`Filtering by relation '${c}' on '${e}' is not allowed`);let d=l.targetTableName||l.targetTable;if(typeof d!="string"||!d)throw new w(`Relation '${c}' on '${e}' has no target table metadata`);a[c]=Wn(u,d,t,r,o+1,i);continue}if(s.columns?.find(d=>d.name===c)){if(!r(e,c,"column"))throw new w(`Filtering by field '${c}' on '${e}' is not allowed`);hs(u,o+1,i),a[c]=u;continue}throw new w(`Unknown filter field '${c}' on table '${e}'`)}return a}finally{i.delete(n)}}function ys(n,e,t,r){if(n===void 0)return n;if(typeof n!="string"&&!Array.isArray(n))throw new w("Sort must be a string or string array");let o=Array.isArray(n)?n:n.split(",");if(o.some(a=>typeof a!="string"))throw new w("Sort entries must be strings");let i=o.map(a=>a.trim()).filter(Boolean),s=[];for(let a of i){let l=(a.startsWith("-")?a.slice(1):a).split("."),f=!0,d=e;for(let p=0;p<l.length;p++){let g=l[p],h=p===l.length-1,y=t?.tables?.get(d);if(!y)throw new w(`Sort validation requires metadata for table '${d}'`);if(h)if(y.columns?.find(b=>b.name===g))r(d,g,"column")||(f=!1);else throw new w(`Unknown sort field '${g}' on table '${d}'`);else{let m=y.relations?.find(_=>_.propertyName===g);if(!m)throw new w(`Unknown sort relation '${g}' on table '${d}'`);if(!r(d,g,"relation")){f=!1;break}let b=m.targetTableName||m.targetTable;if(typeof b!="string"||!b||!t?.tables?.has(b))throw new w(`Sort relation '${g}' on '${d}' has no resolvable target table metadata`);d=b}}f&&s.push(a)}if(s.length!==0)return Array.isArray(n)?s:s.join(",")}cr();Le();sr();async function bs(n,e,t){if(!Number.isInteger(t)||t<1)throw new Error("Per-parent concurrency must be a positive integer");let r=new Map,o=[];for(let d of n){let p=String(d);if(r.has(p)){if(!Object.is(r.get(p),d))throw new Error(`Per-parent identity collision for key: ${p}`);continue}r.set(p,d),o.push({id:d,key:p})}let i=new Array(o.length),s=0,a=!1,c=!1,u;async function l(){for(;!a;){let d=s;if(d>=o.length)return;s+=1;let p=o[d];try{i[d]=await e(p.id)}catch(g){c||(c=!0,u=g),a=!0}}}let f=Math.min(t,o.length);if(f===0)return new Map;if(await Promise.all(Array.from({length:f},()=>l())),c)throw u;return new Map(o.map((d,p)=>[d.key,i[p]]))}wt();et();re();function ml(n){let e=new qt({knexService:n.knexService,mongoService:n.mongoService,databaseConfigService:n.databaseConfigService,runtimeMetricsCollectorService:n.runtimeMetricsCollectorService,lazyRef:n.lazyRef}),t,r,o=!1,i,s=()=>{if(o)throw new Error("Enfyra kernel has been destroyed")},a=()=>{if(s(),!t){let u=n.getPackageCacheService?.()??n.packageCacheService,l=n.getPackageCdnLoaderService?.()??n.packageCdnLoaderService;if(!u||!l)throw new Error("Executor dependencies packageCacheService and packageCdnLoaderService are required");t=new bt({packageCacheService:u,packageCdnLoaderService:l,onExecutorWorkerCrash:n.onExecutorWorkerCrash,onExecutionFinished:n.onExecutionFinished})}return t},c=()=>(s(),r||(r=new gt({isolatedExecutorService:a()})),r);return{queryBuilderService:e,get isolatedExecutorService(){return a()},get executorEngineService(){return c()},onDestroy(){return i||(o=!0,i=Promise.resolve().then(async()=>{try{await e.flushBatchInserts()}finally{await t?.onDestroy?.()}}),i)}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildMongoSortSpec,buildMongoSortSpecFromPlan,buildRelationSortSubquery,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,checkIfFilterContainsIsNull,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeAggregationPipeline,executeBatchFetches,executeCountQueries,executeMongoBatchFetches,expandFieldsMongo,expandFieldsToJoinsAndSelect,expandFieldsToSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getMetadataGetter,getMongoInverseRelationForeignField,getMongoMetadataGetter,getMongoStoredRelationField,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasLogicalOperators,isExecutableJavaScript,isMongoInverseRelation,isScriptTable,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeMongoDocument,normalizeMongoResults,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,parseSortInput,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,renderFilterToKnex,resolveExecutableScript,resolveMongoJunctionInfo,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|
|
52
|
+
}`}var Pi="mongo-fold-text-search.body.txt",kt=null;function Fa(){let n=[mo.join(__dirname,Pi),mo.join(process.cwd(),"dist","kernel","query","utils",Pi)];for(let e of n)try{if(dn.existsSync(e))return dn.readFileSync(e,"utf8")}catch{}return null}function pn(){if(kt!==null)return kt;let n=Fa();return n?(kt=n,kt):(kt=fn(),kt)}var be=require("mongodb");function V(n,e,t,r){if(t==="_id"){if(r instanceof be.ObjectId)return r;if(typeof r=="string")try{return new be.ObjectId(r)}catch{return r}return r}let o=n?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}if(r==null)return r;switch(i.type){case"long":case"bigint":{if(be.Long.isLong(r)&&!r.unsigned)return r;if(typeof r=="number"&&!Number.isSafeInteger(r))throw new TypeError("MongoDB bigint requires an exact integer");if(!["string","number","bigint"].includes(typeof r)&&!be.Long.isLong(r))throw new TypeError("MongoDB bigint requires an integer");let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new TypeError("MongoDB bigint requires an integer");let a=BigInt(s);if(a<-(1n<<63n)||a>=1n<<63n)throw new RangeError("MongoDB bigint exceeds signed 64-bit range");return be.Long.fromBigInt(a)}case"int":case"integer":case"smallint":case"tinyint":return typeof r=="string"?parseInt(r,10):Number(r);case"float":case"double":case"decimal":case"numeric":case"real":return typeof r=="string"?parseFloat(r):Number(r);case"boolean":case"bool":return typeof r=="string"?r==="true"||r==="1":!!r;case"date":case"datetime":case"timestamp":return typeof r=="string"?new Date(r):r;case"objectId":case"ObjectId":if(r instanceof be.ObjectId)return r;if(typeof r=="string")try{return new be.ObjectId(r)}catch{return r}return r;case"uuid":return r;default:return r}}cr();sr();var gn="__mongoFoldTextTriples";function xt(n,e){if(!n)return{};let t={};return Et(n,t,e),at(t),t}function Ia(n,e){if(!n)return{};let t={};return hn(n,t,e),at(t),t}function ce(n,e,t){if(!e)return{};let r=new Te,{node:o}=Me(e,t,n,r);return xt(o,{metadata:n,rootTable:t})}function mn(n,e,t){if(!e)return{};let r=new Te,{node:o}=Me(e,t,n,r);return Ia(o,{metadata:n,rootTable:t})}function Et(n,e,t){switch(n.kind){case"true":return;case"false":Ee(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=n.children.map(i=>{let s={};return Et(i,s,t),at(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}Ee(e,...o);return}case"or":{let r=n.children.map(o=>{let i={};return Et(o,i,t),at(i),i});if(r.some(o=>Object.keys(o).length===0))return;if(r.length===0){Et({kind:"false"},e,t);return}Ee(e,{$or:r});return}case"not":hn(n.child,e,t);return;case"compare":Bi(n,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${n.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Bi(n,e,t){let r=n.field.fieldName;if(n.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${n.field.joinId} (field=${n.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let o=i=>V(t.metadata,t.rootTable,r,i);switch(n.op){case"eq":_e(e,r,o(n.value));return;case"neq":{let i=o(n.value);bo(t,r)?Ee(e,{[r]:{$ne:null}},{[r]:{$ne:i}}):_e(e,r,{$ne:i});return}case"gt":_e(e,r,{$gt:o(n.value)});return;case"gte":_e(e,r,{$gte:o(n.value)});return;case"lt":_e(e,r,{$lt:o(n.value)});return;case"lte":_e(e,r,{$lte:o(n.value)});return;case"in":{let i=ji(n.value).map(o);_e(e,r,{$in:i});return}case"not_in":{let i=ji(n.value).map(o);bo(t,r)?Ee(e,{[r]:{$ne:null}},{[r]:{$nin:i}}):_e(e,r,{$nin:i});return}case"between":{let i=Array.isArray(n.value)?n.value:typeof n.value=="string"?n.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&_e(e,r,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":_e(e,r,n.value===!0?{$eq:null}:{$ne:null});return;case"contains":yo(e,r,String(n.value),"contains");return;case"starts_with":yo(e,r,String(n.value),"starts");return;case"ends_with":yo(e,r,String(n.value),"ends");return}}function hn(n,e,t){switch(n.kind){case"true":Ee(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let r=n.children.map(o=>{let i={};return hn(o,i,t),at(i),i});if(r.some(o=>Object.keys(o).length===0))return;if(r.length===0){Et({kind:"false"},e,t);return}Ee(e,{$or:r});return}case"or":{let o=n.children.map(i=>{let s={};return hn(i,s,t),at(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}Ee(e,...o);return}case"not":Et(n.child,e,t);return;case"compare":va(n,e,t);return;case"relation_exists":{_e(e,n.joinId,n.negate?{$ne:null}:{$eq:null});return}}}function va(n,e,t){let r=n.field.fieldName;if(n.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${n.field.joinId} (field=${n.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(n.op==="is_null"){_e(e,r,n.value===!0?{$ne:null}:{$eq:null});return}let o={};Bi(n,o,t),at(o);let i={$nor:[o]};bo(t,r)?Ee(e,i,{[r]:{$ne:null}}):Ee(e,i)}function _e(n,e,t){n[e]===void 0?n[e]=t:(Ee(n,{[e]:n[e]},{[e]:t}),delete n[e])}function Ee(n,...e){if(e.length===0)return;let t=n.$and;n.$and=t?[...t,...e]:e}function bo(n,e){let r=n.metadata?.tables?.get?.(n.rootTable)?.columns?.find(o=>o.name===e);return r?r.isNullable!==!1:!0}function ji(n){return Array.isArray(n)?n:typeof n=="string"&&n.includes(",")?n.split(",").map(e=>e.trim()):[n]}function Ma(n){return n==="_id"?"$_id":`$${n}`}function yo(n,e,t,r){let o=Ma(e),i=n[gn]??[];i.push({ref:o,needle:t,mode:r}),n[gn]=i}function at(n){let e=n[gn];if(delete n[gn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,{$literal:i.needle},i.mode);let r={$eq:[{$function:{body:pn(),args:t,lang:"js"}},!0]},o=n.$expr;Object.prototype.hasOwnProperty.call(n,"$expr")?n.$expr={$and:[o,r]}:n.$expr=r}var xe="__sourceId__",Ue="__targetId__",Ct="__enfyra_target__",yn=class{constructor(e,t,r){this.db=e;this.metadata=t;this.executionBudget=r}runQuery(e){return this.executionBudget.run(e)}normalizeMetadata(){return this.metadata?this.metadata.tables instanceof Map?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}m2mSortCanUseJunction(e){return ke(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,r){if(t.length===0)return{docs:[],hideId:!1};let o=le(r.projection?._id),i=it(r.projection,["_id"]),s=i?{projection:i}:void 0,a=await W(t,c=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:c}},s).toArray()));return{docs:Oe(a,r),hideId:o}}async fetchM2MTopK(e,t,r,o,i,s,a){if(yr(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let c=new Map;for(let _ of e)c.set(B(_),[]);let u=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,l=!i&&this.m2mSortCanUseJunction(t.userSort),f=ke(t.userSort).find(_=>_.field==="_id")?.order??1,d=Tt(t.userSort),p=await W(e,async _=>{if(l&&!u){let C=[{$match:{[r.selfColumn]:{$in:_}}}];return _r(C,r.selfColumn,{[r.otherColumn]:f},s,a),C.push({$sort:{[r.selfColumn]:1,[r.otherColumn]:f}},{$project:{_id:0,[xe]:`$${r.selfColumn}`,[Ue]:`$${r.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate(C).toArray())).map(v=>({sourceId:v[xe],targetId:v[Ue]}))}let $=[{$match:{[r.selfColumn]:{$in:_}}},{$lookup:{from:t.targetTable,localField:r.otherColumn,foreignField:"_id",as:Ct}},{$unwind:`$${Ct}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ct}`,{[xe]:`$${r.selfColumn}`,[Ue]:`$${r.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&$.push({$match:i}),_r($,xe,d,s,a),$.push({$sort:{[xe]:1,...d}}),$.push({$project:{_id:0,[xe]:1,[Ue]:1}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate($).toArray())).map(C=>({sourceId:C[xe],targetId:C[Ue]}))});if(u){let _=new Map;for(let $ of p){let k=B($.targetId);_.has(k)||_.set(k,{_id:$.targetId}),c.get(B($.sourceId))?.push(_.get(k))}return{grouped:c,docs:[],stats:{strategy:l?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:ee(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let g=st(p.map(_=>_.targetId)),h=await this.loadM2MTargets(t.targetTable,g,o),{docs:y}=h,m=new Map(y.map(_=>[B(_._id),_])),w=0;for(let _ of p){let $=m.get(B(_.targetId)),k=c.get(B(_.sourceId));$&&k&&(k.push($),w+=1)}return cn(y,h.hideId),{grouped:c,docs:y,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:ee(e)+(g.length>0?ee(g):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+y.length,rowsDiscarded:p.length-w}}}async fetchM2MEdgeBatch(e,t,r,o,i){let s=new Map;for(let m of e)s.set(B(m),[]);let a=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,c=!i&&this.m2mSortCanUseJunction(t.userSort),u=ke(t.userSort).find(m=>m.field==="_id")?.order??1,l=Tt(t.userSort),f=await W(e,async m=>{if(c&&!a)return(await this.runQuery(()=>this.db.collection(r.junctionName).find({[r.selfColumn]:{$in:m}},{projection:{_id:0,[r.selfColumn]:1,[r.otherColumn]:1},sort:{[r.selfColumn]:1,[r.otherColumn]:u}}).toArray())).map(k=>({sourceId:k[r.selfColumn],targetId:k[r.otherColumn]}));let w=[{$match:{[r.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:r.otherColumn,foreignField:"_id",as:Ct}},{$unwind:`$${Ct}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ct}`,{[xe]:`$${r.selfColumn}`,[Ue]:`$${r.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&w.push({$match:i}),w.push({$sort:{[xe]:1,...l}},{$project:{_id:0,[xe]:1,[Ue]:1}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate(w).toArray())).map($=>({sourceId:$[xe],targetId:$[Ue]}))});if(a){let m=new Map;for(let w of f){let _=B(w.targetId);m.has(_)||m.set(_,{_id:w.targetId}),s.get(B(w.sourceId))?.push(m.get(_))}return{grouped:s,docs:[],stats:{strategy:c?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:ee(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length,rowsDiscarded:0}}}let d=st(f.map(m=>m.targetId)),p=await this.loadM2MTargets(t.targetTable,d,o),{docs:g}=p,h=new Map(g.map(m=>[B(m._id),m])),y=0;for(let m of f){let w=h.get(B(m.targetId)),_=s.get(B(m.sourceId));w&&_&&(_.push(w),y+=1)}return cn(g,p.hideId),{grouped:s,docs:g,stats:{strategy:"m2m-edge-loader",roundtrips:ee(e)+(d.length>0?ee(d):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length+g.length,rowsDiscarded:f.length-y}}}async fetchM2M(e,t,r,o,i){let s=r?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=he(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 c=st(e.map(R=>R._id)),u=new Map;for(let R of e)u.set(B(R._id),[]);if(c.length===0)return{grouped:u,docs:[]};let l=t.userFilter?ce(this.normalizeMetadata(),t.userFilter,t.targetTable):null,f=t.userLimit,d=t.userPage;if(f!==void 0&&(!Number.isSafeInteger(f)||f<0))throw new Error("MongoDB relation limit must be a non-negative safe integer");if(d!==void 0&&(!Number.isSafeInteger(d)||d<1))throw new Error("MongoDB relation page must be a positive safe integer");if(f!==void 0&&f>0){let R=d?(d-1)*f:0;if(!Number.isSafeInteger(R))throw new Error("MongoDB relation pagination offset is too large");return this.fetchM2MTopK(c,t,a,i,l,R,f)}let p=yr(t.userSort);if(!p)return this.fetchM2MEdgeBatch(c,t,a,i,l);let g=await W(c,R=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:R}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:u,docs:[],stats:{strategy:"m2m-batch",roundtrips:ee(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,y=[];for(let R of g){let M=R[a.otherColumn];if(M==null)continue;let N=B(M);h.has(N)||(h.add(N),y.push(M))}if(y.length===0)return{grouped:u,docs:[],stats:{strategy:"m2m-batch",roundtrips:ee(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}};let m=[],w=new Map,_=le(i.projection?._id),$=Pe({_id:{$in:y}},l),k;if(p){k=await W(y,async M=>{let N=Pe({_id:{$in:M}},l),j=an(t.targetTable,N,t.userSort,!0,this.normalizeMetadata());return this.runQuery(()=>this.db.collection(t.targetTable).aggregate(j).toArray())});let R=Tt(t.userSort);k.sort((M,N)=>{for(let[j,O]of Object.entries(R)){let P=(re,E)=>E.split(".").reduce((S,T)=>S?.[T],re),G=ot(P(M,j),P(N,j));if(G!==0)return G*O}return 0})}else{let R=Ke(t.userSort)||{_id:1},M=ln(i.projection,t.userSort),N={sort:R};M.projection&&(N.projection=M.projection),k=await W(y,j=>this.runQuery(()=>this.db.collection(t.targetTable).find(Pe({_id:{$in:j}},l),N).toArray())),Oe(k,i),t.userSort?Mi(k,t.userSort):Ai(k)}let C=new WeakMap;for(let R of k)C.set(R,B(R._id));m=p?Oe(k,i):k;for(let R of m)w.set(C.get(R),R);let x=new Map;for(let R of g){let M=B(R[a.selfColumn]),N=B(R[a.otherColumn]);w.has(N)&&(x.has(N)||x.set(N,[]),x.get(N).push(M))}for(let R of m){let M=x.get(C.get(R))||[];for(let N of M)u.get(N)?.push(R)}un(m,i.projection,p?["__sort_"]:[]),cn(m,_);let v=y.length===0?0:ee(y);return{grouped:u,docs:m,stats:{strategy:"m2m-batch",roundtrips:ee(c)+v,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+m.length}}}};var Rt=class{constructor(e,t,r,o=new We){this.db=e;this.metadata=t;this.fieldRenamesByTable=r;this.executionBudget=o;this.hiddenInverseIds=new WeakSet;this.pkField="_id"}buildSortFromTokens(e){return Ke(e)}compareSortValues(e,t){return ot(e,t)}projectionWithSortFields(e,t){return ln(e,t)}keyOf(e){return B(e)}async fetchM2M(e,t,r,o,i){return new yn(this.db,this.metadata,this.executionBudget).fetchM2M(e,t,r,o,i)}runQuery(e){return this.executionBudget.run(e)}inverseKeyFields(e,t){return[e,...(t.pendingRenames??[]).filter(r=>r.newName===e).map(r=>r.oldName)]}inverseScope(e,t){return e.length===1?{[e[0]]:t}:{$or:e.map(r=>({[r]:t}))}}normalizeInverseKey(e,t,r){for(let o of e){if(o[t]!==void 0)continue;let i=r.find(s=>s!==t&&o[s]!==void 0);i&&(o[t]=o[i])}}normalizeMetadata(){return this.metadata?this.metadata.tables instanceof Map?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortAggregatePipeline(e,t,r,o=!1){return an(e,t,r,o,this.normalizeMetadata())}toObjectId(e){try{return typeof e=="string"?new Di.ObjectId(e):e}catch{return e}}applyPublicProjection(e,t,r=[]){return un(e,t,r)}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){return Ii(e,t,this.fieldRenamesByTable)}async fetchOwner(e,t,r,o){let i=o?.userFilter?ce(this.normalizeMetadata(),o.userFilter,e):null,s=Ke(o?.userSort),a=it(r.projection,["_id"]),c=st(t),u=await W(c,f=>{let d=Pe({_id:{$in:f}},i),p={projection:a};return s&&(p.sort=s),this.runQuery(()=>this.db.collection(e).find(d,p).toArray())}),l=Oe(u,r);return{docs:l,stats:{strategy:"batch-in",roundtrips:ee(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:l.length}}}async fetchInverse(e,t,r,o,i){let s=this.inverseKeyFields(t,o),a=it(o.projection,[...s,"_id"]),c=$=>{if(le(o.projection?._id))for(let k of $)this.hiddenInverseIds.add(k);return $},u=st(r.map($=>this.toObjectId($))),l=i?.userFilter?ce(this.normalizeMetadata(),i.userFilter,e):null,f=i?.userLimit,d=i?.userPage,p=yr(i?.userSort);if(f!==void 0&&f>0){let $=d?(d-1)*f:0;if(p)throw new Error(`Dotted sort is not supported for batch relation '${i?.relationName}'`);let k=Tt(i?.userSort),C=await W(u,async x=>{let R=[{$match:Pe(this.inverseScope(s,{$in:x}),l)}];s.length>1&&R.push({$set:{[t]:{$ifNull:s.map(N=>`$${N}`)}}},{$match:{[t]:{$in:x}}}),_r(R,t,k,$,f),R.push({$sort:{[t]:1,...k}}),Ni(R,a,[t]);let M=await this.runQuery(()=>this.db.collection(e).aggregate(R).toArray());return Oe(M,o)});return{docs:c(C),groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:ee(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:C.length}}}if(p){let $=await W(u,async C=>{let x=Pe(this.inverseScope(s,{$in:C}),l),v=this.buildSortAggregatePipeline(e,x,i.userSort);s.length>1&&v.splice(1,0,{$set:{[t]:{$ifNull:s.map(M=>`$${M}`)}}},{$match:{[t]:{$in:C}}});let R=v.find(M=>M.$sort);return R&&(R.$sort={[t]:1,...R.$sort}),a&&v.push({$project:a}),this.runQuery(()=>this.db.collection(e).aggregate(v).toArray())});this.normalizeInverseKey($,t,s);let k=Oe($,o);return{docs:c(k),groupKeyField:t,stats:{strategy:"batch-dotted-sort",roundtrips:ee(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:k.length}}}let g=Ke(i?.userSort)||{_id:1},h={projection:a,sort:g},y=await W(u,async $=>{let k=await this.runQuery(()=>this.db.collection(e).find(Pe(this.inverseScope(s,{$in:$}),l),h).toArray());this.normalizeInverseKey(k,t,s);let C=new Set($.map(x=>B(x)));return k.filter(x=>C.has(B(x[t])))});this.normalizeInverseKey(y,t,s);let m=new Set(u.map($=>B($))),w=Array.from(new Map(y.filter($=>m.has(B($[t]))).map($=>[`${B($[t])}:${B($._id)}`,$])).values()),_=Oe(w,o);return{docs:c(_),groupKeyField:t,stats:{strategy:"batch-in",roundtrips:ee(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:_.length}}}postProcessInverseChild(e,t,r){this.hiddenInverseIds.delete(e)&&delete e._id,r||delete e[t]}};async function bn(n,e,t,r,o=3,i=0,s,a,c,u){let l=await u?.getActiveFieldRenamesByTable?.(),f=new Rt(n,a,l);await new qe(f,r,c).execute(e,t,o,i,s)}var _n=new WeakMap,Aa=new Set(["__proto__","constructor","prototype"]);function Sr(n){if(n.split(".").some(t=>t.length===0||t.startsWith("$")||Aa.has(t)))throw new Error(`Invalid MongoDB field: ${n}`)}function Ce(n,e){let t=n.$and;if(t===void 0){n.$and=[e];return}if(!Array.isArray(t))throw new Error("Invalid MongoDB $and predicate");t.push(e)}function Li(n){Ce(n,{_id:{$exists:!1,$type:"null"}})}function q(n,e,t){if(Sr(e),!Object.prototype.hasOwnProperty.call(n,e)){n[e]=t;return}let r=n[e];delete n[e],Ce(n,{[e]:r}),Ce(n,{[e]:t})}function Na(n){let e="^";for(let t of String(n))t==="%"?e+="[\\s\\S]*":t==="_"?e+="[\\s\\S]":e+=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&");return`${e}(?![\\s\\S])`}function Oa(n){return Sr(n),n==="_id"?"$_id":`$${n}`}function Ft(n,e,t,r){let o=Oa(e),i=_n.get(n)??[];i.push({ref:o,needle:t,mode:r}),_n.set(n,i)}function wn(n){let e=_n.get(n);if(_n.delete(n),!e?.length)return;let t=[];for(let i of e)t.push(i.ref,{$literal:i.needle},i.mode);let r={$eq:[{$function:{body:pn(),args:t,lang:"js"}},!0]},o=n.$expr;Object.prototype.hasOwnProperty.call(n,"$expr")?n.$expr={$and:[o,r]}:n.$expr=r}function It(n,e,t,r){let o={},i=r==="mongodb"||!r;for(let s of e){Sr(s.field);let a=i&&t&&s.field.startsWith(`${t}.`)?s.field.slice(t.length+1):i||!s.field.includes(".")?s.field:s.field.split(".").pop()??s.field,c=t??"";i&&a==="id"&&(a="_id");let u=V(n,c,a,s.value);switch(Sr(a),s.operator){case"=":q(o,a,u!==null&&typeof u=="object"?{$eq:u}:u);break;case"!=":Sn(n,c,a)?(Ce(o,{[a]:{$ne:null}}),Ce(o,{[a]:{$ne:u}})):q(o,a,{$ne:u});break;case">":q(o,a,{$gt:u});break;case"<":q(o,a,{$lt:u});break;case">=":q(o,a,{$gte:u});break;case"<=":q(o,a,{$lte:u});break;case"like":q(o,a,{$regex:Na(u),$options:"i"});break;case"in":let l=s.value;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(m=>m.trim()):[l]);let f=l.map(m=>V(n,c,a,m)).filter(m=>m!==null);q(o,a,{$in:f});break;case"not in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let p=d.map(m=>V(n,c,a,m));if(p.some(m=>m===null)){Li(o);break}Sn(n,c,a)?(Ce(o,{[a]:{$ne:null}}),Ce(o,{[a]:{$nin:p}})):q(o,a,{$nin:p});break;case"is null":q(o,a,null);break;case"is not null":q(o,a,{$ne:null});break;case"_contains":Ft(o,a,String(u),"contains");break;case"_starts_with":Ft(o,a,String(u),"starts");break;case"_ends_with":Ft(o,a,String(u),"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=V(n,c,a,g[0]),w=V(n,c,a,g[1]);q(o,a,{$gte:m,$lte:w})}break;case"_is_null":let h=s.value===!0||s.value==="true";q(o,a,h?{$eq:null}:{$ne:null});break;case"_is_not_null":let y=s.value===!0||s.value==="true";q(o,a,y?{$ne:null}:{$eq:null});break}}return wn(o),o}function Sn(n,e,t){let o=n?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function $r(n,e,t,r,o,i){switch(Sr(r),o){case"_contains":Ft(e,r,String(i),"contains"),wn(e);break;case"_starts_with":Ft(e,r,String(i),"starts"),wn(e);break;case"_ends_with":Ft(e,r,String(i),"ends"),wn(e);break;case"_eq":{let f=V(n,t,r,i);q(e,r,f!==null&&typeof f=="object"?{$eq:f}:f);break}case"_neq":{let f=V(n,t,r,i);Sn(n,t,r)?(Ce(e,{[r]:{$ne:null}}),Ce(e,{[r]:{$ne:f}})):q(e,r,{$ne:f});break}case"_in":{let f=i;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]);let d=f.map(p=>V(n,t,r,p)).filter(p=>p!==null);q(e,r,{$in:d});break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(f=>f.trim()):[s]);let a=s.map(f=>V(n,t,r,f));if(a.some(f=>f===null)){Li(e);break}Sn(n,t,r)?(Ce(e,{[r]:{$ne:null}}),Ce(e,{[r]:{$nin:a}})):q(e,r,{$nin:a});break;case"_gt":q(e,r,{$gt:V(n,t,r,i)});break;case"_gte":q(e,r,{$gte:V(n,t,r,i)});break;case"_lt":q(e,r,{$lt:V(n,t,r,i)});break;case"_lte":q(e,r,{$lte:V(n,t,r,i)});break;case"_is_null":q(e,r,i===!0||i==="true"?{$eq:null}:{$ne:null});break;case"_is_not_null":q(e,r,i===!0||i==="true"?{$ne:null}:{$eq:null});break;case"_between":let l=i;if(typeof l=="string"&&(l=l.split(",").map(f=>f.trim())),Array.isArray(l)&&l.length===2){let f=V(n,t,r,l[0]),d=V(n,t,r,l[1]);q(e,r,{$gte:f,$lte:d})}break}}var _o=require("mongodb");function vt(n,e){if(e)return n.some(r=>r&&Object.keys(r).length===0)?{}:n.length===0?{_id:{$in:[]}}:n.length===1?n[0]:{$or:n};let t=n.filter(r=>r&&Object.keys(r).length>0);return t.length===0?{}:t.length===1?t[0]:{$and:t}}async function je(n,e,t,r){if(!n||typeof n!="object")return{};let o=t?.tables?.get(e);if(!o)return ce(t,n,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!ye(n,i))return ce(t,n,e);let s=Object.entries(n);if(s.length>1){let l=await Promise.all(s.map(([f,d])=>je({[f]:d},e,t,r)));return vt(l,!1)}if(Array.isArray(n._and)){let l=await Promise.all(n._and.map(f=>je(f,e,t,r)));return vt(l,!1)}if(Array.isArray(n._or)){let l=await Promise.all(n._or.map(f=>je(f,e,t,r)));return vt(l,!0)}if(Object.prototype.hasOwnProperty.call(n,"_not"))return $n(n._not,e,t,r);let{fieldFilters:a,relationFilters:c}=Ae(n,o),u=[];if(a&&Object.keys(a).length>0){let l=ce(t,a,e);l&&Object.keys(l).length>0&&u.push(l)}if(c&&Object.keys(c).length>0)for(let[l,f]of Object.entries(c)){let d=await Pa(l,f,e,o,t,r);d&&Object.keys(d).length>0&&u.push(d)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function $n(n,e,t,r){if(!n||typeof n!="object")return{};let o=t?.tables?.get(e);if(!o)return mn(t,n,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!ye(n,i))return mn(t,n,e);let s=Object.entries(n);if(s.length>1){let l=await Promise.all(s.map(([f,d])=>$n({[f]:d},e,t,r)));return vt(l,!0)}if(Array.isArray(n._and)){let l=await Promise.all(n._and.map(f=>$n(f,e,t,r)));return vt(l,!0)}if(Array.isArray(n._or)){let l=await Promise.all(n._or.map(f=>$n(f,e,t,r)));return vt(l,!1)}if(Object.prototype.hasOwnProperty.call(n,"_not"))return je(n._not,e,t,r);let{fieldFilters:a,relationFilters:c}=Ae(n,o),u=[];if(a&&Object.keys(a).length>0){let l=mn(t,a,e);l&&Object.keys(l).length>0&&u.push(l)}if(c&&Object.keys(c).length>0)for(let[l,f]of Object.entries(c)){let d=await Ba(l,f,e,o,t,r);d&&Object.keys(d).length>0&&u.push(d)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function Pa(n,e,t,r,o,i){let s=(r.relations||[]).find(u=>u.propertyName===n);if(!s)return{};let a=s.targetTableName||s.targetTable,c=o?.tables?.get(a);return!a||!c?{}:s.type==="many-to-one"||s.type==="one-to-one"?ja(e,s,n,a,c,o,i):s.type==="one-to-many"?Ki(e,s,t,a,c,o,i):s.type==="many-to-many"?Ui(e,s,t,a,c,o,i):{}}async function ja(n,e,t,r,o,i,s){let a=Z(e)||t,c=kn(n),u=En(c);if(u!==null)return u?{[a]:null}:{[a]:{$ne:null}};let l=So(c);if(l!==null){let g=xn(l.value);if(l.op==="eq")return{[a]:g};if(l.op==="neq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(l.op==="in")return{[a]:{$in:g}};if(l.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(g=>g!=null);return p.length===0?Qe():{[a]:{$in:p}}}async function Ba(n,e,t,r,o,i){let s=(r.relations||[]).find(u=>u.propertyName===n);if(!s)return{};let a=s.targetTableName||s.targetTable,c=o?.tables?.get(a);if(!a||!c)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return Da(e,s,n,a,c,o,i);if(s.type==="one-to-many"){let u=await Ki(e,s,t,a,c,o,i);return Wi(u)}if(s.type==="many-to-many"){let u=await Ui(e,s,t,a,c,o,i);return Wi(u)}return{}}async function Da(n,e,t,r,o,i,s){let a=Z(e)||t,c=kn(n),u=En(c);if(u!==null)return u?{[a]:{$ne:null}}:{[a]:null};let l=So(c);if(l!==null){let g=xn(l.value);if(l.op==="eq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(l.op==="neq")return{[a]:g};if(l.op==="in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]};if(l.op==="not_in")return{[a]:{$in:g}}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{[a]:null};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(g=>g!=null);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function Ki(n,e,t,r,o,i,s){let a=H(e)||t,c=kn(n),u=En(c);if(u!==null){let d=await qi(s,r,a,{});return u?d.length===0?{}:{_id:{$nin:d}}:d.length===0?Qe():{_id:{$in:d}}}let l=await Tn(c,r,o,i,s);if(!l||Object.keys(l).length===0)return{};let f=await qi(s,r,a,l);return f.length===0?Qe():{_id:{$in:f}}}async function Ui(n,e,t,r,o,i,s){let a=he(t,e);if(!a)return{};let c=kn(n),u=En(c);if(u!==null){let h=await wo(s,a,r,null);return u?h.length===0?{}:{_id:{$nin:h}}:h.length===0?Qe():{_id:{$in:h}}}let l=So(c);if(l!==null){let h=xn(l.value),y=Array.isArray(h)?h:[h],m=await wo(s,a,r,{_id:l.op==="neq"||l.op==="not_in"?{$nin:y,$ne:null}:{$in:y}});return m.length===0?Qe():{_id:{$in:m}}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(h=>h!=null);if(p.length===0)return Qe();let g=await wo(s,a,r,{_id:{$in:p}});return g.length===0?Qe():{_id:{$in:g}}}async function Tn(n,e,t,r,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return ye(n,i)?je(n,e,r,o):ce(r,n,e)}async function qi(n,e,t,r){let o=await n.collection(e).find(r,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let c=a[t];if(c==null)continue;let u=String(c);i.has(u)||(i.add(u),s.push(c))}return s}function Qe(){return{_id:{$in:[]}}}function La(n){if(!n||typeof n!="object")return!1;let e=Object.keys(n);if(e.length!==1||e[0]!=="_id")return!1;let t=n._id;return!!t&&typeof t=="object"&&Array.isArray(t.$in)&&t.$in.length===0}function Wi(n){if(!n||Object.keys(n).length===0)return Qe();if(La(n))return{};let e=n._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:[n]}}async function wo(n,e,t,r){let o=null;r&&t&&(o=(await n.collection(t).find(r,{projection:{_id:1}}).toArray()).map(l=>l._id).filter(l=>l!=null));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await n.collection(e.junctionName).find(i,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,c=[];for(let u of s){let l=u[e.selfColumn];if(l==null)continue;let f=String(l);a.has(f)||(a.add(f),c.push(l))}return c}function kn(n){return n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===1&&n.id&&typeof n.id=="object"?n.id:n}function En(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=Object.keys(n);if(e.length!==1)return null;let t=e[0],r=n[t];return t==="_is_null"?r===!0:t==="_is_not_null"?r!==!0:t==="_eq"?r===null?!0:null:t==="_neq"&&r===null?!1:null}function xn(n){if(Array.isArray(n))return n.map(e=>xn(e));if(typeof n!="string")return n;try{return new _o.ObjectId(n)}catch{return n}}function So(n){if(Array.isArray(n))return{op:"in",value:n};if(n instanceof _o.ObjectId)return{op:"eq",value:n};if(n==null)return null;if(typeof n!="object")return{op:"eq",value:n};if(!n||typeof n!="object"||Array.isArray(n))return null;let e=Object.keys(n);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:n._eq}:t==="_neq"?{op:"neq",value:n._neq}:t==="_in"&&Array.isArray(n._in)?{op:"in",value:n._in}:t==="_not_in"&&Array.isArray(n._not_in)?{op:"not_in",value:n._not_in}:null}function Tr(n){let{targetTable:e,localField:t,foreignField:r,alias:o,pipeline:i,junction:s}=n,a=u=>({$match:{$expr:{$and:[{$ne:[{$ifNull:["$$localId",null]},null]},{$ne:[{$ifNull:[`$${u}`,null]},null]},{$eq:[`$${u}`,"$$localId"]}]}}});if(!s)return{$lookup:{from:e,let:{localId:`$${t}`},pipeline:[a(r),...i],as:o}};let c="__enfyra_sorted_relation_target__";return{$lookup:{from:s.junctionName,let:{localId:`$${t}`},pipeline:[a(s.selfColumn),Tr({targetTable:e,localField:s.otherColumn,foreignField:r,alias:c,pipeline:[]}),{$unwind:`$${c}`},{$replaceRoot:{newRoot:`$${c}`}},...i],as:o}}}wt();async function $o(n,e,t,r,o=1){if(o>me)throw new Error(`MongoDB lookup exceeds maximum relation depth of ${me}`);let i=n?.tables?.get(e);if(!i)throw new Error(`Metadata not found for lookup table '${e}'`);let s=i.relations??[],a=t.map(g=>g==="id"&&!i.columns?.some(h=>h.name==="id")?"_id":g),c=await tt(n,e,a),u=[],l=new Map;if(r&&["_and","_or","_not"].some(g=>Object.prototype.hasOwnProperty.call(r,g))){if(ye(r,new Set(s.map(h=>h.propertyName))))throw new Error(`Logical relation filter is not supported inside nested lookup '${e}'`);let g=ce(n,r,e);Object.keys(g).length>0&&u.push({$match:g})}else if(r){let g={};for(let[h,y]of Object.entries(r)){let m=s.find(_=>_.propertyName===h),w=y&&typeof y=="object"&&Object.keys(y).every(_=>de.has(_));if(m&&y&&typeof y=="object"&&!w)l.set(h,y);else if(y&&typeof y=="object")for(let[_,$]of Object.entries(y))$r(n,g,e,h,_,$);else $r(n,g,e,h,"_eq",y)}Object.keys(g).length>0&&u.push({$match:g})}let d=[...c.relations];for(let g of l.keys()){if(d.some(m=>m.propertyName===g))continue;let h=s.find(m=>m.propertyName===g),y=h.type==="one-to-many"||ge(h);d.push({propertyName:g,targetTable:h.targetTableName||h.targetTable,localField:y||h.type==="many-to-many"?"_id":Z(h)||g,foreignField:y&&h.type!=="many-to-many"?H(h)||g:"_id",type:h.type==="one-to-many"||h.type==="many-to-many"?"many":"one",nestedFields:["_id"]})}for(let g of d){let h=s.find(w=>w.propertyName===g.propertyName),y=l.get(g.propertyName),m=await $o(n,g.targetTable,g.nestedFields.length?g.nestedFields:["_id"],y,o+1);g.type==="one"&&m.push({$limit:1}),u.push(Tr({targetTable:g.targetTable,localField:h?.type==="many-to-many"?"_id":g.localField,foreignField:g.foreignField,alias:g.propertyName,pipeline:m,junction:h?.type==="many-to-many"?he(e,h):null})),g.type==="one"&&u.push({$unwind:{path:`$${g.propertyName}`,preserveNullAndEmptyArrays:!0}}),y&&u.push({$match:g.type==="one"?{[g.propertyName]:{$ne:null}}:{[`${g.propertyName}.0`]:{$exists:!0}}})}let p={_id:1};for(let g of c.scalarFields)p[g]=1;for(let g of c.relations)p[g.propertyName]=1;return u.push({$project:p}),u}async function Qi(n,e,t,r,o){let i={_id:1};for(let s of r)i[s]=1;for(let s of o)s.type==="one"&&s.localField&&(i[s.localField]=1);e.push({$project:i})}function To(n,e){if(!n||typeof n!="object"||Array.isArray(n))return!1;let t=Object.entries(n);return t.length>0&&t.every(([r,o])=>r===e?!0:r==="_not"?To(o,e):r==="_and"||r==="_or"?Array.isArray(o)&&o.length>0&&o.every(i=>To(i,e)):!1)}function Cn(n,e){if(!n||typeof n!="object"||Array.isArray(n))return;let t=[];if(Object.prototype.hasOwnProperty.call(n,e)&&t.push(n[e]),Array.isArray(n._and)){let r=n._and.map(o=>Cn(o,e)).filter(o=>o!==void 0);t.push(...r)}if(Array.isArray(n._or)&&n._or.length>0){let r=n._or.map(o=>Cn(o,e));r.every(o=>o!==void 0)&&t.push({_or:r})}if(To(n._not,e)){let r=Cn(n._not,e);r!==void 0&&t.push({_not:r})}if(t.length!==0)return t.length===1?t[0]:{_and:t}}async function Fn(n,e,t){let r=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,c=t.execute!==!1;e.deep!==void 0&&rt(e.table,e.deep,i);let u=e.offset??0,l=e.limit===0?void 0:e.limit;if(!Number.isSafeInteger(u)||u<0)throw new Error("MongoDB offset must be a non-negative safe integer");if(l!=null&&(!Number.isSafeInteger(l)||l<0))throw new Error("MongoDB limit must be a non-negative safe integer");!e.mongoRawFilter&&e.plan?.rawFilter&&(e={...e,mongoRawFilter:e.plan.rawFilter});let f=i?.tables?.get(e.table),d=new Set((f?.relations??[]).map(T=>T.propertyName)),p=!!e.mongoRawFilter&&!!i&&ye(e.mongoRawFilter,d),g=e.plan,h=g?.filterTree&&!g.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&p){let T=await je(e.mongoRawFilter,e.table,i,o);T&&Object.keys(T).length>0&&r.push({$match:T})}else if(h){let T=xt(g.filterTree,{metadata:i,rootTable:e.table});Object.keys(T).length>0&&r.push({$match:T})}else if(e.mongoRawFilter){let T=ce(i,e.mongoRawFilter,e.table);Object.keys(T).length>0&&r.push({$match:T})}else if(e.where){let T=It(i,e.where,e.table,s);r.push({$match:T})}let y=e.plan,w=y?y.hasRelationSort:e.sort?.some(T=>{if(!T.field.includes("."))return!1;let F=T.field.split(".")[0];return d.has(F)||(e.mongoFieldsExpanded?.relations?.some(L=>L.propertyName===F)??!1)})??!1,_=(T,F=e.table)=>{let L=T.split("."),A=F;for(let J of L.slice(0,-1)){let K=i?.tables?.get(A)?.relations?.find(Fe=>Fe.propertyName===J);if(!K)return T;A=K.targetTableName||K.targetTable}let Re=i?.tables?.get(A);return L.at(-1)==="id"&&!Re?.columns?.some(J=>J.name==="id")&&(L[L.length-1]="_id"),L.join(".")},$=()=>{let T=y?.sortItems?.length?gr(y.sortItems):e.sort?.length?Object.fromEntries(e.sort.map(F=>[_(F.field),F.direction==="desc"?-1:1])):null;return T&&Object.keys(T).length>0?T:null},k=y?.sortItems?$i(y.sortItems):[],C=y?.sortItems?Ti(y.sortItems):[],x=new Set((i?.tables?.get(e.table)?.columns??[]).map(T=>T.name));for(let T of e.mongoCountOnly?[]:[...k,...C])if(x.has(T))throw new Error(`MongoDB relation sort alias conflicts with a root field: ${T}`);let v=()=>{!y||k.length===0||ki(r,e.table,y.sortItems,i)},R=()=>{!y||C.length===0||Ei(r,e.table,y.sortItems,i)},M=()=>{let T=[...k,...C];T.length===0||e.mongoCountOnly||r.push({$project:Object.fromEntries(T.map(F=>[F,0]))})};if(!e.mongoFieldsExpanded){if(w&&!e.mongoCountOnly&&(y?.sortItems.some(F=>!F.function&&F.joinId!==null)??!0))throw new Error("MongoDB relation sort requires expanded relation fields");if(!e.mongoCountOnly){v(),R();let F=$();F&&r.push({$sort:F})}if(e.mongoCountOnly?r.push({$count:"count"}):(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l})),M(),!e.mongoCountOnly&&e.select?.length){let F={_id:0};for(let L of e.select)F[_(L)]=1;r.push({$project:F})}if(a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:[...r]}),!c)return{results:[],pipeline:r};let T=await n.aggregate(r).toArray();return e.mongoCountOnly?{results:T,pipeline:r}:{results:Rn(T),pipeline:r}}let{scalarFields:N,relations:j}=e.mongoFieldsExpanded;if(!w){if(!e.mongoCountOnly){v(),R();let T=$();T&&r.push({$sort:T})}e.mongoCountOnly||(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l}))}let O=new Set(e.mongoCountOnly?[]:y?.sortItems.filter(T=>T.joinId!==null&&!T.function).map(T=>T.fullPath.split(".")[0])??e.sort?.filter(T=>T.field.includes(".")&&(d.has(T.field.split(".")[0])||j.some(F=>F.propertyName===T.field.split(".")[0]))).map(T=>T.field.split(".")[0])??[]);for(let T of O)if(!j.some(F=>F.propertyName===T))throw new Error(`MongoDB relation sort expansion is missing for '${T}'`);let P=j,G=new Map,re=new Set([...x,...j.map(T=>T.propertyName)]);for(let T of j){if(!O.has(T.propertyName))continue;let F=`__enfyra_relation_sort_${G.size}`;for(;re.has(F);)F+="_";re.add(F),G.set(T.propertyName,F);let L=(y?.sortItems??e.sort?.map(K=>({fullPath:K.field,direction:K.direction,function:void 0}))??[]).filter(K=>!K.function&&K.fullPath.startsWith(`${T.propertyName}.`)),A=L.map(K=>K.fullPath.slice(T.propertyName.length+1)),Re=await $o(i,T.targetTable,A.length?A:["_id"],Cn(e.mongoRawFilter,T.propertyName)),J=Object.create(null);for(let K of L){let Fe=K.fullPath.slice(T.propertyName.length+1);J[y?Fe:_(Fe,T.targetTable)]=K.direction==="desc"?-1:1}J._id===void 0&&(J._id=1),Re.push({$sort:J},{$limit:1});let U=i?.tables?.get(e.table)?.relations?.find(K=>K.propertyName===T.propertyName);r.push(Tr({targetTable:T.targetTable,localField:U?.type==="many-to-many"?"_id":T.localField,foreignField:T.foreignField,alias:F,pipeline:Re,junction:U?.type==="many-to-many"?he(e.table,U):null})),r.push({$unwind:{path:`$${F}`,preserveNullAndEmptyArrays:!0}})}if(w){if(!e.mongoCountOnly){v(),R();let T=$();if(T){let F=Object.create(null);for(let[L,A]of Object.entries(T)){let[Re,...J]=L.split("."),U=G.get(Re);F[U&&J.length?`${U}.${J.join(".")}`:L]=A}r.push({$sort:F})}}e.mongoCountOnly||(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l}))}if(e.mongoCountOnly?r.push({$count:"count"}):(M(),await Qi(i,r,e.table,N,[...j])),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:[...r]}),!c)return{results:[],pipeline:r};let E=performance.now(),S=await n.aggregate(r).toArray();if(e.debugTrace?.dur("db_execute",E,{table:e.table}),e.mongoCountOnly)return{results:S,pipeline:r};if(P.length>0&&S.length>0){let T=e.deep||{},F=P.map(A=>{let J=i?.tables?.get(e.table)?.relations?.find(Kn=>Kn.propertyName===A.propertyName),U=T[A.propertyName],K=U?.limit===void 0?void 0:Number(U.limit),Fe=U?.page===void 0?void 0:Number(U.page);if(K!==void 0&&(!Number.isSafeInteger(K)||K<0))throw new Error("MongoDB relation limit must be a non-negative safe integer");if(Fe!==void 0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new Error("MongoDB relation page must be a positive safe integer");let ws=U?.fields!=null?Array.isArray(U.fields)?U.fields:String(U.fields).split(",").map(Kn=>Kn.trim()).filter(Boolean):A.nestedFields&&A.nestedFields.length>0?A.nestedFields:["_id"];return{relationName:A.propertyName,type:J?.type,targetTable:A.targetTable,fields:ws,isInverse:J?.isInverse,mappedBy:J?.mappedBy,junctionTableName:J?.junctionTableName,junctionSourceColumn:J?.junctionSourceColumn,junctionTargetColumn:J?.junctionTargetColumn,localField:A.localField,foreignField:A.foreignField,injectedParentFields:A.type==="one"&&A.localField&&A.localField!==A.propertyName&&!N.includes(A.localField)?[A.localField]:void 0,userFilter:U?.filter,userSort:U?.sort,userLimit:K,userPage:Fe,nestedDeep:U?.deep}}),L=ko(i);if(!L)throw new Error("MongoDB relation hydration requires metadata");await bn(o,S,F,L,3,0,e.table,i,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Rn(S),pipeline:r}}function ko(n){let e=n;return e?async t=>{let r=e.tables?.get(t);return r?{name:r.name,columns:(r.columns||[]).map(o=>({name:o.name,type:o.type})),relations:r.relations||[]}:null}:null}function zi(n){if(n===null||typeof n!="object")return!1;let e=new WeakSet,t=[n];for(;t.length>0;){let r=t.pop();if(!e.has(r)){if(e.add(r),Array.isArray(r)){for(let o of r)o&&typeof o=="object"&&t.push(o);continue}for(let[o,i]of Object.entries(r)){if(i===null){if(o==="_eq"||o==="$eq")return!0;continue}if(!(!i||typeof i!="object")){if(Object.prototype.hasOwnProperty.call(i,"_is_null")&&(i._is_null===!0||i._is_null==="true")||Object.prototype.hasOwnProperty.call(i,"_eq")&&i._eq===null||Object.prototype.hasOwnProperty.call(i,"$eq")&&i.$eq===null)return!0;t.push(i)}}}}return!1}function Rn(n){return n.map(se)}function Ji(n,e){let t=[],r=[],o=e?.tables?.get(n.rootTable);if(!o)return{scalarFields:t,relations:r};for(let i of n.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"&&r.push(qa(i,o,e));return{scalarFields:t,relations:r}}function qa(n,e,t){let r=e.relations?.find(u=>u.propertyName===n.propertyName),o,i,s=!1;n.relationType==="many-to-one"||n.relationType==="one-to-one"?r&&ge(r)?(o="_id",i=H(r)||n.propertyName,s=!0):(o=r&&Z(r)||n.propertyName,i="_id",s=!1):n.relationType==="one-to-many"?(o="_id",i=r&&H(r)||n.propertyName,s=!0):r?.mappedBy?(o="_id",i=r.mappedBy,s=!0):(o=n.propertyName,i="_id",s=!1);let a=n.relationType==="one-to-many"||n.relationType==="many-to-many",c=Hi(n.children);return{propertyName:n.propertyName,targetTable:n.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:c}}function Hi(n){let e=[];for(let t of n)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let r=Hi(t.children);if(r.length===0)e.push(`${t.propertyName}.id`);else for(let o of r)e.push(`${t.propertyName}.${o}`)}return e}Le();ne();var Wa=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Ka=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),Ua=new Set(["hour","day","week","month","year"]),Qa=new Set(["count","countDistinct","sum","avg","min","max"]);function D(n,e){throw new b(e,{path:n})}function Mt(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function za(n,e){let t=n?.tables?.get(e);return t||D("aggregate",`Table "${e}" metadata is not available`),t}function Vi(n,e,t){let r=n.columns?.find(o=>o.name===e);return r||D(t,`Unknown aggregate field "${e}"`),r.isEncrypted===!0&&D(t,`Encrypted field "${e}" cannot be used in aggregate queries`),r}function Ja(n,e){let t=n===void 0?"UTC":n;(typeof t!="string"||t.length===0)&&D(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{D(e,`Invalid aggregate timezone "${t}"`)}return t}function Ha(n,e){return n==null?{}:(Mt(n)||D(e,"Aggregate filter must be an object"),n)}function Gi(n,e,t){let r;return typeof n=="number"?r=n:typeof n=="string"&&/^\d+$/.test(n)?r=Number(n):D(e,t),Number.isSafeInteger(r)||D(e,t),r}function At(n,e,t){Mt(n)||D("aggregate","Aggregate options must be an object");let r=za(t,e),o=n.dimensions===void 0?[]:n.dimensions,i=n.measures;Array.isArray(o)||D("aggregate.dimensions","Aggregate dimensions must be an array"),(!Mt(i)||Object.keys(i).length===0)&&D("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=o.map((m,w)=>{let _=`aggregate.dimensions[${w}]`;(!Mt(m)||typeof m.field!="string"||m.field.length===0)&&D(_,"Aggregate dimension requires a field");let $=Vi(r,m.field,`${_}.field`);return s.has(m.field)&&D(`${_}.field`,`Duplicate aggregate dimension "${m.field}"`),s.add(m.field),m.bucket===void 0?(m.timezone!==void 0&&D(`${_}.timezone`,"Aggregate timezone requires a bucket"),{field:m.field,outputKey:m.field,column:$}):((typeof m.bucket!="string"||!Ua.has(m.bucket))&&D(`${_}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Ka.has(String($.type).toLowerCase())||D(`${_}.bucket`,`Aggregate bucket requires a date field, but "${m.field}" is "${$.type}"`),{field:m.field,outputKey:m.field,bucket:m.bucket,timezone:Ja(m.timezone,`${_}.timezone`),column:$})}),c=new Set,u=Object.entries(i).map(([m,w])=>{let _=`aggregate.measures.${m}`;(!m||!Mt(w))&&D(_,"Aggregate measure must be an object");let $=Object.entries(w);$.length!==1&&D(_,"Aggregate measure must define exactly one operation");let[k,C]=$[0];Qa.has(k)||D(_,`Unsupported aggregate measure "${k}"`),(typeof C!="string"||C.length===0)&&D(_,"Aggregate measure field must be a non-empty string");let x=Vi(r,C,`${_}.${k}`);return(c.has(m)||s.has(m))&&D(_,`Aggregate output key "${m}" is duplicated`),c.add(m),["sum","avg","min","max"].includes(k)&&!Wa.has(String(x.type).toLowerCase())&&D(_,`Aggregate ${k} requires a numeric field, but "${C}" is "${x.type}"`),{outputKey:m,operation:k,field:C,column:x}}),l=n.sort===void 0?[]:n.sort;Array.isArray(l)||D("aggregate.sort","Aggregate sort must be an array");let f=new Set([...s,...c]),d=l.map((m,w)=>{let _=`aggregate.sort[${w}]`;return(!Mt(m)||typeof m.field!="string"||!f.has(m.field))&&D(_,"Aggregate sort field must reference a dimension or measure output"),m.direction!=="asc"&&m.direction!=="desc"&&D(`${_}.direction`,"Aggregate sort direction must be asc or desc"),{field:m.field,direction:m.direction}}),p="Aggregate limit must be an integer between 1 and 10000",g="Aggregate page must be a positive integer",h=n.limit===void 0?void 0:Gi(n.limit,"aggregate.limit",p),y=n.page===void 0?1:Gi(n.page,"aggregate.page",g);return h!==void 0&&(h<=0||h>1e4)&&D("aggregate.limit",p),y<=0&&D("aggregate.page",g),{tableName:e,filter:Ha(n.filter,"aggregate.filter"),dimensions:a,measures:u,sort:d,page:y,limit:h}}var lt=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.db=e.getDb()}async execute(e){let t={metadata:e.metadata,dbType:e.dbType||"mongodb",debugLog:e.debugLog,execute:!e.debugMode};if(!e.plan){let m=new pe;e={...e,plan:m.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"})}}e={...e,fields:e.plan.rawFields};let r=e.plan.rawFields!==void 0&&e.plan.rawFields.length===0&&!Object.keys(e.deep??{}).length;e.deep!==void 0&&rt(e.tableName,e.deep,e.metadata);let o={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};e.pipeline&&(o.pipeline=e.pipeline),r?(o.fields=["_id"],o.mongoFieldsExpanded={scalarFields:["_id"],relations:[]}):e.fields&&(Array.isArray(e.fields)?o.fields=e.fields:typeof e.fields=="string"&&(o.fields=e.fields.split(",").map(m=>m.trim())));let i=e.filter??e.plan?.rawFilter;if(i&&(De(i,e.tableName,e.metadata),o.mongoRawFilter=i),e.sort){let m=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(w=>w.trim());o.sort=m.map(w=>{let _=w.trim();return _.startsWith("-")?{field:_.substring(1),direction:"desc"}:{field:_,direction:"asc"}})}else o.sort=[{field:"id",direction:"asc"}];let s=this.normalizePaginationValue(e.page,"page",1),a=this.normalizePaginationValue(e.limit,"limit",0);if(s!==void 0&&a===void 0)throw new Error("limit is required when page is provided");s!==void 0&&a!==void 0?(o.offset=(s-1)*a,o.limit=a):a!==void 0&&(o.limit=a);let c=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(m=>m.trim()).filter(Boolean),u=0,l=0;(c.includes("totalCount")||c.includes("*"))&&(u=await this.mongoService.collection(e.tableName).countDocuments({}));let f=t.metadata?.tables?.get(e.tableName),d=new Set((f?.relations??[]).map(m=>m.propertyName)),p=!!o.mongoRawFilter&&ye(o.mongoRawFilter,d);if((c.includes("filterCount")||c.includes("*"))&&!p){let m=this.mongoService.collection(e.tableName),w=e.plan?.filterTree?xt(e.plan.filterTree,{metadata:t.metadata,rootTable:e.tableName}):{};l=await m.countDocuments(w)}o.plan=e.plan,o.deep=e.deep;let g=await this.selectLegacy(o,t),h=r?g.results.map(()=>({})):g.results,y=typeof this.mongoService?.parseResult=="function"?await this.mongoService.parseResult(h,e.tableName):h;if(e.debugMode){let m;try{m=await this.db.collection(e.tableName).aggregate(g.pipeline).explain()}catch(w){m={error:String(w)}}return{pipeline:g.pipeline,explain:m}}if(p&&(c.includes("filterCount")||c.includes("*"))){let m={...o,pipeline:void 0,mongoCountOnly:!0},w=await this.selectLegacy(m,t);l=w.results.length>0?w.results[0].count:0}return{data:y,...c.length>0&&{meta:{...c.includes("totalCount")||c.includes("*")?{totalCount:u}:{},...c.includes("filterCount")||c.includes("*")?{filterCount:l}:{}}}}}async aggregate(e){let t=At(e.aggregate,e.tableName,e.metadata),r=this.db.collection(e.tableName),o=new pe().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),i=o.hasRelationFilters?await je(t.filter,e.tableName,e.metadata,this.db):o.filterTree?xt(o.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(i).length>0&&s.push({$match:i});let a={_id:{}},c={};for(let l of t.dimensions){let f=`$${l.field}`,d=l.bucket?{$dateTrunc:{date:f,unit:l.bucket,timezone:l.timezone}}:f;a._id[l.outputKey]=d,c[l.outputKey]=`$_id.${l.outputKey}`}for(let l of t.measures){let f=`$${l.field}`;a[l.outputKey]=l.operation==="count"?{$sum:{$cond:[{$ne:[{$ifNull:[f,null]},null]},1,0]}}:l.operation==="countDistinct"?{$addToSet:f}:{[`$${l.operation}`]:f},c[l.outputKey]=l.operation==="countDistinct"?{$size:{$setDifference:[`$${l.outputKey}`,[null]]}}:`$${l.outputKey}`}return s.push({$group:a},{$project:{_id:0,...c}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(l=>[l.field,l.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),e.debugMode?{pipeline:s,explain:await r.aggregate(s).explain()}:{data:(await r.aggregate(s).toArray()).map(se)}}normalizePaginationValue(e,t,r){if(e==null)return;let o;if(typeof e=="number")o=e;else if(typeof e=="string"&&/^\d+$/.test(e))o=Number(e);else throw new Error(`${t} must be a ${r===1?"positive":"non-negative"} integer`);if(!Number.isSafeInteger(o)||o<r)throw new Error(`${t} must be a ${r===1?"positive":"non-negative"} integer`);return o}async selectLegacy(e,t){let r=[],o=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=t.metadata?.tables?.get(e.table),s=i?.relations&&i.relations.length>0;if(!e.mongoFieldsExpanded&&(e.fields&&e.fields.length>0||o||s)){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=Ji(l.fieldTree,t.metadata),o){let d=await tt(t.metadata,e.table,[],e.deep),p=new Set(e.mongoFieldsExpanded.relations.map(g=>g.propertyName));e.mongoFieldsExpanded.relations.push(...d.relations.filter(g=>!p.has(g.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await tt(t.metadata,e.table,f,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let d=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:d.scalarFields},r=d.hiddenFields}}e.where&&(e.where=e.where.map(l=>l.field.includes(".")?l:{...l,field:`${e.table}.${l.field}`}));let a=this.db.collection(e.table);if(e.pipeline)return t.debugLog?.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),t.execute?{results:(await a.aggregate(e.pipeline).toArray()).map(se),pipeline:e.pipeline}:{results:[],pipeline:e.pipeline};let{results:c,pipeline:u}=await Fn(a,e,{db:this.db,metadata:t.metadata,dbType:t.dbType,debugLog:t.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService,execute:t.execute});return this.mongoPhysicalMigrationService&&t.execute?{results:await this.mongoPhysicalMigrationService.applyReadFallback(e.table,c,r),pipeline:u}:{results:c,pipeline:u}}};Le();var Yi=require("util"),In=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;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{try{t=(0,Yi.inspect)(e,{depth:4,maxArrayLength:100,maxStringLength:4e3,customInspect:!1,getters:!1})}catch{t="[Unserializable]"}}return this.context?`[${this.context}] ${t}`:t}};Se();Se();var Va=new Set(["_and","_or","_not"]),Ga=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]);function ct(n){if(!n||typeof n!="object")return!1;let e=new WeakSet,t=[n];try{for(;t.length>0;){let r=t.pop();if(e.has(r))continue;e.add(r);let o=Object.getOwnPropertyDescriptors(r);for(let[i,s]of Object.entries(o)){if(!s.enumerable)continue;if(s.get||s.set||Va.has(i))return!0;if(Ga.has(i))continue;let a=s.value;a&&typeof a=="object"&&t.push(a)}}}catch{return!0}return!1}var Eo=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"],Ya=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kr(n){if(typeof n!="string"||!Ya.test(n))throw new Error("Invalid UUID filter value")}function Xa(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Za(n){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[n]||n}function vn(n,e,t){if(!t)return!1;let r=n;if(n.includes(".")){let s=n.split(".");r=s[s.length-1]}let o=t.columns.find(s=>s.name===r);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function el(n,e,t,r,o){return r!=="postgres"||typeof e!="string"||vn(n,t,o)&&kr(e),e}function Xi(n,e,t,r,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,c=ze(a,i??"postgres"),u=vn(e,o,s),l=["_eq","_neq","_gt","_gte","_lt","_lte"].includes(t)?el(e,r,o,i,s):r;switch(t){case"_eq":r===null?n.whereNull(a):u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} = ?::uuid`,[r]):n.where(a,"=",l);break;case"_neq":r===null?n.whereNotNull(a):u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} != ?::uuid`,[r]):n.where(a,"!=",l);break;case"_gt":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} > ?::uuid`,[r]):n.where(a,">",l);break;case"_gte":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} >= ?::uuid`,[r]):n.where(a,">=",l);break;case"_lt":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} < ?::uuid`,[r]):n.where(a,"<",l);break;case"_lte":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} <= ?::uuid`,[r]):n.where(a,"<=",l);break;case"_in":let f=r;if(Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&i==="postgres"){for(let p of f)kr(p);n.whereRaw(`${c} = ANY(?::uuid[])`,[f])}else n.whereIn(a,f);break;case"_not_in":case"_nin":let d=r;if(Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(p=>p.trim()):[d]),u&&i==="postgres"){for(let p of d)kr(p);n.whereRaw(`${c} != ALL(?::uuid[])`,[d])}else n.whereNotIn(a,d);break;case"_contains":case"_starts_with":case"_ends_with":{let p=Xa(r),g=t==="_contains"?`%${p}%`:t==="_starts_with"?`${p}%`:`%${p}`;i==="postgres"?n.whereRaw(`lower(unaccent(${c})) ILIKE lower(unaccent(?)) ESCAPE '='`,[g]):i==="sqlite"?n.whereRaw(`lower(${c}) LIKE lower(?) ESCAPE '='`,[g]):n.whereRaw(`lower(${c}) COLLATE utf8mb4_general_ci LIKE lower(?) COLLATE utf8mb4_general_ci ESCAPE '='`,[g]);break}case"_between":if(!Array.isArray(r)||r.length!==2)throw new Error("Invalid SQL _between filter");n.whereBetween(a,[r[0],r[1]]);break;case"_is_null":r===!0?n.whereNull(a):n.whereNotNull(a);break;case"_is_not_null":r===!0?n.whereNotNull(a):n.whereNull(a);break;default:n.where(a,Za(t),r)}}function tl(n,e,t){if(n==="_and"||n==="_or"||n==="_not"||!t)return!0;let r=n.split(".");if(r.length>1&&(!e||r[0]!==e))return!1;let o=r[r.length-1],i=t.columns?.some(a=>a.name===o),s=t.relations?.some(a=>a.propertyName===o);return i||s}function Nt(n,e,t,r="and",o,i){if(!(!e||typeof e!="object")){if(Object.keys(e).length===0){n.whereRaw("1 = 1");return}if(Array.isArray(e)){for(let s of e)r==="and"?n.where(function(){Nt(this,s,t,"and",o,i)}):n.orWhere(function(){Nt(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e)){if(!tl(s,t,i))throw new Error(`Invalid SQL filter field: ${s}`);if(s==="_and"){if(Array.isArray(a)){if(a.length===0){n.whereRaw("1 = 1");continue}n.where(function(){for(let c of a)this.where(function(){Nt(this,c,t,"and",o,i)})})}continue}if(s==="_or"){if(Array.isArray(a)){if(a.length===0){n.whereRaw("1 = 0");continue}n.where(function(){for(let c of a)this.orWhere(function(){Nt(this,c,t,"and",o,i)})})}continue}if(s==="_not"){let c=function(){Nt(this,a,t,"and",o,i)};r==="or"?n.orWhereNot(c):n.whereNot(c);continue}if(typeof a=="object"&&a!==null){let c=Object.keys(a),u=c.some(l=>Eo.includes(l));if(u&&c.some(l=>!Eo.includes(l)))throw new Error(`Invalid SQL filter operator for field: ${s}`);if(u)for(let[l,f]of Object.entries(a))Eo.includes(l)&&(r==="and"?n.where(function(){Xi(this,s,l,f,t,o,i)}):n.orWhere(function(){Xi(this,s,l,f,t,o,i)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s,f=ze(l,o??"postgres");vn(s,t,i)&&o==="postgres"&&typeof a=="string"?(kr(a),r==="and"?n.whereRaw(`${f} = ?::uuid`,[a]):n.orWhereRaw(`${f} = ?::uuid`,[a])):r==="and"?n.where(l,"=",a):n.orWhere(l,"=",a)}}else{let c=t&&!s.includes(".")?`${t}.${s}`:s,u=ze(c,o??"postgres"),l=vn(s,t,i);a===null?r==="and"?n.whereNull(c):n.orWhereNull(c):l&&o==="postgres"&&typeof a=="string"?(kr(a),r==="and"?n.whereRaw(`${u} = ?::uuid`,[a]):n.orWhereRaw(`${u} = ?::uuid`,[a])):r==="and"?n.where(c,"=",a):n.orWhere(c,"=",a)}}}}function ut(n,e,t,r,o){return!e||typeof e!="object"||Nt(n,e,t,"and",r,o),n}function Zi(n){let e=String(n??0);if(!/^\d+$/.test(e))throw new Error("Database count is not a non-negative integer");let t=Number(e);if(!Number.isSafeInteger(t))throw new Error("Database count exceeds JavaScript safe integer range");return t}async function Mn(n,e,t,r,o){let i={};if(r.includes("totalCount")||r.includes("*")){let s=await n(t).count("* as count").first();i.totalCount=Zi(s?.count)}if(r.includes("filterCount")||r.includes("*")){let s=e.clone().clearOrder().clear("limit").clear("offset"),a=await n.from(s.as("enfyra_count_source")).count("* as count").first();i.filterCount=Zi(a?.count)}return i}function Er(n,e,t){if(!n||!t)return n;let r=t.tables?.get(e);if(!r)return n;if(Array.isArray(n))return n.map(i=>Er(i,e,t));if(typeof n!="object"||Buffer.isBuffer(n))return n;let o={...n};for(let i of r.columns)if(i.type==="simple-json"&&o[i.name]&&typeof o[i.name]=="string")try{o[i.name]=JSON.parse(o[i.name])}catch{}for(let i of r.relations??[]){let s=i.propertyName;if(!Object.prototype.hasOwnProperty.call(o,s))continue;let a=i.targetTableName||i.targetTable;a&&(o[s]=Er(o[s],a,t))}return o}var os=require("crypto");ft();Se();var rl=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);function es(n,e){if(!e)return!1;let t=e.columns.find(o=>o.name===n);if(!t)return!1;let r=t.type?.toLowerCase()||"";return r==="uuid"||r==="uuidv4"||r.includes("uuid")}function ts(n){return n===!0||n==="true"?!0:n===!1||n==="false"?!1:null}function rs(n){return n&&te(n)?.name||"id"}function An(n,e,t,r,o,i,s){let a=es(e,o),c=es(r,i),u=`${I(n,s)}.${I(e,s)}`,l=`${I(t,s)}.${I(r,s)}`;if(s==="postgres"){if(a&&!c)return`${u} = ${l}::uuid`;if(!a&&c)return`${u}::uuid = ${l}`}return`${u} = ${l}`}function nl(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return Object.keys(e).length!==1||!e.id||typeof e.id!="object"||Array.isArray(e.id)?!1:Object.keys(e.id).every(t=>rl.has(t))}function ol(n,e,t){return`__enfyra_relation_${(0,os.createHash)("sha256").update(JSON.stringify([t,n,e])).digest("hex").slice(0,16)}`}function ns(n,e,t){return n(e===t?e:{[t]:e})}async function is(n,e,t,r,o,i,s){let a=o.relations.find(g=>g.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${o.name}"`);let c=a.targetTableName||a.targetTable;if(!c)throw new Error(`Relation "${t}" in table "${o.name}" is missing target metadata`);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn&&nl(r))return null;let u=s?await s(c):null,l=ol(t,c,e),f=rs(o),d=rs(u),p;switch(a.type){case"one-to-many":{if(!a.foreignKeyColumn)throw new Error(`Relation "${t}" is missing a foreign key`);p=ns(n,c,l).select(n.raw("1")).whereRaw(An(l,a.foreignKeyColumn,e,f,u,o,i));break}case"many-to-many":{if(!a.junctionTableName||!a.junctionSourceColumn||!a.junctionTargetColumn)throw new Error(`Relation "${t}" is missing junction metadata`);let g=s?await s(a.junctionTableName):null;p=n(a.junctionTableName).select(n.raw("1")).join({[l]:c},n.raw(An(a.junctionTableName,a.junctionTargetColumn,l,d,g,u,i))).whereRaw(An(a.junctionTableName,a.junctionSourceColumn,e,f,g,o,i));break}case"many-to-one":case"one-to-one":{if(!a.foreignKeyColumn)throw new Error(`Relation "${t}" is missing a foreign key`);p=ns(n,c,l).select(n.raw("1")).whereRaw(An(l,d,e,a.foreignKeyColumn,u,o,i));break}default:throw new Error(`Unsupported relation type: ${a.type}`)}return u?await as(n,p,r,l,u,i,s,c):ut(p,r,l,i),{query:p}}async function ss(n,e,t,r,o,i,s){let a=await is(n,e,t,r,o,i,s);return a?a.query.toString():null}function il(n,e,t){for(let[r,o]of Object.entries(t))switch(r){case"_is_null":{let i=ts(o);i===!0?n.whereNull(e):i===!1&&n.whereNotNull(e);break}case"_is_not_null":{let i=ts(o);i===!0?n.whereNotNull(e):i===!1&&n.whereNull(e);break}case"_eq":o===null?n.whereNull(e):n.where(e,"=",o);break;case"_neq":o===null?n.whereNotNull(e):n.where(e,"!=",o);break;case"_in":{let i=(Array.isArray(o)?o:[o]).filter(s=>s!==null);i.length===0?n.whereRaw("1 = 0"):n.whereIn(e,i);break}case"_not_in":case"_nin":{let i=Array.isArray(o)?o:[o];i.some(s=>s===null)?n.whereRaw("1 = 0"):i.length===0?n.whereRaw("1 = 1"):n.whereNotIn(e,i);break}case"_gt":n.where(e,">",o);break;case"_gte":n.where(e,">=",o);break;case"_lt":n.where(e,"<",o);break;case"_lte":n.where(e,"<=",o);break;default:throw new Error(`Unsupported direct relation operator: ${r}`)}}function dt(n){return{constant:n,apply(e){e.whereRaw(n?"1 = 1":"1 = 0")}}}function xo(n){if(n.some(t=>t.constant===!1))return dt(!1);let e=n.filter(t=>t.constant!==!0);return e.length===0?dt(!0):{apply(t){for(let r of e)r.apply(t)}}}function sl(n){if(n.some(t=>t.constant===!0))return dt(!0);let e=n.filter(t=>t.constant!==!1);return e.length===0?dt(!1):{apply(t){t.where(function(){e.forEach((r,o)=>{let i=function(){r.apply(this)};o===0?this.where(i):this.orWhere(i)})})}}}function al(n){return n.constant!==void 0?dt(!n.constant):{apply(e){e.whereNot(function(){n.apply(this)})}}}async function ll(n,e,t,r,o,i){let{fieldFilters:s,relationFilters:a}=Ae(e,r),c=[];for(let[u,l]of Object.entries(a)){let f=r.relations.find(g=>g.propertyName===u),d=await is(n,t,u,l,r,o,i);if(d){c.push(d);continue}if(!f?.foreignKeyColumn)throw new Error(`Relation "${u}" has no direct foreign key`);let p=l?.id;if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`Relation "${u}" has an invalid ID filter`);c.push({field:`${t}.${f.foreignKeyColumn}`,idFilter:p})}return Object.keys(s).length===0&&c.length===0?dt(!0):{apply(u){Object.keys(s).length>0&&ut(u,s,t,o,r);for(let l of c)"query"in l?u.whereExists(l.query):il(u,l.field,l.idFilter)}}}async function xr(n,e,t,r,o,i){if(!e||typeof e!="object")return dt(!0);if(Array.isArray(e))return xo(await Promise.all(e.map(c=>xr(n,c,t,r,o,i))));let s=[],a=Object.entries(e).filter(([c])=>c!=="_and"&&c!=="_or"&&c!=="_not");return a.length>0&&s.push(await ll(n,Object.fromEntries(a),t,r,o,i)),Array.isArray(e._and)&&s.push(xo(await Promise.all(e._and.map(c=>xr(n,c,t,r,o,i))))),Array.isArray(e._or)&&s.push(sl(await Promise.all(e._or.map(c=>xr(n,c,t,r,o,i))))),Object.prototype.hasOwnProperty.call(e,"_not")&&s.push(al(await xr(n,e._not,t,r,o,i))),xo(s)}async function as(n,e,t,r,o,i,s,a=r){(await xr(n,t,r,o,i,s)).apply(e)}async function Ot(n,e,t,r,o,i,s){await as(n,e,t,r,o,i,s)}ne();ft();Se();var Cr=class{constructor(e,t){this.metadata=e;this.dbType=t}buildRelationCountSortSubquery(e,t){let r=t.relationMeta,o=t.relationName||t.field,i=r?.targetTableName||r?.targetTable,s=this.metadata?.tables?.get(e),a=te(s)?.name||"id",c=I(e,this.dbType),u=I(a,this.dbType);if(!r||!i)throw new b(`Sort relation '${o}' does not exist on '${e}'.`);if(r.type==="one-to-many"){let l=r.foreignKeyColumn||r.mappedBy;if(!l)throw new b(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let f=I(i,this.dbType),d=I(l,this.dbType),p=i===e?I(e==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target",this.dbType):f;return`(SELECT COUNT(*) FROM ${p===f?f:`${f} AS ${p}`} WHERE ${p}.${d} = ${c}.${u})`}if(r.type==="many-to-many"){let l=this.resolveManyToManyContract(r,o,e),f=I(l.tableName,this.dbType),d=I(l.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${f} WHERE ${f}.${d} = ${c}.${u})`}throw new b(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let r=t.relationMeta,o=t.relationName||t.field,i=t.aggregateField,s=r?.targetTableName||r?.targetTable,a=this.metadata?.tables?.get(e),c=this.metadata?.tables?.get(s),u=te(a)?.name||"id",l=te(c)?.name||"id",f=I(e,this.dbType),d=I(u,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!r||!s||!i)throw new b(`Sort function '${t.field}' is not supported on '${e}'.`);let g=I(s,this.dbType),h=I(i,this.dbType),y=s===e?I(e==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target",this.dbType):g,m=y===g?g:`${g} AS ${y}`;if(r.type==="one-to-many"){let w=r.foreignKeyColumn||r.mappedBy;if(!w)throw new b(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let _=I(w,this.dbType);return`(SELECT ${p}(${y}.${h}) FROM ${m} WHERE ${y}.${_} = ${f}.${d})`}if(r.type==="many-to-many"){let w=this.resolveManyToManyContract(r,o,e),_=I(w.tableName,this.dbType),$=I(w.sourceColumn,this.dbType),k=I(w.targetColumn,this.dbType),C=I(l,this.dbType);return`(SELECT ${p}(${y}.${h}) FROM ${_} JOIN ${m} ON ${y}.${C} = ${_}.${k} WHERE ${_}.${$} = ${f}.${d})`}throw new b(`Sort function '_${t.function}(${o}.${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,r){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new b(`Relation '${t}' on '${r}' is missing physical many-to-many metadata.`)}};Rr();Se();ft();et();async function Nn(n,e,t,r,o,i,s){if(!r)return{select:t};let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Fo(),fs)),c=await a(e,t,r,o,i,s);return{select:c.select,batchFetchDescriptors:c.batchFetchDescriptors}}function Fr(n){let e=n;return e?async t=>{let r=e.tables?.get(t);return r?{name:r.name,columns:(r.columns||[]).map(o=>({name:o.name,type:o.type,isPrimary:o.isPrimary})),relations:r.relations||[]}:null}:null}function On(n,e,t,r,o){let i=n.targetTableName||n.targetTable;if(!i)return null;if(!(n.type==="many-to-one"||n.type==="one-to-one"&&n.isInverse===!1))throw new Error("Relation sorting requires an explicitly parent-owned to-one relation");let a=n.foreignKeyColumn||(n.propertyName?X(n.propertyName):null);if(!a)throw new Error("Relation sorting requires a parent foreign-key column");let c=p=>I(p,o),u=r?.tables?.get(i);if(!u)throw new Error(`SQL relation sort requires target metadata for '${i}'`);let l=te(u)?.name;if(!l)throw new Error(`SQL relation sort requires a primary key for '${i}'`);if(!u.columns?.some(p=>p.name===e))throw new Error(`SQL relation sort requires target column '${e}' on '${i}'`);let f=r?.tables?.get(t);if(!f)throw new Error(`SQL relation sort requires parent metadata for '${t}'`);if(!f.columns?.some(p=>p.name===a))throw new Error(`SQL relation sort requires foreign-key column '${a}' on '${t}'`);let d=t==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target";return`(SELECT ${c(d)}.${c(e)} FROM ${c(i)} AS ${c(d)} WHERE ${c(d)}.${c(l)} = ${c(t)}.${c(a)})`}Se();var gl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Io(n){if(typeof n!="string"||!gl.test(n))throw new Error("Invalid UUID filter value")}function Pn(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Bt(n,e,t,r,o){for(let i of e){let s=i.field.split("."),a=s.length>1?s[0]:t,c=s[s.length-1],l=["=","!=",">","<",">=","<=","like"].includes(i.operator)?Ir(r,a,c,i.value):i.value;switch(i.operator){case"=":n=n.where(i.field,"=",l);break;case"!=":n=n.where(i.field,"!=",l);break;case">":n=n.where(i.field,">",l);break;case"<":n=n.where(i.field,"<",l);break;case">=":n=n.where(i.field,">=",l);break;case"<=":n=n.where(i.field,"<=",l);break;case"like":n=n.where(i.field,"like",l);break;case"in":let f=Array.isArray(i.value)?i.value.map(w=>Ir(r,a,c,w)):[l];n=n.whereIn(i.field,f);break;case"not in":let d=Array.isArray(i.value)?i.value.map(w=>Ir(r,a,c,w)):[l];n=n.whereNotIn(i.field,d);break;case"is null":n=n.whereNull(i.field);break;case"is not null":n=n.whereNotNull(i.field);break;case"_contains":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`%${Pn(i.value)}%`]);break;case"_starts_with":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`${Pn(i.value)}%`]);break;case"_ends_with":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`%${Pn(i.value)}`]);break;case"_between":let p=i.value;if(typeof p=="string"&&(p=p.split(",").map(w=>w.trim())),!Array.isArray(p)||p.length!==2)throw new Error("Invalid _between filter value");let g=Ir(r,a,c,p[0]),h=Ir(r,a,c,p[1]);n=n.whereBetween(i.field,[g,h]);break;case"_is_null":n=l===!0||l==="true"?n.whereNull(i.field):n.whereNotNull(i.field);break;case"_is_not_null":n=l===!0||l==="true"?n.whereNotNull(i.field):n.whereNull(i.field);break}}return n}function vr(n,e,t,r){let o=[],i=t;if(!n||typeof n!="object")return o;for(let[s,a]of Object.entries(n))if(s==="_and"&&Array.isArray(a)){let c=a.map(u=>{let l=vr(u,e,t,r);return l.length>0?`(${l.join(" AND ")})`:null}).filter(u=>u!==null);c.length>0&&o.push(`(${c.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let c=a.map(u=>{let l=vr(u,e,t,r);return l.length>0?`(${l.join(" AND ")})`:null}).filter(u=>u!==null);c.length>0&&o.push(`(${c.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let c=vr(a,e,t,r);c.length>0&&o.push(`NOT (${c.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[c,u]of Object.entries(a)){let l=`${I(e,r)}.${I(s,r)}`,f=i.columns?.find(h=>h.name===s),d=f&&(f.type?.toLowerCase()==="uuid"||f.type?.toLowerCase().includes("uuid")),p=["_eq","_neq","_gt","_gte","_lt","_lte"].includes(c);d&&r==="postgres"&&u!==null&&p&&Io(u);let g=d&&r==="postgres"&&u!==null&&p?`${we(u,r)}::uuid`:we(u,r);if(c==="_eq")o.push(u===null?`${l} IS NULL`:`${l} = ${g}`);else if(c==="_neq")o.push(u===null?`${l} IS NOT NULL`:`${l} != ${g}`);else if(c==="_gt")o.push(`${l} > ${g}`);else if(c==="_gte")o.push(`${l} >= ${g}`);else if(c==="_lt")o.push(`${l} < ${g}`);else if(c==="_lte")o.push(`${l} <= ${g}`);else if(c==="_is_null")o.push(`${l} IS ${u===!0||u==="true"?"":"NOT "}NULL`);else if(c==="_is_not_null")o.push(`${l} IS ${u===!0||u==="true"?"NOT ":""}NULL`);else if(c==="_in"){let h=Array.isArray(u)?u:[u];if(h.length===0)o.push("FALSE");else{let y=h.map(m=>{d&&r==="postgres"&&m!==null&&Io(m);let w=we(m,r);return d&&r==="postgres"?`${w}::uuid`:w}).join(", ");o.push(`${l} IN (${y})`)}}else if(c==="_not_in"||c==="_nin"){let h=Array.isArray(u)?u:[u];if(h.length===0)o.push("TRUE");else{let y=h.map(m=>{d&&r==="postgres"&&m!==null&&Io(m);let w=we(m,r);return d&&r==="postgres"?`${w}::uuid`:w}).join(", ");o.push(`${l} NOT IN (${y})`)}}else if(c==="_contains"||c==="_starts_with"||c==="_ends_with"){let h=Pn(u).toLowerCase(),y=we(h,r),m=c==="_contains"?r==="mysql"?`CONCAT('%', lower(${y}), '%')`:`'%' || lower(${y}) || '%'`:c==="_starts_with"?r==="mysql"?`CONCAT(lower(${y}), '%')`:`lower(${y}) || '%'`:r==="mysql"?`CONCAT('%', lower(${y}))`:`'%' || lower(${y})`;r==="postgres"?o.push(`lower(unaccent(${l})) ILIKE unaccent(${m}) ESCAPE '='`):r==="mysql"?o.push(`lower(${l}) COLLATE utf8mb4_general_ci LIKE ${m} ESCAPE '='`):o.push(`lower(${l}) LIKE ${m} ESCAPE '='`)}else if(c==="_between"){if(!Array.isArray(u)||u.length!==2)throw new Error("Invalid _between filter value");o.push(`${l} BETWEEN ${we(u[0],r)} AND ${we(u[1],r)}`)}}else{let c=`${I(e,r)}.${I(s,r)}`;o.push(a===null?`${c} IS NULL`:`${c} = ${we(a,r)}`)}return o}function we(n,e="postgres"){if(n==null)return"NULL";if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("Invalid numeric SQL value");return String(n)}if(typeof n=="bigint")return n.toString();let t=Buffer.from(String(n),"utf8").toString("hex");return e==="mysql"?`CONVERT(X'${t}' USING utf8mb4)`:e==="sqlite"?`CAST(X'${t}' AS TEXT)`:`E'${String(n).replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}function Ir(n,e,t,r){if(r==null)return r;let o=n?.tables?.get(e);if(!o?.columns)return r;let i=o.columns.find(s=>s.name===t);if(!i)return r;switch(i.type){case"bigint":{let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new Error("Invalid bigint value");return s}case"int":case"integer":case"smallint":case"tinyint":{let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new Error("Invalid integer value");let a=Number(s);if(!Number.isSafeInteger(a))throw new Error("Integer value exceeds JavaScript safe range");return a}case"decimal":case"numeric":{let s=String(r);if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(s))throw new Error("Invalid decimal value");return s}case"float":case"double":case"real":{let s=Number(r);if(!Number.isFinite(s))throw new Error("Invalid float value");return s}case"boolean":case"bool":if(r===!0||r===!1)return r;if(r==="true"||r==="1"||r===1)return!0;if(r==="false"||r==="0"||r===0)return!1;throw new Error("Invalid boolean value");case"date":case"datetime":case"timestamp":if(typeof r=="string"){let s=new Date(r);if(Number.isNaN(s.getTime()))throw new Error("Invalid date value");return s}return r;default:return r}}ne();Se();Rr();var jn=class{constructor(e,t){this.knex=e;this.dbType=t}async aggregate(e){let t=At(e.aggregate,e.tableName,e.metadata),r=this.knex(e.tableName),o=I(e.tableName,this.dbType),i=[],s=[];for(let f of t.dimensions){let d=`${o}.${I(f.field,this.dbType)}`,p=f.bucket?this.buildSqlBucketExpression(d,f.bucket,f.timezone,f.column.type):d;s.push(this.knex.raw(`${p} as ${I(f.outputKey,this.dbType)}`)),i.push(p)}for(let f of t.measures){let d=`${o}.${I(f.field,this.dbType)}`,p=f.operation==="count"?`COUNT(${d})`:f.operation==="countDistinct"?`COUNT(DISTINCT ${d})`:`${f.operation.toUpperCase()}(${d})`;s.push(this.knex.raw(`${p} as ${I(f.outputKey,this.dbType)}`))}let c=new pe().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});c.hasRelationFilters?await Ot(this.knex,r,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,f=>e.metadata?.tables?.get(f)):c.filterTree&&ue(r,c.filterTree,{dbType:this.dbType,rootTable:e.tableName}),r.select(s),i.length>0&&r.groupByRaw(i.join(", "));for(let f of t.sort)r.orderByRaw(`${I(f.field,this.dbType)} ${f.direction.toUpperCase()}`);return t.limit!==void 0&&r.limit(t.limit).offset((t.page-1)*t.limit),{data:(await r).map(f=>{let d={...f};for(let p of t.measures){let g=d[p.outputKey];if(typeof g=="string"&&/^-?\d+$/.test(g)){let h=Number(g);Number.isSafeInteger(h)&&(d[p.outputKey]=h)}}return d})}}buildSqlBucketExpression(e,t,r,o){let i=we(r,this.dbType);if(this.dbType==="postgres"){let c=`(${["timestamp without time zone","date"].includes(o.toLowerCase())?`(${e}::timestamp AT TIME ZONE 'UTC')`:e} AT TIME ZONE ${i})`;return`DATE_TRUNC(${we(t,this.dbType)}, ${c})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${i})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`DATE_SUB(DATE(${s}), INTERVAL WEEKDAY(${s}) DAY)`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new b(`Aggregate time bucket is not supported on ${this.dbType}`)}};var pt=class n{constructor(e,t,r,o){this.knex=e;this.dbType=t;this.knexService=r;this.maxQueryDepth=o;this.logger=new In(n.name)}async execute(e){let t=performance.now(),r=e.debugLog||[],o=e.debugTrace;if(e.filter&&De(e.filter,e.tableName,e.metadata),!e.plan){let S=new pe;e={...e,plan:S.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;e={...e,fields:i.rawFields};let s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,c=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,u=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!c&&!a&&u){o&&o.setQueryPath("simple");let S=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),S}let f={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?f.fields=e.fields:typeof e.fields=="string"&&(f.fields=e.fields.split(",").map(S=>S.trim())));let d=e.filter;if(e.filter&&!ct(e.filter)){f.where=[];for(let[S,T]of Object.entries(e.filter))if(typeof T=="object"&&T!==null)for(let[F,L]of Object.entries(T)){let A;if(F==="_eq")A="=";else if(F==="_neq")A="!=";else if(F==="_in")A="in";else if(F==="_not_in"||F==="_nin")A="not in";else if(F==="_gt")A=">";else if(F==="_gte")A=">=";else if(F==="_lt")A="<";else if(F==="_lte")A="<=";else if(F==="_contains")A="_contains";else if(F==="_starts_with")A="_starts_with";else if(F==="_ends_with")A="_ends_with";else if(F==="_between")A="_between";else if(F==="_is_null")A="_is_null";else if(F==="_is_not_null")A="_is_not_null";else if(F==="_like")A="like";else if(F==="_ilike")A="ilike";else continue;f.where.push({field:S,operator:A,value:L})}else f.where.push({field:S,operator:"=",value:T})}if(e.sort){let S=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(T=>T.trim());f.sort=S.map(T=>{let F=T.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else f.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,h=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,y=h===void 0||Number.isNaN(h)?void 0:h;y&&g!==void 0?(f.offset=(y-1)*g,f.limit=g):g!==void 0&&(f.limit=g);let m=e.plan?.sortItems??(f.sort??[]).map(S=>({joinId:null,field:S.field,direction:S.direction,fullPath:S.field})),w=[],_=[];for(let S of m){if(S.function==="count"){let T={sql:this.buildRelationCountSortSubquery(f.table,S,e.metadata),direction:S.direction};_.push(T);continue}if(S.function==="max"||S.function==="min"){let T={sql:this.buildRelationAggregateSortSubquery(f.table,S,e.metadata),direction:S.direction};_.push(T);continue}if(S.joinId===null){if(S.field.includes(".")&&!e.plan){let F=S.field.split(".")[0];if(e.metadata?.tables?.get(f.table)?.relations?.some(Re=>Re.propertyName===F))continue}let T={field:S.field.includes(".")?S.field:`${f.table}.${S.field}`,direction:S.direction};w.push(T),_.push(T)}else{let T=e.plan?.joins.find(F=>F.id===S.joinId);if(T&&(T.relationType==="many-to-one"||T.relationType==="one-to-one")){let F=On(T.relationMeta,S.field,f.table,e.metadata,this.dbType);if(F){let L={sql:F,direction:S.direction};_.push(L)}}}}let $=[],k=[];if(f.fields&&f.fields.length>0||c||a){let S=Fr(e.metadata),T=f.fields??["*"],F=await Nn(this.knex,f.table,T,S,this.dbType,this.maxQueryDepth,e.deep);k=F.select.map(L=>S?this.knex.raw(L):L),$=F.batchFetchDescriptors||[]}f.where&&(f.where=f.where.map(S=>S.field.includes(".")?S:{...S,field:`${f.table}.${S.field}`})),f.sort=w;let C=this.knex(f.table),x=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(S=>S.trim()).filter(Boolean),v=x.includes("filterCount")||x.includes("*"),R=x.includes("totalCount")||x.includes("*");if(f.select||k.length>0){let S=(f.select??[]).map(T=>typeof T=="string"&&T.trim().startsWith("(")?this.knex.raw(T):typeof T=="string"&&/ as /i.test(T)?this.knex.raw(T):T);C=C.select([...S,...k])}let M=i.rawFields!==void 0&&i.rawFields.length===0&&!c;if(M&&C.select(this.knex.raw("1 as ??",["__enfyra_empty_selection"])),!M&&!f.select&&k.length===0&&(v||R)&&C.select(`${f.table}.*`),v&&C.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),R){let S=I(f.table,this.dbType);C.select(this.knex.raw(`(SELECT COUNT(*) FROM ${S}) as __total_count__`))}let N=["table_definition","column_definition","relation_definition","method_definition"].includes(f.table);if(d&&(ct(d)||Object.keys(d).length>0)){let S=e.metadata?.tables?.get(f.table);(!N&&S&&S.relations&&S.relations.length>0?Ae(d,S).hasRelations:!1)?await Ot(this.knex,C,d,f.table,S,this.dbType,F=>e.metadata?.tables?.get(F)):e.plan?.filterTree?ue(C,e.plan.filterTree,{dbType:this.dbType,rootTable:f.table}):(this.logger.debug(`buildWhereClause fallback for table=${f.table}`),C=ut(C,d,f.table,this.dbType,S))}else e.plan?.filterTree?ue(C,e.plan.filterTree,{dbType:this.dbType,rootTable:f.table}):f.where&&f.where.length>0&&(C=Bt(C,f.where,f.table,e.metadata,this.dbType));for(let S of _)if(S.field){let T=S.field.includes(".")?S.field:`${f.table}.${S.field}`;C=C.orderBy(T,S.direction)}else S.sql&&(C=C.orderByRaw(`${S.sql} ${S.direction.toUpperCase()}`));f.groupBy&&(C=C.groupBy(f.groupBy)),f.offset&&(C=C.offset(f.offset)),f.limit!==void 0&&f.limit>0&&(C=C.limit(f.limit));let j=0;r&&r.push({type:"SQL Query",table:f.table,sql:C.toSQL().toNative()});let O;if(e.debugMode&&(O=C.toSQL().toNative().sql),e.debugMode&&o){let S=C.toSQL().toNative();o.setSql(S.sql);try{let T=S.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${T}`,S.bindings);o.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(T){o.setExplain({error:String(T)})}}let P,G=performance.now();P=await C,o&&o.dur("db_execute",G,{table:e.tableName});let re=await this.resolveEmptyPageMeta(C,f.table,x,P.length),E=re.filterCount??0;if(j=re.totalCount??0,v&&P.length>0&&(E=Number(P[0].__filter_count__||0),P.forEach(S=>{delete S.__filter_count__})),R&&P.length>0&&P[0].__total_count__!==void 0&&(j=Number(P[0].__total_count__||0),P.forEach(S=>{delete S.__total_count__})),$&&$.length>0&&P.length>0){let S=Fr(e.metadata);if(S){let{executeBatchFetches:T}=await Promise.resolve().then(()=>(Ao(),ps));await T(this.knex,P,$,S,this.maxQueryDepth??3,0,f.table,this.dbType,e.metadata,o)}}if(this.knexService){let S=performance.now();P=await this.knexService.parseResult(P,f.table),o&&o.dur("db_parseResult",S,{table:e.tableName})}else P=Er(P,f.table,e.metadata);return M&&(P=P.map(()=>({}))),o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName})),{data:P,...x.length>0&&{meta:{...x.includes("totalCount")||x.includes("*")?{totalCount:j}:{},...x.includes("filterCount")||x.includes("*")?{filterCount:E}:{}}},...O!==void 0&&{sql:O}}}buildRelationCountSortSubquery(e,t,r){return new Cr(r,this.dbType).buildRelationCountSortSubquery(e,t)}buildRelationAggregateSortSubquery(e,t,r){return new Cr(r,this.dbType).buildRelationAggregateSortSubquery(e,t)}async resolveEmptyPageMeta(e,t,r,o){return o>0||r.length===0?{}:Mn(this.knex,e,t,r,!1)}async executeSimple(e,t){let r=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(r).select(o);t.filterTree&&ue(i,t.filterTree,{dbType:this.dbType,rootTable:r});for(let y of t.sortItems){let m=y.field.includes(".")?y.field:`${r}.${y.field}`;i=i.orderBy(m,y.direction)}t.limit!==void 0&&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(y=>y.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),c=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),c){let y=I(r,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${y}) as __total_count__`))}let u=e.debugTrace,l;if(e.debugMode){let y=i.toSQL().toNative();if(l=y.sql,u){u.setSql(y.sql);try{let m=y.sql.replace(/\$\d+/g,"?"),w=await this.knex.raw(`EXPLAIN ${m}`,y.bindings);u.setExplain(this.dbType==="postgres"?w.rows:w[0])}catch(m){u.setExplain({error:String(m)})}}}let f=performance.now(),d;d=await i,u&&u.dur("db_execute",f,{table:r}),this.knexService?d=await this.knexService.parseResult(d,r):d=Er(d,r,e.metadata);let p=await this.resolveEmptyPageMeta(i,r,s,d.length),g=p.filterCount??0,h=p.totalCount??0;return a&&d.length>0&&(g=Number(d[0].__filter_count__||0),d.forEach(y=>delete y.__filter_count__)),c&&d.length>0&&(h=Number(d[0].__total_count__||0),d.forEach(y=>delete y.__total_count__)),{data:d,...s.length>0&&{meta:{...c?{totalCount:h}:{},...a?{filterCount:g}:{}}},...l!==void 0&&{sql:l}}}async aggregate(e){return new jn(this.knex,this.dbType).aggregate(e)}};var Ln=require("mongodb"),qn=class{constructor(e){this.databaseConfigService=e}safeObjectId(e){if(!Ln.ObjectId)return e;if(typeof e=="string")try{return new Ln.ObjectId(e)}catch{return e}return e}whereToFilter(e){let t={},r=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?r?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 Ln.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[r,o]of Object.entries(e))t[r]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[r,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o))for(let[i,s]of Object.entries(o))t.push({field:r,operator:this.mapFilterOperatorToSql(i),value:s});return t}mapFilterOperatorToSql(e){let t={_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"_contains",_starts_with:"_starts_with",_ends_with:"_ends_with",_is_null:"is null",_is_not_null:"is not null"},r=t[e];if(!Object.prototype.hasOwnProperty.call(t,e))throw new Error(`Unsupported filter operator: ${e}`);return r}};var qt=class{constructor(e){this.debugLog=[];this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.conditions=new qn(this.databaseConfigService),this.batchInsertBuffer=new en(this.dbType,this.knexService,this.mongoService,t=>this.runMongoMutationInSaga(t))}async runWithPolicy(e,t){if(this.dbType==="mongodb"){if(typeof this.mongoService?.runWithPolicy!="function")throw new Error("MongoDB policy context is not available");return this.mongoService.runWithPolicy(e,t)}if(typeof this.knexService?.runWithPolicy!="function")throw new Error("SQL policy context is not available");return this.knexService.runWithPolicy(e,t)}async runWithFieldPermissionCheck(e,t){if(this.dbType==="mongodb"){if(typeof this.mongoService?.runWithFieldPermissionCheck!="function")throw new Error("MongoDB field-permission context is not available");return this.mongoService.runWithFieldPermissionCheck(e,t)}if(typeof this.knexService?.runWithFieldPermissionCheck!="function")throw new Error("SQL field-permission context is not available");return this.knexService.runWithFieldPermissionCheck(e,t)}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}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 r=await this.getMetadataForQuery(),o=It(r,e,t,this.dbType);return o._id!==void 0&&(o._id=this.conditions.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,r){let o=await this.getMetadataForQuery();return{query:Bt(e,t,r??"",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.batchInsertBuffer.enqueue(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let r of e.data){let o=await this.mongoService.insertOne(e.table,r);t.push(se(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let r of e.data){let o=await this.knexService.insertWithCascade(e.table,r);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),r=await this.getMetadataForQuery(),o=performance.now(),s=new pe().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:r,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 f=await new lt(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:r,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),f}let u=await new pt(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:r,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),u}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},c=await s.find(i,a).toArray(),u=[];for(let l of c){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),r=t(e.table);e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table));let o=await r;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);return e.returning?o.length===0?[]:await t(e.table).whereIn("id",o.map(i=>i.id)).select(e.returning):{affected:o.length}}async deleteWithOptions(e){if(!Array.isArray(e.where))throw new TypeError("Delete conditions must be an array");if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),i=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await i.find(o,s).toArray(),c=0;for(let u of a)await this.mongoService.deleteOne(e.table,u._id)&&c++;return c});let r=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table)),await r.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 r=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table));let o=await r.count("* as count").first();return Number(o?.count||0)}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.conditions.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new lt(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new pt(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,r){return r?.batch?await this.batchInsertBuffer.enqueue(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return se(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 createMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService.insertManyWithCascade=="function")return this.mongoService.insertManyWithCascade(e,t);let o=[];for(let i of t)o.push(await this.mongoService.insertOne(e,i));return o})).map(o=>se(o)):this.knexService.insertManyWithCascade(e,t))}async insertMany(e,t){return this.createMany(e,t)}async flushBatchInserts(){await this.batchInsertBuffer.flush()}async update(e,t,r){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:r});if(this.dbType==="mongodb"){let i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,r));return se(i)}return await this.knexService.updateWithCascade(e,t,r),await this.knexService.getKnex()(e).where("id",t).first()})}async updateMany(e,t,r,o=this.getPkField()){return t.length===0?0:this.trackQueryMetric("update_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let a=this.mongoService.collection(e),c=this.mongoService.ioSignalPublic?.()??{},u=o==="_id"?t.map(f=>this.conditions.safeObjectId(f)):t;return(await a.updateMany({[o]:{$in:u}},{$set:r},c)).modifiedCount});let s=await this.knexService.getKnex()(e).whereIn(o,t).update(r);return typeof s=="number"?s:0})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async deleteMany(e,t,r=this.getPkField()){return t.length===0?0:this.trackQueryMetric("delete_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let s=this.mongoService.collection(e),a=this.mongoService.ioSignalPublic?.()??{},c=r==="_id"?t.map(f=>this.conditions.safeObjectId(f)):t,u=await s.find({[r]:{$in:c}},a).toArray(),l=0;for(let f of u)await this.mongoService.deleteOne(e,f._id)&&l++;return l});let i=await this.knexService.getKnex()(e).whereIn(r,t).delete();return typeof i=="number"?i: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.conditions.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.conditions.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.conditions.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[c,u]of Object.entries(t))c==="id"||c==="_id"?o._id=this.conditions.safeObjectId(u):o[c]=u;let i=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await i.find(o,s).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let r=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=r||t.id;return await o(e).where("id",i).first()}async updateById(e,t,r){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,r)):(await this.knexService.updateWithCascade(e,t,r),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 r=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",r,async()=>{if(this.dbType==="mongodb"){let i=this.mongoService.getDb();if(typeof e=="string"){if(/^\s*select\s+1\s*;?\s*$/i.test(e))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,r){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},r):await r()}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}};Ao();vo();Fo();function gs(n){return n?(Array.isArray(n)?n:n.split(",")).flatMap(t=>{let r=typeof t=="string"?t.trim():"",o=r.startsWith("-"),i=o?r.substring(1).trim():r;return i?[{field:i,direction:o?"DESC":"ASC"}]:[]}):[]}Rr();Se();ft();Ne();on();ne();Le();wt();function hs(n,e,t){if(!(!n||typeof n!="object")){if(e>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`);if(t.has(n))throw new b("Filter contains a circular reference");t.add(n);try{for(let r of Object.values(n))hs(r,e+1,t)}finally{t.delete(n)}}}function ms(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new b("Filter must be an object");return Wn(n,e,t,r,0,new Set)}function Wn(n,e,t,r,o,i){if(!n||typeof n!="object"||Array.isArray(n))throw new b("Filter operand must be an object");if(o>oe)throw new b(`Filter nesting depth exceeds maximum of ${oe}`);if(i.has(n))throw new b("Filter contains a circular reference");let s=t?.tables?.get(e);if(!s)throw new b(`Filter validation requires metadata for table '${e}'`);i.add(n);let a=Object.create(null);try{for(let[c,u]of Object.entries(n)){if(de.has(c))throw new b(`Filter operator '${c}' is not valid at table scope`);if(c==="_and"||c==="_or"){if(!Array.isArray(u))throw new b(`Filter '${c}' value must be an array`);a[c]=u.map(d=>Wn(d,e,t,r,o+1,i));continue}if(c==="_not"){a[c]=Wn(u,e,t,r,o+1,i);continue}let l=s.relations?.find(d=>d.propertyName===c);if(l){if(!r(e,c,"relation"))throw new b(`Filtering by relation '${c}' on '${e}' is not allowed`);let d=l.targetTableName||l.targetTable;if(typeof d!="string"||!d)throw new b(`Relation '${c}' on '${e}' has no target table metadata`);a[c]=Wn(u,d,t,r,o+1,i);continue}if(s.columns?.find(d=>d.name===c)){if(!r(e,c,"column"))throw new b(`Filtering by field '${c}' on '${e}' is not allowed`);hs(u,o+1,i),a[c]=u;continue}throw new b(`Unknown filter field '${c}' on table '${e}'`)}return a}finally{i.delete(n)}}function ys(n,e,t,r){if(n===void 0)return n;if(typeof n!="string"&&!Array.isArray(n))throw new b("Sort must be a string or string array");let o=Array.isArray(n)?n:n.split(",");if(o.some(a=>typeof a!="string"))throw new b("Sort entries must be strings");let i=o.map(a=>a.trim()).filter(Boolean),s=[];for(let a of i){let l=(a.startsWith("-")?a.slice(1):a).split("."),f=!0,d=e;for(let p=0;p<l.length;p++){let g=l[p],h=p===l.length-1,y=t?.tables?.get(d);if(!y)throw new b(`Sort validation requires metadata for table '${d}'`);if(h)if(y.columns?.find(w=>w.name===g))r(d,g,"column")||(f=!1);else throw new b(`Unknown sort field '${g}' on table '${d}'`);else{let m=y.relations?.find(_=>_.propertyName===g);if(!m)throw new b(`Unknown sort relation '${g}' on table '${d}'`);if(!r(d,g,"relation")){f=!1;break}let w=m.targetTableName||m.targetTable;if(typeof w!="string"||!w||!t?.tables?.has(w))throw new b(`Sort relation '${g}' on '${d}' has no resolvable target table metadata`);d=w}}f&&s.push(a)}if(s.length!==0)return Array.isArray(n)?s:s.join(",")}cr();Le();sr();async function bs(n,e,t){if(!Number.isInteger(t)||t<1)throw new Error("Per-parent concurrency must be a positive integer");let r=new Map,o=[];for(let d of n){let p=String(d);if(r.has(p)){if(!Object.is(r.get(p),d))throw new Error(`Per-parent identity collision for key: ${p}`);continue}r.set(p,d),o.push({id:d,key:p})}let i=new Array(o.length),s=0,a=!1,c=!1,u;async function l(){for(;!a;){let d=s;if(d>=o.length)return;s+=1;let p=o[d];try{i[d]=await e(p.id)}catch(g){c||(c=!0,u=g),a=!0}}}let f=Math.min(t,o.length);if(f===0)return new Map;if(await Promise.all(Array.from({length:f},()=>l())),c)throw u;return new Map(o.map((d,p)=>[d.key,i[p]]))}wt();et();ne();function ml(n){let e=new qt({knexService:n.knexService,mongoService:n.mongoService,databaseConfigService:n.databaseConfigService,runtimeMetricsCollectorService:n.runtimeMetricsCollectorService,lazyRef:n.lazyRef}),t,r,o=!1,i,s=()=>{if(o)throw new Error("Enfyra kernel has been destroyed")},a=()=>{if(s(),!t){let u=n.getPackageCacheService?.()??n.packageCacheService,l=n.getPackageCdnLoaderService?.()??n.packageCdnLoaderService;if(!u||!l)throw new Error("Executor dependencies packageCacheService and packageCdnLoaderService are required");t=new bt({packageCacheService:u,packageCdnLoaderService:l,onExecutorWorkerCrash:n.onExecutorWorkerCrash,onExecutionFinished:n.onExecutionFinished})}return t},c=()=>(s(),r||(r=new gt({isolatedExecutorService:a()})),r);return{queryBuilderService:e,get isolatedExecutorService(){return a()},get executorEngineService(){return c()},onDestroy(){return i||(o=!0,i=Promise.resolve().then(async()=>{try{await e.flushBatchInserts()}finally{await t?.onDestroy?.()}}),i)}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildMongoSortSpec,buildMongoSortSpecFromPlan,buildRelationSortSubquery,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,checkIfFilterContainsIsNull,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeAggregationPipeline,executeBatchFetches,executeCountQueries,executeMongoBatchFetches,expandFieldsMongo,expandFieldsToJoinsAndSelect,expandFieldsToSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getMetadataGetter,getMongoInverseRelationForeignField,getMongoMetadataGetter,getMongoStoredRelationField,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasLogicalOperators,isExecutableJavaScript,isMongoInverseRelation,isScriptTable,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeMongoDocument,normalizeMongoResults,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,parseSortInput,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,renderFilterToKnex,resolveExecutableScript,resolveMongoJunctionInfo,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|