@enfyra/kernel 1.1.3 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -50,5 +50,5 @@ ${e}
50
50
  }
51
51
  }
52
52
  return true;
53
- }`}var $r="mongo-fold-text-search.body.txt",qe=null;function Ei(){let r=[vn.join(__dirname,$r),vn.join(process.cwd(),"dist","kernel","query","utils",$r)];for(let e of r)try{if(Gt.existsSync(e))return Gt.readFileSync(e,"utf8")}catch{}return null}function Yt(){if(qe!==null)return qe;let r=Ei();return r?(qe=r,qe):(qe=Ht(),qe)}var we=require("mongodb");function B(r,e,t,n){if(t==="_id"){if(n instanceof we.ObjectId)return n;if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n;default:return n}}var Xt="__mongoFoldTextTriples";function Pi(r){return r==="_id"?"$_id":`$${r}`}function He(r,e,t,n){let i=Pi(e),o=r[Xt]??[];o.push({ref:i,needle:t,mode:n}),r[Xt]=o}function ji(r){let e=r[Xt];if(delete r[Xt],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Yt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Ge(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let l=B(r,u,a,s.value);switch(s.operator){case"=":i[a]=l;break;case"!=":i[a]={$ne:l};break;case">":i[a]={$gt:l};break;case"<":i[a]={$lt:l};break;case">=":i[a]={$gte:l};break;case"<=":i[a]={$lte:l};break;case"like":i[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(y=>y.trim()):[f]);let c=f.map(y=>B(r,u,a,y));i[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(y=>y.trim()):[p]);let d=p.map(y=>B(r,u,a,y));i[a]={$nin:d};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":He(i,a,String(l),"contains");break;case"_starts_with":He(i,a,String(l),"starts");break;case"_ends_with":He(i,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(y=>y.trim())),Array.isArray(g)&&g.length===2){let y=B(r,u,a,g[0]),b=B(r,u,a,g[1]);i[a]={$gte:y,$lte:b}}break;case"_is_null":let m=l===!0||l==="true";i[a]=m?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=l===!0||l==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return ji(i),i}function xr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function Zt(r,e,t,n,i,o){switch(i){case"_contains":He(e,n,String(o),"contains");break;case"_starts_with":He(e,n,String(o),"starts");break;case"_ends_with":He(e,n,String(o),"ends");break;case"_eq":e[n]=B(r,t,n,o);break;case"_neq":{let c=B(r,t,n,o);xr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=o;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>B(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>B(r,t,n,c));xr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:B(r,t,n,o)};break;case"_gte":e[n]={$gte:B(r,t,n,o)};break;case"_lt":e[n]={$lt:B(r,t,n,o)};break;case"_lte":e[n]={$lte:B(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=o===!0||o==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=o;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=B(r,t,n,f[0]),p=B(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var An=require("mongodb");function ie(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(ie(i,e))return!0}}else if(t==="_not"){if(ie(n,e))return!0}else if(e.has(t))return!0;return!1}function G(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ie(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}vt();It();var sn="__mongoFoldTextTriples";function We(r,e){if(!r)return{};let t={};return rn(r,t,e),on(t),t}function ue(r,e,t){if(!e)return{};let n=new oe,{node:i}=Se(e,t,r,n);return We(i,{metadata:r,rootTable:t})}function rn(r,e,t){switch(r.kind){case"true":return;case"false":Mt(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return rn(o,s,t),on(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}Mt(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return rn(s,a,t),on(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};rn(r.child,n,t),on(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Ji(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Ji(r,e,t){let n=r.field.fieldName;if(n==="id"&&(n="_id"),r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>B(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":se(e,n,i(r.value));return;case"neq":{let o=i(r.value);Rr(t,n)?Mt(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):se(e,n,{$ne:o});return}case"gt":se(e,n,{$gt:i(r.value)});return;case"gte":se(e,n,{$gte:i(r.value)});return;case"lt":se(e,n,{$lt:i(r.value)});return;case"lte":se(e,n,{$lte:i(r.value)});return;case"in":{let o=vr(r.value).map(i);se(e,n,{$in:o});return}case"not_in":{let o=vr(r.value).map(i);Rr(t,n)?Mt(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):se(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&se(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":se(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Mn(e,n,String(r.value),"contains");return;case"starts_with":Mn(e,n,String(r.value),"starts");return;case"ends_with":Mn(e,n,String(r.value),"ends");return}}function se(r,e,t){r[e]===void 0?r[e]=t:(Mt(r,{[e]:r[e]},{[e]:t}),delete r[e])}function Mt(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Rr(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function vr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function zi(r){return r==="_id"?"$_id":`$${r}`}function Mn(r,e,t,n){let i=zi(e),o=r[sn]??[];o.push({ref:i,needle:t,mode:n}),r[sn]=o}function on(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Yt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function fe(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return ue(t,r,e);let o=new Set((i.relations||[]).map(l=>l.propertyName));if(!ie(r,o))return ue(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>fe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>fe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not){let l=await fe(r._not,e,t,n);return!l||Object.keys(l).length===0?{}:{$nor:[l]}}let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let l=ue(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await Vi(l,f,e,i,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Vi(r,e,t,n,i,o){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?qi(e,s,r,a,u,i,o):s.type==="one-to-many"?Hi(e,s,t,a,u,i,o):s.type==="many-to-many"?Gi(e,s,t,a,u,i,o):{}}async function qi(r,e,t,n,i,o,s){let a=H(e)||t,u=En(r),l=Pn(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Mr(u);if(f!==null){let g=jn(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await On(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:null}:{[a]:{$in:d}}}async function Hi(r,e,t,n,i,o,s){let a=K(e)||t,u=En(r),l=Pn(u);if(l!==null){let p=await Ir(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await On(u,n,i,o,s);if(!f||Object.keys(f).length===0)return{};let c=await Ir(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Gi(r,e,t,n,i,o,s){let a=_e(t,e);if(!a)return{};let u=En(r),l=Pn(u);if(l!==null){let m=await Nn(s,a,n,null);return l?m.length===0?{}:{_id:{$nin:m}}:m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let f=Mr(u);if(f!==null){let m=jn(f.value),h=Array.isArray(m)?m:[m],y=await Nn(s,a,n,{_id:{$in:h}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let c=await On(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await Nn(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function On(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ie(r,o)?fe(r,e,n,i):ue(n,r,e)}async function Ir(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let l=String(u);o.has(l)||(o.add(l),s.push(u))}return s}async function Nn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function En(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function Pn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function jn(r){if(Array.isArray(r))return r.map(e=>jn(e));if(typeof r!="string")return r;try{return new An.ObjectId(r)}catch{return r}}function Mr(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof An.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function Nt(r,e,t,n){let i=await qt(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let m=Object.keys(g)[0];m&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(m)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,m]of Object.entries(s))if(typeof m=="object"&&m!==null)for(let[h,y]of Object.entries(m))Zt(r,d,e,g,h,y);else d[g]=m;Object.keys(d).length>0&&o.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===d)){let h=l.find(y=>y.propertyName===d);if(h){let y="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")y=H(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")y="_id",b=K(h)||h.propertyName;else if(h.type==="many-to-many")continue;let $=h.type==="one-to-many"||h.type==="many-to-many";f.push({propertyName:d,targetTable:h.targetTableName,localField:y,foreignField:b,type:$?"many":"one",nestedFields:[]})}}let c=[...i.relations,...f];for(let d of c){let g=a[d.propertyName],m=d.nestedFields&&d.nestedFields.length>0?await Nt(r,d.targetTable,d.nestedFields,g):g?await Nt(r,d.targetTable,["_id"],g):[];d.type==="one"&&m.length>0&&m.push({$limit:1}),o.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:m.length>0?m:void 0}}),d.type==="one"&&(o.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Xe(g)||o.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(i.scalarFields.length>0||i.relations.length>0||p.length>0){let d={_id:1};for(let m of i.scalarFields)d[m]=1;for(let m of c)d[m.propertyName]=1,m.type==="one"&&m.localField&&m.localField!==m.propertyName&&(d[m.localField]=1);if(t.includes("*"))for(let m of p){if(m.type==="one-to-many"||m.type==="many-to-many")continue;m.type==="many-to-many"?d[m.propertyName]={$map:{input:`$${m.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[m.propertyName]={$cond:{if:{$ne:[`$${m.propertyName}`,null]},then:{_id:`$${m.propertyName}`},else:null}}}o.push({$project:d})}return o}async function Nr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(f=>!i.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of i)f[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(f[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function Xe(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Xe(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Xe(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Xe(e));if("_not"in r)return Xe(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Xe(t)))return!0}return!1}et();var At=require("mongodb");et();an();var tt=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-");return{field:i?n.slice(1):n,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let l of i){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],m=this.normalizeMetadata()?.tables?.get(p);if(!m)break;let h=m.relations?.find($=>$.propertyName===g);if(!h)break;let y=h.targetTableName||h.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let $=H(h)||h.propertyName,w=d===0?null:`__sort_${c.slice(0,d).join("_")}`,T=w?`${w}.${$}`:$;o.push({$lookup:{from:y,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=y}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new At.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof At.ObjectId||t instanceof At.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let a=this.compareSortValues(i[s.field],o[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(i._id,o._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof At.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ze(e),o={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])i.has(p.propertyName)||i.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?o[d.name]=1:t.relations?.find(m=>m.propertyName===p)&&!i.has(p)&&i.set(p,["_id"])}i.forEach((p,d)=>{let g=t.relations?.find(m=>m.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(o[H(g)||g.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let m=g.targetTableName||g.targetTable;if(!m)return;let h,y;g.type==="many-to-one"||g.type==="one-to-one"?Be(g)?(h="_id",y=K(g)||g.propertyName):(h=H(g)||g.propertyName,y="_id"):g.type==="one-to-many"?(h="_id",y=K(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(h="_id",y=g.mappedBy):(h=g.propertyName,y="_id")),a.push({relationName:d,type:g.type,targetTable:m,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:h,foreignField:y})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)o[p.newName]===1&&o[p.oldName]!==1&&(o[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?ue(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await Y(t,u=>{let l={_id:{$in:u}};o&&Object.keys(o).length>0&&Object.assign(l,o);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(h=>h!=null).map(h=>this.toObjectId(h)),u=o?.userFilter?ue(this.normalizeMetadata(),o.userFilter,e):null,l=o?.userLimit,f=o?.userPage,c=this.hasDottedSort(o?.userSort);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,y=await de(a,async $=>{let w={[t]:$};if(u&&Object.keys(u).length>0&&Object.assign(w,u),c){let _=this.buildSortAggregatePipeline(e,w,o.userSort);h>0&&_.push({$skip:h}),_.push({$limit:l}),s&&_.push({$project:s});let I=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback(I,i)}let x={sort:this.buildSortFromTokens(o?.userSort)||{_id:1}};s&&(x.projection=s);let R=this.db.collection(e).find(w,x);return h>0&&R.skip(h),R.limit(l),this.applyReadFallback(await R.toArray(),i)},te),b=[];for(let[$,w]of y.entries()){let T=a.find(x=>this.keyOf(x)===$);for(let x of w)x[t]||(x[t]=T??$),b.push(x)}return{docs:b,groupKeyField:t}}if(s&&(s[t]=1),c){let h=[],y=await de(a,async b=>{let $={[t]:b};u&&Object.keys(u).length>0&&Object.assign($,u);let w=this.buildSortAggregatePipeline(e,$,o.userSort);s&&w.push({$project:s});let T=await this.db.collection(e).aggregate(w).toArray();return this.applyReadFallback(T,i)},te);for(let b of y.values())for(let $ of b)h.push($);return{docs:h,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(o?.userSort)||{_id:1},g={projection:s,sort:d},m=await Y(a,h=>this.db.collection(e).find({[t]:{$in:h},...u||{}},g).toArray());return{docs:this.applyReadFallback(m,i),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=_e(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(w=>w._id).filter(w=>w!=null),l=new Map;for(let w of e)l.set(this.keyOf(w._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await Y(u,w=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:w}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?ue(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let w=d?(d-1)*p:0,T=await de(u,async R=>{let I=(await this.db.collection(a.junctionName).find({[a.selfColumn]:R},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(L=>L[a.otherColumn]).filter(L=>L!=null);if(I.length===0)return[];let v={_id:{$in:I}};if(c&&Object.keys(c).length>0&&Object.assign(v,c),this.hasDottedSort(t.userSort)){let L=this.buildSortAggregatePipeline(t.targetTable,v,t.userSort);w>0&&L.push({$skip:w}),L.push({$limit:p}),o.projection&&L.push({$project:o.projection});let S=await this.db.collection(t.targetTable).aggregate(L).toArray();return this.applyReadFallback(S,o)}let D={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};o.projection&&(D.projection=o.projection);let P=this.db.collection(t.targetTable).find(v,D);return w>0&&P.skip(w),P.limit(p),this.applyReadFallback(await P.toArray(),o)},te),x=[];for(let[R,_]of T.entries()){l.set(R,_);for(let I of _)x.push(I)}return{grouped:l,docs:x}}let g=new Set,m=[];for(let w of f){let T=w[a.otherColumn];if(T==null)continue;let x=this.keyOf(T);g.has(x)||(g.add(x),m.push(T))}let h=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!c,y=[],b=new Map;if(h)y=m.map(w=>({_id:w})),this.sortDocsByPk(y);else{let w={_id:{$in:m}};c&&Object.keys(c).length>0&&Object.assign(w,c);let T=this.hasDottedSort(t.userSort),x;if(T){let R=this.buildSortAggregatePipeline(t.targetTable,w,t.userSort);o.projection&&R.push({$project:o.projection}),x=await this.db.collection(t.targetTable).aggregate(R).toArray()}else{let R=this.buildSortFromTokens(t.userSort)||{_id:1},_=this.projectionWithSortFields(o.projection,t.userSort),I={sort:R};_.projection&&(I.projection=_.projection),x=await Y(m,v=>this.db.collection(t.targetTable).find({_id:{$in:v},...c||{}},I).toArray()),t.userSort?this.sortDocsInMemory(x,t.userSort):this.sortDocsByPk(x),this.removeHiddenFields(x,_.hiddenFields)}y=this.applyReadFallback(x,o)}for(let w of y)b.set(this.keyOf(w._id),w);let $=new Map;for(let w of f){let T=this.keyOf(w[a.selfColumn]),x=this.keyOf(w[a.otherColumn]);b.has(x)&&($.has(x)||$.set(x,[]),$.get(x).push(T))}for(let w of y){let T=$.get(this.keyOf(w._id))||[];for(let x of T)l.get(x)?.push(w)}return{grouped:l,docs:y}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function ln(r,e,t,n,i=3,o=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new tt(r,a,f);await new xe(c,n,u).execute(e,t,i,o,s)}async function Dn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),l=new Set((u?.relations??[]).map(_=>_.propertyName)),f=!!e.mongoRawFilter&&!!o&&ie(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&f){let _=await fe(e.mongoRawFilter,e.table,o,i);_&&Object.keys(_).length>0&&n.push({$match:_})}else if(p){let _=We(c.filterTree,{metadata:o,rootTable:e.table});Object.keys(_).length>0&&n.push({$match:_})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let _=Ge(o,e.where,e.table,s);n.push({$match:_})}let d=e.plan,m=d?d.hasRelationSort:e.sort?.some(_=>{if(!_.field.includes("."))return!1;let I=_.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(v=>v.propertyName===I)??!1})??!1,h=()=>d?.sortItems?to(d.sortItems):e.sort?eo(e.sort):null,y=d?.sortItems?Yi(d.sortItems):[],b=()=>{!d||y.length===0||Xi(n,e.table,d.sortItems,o)},$=()=>{y.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(y.map(_=>[_,0]))})};if(!e.mongoFieldsExpanded){b();let _=h();if(_&&n.push({$sort:_}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),$(),e.select){let v={};for(let O of e.select)v[O]=1;n.push({$project:v})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let I=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:I,pipeline:n}:{results:Ar(I),pipeline:n}}let{scalarFields:w,relations:T}=e.mongoFieldsExpanded;if(!m){b();let _=h();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let x=[];for(let _ of T)if(e.sort?.some(v=>v.field.startsWith(`${_.propertyName}.`))){let v=e.mongoRawFilter?.[_.propertyName];if(_.nestedFields&&_.nestedFields.length>0){let N=await Nt(o,_.targetTable,_.nestedFields??[],v);_.type==="one"&&N.length>0&&N.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:N.length>0?N:void 0}})}else if(v){let N=await Nt(o,_.targetTable,["_id"],v);_.type==="one"&&N.length>0&&N.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:N.length>0?N:void 0}})}else n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName}});_.type==="one"&&(n.push({$unwind:{path:`$${_.propertyName}`,preserveNullAndEmptyArrays:!0}}),v&&(nt(v)||n.push({$match:{[_.propertyName]:{$ne:null}}})))}else x.push(_);if(m){b();let _=h();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}await Nr(o,n,e.table,w,[...T]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let R=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:R,pipeline:n};if(x.length>0&&R.length>0){let _=e.deep||{},I=x.map(O=>{let D=o?.tables?.get(e.table)?.relations?.find(S=>S.propertyName===O.propertyName),P=_[O.propertyName],L=P?.fields!=null?Array.isArray(P.fields)?P.fields:String(P.fields).split(",").map(S=>S.trim()).filter(Boolean):O.nestedFields&&O.nestedFields.length>0?O.nestedFields:["_id"];return{relationName:O.propertyName,type:D?.type,targetTable:O.targetTable,fields:L,isInverse:D?.isInverse,mappedBy:D?.mappedBy,junctionTableName:D?.junctionTableName,localField:O.localField,foreignField:O.foreignField,userFilter:P?.filter,userSort:P?.sort,userLimit:P?.limit!==void 0?Number(P.limit):void 0,userPage:P?.page!==void 0?Number(P.page):void 0,nestedDeep:P?.deep}}),v=Zi(o);v&&await ln(i,R,I,v,3,0,e.table,o,void 0,t.mongoPhysicalMigrationService)}return{results:Ar(R),pipeline:n}}function Wn(r){return`__sort_count_${r.relationName||r.field}`}function Yi(r){return r.filter(e=>e.function==="count").map(Wn)}function Xi(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=Wn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=K(a)||u;r.push({$lookup:{from:l,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=_e(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function Zi(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function eo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function to(r){let e={};for(let t of r){let n=t.function==="count"?Wn(t):t.joinId!==null?t.fullPath:t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function nt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>nt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>nt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>nt(e));if("_not"in r)return nt(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||nt(t)))return!0}return!1}function Ar(r){return r.map(re)}function Or(r,e){let t=[],n=[],i=e?.tables?.get(r.rootTable);if(!i)return{scalarFields:t,relations:n};for(let o of r.nodes)if(o.kind==="wildcard")for(let s of i.columns||[])t.includes(s.name)||t.push(s.name);else o.kind==="scalar"?i.columns?.some(a=>a.name===o.name)&&!t.includes(o.name)&&t.push(o.name):o.kind==="relation"&&n.push(no(o,i,e));return{scalarFields:t,relations:n}}function no(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Be(n)?(i="_id",o=K(n)||r.propertyName,s=!0):(i=n&&H(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&K(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Er(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Er(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Er(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Ye();It();vt();function cn(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=o.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),m=p.substring(d+1);if(!o.relations?.some(y=>y.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(m)}else if(o.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!o.columns?.some(m=>m.name===p))continue;f.push(p)}}if(f.includes("*")){i.nodes.push({kind:"wildcard"});for(let c of o.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)i.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=o.relations?.find(h=>h.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,m={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Pr(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let h=n.registerWithParent(e,c,t,"left",null,"data");m.joinId=h}i.nodes.push(m)}return i}function Pr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),o=n.columns?.some(f=>f.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Pr(c,d,t)})}return l}Te();var Q=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new oe,d=this.parseFields(n),g=null;d&&c&&(g=cn(d,t,l,p));let m=!1,h=null;if(i&&c){let O=Se(i,t,l,p);h=O.node,m=O.hasRelationFilters}let y=this.parseSort(o),b=[],$=!1;for(let O of y){let N=O.startsWith("-"),D=N?O.substring(1):O,P=N?"desc":"asc";if(c){let L=this.parseRelationCountSort(t,c,D);if(L){b.push({joinId:null,field:D,direction:P,fullPath:D,function:"count",relationName:L.relationName,relationMeta:L.relationMeta});continue}this.assertLocalSortField(t,c,D)}b.push({joinId:null,field:D,direction:P,fullPath:D})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let w=this.parseLimit(a),T=this.parsePage(s),x=T!==void 0&&w!==void 0?(T-1)*w:void 0,R=this.parseMeta(u),_=R.includes("totalCount")||R.includes("*"),I=R.includes("filterCount")||R.includes("*"),v=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:i??null,joins:v,sortItems:b,limit:w,offset:x,needsTotalCount:_,needsFilterCount:I,hasRelationFilters:m,hasRelationSort:$,filterTree:h,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new M(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new M(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationCountSort(e,t,n){if(!n.startsWith("_count"))return null;let i=n.match(/^_count\(([^)]+)\)$/);if(!i)throw new M(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName).`);let o=i[1].trim();if(!o||o.includes("."))throw new M(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let s=t.relations?.find(a=>a.propertyName===o);if(!s)throw new M(`Sort relation '${o}' does not exist on '${e}'.`);if(s.type!=="one-to-many"&&s.type!=="many-to-many")throw new M(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`);return{relationName:o,relationMeta:s}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=i.registerWithParent(t,a,n,"left",o,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,i,c)}};Te();Rt();var ro=new Set(["count","sum","avg","min","max","countRecords"]),io=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),oo=new Set(["_and","_or","_not"]);function ke(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function E(r,e){let t=r.replace(/^aggregate\./,"");throw new M(e,{path:r,aggregate:{[t]:e}})}function so(r){return typeof r!="string"?!1:io.has(r.toLowerCase())}function jr(r){return Object.keys(r).length===0}function ao(r,e,t){return r===!0?{}:(r==null&&E(t,`aggregate.${e} condition must be true or an object`),ke(r)||E(t,`aggregate.${e} condition must be true or an object`),r)}function lo(r,e,t){let n=r?.tables?.get(e);return n||E(t,`Table "${e}" metadata is not available`),n}function Lr(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&E(e,"aggregate.countRecords relation target is not available"),t}function un(r,e,t,n){let i=lo(t,e,n);for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){Array.isArray(s)||E(n,`aggregate.countRecords ${o} condition must be an array`);for(let f of s)ke(f)||E(n,`aggregate.countRecords ${o} items must be objects`),un(f,e,t,n);continue}if(o==="_not"){ke(s)||E(n,"aggregate.countRecords _not condition must be an object"),un(s,e,t,n);continue}(o.startsWith("_")||oo.has(o))&&E(n,`Unsupported aggregate.countRecords condition key "${o}"`);let a=i.columns?.find(f=>f.name===o),u=i.relations?.find(f=>f.propertyName===o);if(!a&&!u&&E(n,`Unknown aggregate.countRecords field or relation "${o}" on table "${e}"`),ke(s)||E(n,`aggregate.countRecords condition for "${o}" must be an object`),a){for(let f of Object.keys(s))ee.has(f)||E(n,`aggregate.countRecords condition for "${o}" only supports field operators`);continue}let l=Lr(u,n);un(s,l,t,n)}}function Kn(r){return ke(r)&&Object.keys(r).length>0}function rt(r,e,t){if(!Kn(r))return[];ke(r)||E("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||E("aggregate",`Table "${e}" metadata is not available`);let i=[];for(let[o,s]of Object.entries(r)){let a=`aggregate.${o}`;(!o||typeof o!="string")&&E("aggregate","aggregate field name must be a non-empty string"),ke(s)||E(a,"aggregate field config must be an object");let u=o,l=a,f=n.columns?.find(d=>d.name===o),c=n.relations?.find(d=>d.propertyName===o);!f&&!c&&E(l,`Unknown aggregate field or relation "${o}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&E(l,"aggregate field must define at least one operation");for(let[d,g]of p){ro.has(d)||E(l,`Unsupported aggregate operation "${d}"`);let m=ao(g,d,l);if(c&&d!=="countRecords"&&E(l,`aggregate.${d} is not supported on relation "${o}"; use countRecords`),f&&d==="countRecords"&&E(l,`aggregate.countRecords requires a relation, but "${o}" is a field`),f&&(d==="sum"||d==="avg")&&!so(f.type)&&E(l,`aggregate.${d} requires a numeric field, but "${o}" is "${f.type}"`),f)for(let h of Object.keys(m))ee.has(h)||E(l,`aggregate.${d} condition for "${o}" only supports field operators`);if(c&&d==="countRecords"){let h=Lr(c,l);un(m,h,t,l)}i.push({field:o,outputKey:u,path:l,op:d,condition:m})}}return i}function it(r,e){let t=[];return ke(r)&&!jr(r)&&t.push(r),jr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function Ce(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var ot=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new Q;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(U(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&ie(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?We(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(i.includes("filterCount")||i.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(i.length>0||c)&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[];if(e.fields&&e.fields.length>0){let s=e.plan;if(s?.fieldTree?e.mongoFieldsExpanded=Or(s.fieldTree,this.metadata):(console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await qt(this.metadata,e.table,e.fields)),this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.hiddenFields}}e.where&&(e.where=e.where.map(s=>s.field.includes(".")?s:{...s,field:`${e.table}.${s.field}`}));let n=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await n.aggregate(e.pipeline).toArray()).map(re);let{results:i,pipeline:o}=await Dn(n,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,i,t):i}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Dn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={},o=this.db.collection(e.table);for(let s of n){let a=it(t,s);U(a,e.table,e.metadata);let l=new Q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);Ce(i,s,p);continue}let f=l.hasRelationFilters?await fe(a,e.table,e.metadata,this.db):l.filterTree?We(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await o.countDocuments(f);else{let[{value:p}={value:null}]=await o.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}Ce(i,s,c)}return i}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(o.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[o.foreignKeyColumn]:{$in:c}}]})}if(o.type==="many-to-many"){let f=_e(e.table,o);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(m=>m!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(m=>m[f.otherColumn]).filter(m=>m!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(o.type==="many-to-one"||o.type==="one-to-one"){let f=o.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};U(t,e,n);let o=new Q().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return o.hasRelationFilters?await fe(t,e,n,this.db):o.filterTree?We(o.filterTree,{metadata:n,rootTable:e}):{}}};var fn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};Te();var co=["_and","_or","_not"];function pe(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>pe(e));for(let e of Object.keys(r))if(co.includes(e)||typeof r[e]=="object"&&r[e]!==null&&pe(r[e]))return!0;return!1}var Br=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function uo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function dn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function fo(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||dn(r,t,i),e}function Dr(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=dn(e,i,s),l=fo(e,n,i,o,s);switch(t){case"_eq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} = ?::uuid`,[n]):r.where(a,"=",l);break;case"_neq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} != ?::uuid`,[n]):r.where(a,"!=",l);break;case"_gt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} > ?::uuid`,[n]):r.where(a,">",l);break;case"_gte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} >= ?::uuid`,[n]):r.where(a,">=",l);break;case"_lt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} < ?::uuid`,[n]):r.where(a,"<",l);break;case"_lte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} <= ?::uuid`,[n]):r.where(a,"<=",l);break;case"_in":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${a} = ANY(?::uuid[])`,[f]):r.whereIn(a,f);break;case"_not_in":case"_nin":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(p=>p.trim()):[c]),u&&o==="postgres"&&c.every(p=>typeof p=="string")?r.whereRaw(`${a} != ALL(?::uuid[])`,[c]):r.whereNotIn(a,c);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,uo(t),n)}}function po(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function st(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){st(this,s,t,"and",i,o)}):r.orWhere(function(){st(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(po(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){st(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>Br.includes(l)))for(let[l,f]of Object.entries(a))Br.includes(l)&&(n==="and"?r.where(function(){Dr(this,s,l,f,t,i,o)}):r.orWhere(function(){Dr(this,s,l,f,t,i,o)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s;dn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s;dn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${u} = ?::uuid`,[a]):r.orWhereRaw(`${u} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function ae(r,e,t,n,i){return!e||typeof e!="object"||st(r,e,t,"and",n,i),r}Fe();function Jn(r,e,t){return`${C(r,t)}.${C(e,t)}`}function Re(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Wr(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function at(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function zn(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let l=await Ot(r,e,a,u,t,n,i);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Jn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=at(d._is_null),m=at(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(m===!0)s.push(`${c} IS NOT NULL`);else if(m===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let h=Re(d._eq,n);s.push(`${c} = ${h}`)}else if(d._neq!==void 0){let h=Re(d._neq,n);s.push(`${c} != ${h}`)}else if(d._in!==void 0){let y=(Array.isArray(d._in)?d._in:[d._in]).map(b=>Re(b,n)).join(", ");s.push(`${c} IN (${y})`)}else if(d._not_in!==void 0||d._nin!==void 0){let h=d._not_in??d._nin,b=(Array.isArray(h)?h:[h]).map($=>Re($,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let h=Re(d._gt,n);s.push(`${c} > ${h}`)}else if(d._gte!==void 0){let h=Re(d._gte,n);s.push(`${c} >= ${h}`)}else if(d._lt!==void 0){let h=Re(d._lt,n);s.push(`${c} < ${h}`)}else if(d._lte!==void 0){let h=Re(d._lte,n);s.push(`${c} <= ${h}`)}}}}}return s}function Vn(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function Un(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(Vn(l)){let f=e(t).select(`${t}.id`);await Ke(e,f,l,t,n,i,o),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=G(l,n),p=await zn(e,t,n,i,o,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(Vn(a)){let u=e(t).select(`${t}.id`);await Ke(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=G(a,n),f=await zn(e,t,n,i,o,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Kr(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&ae(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function Qn(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)Kr(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function pn(r,e,t,n,i,o,s){let a=Wr(e,i),u=Wr(n,o),l=`${C(r,s)}.${C(e,s)}`,f=`${C(t,s)}.${C(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Ot(r,e,t,n,i,o,s){let a=i.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(pn(u,a.foreignKeyColumn,e,"id",f,i,o));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(pn(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,o))).whereRaw(pn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,i,o));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(pn(u,"id",e,a.foreignKeyColumn,f,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await Ke(r,c,n,u,f,o,s):c=ae(c,n,u,o,f||void 0):c=ae(c,n,u,o),c.toString()}async function Ke(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Un(l._or,r,n,i,o,s);e.where(function(){Qn(this,f,n,i,o)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await Ke(r,e,f,n,i,o,s);else await Ke(r,e,l,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let l=await Un(t._or,r,n,i,o,s);e.where(function(){Qn(this,l,n,i,o)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(Vn(d)){let g=r(n).select(`${n}.id`);await Ke(r,g,d,n,i,o,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:m}=G(d,i),h=await zn(r,n,i,o,s,m);p.push({fieldFilters:g,subqueries:h})}e.whereNot(function(){for(let d of p)Kr(this,d,n,i,o)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Un(l._or,r,n,i,o,s);e.whereNot(function(){Qn(this,p,n,i,o)});return}let{fieldFilters:f,relationFilters:c}=G(l,i);e.whereNot(function(){Object.keys(f).length>0&&ae(this,f,n,o,i)});for(let[p,d]of Object.entries(c)){let g=await Ot(r,n,p,d,i,o,s);if(g===null){let m=i.relations.find(h=>h.propertyName===p);if(m&&m.foreignKeyColumn){let h=Jn(n,m.foreignKeyColumn,o),b=d.id;if(b&&typeof b=="object"){let $=at(b._is_null),w=at(b._is_not_null);if($===!0)e.whereRaw(`${h} IS NOT NULL`);else if($===!1)e.whereRaw(`${h} IS NULL`);else if(w===!0)e.whereRaw(`${h} IS NULL`);else if(w===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,x=Array.isArray(T)?T:[T];e.whereRaw(`${h} IN (${x.map(()=>"?").join(", ")})`,x)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=G(t,i);Object.keys(a).length>0&&ae(e,a,n,o,i);for(let[l,f]of Object.entries(u)){let c=await Ot(r,n,l,f,i,o,s);if(c===null){let p=i.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Jn(n,p.foreignKeyColumn,o),m=f.id;if(m&&typeof m=="object"){let h=at(m._is_null),y=at(m._is_not_null);if(h===!0)e.whereRaw(`${d} IS NULL`);else if(h===!1)e.whereRaw(`${d} IS NOT NULL`);else if(y===!0)e.whereRaw(`${d} IS NOT NULL`);else if(y===!1)e.whereRaw(`${d} IS NULL`);else if(m._eq!==void 0)e.whereRaw(`${d} = ?`,[m._eq]);else if(m._neq!==void 0)e.whereRaw(`${d} != ?`,[m._neq]);else if(m._in!==void 0){let b=Array.isArray(m._in)?m._in:[m._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(m._not_in!==void 0||m._nin!==void 0){let b=m._not_in??m._nin,$=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${$.map(()=>"?").join(", ")})`,$)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Ue(r,e,t,n,i,o,s){await Ke(r,e,t,n,i,o,s)}Fe();Hn();Ye();Fe();function lt(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],l=Et(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",l);break;case"!=":r=r.where(o.field,"!=",l);break;case">":r=r.where(o.field,">",l);break;case"<":r=r.where(o.field,"<",l);break;case">=":r=r.where(o.field,">=",l);break;case"<=":r=r.where(o.field,"<=",l);break;case"like":r=r.where(o.field,"like",l);break;case"in":let f=Array.isArray(o.value)?o.value.map(m=>Et(n,a,u,m)):[l];r=r.whereIn(o.field,f);break;case"not in":let c=Array.isArray(o.value)?o.value.map(m=>Et(n,a,u,m)):[l];r=r.whereNotIn(o.field,c);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let p=o.value;if(typeof p=="string"&&(p=p.split(",").map(m=>m.trim())),Array.isArray(p)&&p.length===2){let m=Et(n,a,u,p[0]),h=Et(n,a,u,p[1]);r=r.whereBetween(o.field,[m,h])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Pt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let f=Pt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=Pt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Pt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let f=`${C(e,n)}.${C(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=o.columns?.find(m=>m.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${f} = ${c}`);else if(u==="_neq")i.push(`${f} != ${c}`);else if(u==="_gt")i.push(`${f} > ${c}`);else if(u==="_gte")i.push(`${f} >= ${c}`);else if(u==="_lt")i.push(`${f} < ${c}`);else if(u==="_lte")i.push(`${f} <= ${c}`);else if(u==="_is_null")i.push(`${f} IS NULL`);else if(u==="_is_not_null")i.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);i.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${C(e,n)}.${C(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),i.push(`${u} = ${l}`)}return i}function Qr(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Et(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}Fe();jt();Ve();async function zr(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Yn(),Jr)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function Xn(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function Vr(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||V(r.propertyName);if(!s)return null;let a=c=>C(c,i),u=n?.tables?.get(o),f=(u?ne(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(f)} = ${a(t)}.${a(s)})`}jt();var ut=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new fn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&U(e.filter,e.tableName,e.metadata),!e.plan){let S=new Q;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 o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&l){i&&i.setQueryPath("simple");let S=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),S}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(S=>S.trim())));let p=e.filter;if(e.filter&&!pe(e.filter)){c.where=[];for(let[S,k]of Object.entries(e.filter))if(typeof k=="object"&&k!==null)for(let[F,le]of Object.entries(k)){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;c.where.push({field:S,operator:A,value:le})}else c.where.push({field:S,operator:"=",value:k})}if(e.sort){let S=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(k=>k.trim());c.sort=S.map(k=>{let F=k.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,m=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=m===void 0||Number.isNaN(m)?void 0:m;h&&g!==void 0?(c.offset=(h-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let y=e.plan?.sortItems??(c.sort??[]).map(S=>({joinId:null,field:S.field,direction:S.direction,fullPath:S.field})),b=[],$=[];for(let S of y){if(S.function==="count"){let k={sql:this.buildRelationCountSortSubquery(c.table,S),direction:S.direction};$.push(k);continue}if(S.joinId===null){if(S.field.includes(".")&&!e.plan){let F=S.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(J=>J.propertyName===F))continue}let k={field:S.field.includes(".")?S.field:`${c.table}.${S.field}`,direction:S.direction};b.push(k),$.push(k)}else{let k=e.plan?.joins.find(F=>F.id===S.joinId);if(k&&(k.relationType==="many-to-one"||k.relationType==="one-to-one")){let F=Vr(k.relationMeta,S.field,c.table,this.metadata,this.dbType);if(F){let le={sql:F,direction:S.direction};$.push(le)}}}}let w=[];if(c.fields&&c.fields.length>0){let S=Xn(this.metadata),k=await zr(this.knex,c.table,c.fields,S,this.dbType,this.maxQueryDepth,e.deep);c.select=[...c.select||[],...k.select],w=k.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(S=>S.field.includes(".")?S:{...S,field:`${c.table}.${S.field}`})),c.sort=b;let T=this.knex(c.table),x=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(S=>S.trim()).filter(Boolean),R=x.includes("filterCount")||x.includes("*"),_=x.includes("totalCount")||x.includes("*");if(c.select){let S=c.select.map(k=>typeof k=="string"&&k.trim().startsWith("(")?this.knex.raw(k):typeof k=="string"&&/ as /i.test(k)?this.knex.raw(k):k);T=T.select(S)}if(R&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let S=C(c.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${S}) as __total_count__`))}let I=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(pe(p)||Object.keys(p).length>0)){let S=this.metadata?.tables?.get(c.table);(!I&&S&&S.relations&&S.relations.length>0?G(p,S).hasRelations:!1)?await Ue(this.knex,T,p,c.table,S,this.dbType,F=>this.metadata?.tables?.get(F)):e.plan?.filterTree?X(T,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),T=ae(T,p,c.table,this.dbType,S))}else c.where&&c.where.length>0&&(T=lt(T,c.where,c.table,this.metadata,this.dbType));for(let S of $)if(S.field){let k=S.field.includes(".")?S.field:`${c.table}.${S.field}`;T=T.orderBy(k,S.direction)}else S.sql&&(T=T.orderByRaw(`${S.sql} ${S.direction.toUpperCase()}`));c.groupBy&&(T=T.groupBy(c.groupBy)),c.offset&&(T=T.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&(T=T.limit(c.limit));let v=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:T.toSQL().toNative()});let O;if(e.debugMode&&(O=T.toSQL().toNative().sql),e.debugMode&&i){let S=T.toSQL().toNative();i.setSql(S.sql);try{let k=S.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${k}`,S.bindings);i.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(k){i.setExplain({error:String(k)})}}let N,D=performance.now();N=await T,i&&i.dur("db_execute",D,{table:e.tableName});let P=0;if(R&&N.length>0&&(P=Number(N[0].__filter_count__||0),N.forEach(S=>{delete S.__filter_count__})),_&&N.length>0&&N[0].__total_count__!==void 0&&(v=Number(N[0].__total_count__||0),N.forEach(S=>{delete S.__total_count__})),w&&w.length>0&&N.length>0){let S=Xn(this.metadata);if(S){let{executeBatchFetches:k}=await Promise.resolve().then(()=>(tr(),qr));await k(this.knex,N,w,S,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,i)}}if(this.knexService){let S=performance.now();N=await this.knexService.parseResult(N,c.table),i&&i.dur("db_parseResult",S,{table:e.tableName})}else{let S=(k,F)=>{if(!k||!this.metadata)return k;let le=this.metadata.tables?.get(F);if(!le)return k;if(Array.isArray(k))return k.map(J=>S(J,F));if(typeof k!="object"||Buffer.isBuffer(k))return k;let A={...k};for(let J of le.columns)if(J.type==="simple-json"&&A[J.name]&&typeof A[J.name]=="string")try{A[J.name]=JSON.parse(A[J.name])}catch{}for(let[J,q]of Object.entries(A))if(q&&typeof q=="object"&&!Array.isArray(q)&&!Buffer.isBuffer(q)){let _n=q;if(_n.id!==void 0||_n.createdAt!==void 0){let dt=le.relations?.find(pt=>pt.propertyName===J);dt&&(A[J]=S(q,dt.targetTableName))}}else if(Array.isArray(q)&&q.length>0&&typeof q[0]=="object"&&q[0].id!==void 0){let dt=le.relations?.find(pt=>pt.propertyName===J);dt&&(A[J]=q.map(pt=>S(pt,dt.targetTableName)))}return A};N=S(N,c.table)}i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName}));let L=await this.executeAggregate(c,p);return{data:N,...(x.length>0||L)&&{meta:{...x.includes("totalCount")||x.includes("*")?{totalCount:v}:{},...x.includes("filterCount")||x.includes("*")?{filterCount:P}:{},...L?{aggregate:L}:{}}},...O!==void 0&&{sql:O}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=ne(s)?.name||"id",u=C(e,this.dbType),l=C(a,this.dbType);if(!n||!o)throw new M(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new M(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let c=C(o,this.dbType),p=C(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=this.resolveManyToManyContract(n,i,e),c=C(f.tableName,this.dbType),p=C(f.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new M(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new M(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&X(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let y=h.field.includes(".")?h.field:`${n}.${h.field}`;o=o.orderBy(y,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=C(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let h=o.toSQL().toNative();if(f=h.sql,l){l.setSql(h.sql);try{let y=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${y}`,h.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(y){l.setExplain({error:String(y)})}}}let c=performance.now(),p;p=await o,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(h=>delete h.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(h=>delete h.__total_count__));let m=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||m)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...m?{aggregate:m}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={};for(let o of n){let s=it(t,o);U(s,e.table,e.metadata);let u=new Q().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(o.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,o);Ce(i,o,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Ue(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&X(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${C(e.table,this.dbType)}.${C(o.field,this.dbType)}`,c=o.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${o.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();Ce(i,o,p?.value??0)}return i}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table),o=i?.relations?.find(c=>c.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new Q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,u,t,e.table,i,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){U(n.condition,s,e.metadata);let p=new Q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(o.type==="one-to-many")l.whereIn(`${s}.${o.foreignKeyColumn}`,u);else if(o.type==="many-to-many"){let c=this.resolveManyToManyContract(o,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(o.type==="many-to-one"||o.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${o.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${o.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var hn=require("mongodb"),ft=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.contextIds=new WeakMap;this.nextContextId=1;this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,mn.mkdirSync)((0,Hr.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!hn.ObjectId)return e;if(typeof e=="string")try{return new hn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Ge(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:lt(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.mongoService.insertOne(e.table,n);t.push(re(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new Q().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb")return new ot(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new ut(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(o).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(i).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof hn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return re(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t],i=this.captureMutationContextSnapshot();for(let o of n)this.batchInserts.items.push({table:e,data:o,contextSnapshot:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now(),i=this.groupBatchInsertsByContext(t);await this.runLimited([...i.values()],o=>this.runBatchInsertWithIsolation(e,o.items,o.contextSnapshot)),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t,n){if(t.length!==0)try{let i=async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{await Promise.all(t.map(o=>this.mongoService.insertOne(e,o.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.knexService.insertWithCascade(e,o.data)))};await this.runWithMutationContextSnapshot(n,i)}catch(i){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,i);return}let o=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,o),n),this.runBatchInsertWithIsolation(e,t.slice(o),n)])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}groupBatchInsertsByContext(e){let t=new Map;for(let n of e){let i=n.contextSnapshot?.key||null,o=t.get(i);o?o.items.push(n):t.set(i,{contextSnapshot:n.contextSnapshot||null,items:[n]})}return t}captureMutationContextSnapshot(){let e=this.dbType==="mongodb"?this.mongoService?.getMutationContextSnapshot?.()??null:this.knexService?.getMutationContextSnapshot?.()??null;return!e?.policy&&!e?.fieldPermission?null:{key:`${this.getContextId(e.policy)}:${this.getContextId(e.fieldPermission)}`,value:e}}async runWithMutationContextSnapshot(e,t){return e?this.dbType==="mongodb"?typeof this.mongoService?.runWithMutationContextSnapshot=="function"?await this.mongoService.runWithMutationContextSnapshot(e.value,t):await t():typeof this.knexService?.runWithMutationContextSnapshot=="function"?await this.knexService.runWithMutationContextSnapshot(e.value,t):await t():await t()}getContextId(e){if(!e)return 0;let t=this.contextIds.get(e);if(t)return t;let n=this.nextContextId++;return this.contextIds.set(e,n),n}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,mn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
53
+ }`}var $r="mongo-fold-text-search.body.txt",qe=null;function Ei(){let r=[vn.join(__dirname,$r),vn.join(process.cwd(),"dist","kernel","query","utils",$r)];for(let e of r)try{if(Gt.existsSync(e))return Gt.readFileSync(e,"utf8")}catch{}return null}function Yt(){if(qe!==null)return qe;let r=Ei();return r?(qe=r,qe):(qe=Ht(),qe)}var we=require("mongodb");function B(r,e,t,n){if(t==="_id"){if(n instanceof we.ObjectId)return n;if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n;default:return n}}var Xt="__mongoFoldTextTriples";function Pi(r){return r==="_id"?"$_id":`$${r}`}function He(r,e,t,n){let i=Pi(e),o=r[Xt]??[];o.push({ref:i,needle:t,mode:n}),r[Xt]=o}function ji(r){let e=r[Xt];if(delete r[Xt],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Yt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Ge(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let l=B(r,u,a,s.value);switch(s.operator){case"=":i[a]=l;break;case"!=":i[a]={$ne:l};break;case">":i[a]={$gt:l};break;case"<":i[a]={$lt:l};break;case">=":i[a]={$gte:l};break;case"<=":i[a]={$lte:l};break;case"like":i[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(y=>y.trim()):[f]);let c=f.map(y=>B(r,u,a,y));i[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(y=>y.trim()):[p]);let d=p.map(y=>B(r,u,a,y));i[a]={$nin:d};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":He(i,a,String(l),"contains");break;case"_starts_with":He(i,a,String(l),"starts");break;case"_ends_with":He(i,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(y=>y.trim())),Array.isArray(g)&&g.length===2){let y=B(r,u,a,g[0]),b=B(r,u,a,g[1]);i[a]={$gte:y,$lte:b}}break;case"_is_null":let m=l===!0||l==="true";i[a]=m?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=l===!0||l==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return ji(i),i}function xr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function Zt(r,e,t,n,i,o){switch(i){case"_contains":He(e,n,String(o),"contains");break;case"_starts_with":He(e,n,String(o),"starts");break;case"_ends_with":He(e,n,String(o),"ends");break;case"_eq":e[n]=B(r,t,n,o);break;case"_neq":{let c=B(r,t,n,o);xr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=o;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>B(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>B(r,t,n,c));xr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:B(r,t,n,o)};break;case"_gte":e[n]={$gte:B(r,t,n,o)};break;case"_lt":e[n]={$lt:B(r,t,n,o)};break;case"_lte":e[n]={$lte:B(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=o===!0||o==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=o;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=B(r,t,n,f[0]),p=B(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var An=require("mongodb");function ie(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(ie(i,e))return!0}}else if(t==="_not"){if(ie(n,e))return!0}else if(e.has(t))return!0;return!1}function G(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ie(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}vt();It();var sn="__mongoFoldTextTriples";function We(r,e){if(!r)return{};let t={};return rn(r,t,e),on(t),t}function ue(r,e,t){if(!e)return{};let n=new oe,{node:i}=Se(e,t,r,n);return We(i,{metadata:r,rootTable:t})}function rn(r,e,t){switch(r.kind){case"true":return;case"false":Mt(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return rn(o,s,t),on(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}Mt(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return rn(s,a,t),on(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};rn(r.child,n,t),on(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Ji(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Ji(r,e,t){let n=r.field.fieldName;if(n==="id"&&(n="_id"),r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>B(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":se(e,n,i(r.value));return;case"neq":{let o=i(r.value);Rr(t,n)?Mt(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):se(e,n,{$ne:o});return}case"gt":se(e,n,{$gt:i(r.value)});return;case"gte":se(e,n,{$gte:i(r.value)});return;case"lt":se(e,n,{$lt:i(r.value)});return;case"lte":se(e,n,{$lte:i(r.value)});return;case"in":{let o=vr(r.value).map(i);se(e,n,{$in:o});return}case"not_in":{let o=vr(r.value).map(i);Rr(t,n)?Mt(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):se(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&se(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":se(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Mn(e,n,String(r.value),"contains");return;case"starts_with":Mn(e,n,String(r.value),"starts");return;case"ends_with":Mn(e,n,String(r.value),"ends");return}}function se(r,e,t){r[e]===void 0?r[e]=t:(Mt(r,{[e]:r[e]},{[e]:t}),delete r[e])}function Mt(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Rr(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function vr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function zi(r){return r==="_id"?"$_id":`$${r}`}function Mn(r,e,t,n){let i=zi(e),o=r[sn]??[];o.push({ref:i,needle:t,mode:n}),r[sn]=o}function on(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Yt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function fe(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return ue(t,r,e);let o=new Set((i.relations||[]).map(l=>l.propertyName));if(!ie(r,o))return ue(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>fe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>fe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not){let l=await fe(r._not,e,t,n);return!l||Object.keys(l).length===0?{}:{$nor:[l]}}let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let l=ue(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await Vi(l,f,e,i,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Vi(r,e,t,n,i,o){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?qi(e,s,r,a,u,i,o):s.type==="one-to-many"?Hi(e,s,t,a,u,i,o):s.type==="many-to-many"?Gi(e,s,t,a,u,i,o):{}}async function qi(r,e,t,n,i,o,s){let a=H(e)||t,u=En(r),l=Pn(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Mr(u);if(f!==null){let g=jn(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await On(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:null}:{[a]:{$in:d}}}async function Hi(r,e,t,n,i,o,s){let a=K(e)||t,u=En(r),l=Pn(u);if(l!==null){let p=await Ir(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await On(u,n,i,o,s);if(!f||Object.keys(f).length===0)return{};let c=await Ir(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Gi(r,e,t,n,i,o,s){let a=_e(t,e);if(!a)return{};let u=En(r),l=Pn(u);if(l!==null){let m=await Nn(s,a,n,null);return l?m.length===0?{}:{_id:{$nin:m}}:m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let f=Mr(u);if(f!==null){let m=jn(f.value),h=Array.isArray(m)?m:[m],y=await Nn(s,a,n,{_id:{$in:h}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let c=await On(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await Nn(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function On(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ie(r,o)?fe(r,e,n,i):ue(n,r,e)}async function Ir(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let l=String(u);o.has(l)||(o.add(l),s.push(u))}return s}async function Nn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function En(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function Pn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function jn(r){if(Array.isArray(r))return r.map(e=>jn(e));if(typeof r!="string")return r;try{return new An.ObjectId(r)}catch{return r}}function Mr(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof An.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function Nt(r,e,t,n){let i=await qt(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let m=Object.keys(g)[0];m&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(m)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,m]of Object.entries(s))if(typeof m=="object"&&m!==null)for(let[h,y]of Object.entries(m))Zt(r,d,e,g,h,y);else d[g]=m;Object.keys(d).length>0&&o.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===d)){let h=l.find(y=>y.propertyName===d);if(h){let y="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")y=H(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")y="_id",b=K(h)||h.propertyName;else if(h.type==="many-to-many")continue;let $=h.type==="one-to-many"||h.type==="many-to-many";f.push({propertyName:d,targetTable:h.targetTableName,localField:y,foreignField:b,type:$?"many":"one",nestedFields:[]})}}let c=[...i.relations,...f];for(let d of c){let g=a[d.propertyName],m=d.nestedFields&&d.nestedFields.length>0?await Nt(r,d.targetTable,d.nestedFields,g):g?await Nt(r,d.targetTable,["_id"],g):[];d.type==="one"&&m.length>0&&m.push({$limit:1}),o.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:m.length>0?m:void 0}}),d.type==="one"&&(o.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Xe(g)||o.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(i.scalarFields.length>0||i.relations.length>0||p.length>0){let d={_id:1};for(let m of i.scalarFields)d[m]=1;for(let m of c)d[m.propertyName]=1,m.type==="one"&&m.localField&&m.localField!==m.propertyName&&(d[m.localField]=1);if(t.includes("*"))for(let m of p){if(m.type==="one-to-many"||m.type==="many-to-many")continue;m.type==="many-to-many"?d[m.propertyName]={$map:{input:`$${m.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[m.propertyName]={$cond:{if:{$ne:[`$${m.propertyName}`,null]},then:{_id:`$${m.propertyName}`},else:null}}}o.push({$project:d})}return o}async function Nr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(f=>!i.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of i)f[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(f[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function Xe(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Xe(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Xe(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Xe(e));if("_not"in r)return Xe(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Xe(t)))return!0}return!1}et();var At=require("mongodb");et();an();var tt=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-");return{field:i?n.slice(1):n,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let l of i){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],m=this.normalizeMetadata()?.tables?.get(p);if(!m)break;let h=m.relations?.find($=>$.propertyName===g);if(!h)break;let y=h.targetTableName||h.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let $=H(h)||h.propertyName,w=d===0?null:`__sort_${c.slice(0,d).join("_")}`,T=w?`${w}.${$}`:$;o.push({$lookup:{from:y,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=y}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new At.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof At.ObjectId||t instanceof At.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let a=this.compareSortValues(i[s.field],o[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(i._id,o._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof At.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ze(e),o={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])i.has(p.propertyName)||i.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?o[d.name]=1:t.relations?.find(m=>m.propertyName===p)&&!i.has(p)&&i.set(p,["_id"])}i.forEach((p,d)=>{let g=t.relations?.find(m=>m.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(o[H(g)||g.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let m=g.targetTableName||g.targetTable;if(!m)return;let h,y;g.type==="many-to-one"||g.type==="one-to-one"?Be(g)?(h="_id",y=K(g)||g.propertyName):(h=H(g)||g.propertyName,y="_id"):g.type==="one-to-many"?(h="_id",y=K(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(h="_id",y=g.mappedBy):(h=g.propertyName,y="_id")),a.push({relationName:d,type:g.type,targetTable:m,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:h,foreignField:y})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)o[p.newName]===1&&o[p.oldName]!==1&&(o[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?ue(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await Y(t,u=>{let l={_id:{$in:u}};o&&Object.keys(o).length>0&&Object.assign(l,o);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(h=>h!=null).map(h=>this.toObjectId(h)),u=o?.userFilter?ue(this.normalizeMetadata(),o.userFilter,e):null,l=o?.userLimit,f=o?.userPage,c=this.hasDottedSort(o?.userSort);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,y=await de(a,async $=>{let w={[t]:$};if(u&&Object.keys(u).length>0&&Object.assign(w,u),c){let _=this.buildSortAggregatePipeline(e,w,o.userSort);h>0&&_.push({$skip:h}),_.push({$limit:l}),s&&_.push({$project:s});let I=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback(I,i)}let x={sort:this.buildSortFromTokens(o?.userSort)||{_id:1}};s&&(x.projection=s);let R=this.db.collection(e).find(w,x);return h>0&&R.skip(h),R.limit(l),this.applyReadFallback(await R.toArray(),i)},te),b=[];for(let[$,w]of y.entries()){let T=a.find(x=>this.keyOf(x)===$);for(let x of w)x[t]||(x[t]=T??$),b.push(x)}return{docs:b,groupKeyField:t}}if(s&&(s[t]=1),c){let h=[],y=await de(a,async b=>{let $={[t]:b};u&&Object.keys(u).length>0&&Object.assign($,u);let w=this.buildSortAggregatePipeline(e,$,o.userSort);s&&w.push({$project:s});let T=await this.db.collection(e).aggregate(w).toArray();return this.applyReadFallback(T,i)},te);for(let b of y.values())for(let $ of b)h.push($);return{docs:h,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(o?.userSort)||{_id:1},g={projection:s,sort:d},m=await Y(a,h=>this.db.collection(e).find({[t]:{$in:h},...u||{}},g).toArray());return{docs:this.applyReadFallback(m,i),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=_e(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(w=>w._id).filter(w=>w!=null),l=new Map;for(let w of e)l.set(this.keyOf(w._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await Y(u,w=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:w}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?ue(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let w=d?(d-1)*p:0,T=await de(u,async R=>{let I=(await this.db.collection(a.junctionName).find({[a.selfColumn]:R},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(L=>L[a.otherColumn]).filter(L=>L!=null);if(I.length===0)return[];let v={_id:{$in:I}};if(c&&Object.keys(c).length>0&&Object.assign(v,c),this.hasDottedSort(t.userSort)){let L=this.buildSortAggregatePipeline(t.targetTable,v,t.userSort);w>0&&L.push({$skip:w}),L.push({$limit:p}),o.projection&&L.push({$project:o.projection});let S=await this.db.collection(t.targetTable).aggregate(L).toArray();return this.applyReadFallback(S,o)}let D={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};o.projection&&(D.projection=o.projection);let P=this.db.collection(t.targetTable).find(v,D);return w>0&&P.skip(w),P.limit(p),this.applyReadFallback(await P.toArray(),o)},te),x=[];for(let[R,_]of T.entries()){l.set(R,_);for(let I of _)x.push(I)}return{grouped:l,docs:x}}let g=new Set,m=[];for(let w of f){let T=w[a.otherColumn];if(T==null)continue;let x=this.keyOf(T);g.has(x)||(g.add(x),m.push(T))}let h=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!c,y=[],b=new Map;if(h)y=m.map(w=>({_id:w})),this.sortDocsByPk(y);else{let w={_id:{$in:m}};c&&Object.keys(c).length>0&&Object.assign(w,c);let T=this.hasDottedSort(t.userSort),x;if(T){let R=this.buildSortAggregatePipeline(t.targetTable,w,t.userSort);o.projection&&R.push({$project:o.projection}),x=await this.db.collection(t.targetTable).aggregate(R).toArray()}else{let R=this.buildSortFromTokens(t.userSort)||{_id:1},_=this.projectionWithSortFields(o.projection,t.userSort),I={sort:R};_.projection&&(I.projection=_.projection),x=await Y(m,v=>this.db.collection(t.targetTable).find({_id:{$in:v},...c||{}},I).toArray()),t.userSort?this.sortDocsInMemory(x,t.userSort):this.sortDocsByPk(x),this.removeHiddenFields(x,_.hiddenFields)}y=this.applyReadFallback(x,o)}for(let w of y)b.set(this.keyOf(w._id),w);let $=new Map;for(let w of f){let T=this.keyOf(w[a.selfColumn]),x=this.keyOf(w[a.otherColumn]);b.has(x)&&($.has(x)||$.set(x,[]),$.get(x).push(T))}for(let w of y){let T=$.get(this.keyOf(w._id))||[];for(let x of T)l.get(x)?.push(w)}return{grouped:l,docs:y}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function ln(r,e,t,n,i=3,o=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new tt(r,a,f);await new xe(c,n,u).execute(e,t,i,o,s)}async function Dn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),l=new Set((u?.relations??[]).map(_=>_.propertyName)),f=!!e.mongoRawFilter&&!!o&&ie(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&f){let _=await fe(e.mongoRawFilter,e.table,o,i);_&&Object.keys(_).length>0&&n.push({$match:_})}else if(p){let _=We(c.filterTree,{metadata:o,rootTable:e.table});Object.keys(_).length>0&&n.push({$match:_})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let _=Ge(o,e.where,e.table,s);n.push({$match:_})}let d=e.plan,m=d?d.hasRelationSort:e.sort?.some(_=>{if(!_.field.includes("."))return!1;let I=_.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(v=>v.propertyName===I)??!1})??!1,h=()=>d?.sortItems?to(d.sortItems):e.sort?eo(e.sort):null,y=d?.sortItems?Yi(d.sortItems):[],b=()=>{!d||y.length===0||Xi(n,e.table,d.sortItems,o)},$=()=>{y.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(y.map(_=>[_,0]))})};if(!e.mongoFieldsExpanded){b();let _=h();if(_&&n.push({$sort:_}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),$(),e.select){let v={};for(let O of e.select)v[O]=1;n.push({$project:v})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let I=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:I,pipeline:n}:{results:Ar(I),pipeline:n}}let{scalarFields:w,relations:T}=e.mongoFieldsExpanded;if(!m){b();let _=h();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let x=[];for(let _ of T)if(e.sort?.some(v=>v.field.startsWith(`${_.propertyName}.`))){let v=e.mongoRawFilter?.[_.propertyName];if(_.nestedFields&&_.nestedFields.length>0){let N=await Nt(o,_.targetTable,_.nestedFields??[],v);_.type==="one"&&N.length>0&&N.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:N.length>0?N:void 0}})}else if(v){let N=await Nt(o,_.targetTable,["_id"],v);_.type==="one"&&N.length>0&&N.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:N.length>0?N:void 0}})}else n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName}});_.type==="one"&&(n.push({$unwind:{path:`$${_.propertyName}`,preserveNullAndEmptyArrays:!0}}),v&&(nt(v)||n.push({$match:{[_.propertyName]:{$ne:null}}})))}else x.push(_);if(m){b();let _=h();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}await Nr(o,n,e.table,w,[...T]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let R=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:R,pipeline:n};if(x.length>0&&R.length>0){let _=e.deep||{},I=x.map(O=>{let D=o?.tables?.get(e.table)?.relations?.find(S=>S.propertyName===O.propertyName),P=_[O.propertyName],L=P?.fields!=null?Array.isArray(P.fields)?P.fields:String(P.fields).split(",").map(S=>S.trim()).filter(Boolean):O.nestedFields&&O.nestedFields.length>0?O.nestedFields:["_id"];return{relationName:O.propertyName,type:D?.type,targetTable:O.targetTable,fields:L,isInverse:D?.isInverse,mappedBy:D?.mappedBy,junctionTableName:D?.junctionTableName,localField:O.localField,foreignField:O.foreignField,userFilter:P?.filter,userSort:P?.sort,userLimit:P?.limit!==void 0?Number(P.limit):void 0,userPage:P?.page!==void 0?Number(P.page):void 0,nestedDeep:P?.deep}}),v=Zi(o);v&&await ln(i,R,I,v,3,0,e.table,o,void 0,t.mongoPhysicalMigrationService)}return{results:Ar(R),pipeline:n}}function Wn(r){return`__sort_count_${r.relationName||r.field}`}function Yi(r){return r.filter(e=>e.function==="count").map(Wn)}function Xi(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=Wn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=K(a)||u;r.push({$lookup:{from:l,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=_e(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function Zi(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function eo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function to(r){let e={};for(let t of r){let n=t.function==="count"?Wn(t):t.joinId!==null?t.fullPath:t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function nt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>nt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>nt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>nt(e));if("_not"in r)return nt(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||nt(t)))return!0}return!1}function Ar(r){return r.map(re)}function Or(r,e){let t=[],n=[],i=e?.tables?.get(r.rootTable);if(!i)return{scalarFields:t,relations:n};for(let o of r.nodes)if(o.kind==="wildcard")for(let s of i.columns||[])t.includes(s.name)||t.push(s.name);else o.kind==="scalar"?i.columns?.some(a=>a.name===o.name)&&!t.includes(o.name)&&t.push(o.name):o.kind==="relation"&&n.push(no(o,i,e));return{scalarFields:t,relations:n}}function no(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Be(n)?(i="_id",o=K(n)||r.propertyName,s=!0):(i=n&&H(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&K(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Er(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Er(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Er(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Ye();It();vt();function cn(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=o.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),m=p.substring(d+1);if(!o.relations?.some(y=>y.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(m)}else if(o.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!o.columns?.some(m=>m.name===p))continue;f.push(p)}}if(f.includes("*")){i.nodes.push({kind:"wildcard"});for(let c of o.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)i.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=o.relations?.find(h=>h.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,m={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Pr(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let h=n.registerWithParent(e,c,t,"left",null,"data");m.joinId=h}i.nodes.push(m)}return i}function Pr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),o=n.columns?.some(f=>f.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Pr(c,d,t)})}return l}Te();var Q=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new oe,d=this.parseFields(n),g=null;d&&c&&(g=cn(d,t,l,p));let m=!1,h=null;if(i&&c){let O=Se(i,t,l,p);h=O.node,m=O.hasRelationFilters}let y=this.parseSort(o),b=[],$=!1;for(let O of y){let N=O.startsWith("-"),D=N?O.substring(1):O,P=N?"desc":"asc";if(c){let L=this.parseRelationCountSort(t,c,D);if(L){b.push({joinId:null,field:D,direction:P,fullPath:D,function:"count",relationName:L.relationName,relationMeta:L.relationMeta});continue}this.assertLocalSortField(t,c,D)}b.push({joinId:null,field:D,direction:P,fullPath:D})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let w=this.parseLimit(a),T=this.parsePage(s),x=T!==void 0&&w!==void 0?(T-1)*w:void 0,R=this.parseMeta(u),_=R.includes("totalCount")||R.includes("*"),I=R.includes("filterCount")||R.includes("*"),v=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:i??null,joins:v,sortItems:b,limit:w,offset:x,needsTotalCount:_,needsFilterCount:I,hasRelationFilters:m,hasRelationSort:$,filterTree:h,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new M(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new M(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationCountSort(e,t,n){if(!n.startsWith("_count"))return null;let i=n.match(/^_count\(([^)]+)\)$/);if(!i)throw new M(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName).`);let o=i[1].trim();if(!o||o.includes("."))throw new M(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let s=t.relations?.find(a=>a.propertyName===o);if(!s)throw new M(`Sort relation '${o}' does not exist on '${e}'.`);if(s.type!=="one-to-many"&&s.type!=="many-to-many")throw new M(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`);return{relationName:o,relationMeta:s}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=i.registerWithParent(t,a,n,"left",o,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,i,c)}};Te();Rt();var ro=new Set(["count","sum","avg","min","max","countRecords"]),io=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),oo=new Set(["_and","_or","_not"]);function ke(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function E(r,e){let t=r.replace(/^aggregate\./,"");throw new M(e,{path:r,aggregate:{[t]:e}})}function so(r){return typeof r!="string"?!1:io.has(r.toLowerCase())}function jr(r){return Object.keys(r).length===0}function ao(r,e,t){return r===!0?{}:(r==null&&E(t,`aggregate.${e} condition must be true or an object`),ke(r)||E(t,`aggregate.${e} condition must be true or an object`),r)}function lo(r,e,t){let n=r?.tables?.get(e);return n||E(t,`Table "${e}" metadata is not available`),n}function Lr(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&E(e,"aggregate.countRecords relation target is not available"),t}function un(r,e,t,n){let i=lo(t,e,n);for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){Array.isArray(s)||E(n,`aggregate.countRecords ${o} condition must be an array`);for(let f of s)ke(f)||E(n,`aggregate.countRecords ${o} items must be objects`),un(f,e,t,n);continue}if(o==="_not"){ke(s)||E(n,"aggregate.countRecords _not condition must be an object"),un(s,e,t,n);continue}(o.startsWith("_")||oo.has(o))&&E(n,`Unsupported aggregate.countRecords condition key "${o}"`);let a=i.columns?.find(f=>f.name===o),u=i.relations?.find(f=>f.propertyName===o);if(!a&&!u&&E(n,`Unknown aggregate.countRecords field or relation "${o}" on table "${e}"`),ke(s)||E(n,`aggregate.countRecords condition for "${o}" must be an object`),a){for(let f of Object.keys(s))ee.has(f)||E(n,`aggregate.countRecords condition for "${o}" only supports field operators`);continue}let l=Lr(u,n);un(s,l,t,n)}}function Kn(r){return ke(r)&&Object.keys(r).length>0}function rt(r,e,t){if(!Kn(r))return[];ke(r)||E("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||E("aggregate",`Table "${e}" metadata is not available`);let i=[];for(let[o,s]of Object.entries(r)){let a=`aggregate.${o}`;(!o||typeof o!="string")&&E("aggregate","aggregate field name must be a non-empty string"),ke(s)||E(a,"aggregate field config must be an object");let u=o,l=a,f=n.columns?.find(d=>d.name===o),c=n.relations?.find(d=>d.propertyName===o);!f&&!c&&E(l,`Unknown aggregate field or relation "${o}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&E(l,"aggregate field must define at least one operation");for(let[d,g]of p){ro.has(d)||E(l,`Unsupported aggregate operation "${d}"`);let m=ao(g,d,l);if(c&&d!=="countRecords"&&E(l,`aggregate.${d} is not supported on relation "${o}"; use countRecords`),f&&d==="countRecords"&&E(l,`aggregate.countRecords requires a relation, but "${o}" is a field`),f&&(d==="sum"||d==="avg")&&!so(f.type)&&E(l,`aggregate.${d} requires a numeric field, but "${o}" is "${f.type}"`),f)for(let h of Object.keys(m))ee.has(h)||E(l,`aggregate.${d} condition for "${o}" only supports field operators`);if(c&&d==="countRecords"){let h=Lr(c,l);un(m,h,t,l)}i.push({field:o,outputKey:u,path:l,op:d,condition:m})}}return i}function it(r,e){let t=[];return ke(r)&&!jr(r)&&t.push(r),jr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function Ce(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var ot=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new Q;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(U(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&ie(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?We(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(i.includes("filterCount")||i.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(i.length>0||c)&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[];if(e.fields&&e.fields.length>0){let s=e.plan;if(s?.fieldTree?e.mongoFieldsExpanded=Or(s.fieldTree,this.metadata):(console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await qt(this.metadata,e.table,e.fields)),this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.hiddenFields}}e.where&&(e.where=e.where.map(s=>s.field.includes(".")?s:{...s,field:`${e.table}.${s.field}`}));let n=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await n.aggregate(e.pipeline).toArray()).map(re);let{results:i,pipeline:o}=await Dn(n,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,i,t):i}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Dn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={},o=this.db.collection(e.table);for(let s of n){let a=it(t,s);U(a,e.table,e.metadata);let l=new Q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);Ce(i,s,p);continue}let f=l.hasRelationFilters?await fe(a,e.table,e.metadata,this.db):l.filterTree?We(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await o.countDocuments(f);else{let[{value:p}={value:null}]=await o.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}Ce(i,s,c)}return i}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(o.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[o.foreignKeyColumn]:{$in:c}}]})}if(o.type==="many-to-many"){let f=_e(e.table,o);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(m=>m!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(m=>m[f.otherColumn]).filter(m=>m!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(o.type==="many-to-one"||o.type==="one-to-one"){let f=o.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};U(t,e,n);let o=new Q().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return o.hasRelationFilters?await fe(t,e,n,this.db):o.filterTree?We(o.filterTree,{metadata:n,rootTable:e}):{}}};var fn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};Te();var co=["_and","_or","_not"];function pe(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>pe(e));for(let e of Object.keys(r))if(co.includes(e)||typeof r[e]=="object"&&r[e]!==null&&pe(r[e]))return!0;return!1}var Br=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function uo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function dn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function fo(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||dn(r,t,i),e}function Dr(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=dn(e,i,s),l=fo(e,n,i,o,s);switch(t){case"_eq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} = ?::uuid`,[n]):r.where(a,"=",l);break;case"_neq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} != ?::uuid`,[n]):r.where(a,"!=",l);break;case"_gt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} > ?::uuid`,[n]):r.where(a,">",l);break;case"_gte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} >= ?::uuid`,[n]):r.where(a,">=",l);break;case"_lt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} < ?::uuid`,[n]):r.where(a,"<",l);break;case"_lte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} <= ?::uuid`,[n]):r.where(a,"<=",l);break;case"_in":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${a} = ANY(?::uuid[])`,[f]):r.whereIn(a,f);break;case"_not_in":case"_nin":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(p=>p.trim()):[c]),u&&o==="postgres"&&c.every(p=>typeof p=="string")?r.whereRaw(`${a} != ALL(?::uuid[])`,[c]):r.whereNotIn(a,c);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,uo(t),n)}}function po(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function st(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){st(this,s,t,"and",i,o)}):r.orWhere(function(){st(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(po(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){st(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>Br.includes(l)))for(let[l,f]of Object.entries(a))Br.includes(l)&&(n==="and"?r.where(function(){Dr(this,s,l,f,t,i,o)}):r.orWhere(function(){Dr(this,s,l,f,t,i,o)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s;dn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s;dn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${u} = ?::uuid`,[a]):r.orWhereRaw(`${u} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function ae(r,e,t,n,i){return!e||typeof e!="object"||st(r,e,t,"and",n,i),r}Fe();function Jn(r,e,t){return`${C(r,t)}.${C(e,t)}`}function Re(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Wr(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function at(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function zn(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let l=await Ot(r,e,a,u,t,n,i);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Jn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=at(d._is_null),m=at(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(m===!0)s.push(`${c} IS NOT NULL`);else if(m===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let h=Re(d._eq,n);s.push(`${c} = ${h}`)}else if(d._neq!==void 0){let h=Re(d._neq,n);s.push(`${c} != ${h}`)}else if(d._in!==void 0){let y=(Array.isArray(d._in)?d._in:[d._in]).map(b=>Re(b,n)).join(", ");s.push(`${c} IN (${y})`)}else if(d._not_in!==void 0||d._nin!==void 0){let h=d._not_in??d._nin,b=(Array.isArray(h)?h:[h]).map($=>Re($,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let h=Re(d._gt,n);s.push(`${c} > ${h}`)}else if(d._gte!==void 0){let h=Re(d._gte,n);s.push(`${c} >= ${h}`)}else if(d._lt!==void 0){let h=Re(d._lt,n);s.push(`${c} < ${h}`)}else if(d._lte!==void 0){let h=Re(d._lte,n);s.push(`${c} <= ${h}`)}}}}}return s}function Vn(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function Un(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(Vn(l)){let f=e(t).select(`${t}.id`);await Ke(e,f,l,t,n,i,o),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=G(l,n),p=await zn(e,t,n,i,o,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(Vn(a)){let u=e(t).select(`${t}.id`);await Ke(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=G(a,n),f=await zn(e,t,n,i,o,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Kr(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&ae(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function Qn(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)Kr(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function pn(r,e,t,n,i,o,s){let a=Wr(e,i),u=Wr(n,o),l=`${C(r,s)}.${C(e,s)}`,f=`${C(t,s)}.${C(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Ot(r,e,t,n,i,o,s){let a=i.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(pn(u,a.foreignKeyColumn,e,"id",f,i,o));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(pn(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,o))).whereRaw(pn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,i,o));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(pn(u,"id",e,a.foreignKeyColumn,f,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await Ke(r,c,n,u,f,o,s):c=ae(c,n,u,o,f||void 0):c=ae(c,n,u,o),c.toString()}async function Ke(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Un(l._or,r,n,i,o,s);e.where(function(){Qn(this,f,n,i,o)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await Ke(r,e,f,n,i,o,s);else await Ke(r,e,l,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let l=await Un(t._or,r,n,i,o,s);e.where(function(){Qn(this,l,n,i,o)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(Vn(d)){let g=r(n).select(`${n}.id`);await Ke(r,g,d,n,i,o,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:m}=G(d,i),h=await zn(r,n,i,o,s,m);p.push({fieldFilters:g,subqueries:h})}e.whereNot(function(){for(let d of p)Kr(this,d,n,i,o)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Un(l._or,r,n,i,o,s);e.whereNot(function(){Qn(this,p,n,i,o)});return}let{fieldFilters:f,relationFilters:c}=G(l,i);e.whereNot(function(){Object.keys(f).length>0&&ae(this,f,n,o,i)});for(let[p,d]of Object.entries(c)){let g=await Ot(r,n,p,d,i,o,s);if(g===null){let m=i.relations.find(h=>h.propertyName===p);if(m&&m.foreignKeyColumn){let h=Jn(n,m.foreignKeyColumn,o),b=d.id;if(b&&typeof b=="object"){let $=at(b._is_null),w=at(b._is_not_null);if($===!0)e.whereRaw(`${h} IS NOT NULL`);else if($===!1)e.whereRaw(`${h} IS NULL`);else if(w===!0)e.whereRaw(`${h} IS NULL`);else if(w===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,x=Array.isArray(T)?T:[T];e.whereRaw(`${h} IN (${x.map(()=>"?").join(", ")})`,x)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=G(t,i);Object.keys(a).length>0&&ae(e,a,n,o,i);for(let[l,f]of Object.entries(u)){let c=await Ot(r,n,l,f,i,o,s);if(c===null){let p=i.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Jn(n,p.foreignKeyColumn,o),m=f.id;if(m&&typeof m=="object"){let h=at(m._is_null),y=at(m._is_not_null);if(h===!0)e.whereRaw(`${d} IS NULL`);else if(h===!1)e.whereRaw(`${d} IS NOT NULL`);else if(y===!0)e.whereRaw(`${d} IS NOT NULL`);else if(y===!1)e.whereRaw(`${d} IS NULL`);else if(m._eq!==void 0)e.whereRaw(`${d} = ?`,[m._eq]);else if(m._neq!==void 0)e.whereRaw(`${d} != ?`,[m._neq]);else if(m._in!==void 0){let b=Array.isArray(m._in)?m._in:[m._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(m._not_in!==void 0||m._nin!==void 0){let b=m._not_in??m._nin,$=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${$.map(()=>"?").join(", ")})`,$)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Ue(r,e,t,n,i,o,s){await Ke(r,e,t,n,i,o,s)}Fe();Hn();Ye();Fe();function lt(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],l=Et(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",l);break;case"!=":r=r.where(o.field,"!=",l);break;case">":r=r.where(o.field,">",l);break;case"<":r=r.where(o.field,"<",l);break;case">=":r=r.where(o.field,">=",l);break;case"<=":r=r.where(o.field,"<=",l);break;case"like":r=r.where(o.field,"like",l);break;case"in":let f=Array.isArray(o.value)?o.value.map(m=>Et(n,a,u,m)):[l];r=r.whereIn(o.field,f);break;case"not in":let c=Array.isArray(o.value)?o.value.map(m=>Et(n,a,u,m)):[l];r=r.whereNotIn(o.field,c);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let p=o.value;if(typeof p=="string"&&(p=p.split(",").map(m=>m.trim())),Array.isArray(p)&&p.length===2){let m=Et(n,a,u,p[0]),h=Et(n,a,u,p[1]);r=r.whereBetween(o.field,[m,h])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Pt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let f=Pt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=Pt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Pt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let f=`${C(e,n)}.${C(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=o.columns?.find(m=>m.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${f} = ${c}`);else if(u==="_neq")i.push(`${f} != ${c}`);else if(u==="_gt")i.push(`${f} > ${c}`);else if(u==="_gte")i.push(`${f} >= ${c}`);else if(u==="_lt")i.push(`${f} < ${c}`);else if(u==="_lte")i.push(`${f} <= ${c}`);else if(u==="_is_null")i.push(`${f} IS NULL`);else if(u==="_is_not_null")i.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);i.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${C(e,n)}.${C(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),i.push(`${u} = ${l}`)}return i}function Qr(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Et(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}Fe();jt();Ve();async function zr(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Yn(),Jr)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function Xn(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function Vr(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||V(r.propertyName);if(!s)return null;let a=c=>C(c,i),u=n?.tables?.get(o),f=(u?ne(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(f)} = ${a(t)}.${a(s)})`}jt();var ut=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new fn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&U(e.filter,e.tableName,e.metadata),!e.plan){let S=new Q;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 o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&l){i&&i.setQueryPath("simple");let S=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),S}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(S=>S.trim())));let p=e.filter;if(e.filter&&!pe(e.filter)){c.where=[];for(let[S,k]of Object.entries(e.filter))if(typeof k=="object"&&k!==null)for(let[F,le]of Object.entries(k)){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;c.where.push({field:S,operator:A,value:le})}else c.where.push({field:S,operator:"=",value:k})}if(e.sort){let S=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(k=>k.trim());c.sort=S.map(k=>{let F=k.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,m=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=m===void 0||Number.isNaN(m)?void 0:m;h&&g!==void 0?(c.offset=(h-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let y=e.plan?.sortItems??(c.sort??[]).map(S=>({joinId:null,field:S.field,direction:S.direction,fullPath:S.field})),b=[],$=[];for(let S of y){if(S.function==="count"){let k={sql:this.buildRelationCountSortSubquery(c.table,S),direction:S.direction};$.push(k);continue}if(S.joinId===null){if(S.field.includes(".")&&!e.plan){let F=S.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(J=>J.propertyName===F))continue}let k={field:S.field.includes(".")?S.field:`${c.table}.${S.field}`,direction:S.direction};b.push(k),$.push(k)}else{let k=e.plan?.joins.find(F=>F.id===S.joinId);if(k&&(k.relationType==="many-to-one"||k.relationType==="one-to-one")){let F=Vr(k.relationMeta,S.field,c.table,this.metadata,this.dbType);if(F){let le={sql:F,direction:S.direction};$.push(le)}}}}let w=[];if(c.fields&&c.fields.length>0){let S=Xn(this.metadata),k=await zr(this.knex,c.table,c.fields,S,this.dbType,this.maxQueryDepth,e.deep);c.select=[...c.select||[],...k.select],w=k.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(S=>S.field.includes(".")?S:{...S,field:`${c.table}.${S.field}`})),c.sort=b;let T=this.knex(c.table),x=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(S=>S.trim()).filter(Boolean),R=x.includes("filterCount")||x.includes("*"),_=x.includes("totalCount")||x.includes("*");if(c.select){let S=c.select.map(k=>typeof k=="string"&&k.trim().startsWith("(")?this.knex.raw(k):typeof k=="string"&&/ as /i.test(k)?this.knex.raw(k):k);T=T.select(S)}if(R&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let S=C(c.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${S}) as __total_count__`))}let I=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(pe(p)||Object.keys(p).length>0)){let S=this.metadata?.tables?.get(c.table);(!I&&S&&S.relations&&S.relations.length>0?G(p,S).hasRelations:!1)?await Ue(this.knex,T,p,c.table,S,this.dbType,F=>this.metadata?.tables?.get(F)):e.plan?.filterTree?X(T,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),T=ae(T,p,c.table,this.dbType,S))}else c.where&&c.where.length>0&&(T=lt(T,c.where,c.table,this.metadata,this.dbType));for(let S of $)if(S.field){let k=S.field.includes(".")?S.field:`${c.table}.${S.field}`;T=T.orderBy(k,S.direction)}else S.sql&&(T=T.orderByRaw(`${S.sql} ${S.direction.toUpperCase()}`));c.groupBy&&(T=T.groupBy(c.groupBy)),c.offset&&(T=T.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&(T=T.limit(c.limit));let v=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:T.toSQL().toNative()});let O;if(e.debugMode&&(O=T.toSQL().toNative().sql),e.debugMode&&i){let S=T.toSQL().toNative();i.setSql(S.sql);try{let k=S.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${k}`,S.bindings);i.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(k){i.setExplain({error:String(k)})}}let N,D=performance.now();N=await T,i&&i.dur("db_execute",D,{table:e.tableName});let P=0;if(R&&N.length>0&&(P=Number(N[0].__filter_count__||0),N.forEach(S=>{delete S.__filter_count__})),_&&N.length>0&&N[0].__total_count__!==void 0&&(v=Number(N[0].__total_count__||0),N.forEach(S=>{delete S.__total_count__})),w&&w.length>0&&N.length>0){let S=Xn(this.metadata);if(S){let{executeBatchFetches:k}=await Promise.resolve().then(()=>(tr(),qr));await k(this.knex,N,w,S,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,i)}}if(this.knexService){let S=performance.now();N=await this.knexService.parseResult(N,c.table),i&&i.dur("db_parseResult",S,{table:e.tableName})}else{let S=(k,F)=>{if(!k||!this.metadata)return k;let le=this.metadata.tables?.get(F);if(!le)return k;if(Array.isArray(k))return k.map(J=>S(J,F));if(typeof k!="object"||Buffer.isBuffer(k))return k;let A={...k};for(let J of le.columns)if(J.type==="simple-json"&&A[J.name]&&typeof A[J.name]=="string")try{A[J.name]=JSON.parse(A[J.name])}catch{}for(let[J,q]of Object.entries(A))if(q&&typeof q=="object"&&!Array.isArray(q)&&!Buffer.isBuffer(q)){let _n=q;if(_n.id!==void 0||_n.createdAt!==void 0){let dt=le.relations?.find(pt=>pt.propertyName===J);dt&&(A[J]=S(q,dt.targetTableName))}}else if(Array.isArray(q)&&q.length>0&&typeof q[0]=="object"&&q[0].id!==void 0){let dt=le.relations?.find(pt=>pt.propertyName===J);dt&&(A[J]=q.map(pt=>S(pt,dt.targetTableName)))}return A};N=S(N,c.table)}i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName}));let L=await this.executeAggregate(c,p);return{data:N,...(x.length>0||L)&&{meta:{...x.includes("totalCount")||x.includes("*")?{totalCount:v}:{},...x.includes("filterCount")||x.includes("*")?{filterCount:P}:{},...L?{aggregate:L}:{}}},...O!==void 0&&{sql:O}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=ne(s)?.name||"id",u=C(e,this.dbType),l=C(a,this.dbType);if(!n||!o)throw new M(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new M(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let c=C(o,this.dbType),p=C(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=this.resolveManyToManyContract(n,i,e),c=C(f.tableName,this.dbType),p=C(f.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new M(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new M(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&X(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let y=h.field.includes(".")?h.field:`${n}.${h.field}`;o=o.orderBy(y,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=C(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let h=o.toSQL().toNative();if(f=h.sql,l){l.setSql(h.sql);try{let y=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${y}`,h.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(y){l.setExplain({error:String(y)})}}}let c=performance.now(),p;p=await o,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(h=>delete h.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(h=>delete h.__total_count__));let m=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||m)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...m?{aggregate:m}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={};for(let o of n){let s=it(t,o);U(s,e.table,e.metadata);let u=new Q().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(o.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,o);Ce(i,o,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Ue(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&X(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${C(e.table,this.dbType)}.${C(o.field,this.dbType)}`,c=o.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${o.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();Ce(i,o,p?.value??0)}return i}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table),o=i?.relations?.find(c=>c.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new Q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,u,t,e.table,i,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){U(n.condition,s,e.metadata);let p=new Q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(o.type==="one-to-many")l.whereIn(`${s}.${o.foreignKeyColumn}`,u);else if(o.type==="many-to-many"){let c=this.resolveManyToManyContract(o,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(o.type==="many-to-one"||o.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${o.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${o.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var hn=require("mongodb"),ft=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.contextIds=new WeakMap;this.nextContextId=1;this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,mn.mkdirSync)((0,Hr.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!hn.ObjectId)return e;if(typeof e=="string")try{return new hn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Ge(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:lt(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.mongoService.insertOne(e.table,n);t.push(re(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new Q().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb")return new ot(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new ut(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(o).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(i).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof hn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return re(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t],i=this.captureMutationContextSnapshot();for(let o of n)this.batchInserts.items.push({table:e,data:o,contextSnapshot:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now(),i=this.groupBatchInsertsByContext(t);await this.runLimited([...i.values()],o=>this.runBatchInsertWithIsolation(e,o.items,o.contextSnapshot)),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t,n){if(t.length!==0)try{let i=async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.mongoService.insertOne(e,o.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.knexService.insertWithCascade(e,o.data)))};await this.runWithMutationContextSnapshot(n,i)}catch(i){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,i);return}let o=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,o),n),this.runBatchInsertWithIsolation(e,t.slice(o),n)])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}groupBatchInsertsByContext(e){let t=new Map;for(let n of e){let i=n.contextSnapshot?.key||null,o=t.get(i);o?o.items.push(n):t.set(i,{contextSnapshot:n.contextSnapshot||null,items:[n]})}return t}captureMutationContextSnapshot(){let e=this.dbType==="mongodb"?this.mongoService?.getMutationContextSnapshot?.()??null:this.knexService?.getMutationContextSnapshot?.()??null;return!e?.policy&&!e?.fieldPermission?null:{key:`${this.getContextId(e.policy)}:${this.getContextId(e.fieldPermission)}`,value:e}}async runWithMutationContextSnapshot(e,t){return e?this.dbType==="mongodb"?typeof this.mongoService?.runWithMutationContextSnapshot=="function"?await this.mongoService.runWithMutationContextSnapshot(e.value,t):await t():typeof this.knexService?.runWithMutationContextSnapshot=="function"?await this.knexService.runWithMutationContextSnapshot(e.value,t):await t():await t()}getContextId(e){if(!e)return 0;let t=this.contextIds.get(e);if(t)return t;let n=this.nextContextId++;return this.contextIds.set(e,n),n}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,mn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
54
54
  `)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let o=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return re(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?i._id=this.safeObjectId(u):i[a]=u;return await this.mongoService.collection(e).find(i).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};tr();Zn();Yn();Fe();jt();et();Te();Ye();var Gr=new Set(["fields","filter","sort","limit","page","deep"]),bn=3;function nr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new M(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let l=s.get(a);if(!l)throw new M(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!Gr.has(p))throw new M(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...Gr].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new M(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new M(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(U(u.filter,c,t),yn(u.filter,0,a,r)),u.sort){let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;mo(g,c,t,a,r)}}u.deep&&nr(c,u.deep,t,n+1,i)}}}function mo(r,e,t,n,i){if(r.includes("."))throw new M(`Sort field '${r}' is not supported for relation '${n}' on '${i}'. Sort only by local fields defined on '${e}'.`);let o=t?.tables?.get(e);if(!o)throw new M(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${i}')`);let s=o.columns?.some(u=>u.name===r),a=r==="id"&&o.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new M(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var yo=new Set(["_and","_or","_not"]);function yn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(yo.has(i)){if(Array.isArray(o))for(let l of o)yn(l,e,t,n);else o&&typeof o=="object"&&yn(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>bn)throw new M(`Filter path exceeds max dotted hops of ${bn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(o))l.startsWith("_")||(u[l]=o[l]);yn(u,a,t,n)}}function Yr(r,e,t,n){return!r||typeof r!="object"?r:Lt(r,e,t,n)}function Lt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Lt(s,e,t,n)).filter(s=>s!=null);return o.length>0?o:null}let i={};for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){let c=(Array.isArray(s)?s:[s]).map(p=>Lt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(i[o]=c);continue}if(o==="_not"){let f=Lt(s,e,t,n);f!=null&&Object.keys(f).length>0&&(i[o]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Lt(s,f,t,n);c!=null&&Object.keys(c).length>0&&(i[o]=c);continue}if(a?.columns?.find(f=>f.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function Xr(r,e,t,n){if(!r)return r;let i=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,m=t?.tables?.get(c);if(!m){f=!1;break}if(g)m.columns?.find(y=>y.name===d)?n(c,d,"column")||(f=!1):m.relations?.find(b=>b.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let h=m.relations?.find(y=>y.propertyName===d);if(!h){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=h.targetTableName||h.targetTable||c}}f&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}vt();Ye();It();an();Rt();Ve();Te();function bo(r){let e=new ft({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new ze({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Qe({isolatedExecutorService:i()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return i()},get executorEngineService(){return o()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,transformCode,validateDeepOptions,validateFilterShape,whereToMongoFilter});
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "source": "bundled-compiled-kernel"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "Closed-distribution Enfyra kernel runtime",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "private": false,