bun-query-builder 0.3.11 → 0.3.12

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.
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Ve}from"./chunk-wvae8521.js";import{p,n,e,C,L,T,qe,m,E,l,lt,ee}from"./chunk-s9c63x14.js";function O(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function ke(t){if(typeof t!=="string")return;switch(t.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function _e(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}import{Database as pe}from"bun:sqlite";function ne(t){if(typeof t==="number")return{length:t};return t}function ye(t){if(typeof t==="number")return{max:t};return t}function Fe(t){return typeof t==="function"}function We(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function Me(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function G(t,r={}){if(!t)return r;return new Proxy(t,{get(o,s){if(s in r)return r[s];let i=o[s];if(i!==void 0)return i;let a=o[We(s)];if(Fe(a))return a.bind(o);return}})}function _t(t){let r=(f)=>{let g=Array.isArray(f)?f:[],K=Math.floor(Math.random()*g.length);return g[K]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=G(t.string,{alpha:(f)=>o()?.alpha?.(ne(f)),alphanumeric:(f)=>o()?.alphanumeric?.(ne(f)),numeric:(f)=>o()?.numeric?.(ne(f)),sample:(f)=>o()?.sample?.(ne(f)),hexadecimal:(f)=>o()?.hexadecimal?.(ne(f))}),d=G(t.number,{int:(f)=>s()?.int?.(ye(f)),float:(f)=>{let g=ye(f);return Me(Number(s()?.float?.(g)??0),g)}}),u=G(t.helpers,{arrayElement:r,arrayElements:(f,g)=>{let K=[...Array.isArray(f)?f:[]],k=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*K.length));for(let R=K.length-1;R>0;R-=1){let _=Math.floor(Math.random()*(R+1));[K[R],K[_]]=[K[_],K[R]]}return K.slice(0,Math.min(k,K.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let K=g.length-1;K>0;K-=1){let k=Math.floor(Math.random()*(K+1));[g[K],g[k]]=[g[k],g[K]]}return g},maybe:(f,g)=>{let K=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<K?f():void 0},slugify:(f)=>String(f??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),b={string:a,number:d,helpers:u,datatype:{boolean:(f)=>{let g=typeof f==="number"?f:f?.probability;if(typeof g==="number")return Math.random()<g;return Boolean(i()?.boolean?.())},number:(f)=>Number(s()?.int?.(ye(f))??0),float:(f)=>Me(Number(s()?.float?.(f)??0),f),uuid:()=>crypto.randomUUID(),string:(f)=>String(o()?.alphanumeric?.({length:f??10})??""),hexadecimal:(f)=>String(o()?.hexadecimal?.(ne(f))??""),array:(f)=>Array.from({length:f??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:G(t.address),address:G(t.address),vehicle:G(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:G(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(f,g){if(g in b)return b[g];let K=f[g];if(K&&typeof K==="object")return G(K);return K}})}function Ie(t){if(typeof t==="string")return{model:t};if(t&&typeof t==="object"&&typeof t.model==="string"){let r=t;return{model:r.model,foreignKey:r.foreignKey,onDelete:r.onDelete}}return null}function P(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Ie).filter((o)=>o!==null)}function Y(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var Pe=/^[A-Z_][A-Z0-9_]*$/i;function Q(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);if(t.length>64)throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' exceeds 64 chars`);if(!Pe.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Oe(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);let o=t.split(".");if(o.length>2||o.some((s)=>s.length===0||s.length>64||!Pe.test(s)))throw TypeError(`[bun-query-builder] ${r}: invalid ORDER BY column '${t}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Ke(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&ee(t)===0)return[];return r}var le=null,De=new Map;function Ue(t,r){De.set(t,r),oe.clear()}function It(){De.clear(),oe.clear()}function j(t){if(!le)try{le=import.meta.require("./chunk-ve576j6b.js").getModel}catch{le=()=>{return}}return le(t)??De.get(t)}var ue=new Map,He=500;function Re(t){let r=ue.get(t);if(r!==void 0)return r;let o=lt(t,"postgres");if(ue.size>=He)ue.clear();return ue.set(t,o),o}function Lt(t){if(t==null)return 0;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;if(Array.isArray(t))return t.length;return 0}function Kt(t){if(t==null||typeof t!=="object")return null;if("insertId"in t&&t.insertId!=null)return t.insertId;if("lastInsertRowid"in t&&t.lastInsertRowid!=null)return t.lastInsertRowid;return null}class be{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...p(r)))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...p(r))??void 0)}run(t,r){let o=this.sqliteDb.run(t,p(r));return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class we{dialect;constructor(t){this.dialect=t}conn(){return T()}text(t){return this.dialect==="postgres"?Re(t):t}async all(t,r){let o=await this.conn().unsafe(this.text(t),r);return Array.isArray(o)?o:[]}async get(t,r){let o=await this.conn().unsafe(this.text(t),r);if(Array.isArray(o))return o[0]??void 0;return o??void 0}async run(t,r){let o=await this.conn().unsafe(this.text(t),r);return{changes:Lt(o),lastInsertId:Kt(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${Re(t)} RETURNING ${o}`,r),d=Array.isArray(a)?a[0]:a;return{changes:1,lastInsertId:d?d[o]??null:null}}let s=await this.conn().unsafe(t,r),i=Kt(s);if(i==null&&this.dialect!=="sqlite"){let a=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);i=(Array.isArray(a)?a[0]:a)?.id??null}return{changes:Lt(s)||1,lastInsertId:i}}}var V=null,he=!1,q=null,re=null,de=null,fe=null;function Fn(t){if(t.database instanceof pe)V=t.database,he=!1;else V=new pe(t.database||":memory:",{create:!0}),he=!0,C(V);q=null,re=null}function jn(){let t=he,r=V;if(V=null,he=!1,q=null,re=null,de=null,fe=null,t&&r)try{r.close()}catch{}}var xe=!1;function N(){if(V){if(!q||re!==V)q=new be(V),re=V,de="sqlite",fe=null;return q}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${L()?.url??""}`;if(q&&re===null&&de===t&&fe===o)return q;if(re=null,de=t,fe=o,t==="sqlite"&&L())q=new we(t);else if(t==="sqlite"){if(!r&&!xe)xe=!0,console.warn("[bun-query-builder] The model layer has no database configured, so it is using an in-memory SQLite database and nothing it writes will persist. Configure one with setConfig({ dialect, database }) or configureOrm({ database }), or name ':memory:' explicitly to silence this.");let s=new pe(r||":memory:",{create:!0});C(s),q=new be(s)}else q=new we(t);return q}function qn(){let t=N();if(t.sqliteDb)return t.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${t.dialect}'. Use the async model API instead.`)}var Qe=4096,Ae=1000;function ze(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[v(a),d]));for(let a of r){let d=String(i.get(a)?.type??"").toLowerCase();if(d==="json"||d==="jsonb")return!1}for(let a of o)for(let d of r){let u=a[d];if(u===null||u===void 0||u instanceof Date)continue;let c=typeof u;if(c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="bigint")return!1}return!0}function Ge(t,r){return typeof r==="bigint"?r.toString():r}function Ee(t){return 2**Math.floor(Math.log2(t))}var F="deleted_at",ve=500,ge="__btm_rel__";function te(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Z(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ne=new WeakMap;function Xe(t){let r=Ne.get(t);if(r)return r;let o=new Set,s=t.belongsToMany;if(s){if(Array.isArray(s)){for(let i of s)if(typeof i==="string")o.add(i.toLowerCase());else if(i&&typeof i==="object"&&i.model)o.add(i.model.toLowerCase())}else if(typeof s==="object")for(let i of Object.keys(s))o.add(i)}return Ne.set(t,o),o}function Be(t){let r={};for(let[o,s]of Object.entries(t))r[v(o)]=s;return r}function Ye(t){for(let r in t)if(v(r)!==r)return Be(t);return t}function Je(t,r){if(t[r])return t[r];let o=v(r);if(t[o])return t[o];for(let s of Object.keys(t))if(v(s)===o)return t[s];return}class I{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Ye({...r}),this._original=null;let s=Xe(t);if(s.size===0)return;let i=this;return new Proxy(this,{get(a,d,u){if(typeof d==="string"&&s.has(d)&&!(d in a))return()=>{let c=je(t,d);if(!c||c.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let b=j(c.relatedModelName),f=b?.getDefinition?.()||b?.definition;if(!f)throw Error(`[orm] related model '${c.relatedModelName}' is not registered`);return new Ft(i,t,c,f)};return Reflect.get(a,d,u)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(t){let r=this._definition.get?.[t];if(r)try{let o=r(this._attributes);if(o!==void 0)return o}catch{}return this._attributes[v(t)]}getAttribute(t){return this._attributes[v(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[v(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[v(o)];return r}except(t){let r=new Set(t.map((s)=>v(s))),o={};for(let s of Object.keys(this._attributes))if(!r.has(s))o[s]=this._attributes[s];return o}getRelation(t){return this._relations[t]}setRelation(t,r){this._relations[t]=r}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let t=this._definition.primaryKey||"id";return this._attributes[t]}isDirty(t){if(this._original===null)return!1;if(t){let r=v(t);return this._attributes[r]!==this._original[r]}return Object.keys(this._attributes).some((r)=>this._attributes[r]!==this._original[r])}isClean(t){return!this.isDirty(t)}getOriginal(t){return this.getOriginalAttributes()[v(t)]}getChanges(){if(this._original===null)return{};let t={};for(let r of Object.keys(this._attributes))if(this._attributes[r]!==this._original[r])t[r]=this._attributes[r];return t}fill(t){let r=this._definition.attributes;for(let[o,s]of Object.entries(t)){let i=Je(r,o),a=!i&&v(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[v(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Be(t);Object.assign(this._attributes,r);for(let o of Object.keys(r))this._forced.add(o);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,o=this._definition.attributes,s={};for(let[u,c]of Object.entries(o)){if(c.guarded&&!this._forced.has(v(u)))continue;let b=v(u);if(this._attributes[b]!==void 0)s[b]=this._attributes[b]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in s))s[u]=this._attributes[u];let i=this._attributes[t],d=o[t]?.guarded&&!this._forced.has(t);if(i!=null&&!(t in s)&&!d)s[t]=i;if(Z(this._definition)){let u=Y(),c=this._attributes.created_at;s.created_at=c===void 0||c===null?u:c,s.updated_at=u}if(this._definition.traits?.useUuid&&!s.uuid)s.uuid=crypto.randomUUID();return await r?.beforeCreate?.(s),s}async _markInserted(t,r){let o=this._definition.primaryKey||"id";for(let[s,i]of Object.entries(t))this._attributes[s]=i;if(!(o in t)&&r!=null)this._attributes[o]=r;this._exists=!0,await this._definition.hooks?.afterCreate?.(this),this._original={...this._attributes},this._hasSaved=!0}_applySetters(){let t=this._definition.set||{};for(let[r,o]of Object.entries(t))if(this.isDirty(r))this._attributes[v(r)]=o(this._attributes)}async save(){let t=N(),r=this._definition.primaryKey||"id",o=this._definition.hooks;if(this._exists){this._applySetters(),await o?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let a=i.map((u)=>`${u} = ?`).join(", "),d=[...Object.values(s),this._attributes[r]];if(Z(this._definition)){let u=Y();await t.run(`UPDATE ${this._definition.table} SET ${a}, updated_at = ? WHERE ${r} = ?`,[...Object.values(s),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${a} WHERE ${r} = ?`,d)}await o?.afterUpdate?.(this)}else{let s=await this._prepareInsert(),i=Object.keys(s),a=i.map(()=>"?").join(", "),d=await t.insert(`INSERT INTO ${this._definition.table} (${i.join(", ")}) VALUES (${a})`,Object.values(s),r);return await this._markInserted(s,r in s?void 0:d.lastInsertId),this}return this._original={...this._attributes},this._hasSaved=!0,this}async update(t){return this.fill(t),this.save()}async fresh(){let t=N(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(o==null)return null;let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return new I(this._definition,s,!0)}async delete(){let t=N(),r=this._definition.primaryKey||"id",o=this._attributes[r],s=this._definition.hooks;if(o==null)throw Error("Cannot delete a model without a primary key");if(await s?.beforeDelete?.(this),te(this._definition)){let i=Y();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[F]=i}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[o]);return await s?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],o=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await o?.beforeDelete?.(this),await N().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!te(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let t=this._definition.primaryKey||"id",r=this._attributes[t];if(!r)throw Error("Cannot restore a model without a primary key");return await N().run(`UPDATE ${this._definition.table} SET ${F} = ? WHERE ${t} = ?`,[null,r]),this._attributes[F]=null,this._original=null,this}trashed(){return this._attributes[F]!=null}async refresh(){let t=N(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(!o)throw Error("Cannot refresh a model without a primary key");let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return this._attributes=s,this._original=null,this}replicate(){let t=this._definition.primaryKey||"id",r={...this._attributes};return delete r[t],delete r.uuid,delete r.created_at,delete r.updated_at,new I(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,o]of Object.entries(this._relations))if(Array.isArray(o))t[r]=o.map((s)=>s.toArray());else if(o)t[r]=o.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[o,s]of Object.entries(this._definition.attributes))if(s.hidden)t.add(o);let r={};for(let[o,s]of Object.entries(this._attributes))if(!t.has(o))r[o]=s;for(let[o,s]of Object.entries(this._relations))if(Array.isArray(s))r[o]=s.map((i)=>i.toJSON());else if(s)r[o]=s.toJSON();else r[o]=null;return r}}var Ce=new Map,$e=new Map,oe=new Map,Ze=1000;function U(t){return v(t)}function v(t){let r=Ce.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Ce.set(t,r),r}function X(t){let r=$e.get(t);if(r!==void 0)return r;return r=qe(t),$e.set(t,r),r}var ce=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],et=[...ce,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Se(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>typeof s==="string"?s:String(s?.model??"")).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function tt(t,r){let o=t.name??t.table??"model",i=et.filter((d)=>Se(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!ce.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${ce.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=ce.flatMap((d)=>Se(t,d));return a.length>0?`[orm] '${o}' has no relation '${r}'. Available: ${a.join(", ")}.`:`[orm] '${o}' has no relation '${r}' \u2014 it declares no relations at all.`}function je(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(D){if(!D)return null;if(Array.isArray(D)){for(let h of D){let M=typeof h==="string"?h:h?.model||"";if(M&&M.toLowerCase()===r.toLowerCase())return M}return null}if(typeof D==="object"){for(let[h,M]of Object.entries(D))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof M==="string"?M:M?.model||M?.target||h}return null}function d(){let D=t.belongsTo;if(!D)return null;let h=r.toLowerCase(),M=(w)=>{if(typeof w==="string")return{model:w};if(w&&typeof w==="object"&&typeof w.model==="string")return{model:w.model,foreignKey:w.foreignKey};return null};if(Array.isArray(D)){for(let w of D){let y=M(w);if(y&&y.model.toLowerCase()===h)return y}return null}if(typeof D==="object"){for(let[w,y]of Object.entries(D))if(w===r||w.toLowerCase()===h)return M(y)}return null}function u(){let D=t.belongsToMany;if(!D)return null;if(Array.isArray(D)){for(let h of D)if(typeof h==="string"){if(h.toLowerCase()===r.toLowerCase())return{entry:h}}else if(h&&typeof h==="object"&&h.model){if(h.model.toLowerCase()===r.toLowerCase())return{entry:h}}return null}if(typeof D==="object"){for(let[h,M]of Object.entries(D))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:M}}return null}function c(D){let h=t[D];if(!h)return null;let M=r.toLowerCase();if(Array.isArray(h)){for(let w of h){let y=typeof w==="string"?w:String(w?.model??"");if(!y||y.toLowerCase()!==M)continue;let A=typeof w==="object"?w?.morphName:void 0;return{model:y,morphName:String(A??`${v(o)}able`)}}return null}if(typeof h==="object")for(let[w,y]of Object.entries(h)){let A=typeof y==="string"?y:String(y?.model??"");if(w.toLowerCase()!==M&&A.toLowerCase()!==M)continue;let S=typeof y==="object"?y?.morphName:void 0;return{model:A,morphName:String(S??w)}}return null}for(let D of["morphMany","morphOne"]){let h=c(D);if(!h)continue;let w=j(h.model)?.getTable?.()||X(h.model);return{type:D,relatedModelName:h.model,relatedTable:w,foreignKey:`${h.morphName}_id`,localKey:i,morphTypeColumn:`${h.morphName}_type`,morphTypeValue:s}}let b=a(t.hasMany);if(b){let h=j(b)?.getTable?.()||X(b),M=v(o)+"_id";return{type:"hasMany",relatedModelName:b,relatedTable:h,foreignKey:M,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||X(f),M=v(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:M,localKey:i}}let g=d();if(g){let D=g.model,h=j(D),M=h?.getTable?.()||X(D),w=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${v(D)}_id`;return{type:"belongsTo",relatedModelName:D,relatedTable:M,foreignKey:y,localKey:w}}let K=u();if(K){let D=typeof K.entry==="object",h=D?K.entry.model:K.entry,w=j(h)?.getTable?.()||X(h),y=D?K.entry:null,A,S;if(y?.table)A=y.table;else if(y?.through){S=y.through;let B=j(y.through);if(!B)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${y.through}'. Make sure '${y.through}' is registered.`);A=B.getTable?.()||B.getDefinition?.()?.table||X(y.through)}else{let B=ae(s),H=ae(w);A=[B,H].sort().join("_")}let W=y?.foreignKey||`${ae(s)}_id`,J=y?.relatedKey||`${ae(w)}_id`,z=[];if(y?.pivot?.columns)for(let B of Object.keys(y.pivot.columns))z.push(B);if(S){let B=j(S),H=B?.getDefinition?.()||B?.definition,me=H?.attributes??{},Le=H?.primaryKey??"id";for(let ie of Object.keys(me)){if(ie===W||ie===J||ie===Le)continue;if(!z.includes(ie))z.push(ie)}}return{type:"belongsToMany",relatedModelName:h,relatedTable:w,foreignKey:W,localKey:i,pivotTable:A,pivotFkParent:W,pivotFkRelated:J,pivotColumns:z,pivotModelName:S,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let k=(D,h)=>{if(!D||typeof D!=="object"||Array.isArray(D))return null;let M=D[r]??D[Object.keys(D).find((H)=>H.toLowerCase()===r.toLowerCase())??""];if(!M||typeof M!=="object")return null;let{through:w,target:y}=M;if(!w||!y)return null;let A=j(w),S=A?.getDefinition?.()||A?.definition,W=A?.getTable?.()||S?.table||X(w),J=S?.primaryKey||"id",B=j(y)?.getTable?.()||X(y);return{type:h,relatedModelName:y,relatedTable:B,foreignKey:`${v(o)}_id`,localKey:i,throughTable:W,throughForeignKey:`${v(o)}_id`,throughLocalKey:J,targetForeignKey:`${ae(W)}_id`}},R=k(t.hasManyThrough,"hasManyThrough");if(R)return R;let _=k(t.hasOneThrough,"hasOneThrough");if(_)return _;return null}function Te(t,r){let o=new Set;for(let s of t){let i=s.get(r);if(i!=null)o.add(i)}return[...o]}function ae(t){return m(e.relations?.singularizeStrategy)(t)}class Ft{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,o,s){this._parent=t,this._parentDef=r,this._resolved=o,this._relatedDef=s}get parentId(){let t=this._parentDef.primaryKey||"id";return this._parent.get(t)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(t,r,o){if(o===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivot(t,r,o){if(o===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${o})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${o})`,params:[...r]}),this}wherePivotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NULL`,params:[]}),this}wherePivotNotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NOT NULL`,params:[]}),this}orderBy(t,r="asc"){if(Oe(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push(`${t} ${r.toUpperCase()}`),this}limit(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${t}`);return this._limit=t,this}offset(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${t}`);return this._offset=t,this}relatedSelectColumns(){let t=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),r=this._relatedDef.traits;if(r?.useTimestamps||r?.timestampable)t.add("created_at"),t.add("updated_at");if(r?.useSoftDeletes||r?.softDeletable)t.add("deleted_at");if(r?.useUuid)t.add("uuid");return[...t]}buildSelect(){let t=[],o=`SELECT ${this.relatedSelectColumns().map((s)=>`${this.relatedTable}.${s} AS ${ge}${s}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;o+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,o+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let s of this._pivotWheres)o+=` AND ${s.sql}`,t.push(...s.params);for(let s of this._wheres)o+=` AND ${s.sql}`,t.push(...s.params);if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}hydrateRows(t){let r=this.fkParent,o=this.fkRelated;return t.map((s)=>{let i={},a={};for(let[u,c]of Object.entries(s))if(u.startsWith(ge))i[u.slice(ge.length)]=c;else if(u!==r&&u!==o)a[u]=c;let d=new I(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=N(),{sql:r,params:o}=this.buildSelect(),s=await t.all(r,o);return this.hydrateRows(s)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=N(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,o=[this.parentId];for(let i of this._pivotWheres)r+=` AND ${i.sql}`,o.push(...i.params);let s=await t.get(r,o);return Number(s?.count??0)}async exists(){return await this.count()>0}now(){return Y()}async attach(t,r={}){let o=N(),s=Array.isArray(t)?t:[t];if(s.length===0)return 0;let i=this._resolved.pivotTimestamps?this.now():null,a=0;for(let d of s){let u={[this.fkParent]:this.parentId,[this.fkRelated]:d,...r};if(i){if(u.created_at===void 0)u.created_at=i;if(u.updated_at===void 0)u.updated_at=i}let c=Object.keys(u),b=c.map(()=>"?").join(", "),f=`INSERT INTO ${this.pivotTable} (${c.join(", ")}) VALUES (${b})`,g=c.map((K)=>u[K]);await o.run(f,g),a++}return a}async detach(t){let r=N(),o=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];if(t!==void 0&&t!==null){let i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=i.map(()=>"?").join(", ");o+=` AND ${this.fkRelated} IN (${a})`,s.push(...i)}return(await r.run(o,s)).changes}async updateExistingPivot(t,r){let o=N(),s={...r};if(this._resolved.pivotTimestamps&&s.updated_at===void 0)s.updated_at=this.now();let i=Object.keys(s);if(i.length===0)return 0;let a=i.map((c)=>`${c} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((c)=>s[c]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=N(),o=new Map;for(let b of t)if(b!=null&&typeof b==="object"&&"id"in b){let{id:f,...g}=b;o.set(f,g)}else o.set(b,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((b)=>b[this.fkRelated])),a=[],d=[],u=[],c=[...i].filter((b)=>!o.has(b));if(c.length>0)await this.detach(c),d.push(...c);for(let[b,f]of o)if(!i.has(b))await this.attach(b,f),a.push(b);else if(Object.keys(f).length>0)await this.updateExistingPivot(b,f),u.push(b);return{attached:a,detached:d,updated:u}}async toggle(t){let r=N(),o=Array.isArray(t)?t:[t];if(o.length===0)return{attached:[],detached:[]};let s=o.map(()=>"?").join(", "),i=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${s})`,[this.parentId,...o]),a=new Set(i.map((c)=>c[this.fkRelated])),d=o.filter((c)=>!a.has(c)),u=o.filter((c)=>a.has(c));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class x{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(t){this._definition=t}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:o,boolean:"and"});return this}orWhere(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:o,boolean:"or"});return this}whereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"and"}),this}orWhereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"or"}),this}whereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"and"}),this}orWhereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"or"}),this}whereNull(t){return Q(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return Q(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return Q(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return Q(t,"orWhereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"or"}),this}whereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"and"}),this}orWhereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"or"}),this}whereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"and"}),this}orWhereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"or"}),this}whereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Ke(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Ke(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let o=new x(this._definition);if(r(o),o._wheres.length===0)return this;let s=[],i=o.buildWhereClauses(s);if(!i)return this;return this._wheres.push({raw:`(${i})`,rawParams:s,boolean:t}),this}whereBetween(t,r){return Q(t,"whereBetween(column)"),this._wheres.push({column:t,operator:">=",value:r[0],boolean:"and"}),this._wheres.push({column:t,operator:"<=",value:r[1],boolean:"and"}),this}whereNotBetween(t,r){Q(t,"whereNotBetween(column)");let o=U(t);return this._wheres.push({raw:`(${o} < ? OR ${o} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if(Oe(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push({column:t,direction:r}),this}orderByDesc(t){return this.orderBy(t,"desc")}orderByAsc(t){return this.orderBy(t,"asc")}latest(t="created_at"){return this.orderBy(t,"desc")}oldest(t="created_at"){return this.orderBy(t,"asc")}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}select(...t){return this._select=t,this}with(...t){for(let r of t)if(!this._withRelations.includes(r))this._withRelations.push(r);return this}getWithRelations(){return this._withRelations}buildWhereClauses(t){let r=[];for(let o of this._wheres){let s;if(o.raw){if(s=o.raw,o.rawParams&&o.rawParams.length>0)t.push(...o.rawParams)}else if(o.value===null){let i=U(o.column);s=o.operator==="="?`${i} IS NULL`:`${i} IS NOT NULL`}else if(o.operator==="in"||o.operator==="not in"){let i=o.value;s=l(U(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${U(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return E(r)}softDeleteClause(){if(this._trashed==="include"||!te(this._definition))return"";return this._trashed==="only"?`${F} IS NOT NULL`:`${F} IS NULL`}assertNoUnappliedClauses(t){let r=[];if(this._limit!==void 0)r.push("limit()");if(this._offset!==void 0)r.push("offset()");if(this._orderBy.length>0)r.push("orderBy()");if(r.length>0)throw TypeError(`[orm] ${t}() cannot apply ${r.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(t){let r=this._wheres.length>0?this.buildWhereClauses(t):"",o=this.softDeleteClause();if(r&&o)return`(${r}) AND ${o}`;return r||o}buildQuery(){let t=[],o=`SELECT ${this._select.map((i)=>i==="*"?i:U(i)).join(", ")} FROM ${this._definition.table}`,s=this.composeWhere(t);if(s)o+=` WHERE ${s}`;if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.map((i)=>`${U(i.column)} ${i.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}toSql(){return this.buildQuery()}async eagerLoadRelations(t){if(t.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((r)=>this.eagerLoadRelation(r,t)))}async eagerLoadRelation(t,r){let o=N(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=oe.get(i);if(a===void 0){if(a=je(this._definition,t),oe.size>=Ze)oe.clear();oe.set(i,a)}if(!a)throw Error(tt(this._definition,t));let d=a.type==="hasOne"||a.type==="morphOne";if(a.type==="hasMany"||a.type==="hasOne"||a.type==="morphMany"||a.type==="morphOne"){let u=Te(r,s);if(u.length===0)return;let c=u.map(()=>"?").join(", "),b=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${c})${b}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),g=j(a.relatedModelName),K=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let k=new Map;for(let R of f){let _=R[a.foreignKey];if(!k.has(_))k.set(_,[]);k.get(_).push(R)}for(let R of r){let _=k.get(R.get(s))||[];R.setRelation(t,_.map((D)=>new I(K,D,!0)))}}else{let k=new Map;for(let R of f){let _=R[a.foreignKey];if(!k.has(_))k.set(_,R)}for(let R of r){let _=k.get(R.get(s));R.setRelation(t,_?new I(K,_,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let R of r){let _=R._attributes[a.foreignKey];if(_!=null)u.add(_)}let c=[...u];if(c.length===0)return;let b=c.map(()=>"?").join(", "),f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${b})`,c),g=j(a.relatedModelName),K=g?.getDefinition?.()||g?.definition||this._definition,k=new Map;for(let R of f)k.set(R[a.localKey],R);for(let R of r){let _=R._attributes[a.foreignKey],D=k.get(_);R.setRelation(t,D?new I(K,D,!0):null)}}if(a.type==="belongsToMany"){let u=Te(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let c=u.map(()=>"?").join(", "),b=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${c})`,u);if(b.length===0){for(let w of r)w.setRelation(t,[]);return}let f=new Set;for(let w of b){let y=w[a.pivotFkRelated];if(y!=null)f.add(y)}let g=[...f],K=j(a.relatedModelName),k=K?.getDefinition?.()||K?.definition||this._definition,R=k?.primaryKey||"id",_=[];if(g.length>0){let w=g.map(()=>"?").join(", ");_=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${R} IN (${w})`,g)}let D=new Map;for(let w of _)D.set(w[R],w);let h=new Map;for(let w of b){let y=w[a.pivotFkParent];if(!h.has(y))h.set(y,[]);h.get(y).push(w)}let M=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let w of r){let y=w.get(s),S=(h.get(y)||[]).map((W)=>{let J=D.get(W[a.pivotFkRelated]);if(!J)return null;let z=new I(k,J,!0),B={};for(let[H,me]of Object.entries(W))if(!M.has(H))B[H]=me;return z.pivot=B,z}).filter((W)=>W!==null);w.setRelation(t,S)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=Te(r,s);if(u.length===0)return;let c=a.throughLocalKey||"id",b=u.map(()=>"?").join(", "),f=await o.all(`SELECT ${c}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${b})`,u);if(f.length===0){for(let M of r)M.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let M of f)g.set(M[c],M[a.throughForeignKey]);let K=[...new Set(f.map((M)=>M[c]))],k=K.map(()=>"?").join(", "),R=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${k})`,K),_=j(a.relatedModelName),D=_?.getDefinition?.()||_?.definition||this._definition,h=new Map;for(let M of R){let w=g.get(M[a.targetForeignKey]);if(w==null)continue;if(!h.has(w))h.set(w,[]);h.get(w).push(new I(D,M,!0))}for(let M of r){let w=h.get(M.get(s))||[];M.setRelation(t,a.type==="hasManyThrough"?w:w[0]??null)}}}async get(){let t=N(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new I(this._definition,a,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(i);return i}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let t=await this.first();if(!t)throw Error(`No ${this._definition.name} found`);return t}async find(t){let r=this._definition.primaryKey||"id";return this.where(r,t).first()}async findOrFail(t){let r=await this.find(t);if(!r)throw Error(`${this._definition.name} with id ${t} not found`);return r}async last(){let t=this._definition.primaryKey||"id";return this._orderBy=[{column:t,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let t=N(),r=[],o=`SELECT COUNT(*) as count FROM ${this._definition.table}`,s=this.composeWhere(r);if(s)o+=` WHERE ${s}`;let i=await t.get(o,r);return Number(i?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let t=await this.get();if(t.length===0)throw Error(`No ${this._definition.name} found`);if(t.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return t[0]}async increment(t,r=1){Q(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=N(),s=[r],i=U(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(Z(this._definition))a+=", updated_at = ?",s.push(Y());let d=this.composeWhere(s);if(d)a+=` WHERE ${d}`;return(await o.run(a,s)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let o=0;while(!0){let s=new x(this._definition);s._wheres=[...this._wheres],s._orderBy=[...this._orderBy],s._select=[...this._select],s._withRelations=[...this._withRelations],s._trashed=this._trashed,s._limit=t,s._offset=o*t;let i=await s.get();if(i.length===0)break;if(await r(i)===!1)break;if(i.length<t)break;o++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let a=t;r=a.perPage??15,t=a.page??1}let o=await this.count(),s=Math.ceil(o/r);this._limit=r,this._offset=(t-1)*r;let i=await this.get();return{data:i,total:o,page:t,perPage:r,lastPage:s,hasMorePages:t<s,isEmpty:i.length===0,from:i.length>0?(t-1)*r+1:null,to:i.length>0?(t-1)*r+i.length:null,meta:{perPage:r,page:t,total:o,lastPage:s}}}async pluck(t){Q(t,"pluck(column)");let r=N(),o=[],s=U(t),i=`SELECT ${s} FROM ${this._definition.table}`,a=this.composeWhere(o);if(a)i+=` WHERE ${a}`;if(this._orderBy.length>0)i+=` ORDER BY ${this._orderBy.map((u)=>`${U(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)i+=` LIMIT ${this._limit}`;if(this._offset!==void 0)i+=` OFFSET ${this._offset}`;return(await r.all(i,o)).map((u)=>u[s])}async aggregate(t,r){Q(r,`${t}(column)`);let o=N(),s=[],i=`SELECT ${t}(${U(r)}) as v FROM ${this._definition.table}`,a=this.composeWhere(s);if(a)i+=` WHERE ${a}`;let u=(await o.get(i,s))?.v;if(u==null)return null;if(typeof u==="string"){let c=Number(u);return u.trim()!==""&&!Number.isNaN(c)?c:u}return u}max(t){return this.aggregate("MAX",t)}min(t){return this.aggregate("MIN",t)}async avg(t){return Number(await this.aggregate("AVG",t)??0)||0}async sum(t){return Number(await this.aggregate("SUM",t)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let t=te(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=N(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${F} IS NULL`:`${F} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Y():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${F} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let c=this._definition.primaryKey||"id",f=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((k)=>new I(this._definition,k,!0)),g=f.map((k)=>k._attributes[c]);if(g.some((k)=>k==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let k of f)await s.beforeDelete?.(k);let K=0;for(let k=0;k<g.length;k+=ve){let R=g.slice(k,k+ve),_=`${c} IN (${R.map(()=>"?").join(", ")})`;K+=t?(await r.run(`UPDATE ${o} SET ${F} = ? WHERE ${_}`,[u,...R])).changes:(await r.run(`DELETE FROM ${o} WHERE ${_}`,R)).changes}for(let k of f){if(t)k._attributes[F]=u;await s.afterDelete?.(k)}return K}async update(t){this.assertNoUnappliedClauses("update");let r=N(),o=Object.entries(t),s=o.map(([u])=>`${U(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(Z(this._definition))i.push(Y());let a=`UPDATE ${this._definition.table} SET ${s}${Z(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function nt(t){let r={query:()=>new x(t),where(o,s,i){return new x(t).where(o,s,i)},orWhere(o,s,i){return new x(t).orWhere(o,s,i)},whereIn(o,s){return new x(t).whereIn(o,s)},whereNotIn(o,s){return new x(t).whereNotIn(o,s)},whereNull(o){return new x(t).whereNull(o)},whereNotNull(o){return new x(t).whereNotNull(o)},whereLike(o,s){return new x(t).whereLike(o,s)},orderBy(o,s="asc"){return new x(t).orderBy(o,s)},orderByDesc(o){return new x(t).orderByDesc(o)},select(...o){return new x(t).select(...o)},with(...o){return new x(t).with(...o)},limit:(o)=>new x(t).limit(o),take:(o)=>new x(t).take(o),skip:(o)=>new x(t).skip(o),withTrashed:()=>new x(t).withTrashed(),onlyTrashed:()=>new x(t).onlyTrashed(),async find(o){let s=N(),i=t.primaryKey||"id",a=te(t)?` AND ${F} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new I(t,d,!0):void 0},async findOrFail(o){let s=await r.find(o);if(!s)throw Error(`${t.name} with id ${o} not found`);return s},async findMany(o){let s=N(),i=t.primaryKey||"id",a=te(t)?` AND ${F} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new I(t,u,!0))},all:()=>new x(t).get(),first:()=>new x(t).first(),firstOrFail:()=>new x(t).firstOrFail(),last:()=>new x(t).last(),count:()=>new x(t).count(),exists:()=>new x(t).exists(),doesntExist:()=>new x(t).doesntExist(),paginate:(o,s)=>new x(t).paginate(o,s),whereBetween(o,s){return new x(t).whereBetween(o,s)},whereNotBetween(o,s){return new x(t).whereNotBetween(o,s)},async create(o){let s=new I(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((c)=>new I(t,c,!1));if(!s.length)return[];let i=N(),a=t.primaryKey||"id",d=[];for(let c of s)d.push(await c._prepareInsert());let u=new Map;d.forEach((c,b)=>{let f=Object.keys(c).join("\x00"),g=u.get(f);if(g)g.push(b);else u.set(f,[b])});for(let[c,b]of u){let f=c?c.split("\x00"):[],g=!f.includes(a);if(!f.length||g&&i.dialect==="mysql"){for(let k of b){let R=d[k],_=Object.keys(R),D=await i.insert(_.length?`INSERT INTO ${t.table} (${_.join(", ")}) VALUES (${_.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(R),a);await s[k]._markInserted(R,g?D.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&ze(t,f,b.map((k)=>d[k]))){let k=t.table,R=f.join(", "),_=`INSERT INTO ${k} (${R}) SELECT ${R} FROM jsonb_populate_recordset(NULL::${k}, (?::text)::jsonb)`;for(let D=0;D<b.length;D+=Ae){let h=b.slice(D,D+Ae),M=JSON.stringify(h.map((A)=>Object.fromEntries(f.map((S)=>[S,d[A][S]??null]))),Ge);if(!g){await i.run(_,[M]);for(let A of h)await s[A]._markInserted(d[A]);continue}let w=(await i.all(`${_} RETURNING ${a}`,[M])).map((A)=>A[a]),y=w.every((A)=>typeof A==="number"||typeof A==="bigint")?[...w].sort((A,S)=>A<S?-1:A>S?1:0):w;for(let A=0;A<h.length;A++)await s[h[A]]._markInserted(d[h[A]],y[A])}continue}let K=Ee(Math.max(1,Math.floor(Qe/f.length)));for(let k=0;k<b.length;){let R=Math.min(K,Ee(b.length-k)),_=b.slice(k,k+R);k+=R;let D=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${_.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=_.flatMap((y)=>f.map((A)=>d[y][A]));if(!g){await i.run(D,h);for(let y of _)await s[y]._markInserted(d[y]);continue}let M=(await i.all(`${D} RETURNING ${a}`,h)).map((y)=>y[a]),w=M.every((y)=>typeof y==="number"||typeof y==="bigint")?[...M].sort((y,A)=>y<A?-1:y>A?1:0):M;for(let y=0;y<_.length;y++)await s[_[y]]._markInserted(d[_[y]],w[y])}}return s},async updateOrCreate(o,s){let i=new x(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);let a=await i.first();if(a)return await a.update(s),a;return this.create({...o,...s})},async firstOrCreate(o,s){let i=new x(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);return await i.first()||this.create({...o,...s})},async update(o,s){let i=await r.findOrFail(o);return await i.update(s),i},async delete(o){let s=await r.find(o);return s?s.delete():!1},destroy(o){return r.delete(o)},async forceDelete(o){let s=await r.withTrashed().find(o);return s?s.forceDelete():!1},remove(o){return r.forceDelete(o)},async truncate(){await N().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new I(t,o,!1)},latest:(o="created_at")=>new x(t).orderByDesc(o),oldest:(o="created_at")=>new x(t).orderBy(o,"asc"),max:(o)=>new x(t).max(o),min:(o)=>new x(t).min(o),avg:(o)=>new x(t).avg(o),sum:(o)=>new x(t).sum(o),pluck(o){return new x(t).pluck(o)}};return new Proxy(r,{get(o,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let i=s.slice(5),a=i.charAt(0).toLowerCase()+i.slice(1);if(a in t.attributes||a==="id"||a===t.primaryKey)return(d)=>new x(t).where(a,d)}return Reflect.get(o,s)}})}function jt(t){let r=nt(t);if(t?.name)Ue(t.name,r);return r}async function Wn(t){let r=N(),o=v(t.primaryKey||"id"),s=[],i=new Set([o]);if(s.push(t.autoIncrement!==!1?`${o} INTEGER PRIMARY KEY AUTOINCREMENT`:`${o} INTEGER PRIMARY KEY`),t.traits?.useUuid)s.push("uuid TEXT UNIQUE"),i.add("uuid");for(let[a,d]of Object.entries(t.attributes)){let u=v(a);if(i.has(u))continue;i.add(u);let c=ke(d.type),b=_e(c);if(u.endsWith("_id")&&(c===void 0||O(c)))b="INTEGER";let f=`${u} ${b}`;if(d.unique)f+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let g=d.foreignKey;if(f+=` REFERENCES ${g.table}(${g.column??"id"})`,g.onDelete)f+=` ON DELETE ${g.onDelete.toUpperCase()}`;if(g.onUpdate)f+=` ON UPDATE ${g.onUpdate.toUpperCase()}`}s.push(f)}for(let a of P(t.belongsTo)){let d=a.foreignKey??`${v(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(Z(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(te(t)&&!i.has("deleted_at"))i.add("deleted_at"),s.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${s.join(", ")})`,[])}async function Un(t,r,o){let s=N(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=_t(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<a;d++){let u={};for(let[b,f]of Object.entries(t.attributes))if(f.factory)u[v(b)]=f.factory(o);if(Z(t)){let b=Y();u.created_at=b,u.updated_at=b}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let c=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${c.join(", ")}) VALUES (${c.map(()=>"?").join(", ")})`,Object.values(u))}}var se=new Map;function an(t){return se.get(t)}function on(){return[...se.values()]}function ln(){return Object.fromEntries(se)}function cn(t){return se.has(t)}function un(){se.clear(),It()}function qt(t,r){return se.set(t,r),r}function rt(){return typeof window<"u"&&typeof document<"u"}function dn(t){let r;if(rt())r=Ve(t);else{let o=jt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return qt(t.name,r),r}function fn(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
2
+ import{Ve}from"./chunk-wvae8521.js";import{p,n,e,C,L,T,qe,m,E,l,lt,ee}from"./chunk-hzrsdtv2.js";function O(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function ke(t){if(typeof t!=="string")return;switch(t.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function _e(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}import{Database as pe}from"bun:sqlite";function ne(t){if(typeof t==="number")return{length:t};return t}function ye(t){if(typeof t==="number")return{max:t};return t}function Fe(t){return typeof t==="function"}function We(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function Me(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function G(t,r={}){if(!t)return r;return new Proxy(t,{get(o,s){if(s in r)return r[s];let i=o[s];if(i!==void 0)return i;let a=o[We(s)];if(Fe(a))return a.bind(o);return}})}function _t(t){let r=(f)=>{let g=Array.isArray(f)?f:[],K=Math.floor(Math.random()*g.length);return g[K]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=G(t.string,{alpha:(f)=>o()?.alpha?.(ne(f)),alphanumeric:(f)=>o()?.alphanumeric?.(ne(f)),numeric:(f)=>o()?.numeric?.(ne(f)),sample:(f)=>o()?.sample?.(ne(f)),hexadecimal:(f)=>o()?.hexadecimal?.(ne(f))}),d=G(t.number,{int:(f)=>s()?.int?.(ye(f)),float:(f)=>{let g=ye(f);return Me(Number(s()?.float?.(g)??0),g)}}),u=G(t.helpers,{arrayElement:r,arrayElements:(f,g)=>{let K=[...Array.isArray(f)?f:[]],k=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*K.length));for(let R=K.length-1;R>0;R-=1){let _=Math.floor(Math.random()*(R+1));[K[R],K[_]]=[K[_],K[R]]}return K.slice(0,Math.min(k,K.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let K=g.length-1;K>0;K-=1){let k=Math.floor(Math.random()*(K+1));[g[K],g[k]]=[g[k],g[K]]}return g},maybe:(f,g)=>{let K=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<K?f():void 0},slugify:(f)=>String(f??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),b={string:a,number:d,helpers:u,datatype:{boolean:(f)=>{let g=typeof f==="number"?f:f?.probability;if(typeof g==="number")return Math.random()<g;return Boolean(i()?.boolean?.())},number:(f)=>Number(s()?.int?.(ye(f))??0),float:(f)=>Me(Number(s()?.float?.(f)??0),f),uuid:()=>crypto.randomUUID(),string:(f)=>String(o()?.alphanumeric?.({length:f??10})??""),hexadecimal:(f)=>String(o()?.hexadecimal?.(ne(f))??""),array:(f)=>Array.from({length:f??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:G(t.address),address:G(t.address),vehicle:G(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:G(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(f,g){if(g in b)return b[g];let K=f[g];if(K&&typeof K==="object")return G(K);return K}})}function Ie(t){if(typeof t==="string")return{model:t};if(t&&typeof t==="object"&&typeof t.model==="string"){let r=t;return{model:r.model,foreignKey:r.foreignKey,onDelete:r.onDelete}}return null}function P(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Ie).filter((o)=>o!==null)}function Y(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var Pe=/^[A-Z_][A-Z0-9_]*$/i;function Q(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);if(t.length>64)throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' exceeds 64 chars`);if(!Pe.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Oe(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);let o=t.split(".");if(o.length>2||o.some((s)=>s.length===0||s.length>64||!Pe.test(s)))throw TypeError(`[bun-query-builder] ${r}: invalid ORDER BY column '${t}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Ke(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&ee(t)===0)return[];return r}var le=null,De=new Map;function Ue(t,r){De.set(t,r),oe.clear()}function It(){De.clear(),oe.clear()}function j(t){if(!le)try{le=import.meta.require("./chunk-30mmrj6e.js").getModel}catch{le=()=>{return}}return le(t)??De.get(t)}var ue=new Map,He=500;function Re(t){let r=ue.get(t);if(r!==void 0)return r;let o=lt(t,"postgres");if(ue.size>=He)ue.clear();return ue.set(t,o),o}function Lt(t){if(t==null)return 0;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;if(Array.isArray(t))return t.length;return 0}function Kt(t){if(t==null||typeof t!=="object")return null;if("insertId"in t&&t.insertId!=null)return t.insertId;if("lastInsertRowid"in t&&t.lastInsertRowid!=null)return t.lastInsertRowid;return null}class be{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...p(r)))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...p(r))??void 0)}run(t,r){let o=this.sqliteDb.run(t,p(r));return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class we{dialect;constructor(t){this.dialect=t}conn(){return T()}text(t){return this.dialect==="postgres"?Re(t):t}async all(t,r){let o=await this.conn().unsafe(this.text(t),r);return Array.isArray(o)?o:[]}async get(t,r){let o=await this.conn().unsafe(this.text(t),r);if(Array.isArray(o))return o[0]??void 0;return o??void 0}async run(t,r){let o=await this.conn().unsafe(this.text(t),r);return{changes:Lt(o),lastInsertId:Kt(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${Re(t)} RETURNING ${o}`,r),d=Array.isArray(a)?a[0]:a;return{changes:1,lastInsertId:d?d[o]??null:null}}let s=await this.conn().unsafe(t,r),i=Kt(s);if(i==null&&this.dialect!=="sqlite"){let a=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);i=(Array.isArray(a)?a[0]:a)?.id??null}return{changes:Lt(s)||1,lastInsertId:i}}}var V=null,he=!1,q=null,re=null,de=null,fe=null;function Fn(t){if(t.database instanceof pe)V=t.database,he=!1;else V=new pe(t.database||":memory:",{create:!0}),he=!0,C(V);q=null,re=null}function jn(){let t=he,r=V;if(V=null,he=!1,q=null,re=null,de=null,fe=null,t&&r)try{r.close()}catch{}}var xe=!1;function N(){if(V){if(!q||re!==V)q=new be(V),re=V,de="sqlite",fe=null;return q}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${L()?.url??""}`;if(q&&re===null&&de===t&&fe===o)return q;if(re=null,de=t,fe=o,t==="sqlite"&&L())q=new we(t);else if(t==="sqlite"){if(!r&&!xe)xe=!0,console.warn("[bun-query-builder] The model layer has no database configured, so it is using an in-memory SQLite database and nothing it writes will persist. Configure one with setConfig({ dialect, database }) or configureOrm({ database }), or name ':memory:' explicitly to silence this.");let s=new pe(r||":memory:",{create:!0});C(s),q=new be(s)}else q=new we(t);return q}function qn(){let t=N();if(t.sqliteDb)return t.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${t.dialect}'. Use the async model API instead.`)}var Qe=4096,Ae=1000;function ze(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[v(a),d]));for(let a of r){let d=String(i.get(a)?.type??"").toLowerCase();if(d==="json"||d==="jsonb")return!1}for(let a of o)for(let d of r){let u=a[d];if(u===null||u===void 0||u instanceof Date)continue;let c=typeof u;if(c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="bigint")return!1}return!0}function Ge(t,r){return typeof r==="bigint"?r.toString():r}function Ee(t){return 2**Math.floor(Math.log2(t))}var F="deleted_at",ve=500,ge="__btm_rel__";function te(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Z(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ne=new WeakMap;function Xe(t){let r=Ne.get(t);if(r)return r;let o=new Set,s=t.belongsToMany;if(s){if(Array.isArray(s)){for(let i of s)if(typeof i==="string")o.add(i.toLowerCase());else if(i&&typeof i==="object"&&i.model)o.add(i.model.toLowerCase())}else if(typeof s==="object")for(let i of Object.keys(s))o.add(i)}return Ne.set(t,o),o}function Be(t){let r={};for(let[o,s]of Object.entries(t))r[v(o)]=s;return r}function Ye(t){for(let r in t)if(v(r)!==r)return Be(t);return t}function Je(t,r){if(t[r])return t[r];let o=v(r);if(t[o])return t[o];for(let s of Object.keys(t))if(v(s)===o)return t[s];return}class I{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Ye({...r}),this._original=null;let s=Xe(t);if(s.size===0)return;let i=this;return new Proxy(this,{get(a,d,u){if(typeof d==="string"&&s.has(d)&&!(d in a))return()=>{let c=je(t,d);if(!c||c.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let b=j(c.relatedModelName),f=b?.getDefinition?.()||b?.definition;if(!f)throw Error(`[orm] related model '${c.relatedModelName}' is not registered`);return new Ft(i,t,c,f)};return Reflect.get(a,d,u)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(t){let r=this._definition.get?.[t];if(r)try{let o=r(this._attributes);if(o!==void 0)return o}catch{}return this._attributes[v(t)]}getAttribute(t){return this._attributes[v(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[v(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[v(o)];return r}except(t){let r=new Set(t.map((s)=>v(s))),o={};for(let s of Object.keys(this._attributes))if(!r.has(s))o[s]=this._attributes[s];return o}getRelation(t){return this._relations[t]}setRelation(t,r){this._relations[t]=r}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let t=this._definition.primaryKey||"id";return this._attributes[t]}isDirty(t){if(this._original===null)return!1;if(t){let r=v(t);return this._attributes[r]!==this._original[r]}return Object.keys(this._attributes).some((r)=>this._attributes[r]!==this._original[r])}isClean(t){return!this.isDirty(t)}getOriginal(t){return this.getOriginalAttributes()[v(t)]}getChanges(){if(this._original===null)return{};let t={};for(let r of Object.keys(this._attributes))if(this._attributes[r]!==this._original[r])t[r]=this._attributes[r];return t}fill(t){let r=this._definition.attributes;for(let[o,s]of Object.entries(t)){let i=Je(r,o),a=!i&&v(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[v(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Be(t);Object.assign(this._attributes,r);for(let o of Object.keys(r))this._forced.add(o);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,o=this._definition.attributes,s={};for(let[u,c]of Object.entries(o)){if(c.guarded&&!this._forced.has(v(u)))continue;let b=v(u);if(this._attributes[b]!==void 0)s[b]=this._attributes[b]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in s))s[u]=this._attributes[u];let i=this._attributes[t],d=o[t]?.guarded&&!this._forced.has(t);if(i!=null&&!(t in s)&&!d)s[t]=i;if(Z(this._definition)){let u=Y(),c=this._attributes.created_at;s.created_at=c===void 0||c===null?u:c,s.updated_at=u}if(this._definition.traits?.useUuid&&!s.uuid)s.uuid=crypto.randomUUID();return await r?.beforeCreate?.(s),s}async _markInserted(t,r){let o=this._definition.primaryKey||"id";for(let[s,i]of Object.entries(t))this._attributes[s]=i;if(!(o in t)&&r!=null)this._attributes[o]=r;this._exists=!0,await this._definition.hooks?.afterCreate?.(this),this._original={...this._attributes},this._hasSaved=!0}_applySetters(){let t=this._definition.set||{};for(let[r,o]of Object.entries(t))if(this.isDirty(r))this._attributes[v(r)]=o(this._attributes)}async save(){let t=N(),r=this._definition.primaryKey||"id",o=this._definition.hooks;if(this._exists){this._applySetters(),await o?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let a=i.map((u)=>`${u} = ?`).join(", "),d=[...Object.values(s),this._attributes[r]];if(Z(this._definition)){let u=Y();await t.run(`UPDATE ${this._definition.table} SET ${a}, updated_at = ? WHERE ${r} = ?`,[...Object.values(s),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${a} WHERE ${r} = ?`,d)}await o?.afterUpdate?.(this)}else{let s=await this._prepareInsert(),i=Object.keys(s),a=i.map(()=>"?").join(", "),d=await t.insert(`INSERT INTO ${this._definition.table} (${i.join(", ")}) VALUES (${a})`,Object.values(s),r);return await this._markInserted(s,r in s?void 0:d.lastInsertId),this}return this._original={...this._attributes},this._hasSaved=!0,this}async update(t){return this.fill(t),this.save()}async fresh(){let t=N(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(o==null)return null;let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return new I(this._definition,s,!0)}async delete(){let t=N(),r=this._definition.primaryKey||"id",o=this._attributes[r],s=this._definition.hooks;if(o==null)throw Error("Cannot delete a model without a primary key");if(await s?.beforeDelete?.(this),te(this._definition)){let i=Y();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[F]=i}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[o]);return await s?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],o=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await o?.beforeDelete?.(this),await N().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!te(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let t=this._definition.primaryKey||"id",r=this._attributes[t];if(!r)throw Error("Cannot restore a model without a primary key");return await N().run(`UPDATE ${this._definition.table} SET ${F} = ? WHERE ${t} = ?`,[null,r]),this._attributes[F]=null,this._original=null,this}trashed(){return this._attributes[F]!=null}async refresh(){let t=N(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(!o)throw Error("Cannot refresh a model without a primary key");let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return this._attributes=s,this._original=null,this}replicate(){let t=this._definition.primaryKey||"id",r={...this._attributes};return delete r[t],delete r.uuid,delete r.created_at,delete r.updated_at,new I(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,o]of Object.entries(this._relations))if(Array.isArray(o))t[r]=o.map((s)=>s.toArray());else if(o)t[r]=o.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[o,s]of Object.entries(this._definition.attributes))if(s.hidden)t.add(o);let r={};for(let[o,s]of Object.entries(this._attributes))if(!t.has(o))r[o]=s;for(let[o,s]of Object.entries(this._relations))if(Array.isArray(s))r[o]=s.map((i)=>i.toJSON());else if(s)r[o]=s.toJSON();else r[o]=null;return r}}var Ce=new Map,$e=new Map,oe=new Map,Ze=1000;function U(t){return v(t)}function v(t){let r=Ce.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Ce.set(t,r),r}function X(t){let r=$e.get(t);if(r!==void 0)return r;return r=qe(t),$e.set(t,r),r}var ce=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],et=[...ce,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Se(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>typeof s==="string"?s:String(s?.model??"")).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function tt(t,r){let o=t.name??t.table??"model",i=et.filter((d)=>Se(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!ce.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${ce.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=ce.flatMap((d)=>Se(t,d));return a.length>0?`[orm] '${o}' has no relation '${r}'. Available: ${a.join(", ")}.`:`[orm] '${o}' has no relation '${r}' \u2014 it declares no relations at all.`}function je(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(D){if(!D)return null;if(Array.isArray(D)){for(let h of D){let M=typeof h==="string"?h:h?.model||"";if(M&&M.toLowerCase()===r.toLowerCase())return M}return null}if(typeof D==="object"){for(let[h,M]of Object.entries(D))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof M==="string"?M:M?.model||M?.target||h}return null}function d(){let D=t.belongsTo;if(!D)return null;let h=r.toLowerCase(),M=(w)=>{if(typeof w==="string")return{model:w};if(w&&typeof w==="object"&&typeof w.model==="string")return{model:w.model,foreignKey:w.foreignKey};return null};if(Array.isArray(D)){for(let w of D){let y=M(w);if(y&&y.model.toLowerCase()===h)return y}return null}if(typeof D==="object"){for(let[w,y]of Object.entries(D))if(w===r||w.toLowerCase()===h)return M(y)}return null}function u(){let D=t.belongsToMany;if(!D)return null;if(Array.isArray(D)){for(let h of D)if(typeof h==="string"){if(h.toLowerCase()===r.toLowerCase())return{entry:h}}else if(h&&typeof h==="object"&&h.model){if(h.model.toLowerCase()===r.toLowerCase())return{entry:h}}return null}if(typeof D==="object"){for(let[h,M]of Object.entries(D))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:M}}return null}function c(D){let h=t[D];if(!h)return null;let M=r.toLowerCase();if(Array.isArray(h)){for(let w of h){let y=typeof w==="string"?w:String(w?.model??"");if(!y||y.toLowerCase()!==M)continue;let A=typeof w==="object"?w?.morphName:void 0;return{model:y,morphName:String(A??`${v(o)}able`)}}return null}if(typeof h==="object")for(let[w,y]of Object.entries(h)){let A=typeof y==="string"?y:String(y?.model??"");if(w.toLowerCase()!==M&&A.toLowerCase()!==M)continue;let S=typeof y==="object"?y?.morphName:void 0;return{model:A,morphName:String(S??w)}}return null}for(let D of["morphMany","morphOne"]){let h=c(D);if(!h)continue;let w=j(h.model)?.getTable?.()||X(h.model);return{type:D,relatedModelName:h.model,relatedTable:w,foreignKey:`${h.morphName}_id`,localKey:i,morphTypeColumn:`${h.morphName}_type`,morphTypeValue:s}}let b=a(t.hasMany);if(b){let h=j(b)?.getTable?.()||X(b),M=v(o)+"_id";return{type:"hasMany",relatedModelName:b,relatedTable:h,foreignKey:M,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||X(f),M=v(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:M,localKey:i}}let g=d();if(g){let D=g.model,h=j(D),M=h?.getTable?.()||X(D),w=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${v(D)}_id`;return{type:"belongsTo",relatedModelName:D,relatedTable:M,foreignKey:y,localKey:w}}let K=u();if(K){let D=typeof K.entry==="object",h=D?K.entry.model:K.entry,w=j(h)?.getTable?.()||X(h),y=D?K.entry:null,A,S;if(y?.table)A=y.table;else if(y?.through){S=y.through;let B=j(y.through);if(!B)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${y.through}'. Make sure '${y.through}' is registered.`);A=B.getTable?.()||B.getDefinition?.()?.table||X(y.through)}else{let B=ae(s),H=ae(w);A=[B,H].sort().join("_")}let W=y?.foreignKey||`${ae(s)}_id`,J=y?.relatedKey||`${ae(w)}_id`,z=[];if(y?.pivot?.columns)for(let B of Object.keys(y.pivot.columns))z.push(B);if(S){let B=j(S),H=B?.getDefinition?.()||B?.definition,me=H?.attributes??{},Le=H?.primaryKey??"id";for(let ie of Object.keys(me)){if(ie===W||ie===J||ie===Le)continue;if(!z.includes(ie))z.push(ie)}}return{type:"belongsToMany",relatedModelName:h,relatedTable:w,foreignKey:W,localKey:i,pivotTable:A,pivotFkParent:W,pivotFkRelated:J,pivotColumns:z,pivotModelName:S,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let k=(D,h)=>{if(!D||typeof D!=="object"||Array.isArray(D))return null;let M=D[r]??D[Object.keys(D).find((H)=>H.toLowerCase()===r.toLowerCase())??""];if(!M||typeof M!=="object")return null;let{through:w,target:y}=M;if(!w||!y)return null;let A=j(w),S=A?.getDefinition?.()||A?.definition,W=A?.getTable?.()||S?.table||X(w),J=S?.primaryKey||"id",B=j(y)?.getTable?.()||X(y);return{type:h,relatedModelName:y,relatedTable:B,foreignKey:`${v(o)}_id`,localKey:i,throughTable:W,throughForeignKey:`${v(o)}_id`,throughLocalKey:J,targetForeignKey:`${ae(W)}_id`}},R=k(t.hasManyThrough,"hasManyThrough");if(R)return R;let _=k(t.hasOneThrough,"hasOneThrough");if(_)return _;return null}function Te(t,r){let o=new Set;for(let s of t){let i=s.get(r);if(i!=null)o.add(i)}return[...o]}function ae(t){return m(e.relations?.singularizeStrategy)(t)}class Ft{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,o,s){this._parent=t,this._parentDef=r,this._resolved=o,this._relatedDef=s}get parentId(){let t=this._parentDef.primaryKey||"id";return this._parent.get(t)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(t,r,o){if(o===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivot(t,r,o){if(o===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${o})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${o})`,params:[...r]}),this}wherePivotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NULL`,params:[]}),this}wherePivotNotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NOT NULL`,params:[]}),this}orderBy(t,r="asc"){if(Oe(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push(`${t} ${r.toUpperCase()}`),this}limit(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${t}`);return this._limit=t,this}offset(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${t}`);return this._offset=t,this}relatedSelectColumns(){let t=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),r=this._relatedDef.traits;if(r?.useTimestamps||r?.timestampable)t.add("created_at"),t.add("updated_at");if(r?.useSoftDeletes||r?.softDeletable)t.add("deleted_at");if(r?.useUuid)t.add("uuid");return[...t]}buildSelect(){let t=[],o=`SELECT ${this.relatedSelectColumns().map((s)=>`${this.relatedTable}.${s} AS ${ge}${s}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;o+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,o+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let s of this._pivotWheres)o+=` AND ${s.sql}`,t.push(...s.params);for(let s of this._wheres)o+=` AND ${s.sql}`,t.push(...s.params);if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}hydrateRows(t){let r=this.fkParent,o=this.fkRelated;return t.map((s)=>{let i={},a={};for(let[u,c]of Object.entries(s))if(u.startsWith(ge))i[u.slice(ge.length)]=c;else if(u!==r&&u!==o)a[u]=c;let d=new I(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=N(),{sql:r,params:o}=this.buildSelect(),s=await t.all(r,o);return this.hydrateRows(s)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=N(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,o=[this.parentId];for(let i of this._pivotWheres)r+=` AND ${i.sql}`,o.push(...i.params);let s=await t.get(r,o);return Number(s?.count??0)}async exists(){return await this.count()>0}now(){return Y()}async attach(t,r={}){let o=N(),s=Array.isArray(t)?t:[t];if(s.length===0)return 0;let i=this._resolved.pivotTimestamps?this.now():null,a=0;for(let d of s){let u={[this.fkParent]:this.parentId,[this.fkRelated]:d,...r};if(i){if(u.created_at===void 0)u.created_at=i;if(u.updated_at===void 0)u.updated_at=i}let c=Object.keys(u),b=c.map(()=>"?").join(", "),f=`INSERT INTO ${this.pivotTable} (${c.join(", ")}) VALUES (${b})`,g=c.map((K)=>u[K]);await o.run(f,g),a++}return a}async detach(t){let r=N(),o=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];if(t!==void 0&&t!==null){let i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=i.map(()=>"?").join(", ");o+=` AND ${this.fkRelated} IN (${a})`,s.push(...i)}return(await r.run(o,s)).changes}async updateExistingPivot(t,r){let o=N(),s={...r};if(this._resolved.pivotTimestamps&&s.updated_at===void 0)s.updated_at=this.now();let i=Object.keys(s);if(i.length===0)return 0;let a=i.map((c)=>`${c} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((c)=>s[c]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=N(),o=new Map;for(let b of t)if(b!=null&&typeof b==="object"&&"id"in b){let{id:f,...g}=b;o.set(f,g)}else o.set(b,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((b)=>b[this.fkRelated])),a=[],d=[],u=[],c=[...i].filter((b)=>!o.has(b));if(c.length>0)await this.detach(c),d.push(...c);for(let[b,f]of o)if(!i.has(b))await this.attach(b,f),a.push(b);else if(Object.keys(f).length>0)await this.updateExistingPivot(b,f),u.push(b);return{attached:a,detached:d,updated:u}}async toggle(t){let r=N(),o=Array.isArray(t)?t:[t];if(o.length===0)return{attached:[],detached:[]};let s=o.map(()=>"?").join(", "),i=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${s})`,[this.parentId,...o]),a=new Set(i.map((c)=>c[this.fkRelated])),d=o.filter((c)=>!a.has(c)),u=o.filter((c)=>a.has(c));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class x{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(t){this._definition=t}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:o,boolean:"and"});return this}orWhere(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:o,boolean:"or"});return this}whereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"and"}),this}orWhereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"or"}),this}whereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"and"}),this}orWhereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"or"}),this}whereNull(t){return Q(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return Q(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return Q(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return Q(t,"orWhereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"or"}),this}whereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"and"}),this}orWhereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"or"}),this}whereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"and"}),this}orWhereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"or"}),this}whereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Ke(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Ke(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let o=new x(this._definition);if(r(o),o._wheres.length===0)return this;let s=[],i=o.buildWhereClauses(s);if(!i)return this;return this._wheres.push({raw:`(${i})`,rawParams:s,boolean:t}),this}whereBetween(t,r){return Q(t,"whereBetween(column)"),this._wheres.push({column:t,operator:">=",value:r[0],boolean:"and"}),this._wheres.push({column:t,operator:"<=",value:r[1],boolean:"and"}),this}whereNotBetween(t,r){Q(t,"whereNotBetween(column)");let o=U(t);return this._wheres.push({raw:`(${o} < ? OR ${o} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if(Oe(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push({column:t,direction:r}),this}orderByDesc(t){return this.orderBy(t,"desc")}orderByAsc(t){return this.orderBy(t,"asc")}latest(t="created_at"){return this.orderBy(t,"desc")}oldest(t="created_at"){return this.orderBy(t,"asc")}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}select(...t){return this._select=t,this}with(...t){for(let r of t)if(!this._withRelations.includes(r))this._withRelations.push(r);return this}getWithRelations(){return this._withRelations}buildWhereClauses(t){let r=[];for(let o of this._wheres){let s;if(o.raw){if(s=o.raw,o.rawParams&&o.rawParams.length>0)t.push(...o.rawParams)}else if(o.value===null){let i=U(o.column);s=o.operator==="="?`${i} IS NULL`:`${i} IS NOT NULL`}else if(o.operator==="in"||o.operator==="not in"){let i=o.value;s=l(U(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${U(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return E(r)}softDeleteClause(){if(this._trashed==="include"||!te(this._definition))return"";return this._trashed==="only"?`${F} IS NOT NULL`:`${F} IS NULL`}assertNoUnappliedClauses(t){let r=[];if(this._limit!==void 0)r.push("limit()");if(this._offset!==void 0)r.push("offset()");if(this._orderBy.length>0)r.push("orderBy()");if(r.length>0)throw TypeError(`[orm] ${t}() cannot apply ${r.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(t){let r=this._wheres.length>0?this.buildWhereClauses(t):"",o=this.softDeleteClause();if(r&&o)return`(${r}) AND ${o}`;return r||o}buildQuery(){let t=[],o=`SELECT ${this._select.map((i)=>i==="*"?i:U(i)).join(", ")} FROM ${this._definition.table}`,s=this.composeWhere(t);if(s)o+=` WHERE ${s}`;if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.map((i)=>`${U(i.column)} ${i.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}toSql(){return this.buildQuery()}async eagerLoadRelations(t){if(t.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((r)=>this.eagerLoadRelation(r,t)))}async eagerLoadRelation(t,r){let o=N(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=oe.get(i);if(a===void 0){if(a=je(this._definition,t),oe.size>=Ze)oe.clear();oe.set(i,a)}if(!a)throw Error(tt(this._definition,t));let d=a.type==="hasOne"||a.type==="morphOne";if(a.type==="hasMany"||a.type==="hasOne"||a.type==="morphMany"||a.type==="morphOne"){let u=Te(r,s);if(u.length===0)return;let c=u.map(()=>"?").join(", "),b=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${c})${b}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),g=j(a.relatedModelName),K=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let k=new Map;for(let R of f){let _=R[a.foreignKey];if(!k.has(_))k.set(_,[]);k.get(_).push(R)}for(let R of r){let _=k.get(R.get(s))||[];R.setRelation(t,_.map((D)=>new I(K,D,!0)))}}else{let k=new Map;for(let R of f){let _=R[a.foreignKey];if(!k.has(_))k.set(_,R)}for(let R of r){let _=k.get(R.get(s));R.setRelation(t,_?new I(K,_,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let R of r){let _=R._attributes[a.foreignKey];if(_!=null)u.add(_)}let c=[...u];if(c.length===0)return;let b=c.map(()=>"?").join(", "),f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${b})`,c),g=j(a.relatedModelName),K=g?.getDefinition?.()||g?.definition||this._definition,k=new Map;for(let R of f)k.set(R[a.localKey],R);for(let R of r){let _=R._attributes[a.foreignKey],D=k.get(_);R.setRelation(t,D?new I(K,D,!0):null)}}if(a.type==="belongsToMany"){let u=Te(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let c=u.map(()=>"?").join(", "),b=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${c})`,u);if(b.length===0){for(let w of r)w.setRelation(t,[]);return}let f=new Set;for(let w of b){let y=w[a.pivotFkRelated];if(y!=null)f.add(y)}let g=[...f],K=j(a.relatedModelName),k=K?.getDefinition?.()||K?.definition||this._definition,R=k?.primaryKey||"id",_=[];if(g.length>0){let w=g.map(()=>"?").join(", ");_=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${R} IN (${w})`,g)}let D=new Map;for(let w of _)D.set(w[R],w);let h=new Map;for(let w of b){let y=w[a.pivotFkParent];if(!h.has(y))h.set(y,[]);h.get(y).push(w)}let M=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let w of r){let y=w.get(s),S=(h.get(y)||[]).map((W)=>{let J=D.get(W[a.pivotFkRelated]);if(!J)return null;let z=new I(k,J,!0),B={};for(let[H,me]of Object.entries(W))if(!M.has(H))B[H]=me;return z.pivot=B,z}).filter((W)=>W!==null);w.setRelation(t,S)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=Te(r,s);if(u.length===0)return;let c=a.throughLocalKey||"id",b=u.map(()=>"?").join(", "),f=await o.all(`SELECT ${c}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${b})`,u);if(f.length===0){for(let M of r)M.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let M of f)g.set(M[c],M[a.throughForeignKey]);let K=[...new Set(f.map((M)=>M[c]))],k=K.map(()=>"?").join(", "),R=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${k})`,K),_=j(a.relatedModelName),D=_?.getDefinition?.()||_?.definition||this._definition,h=new Map;for(let M of R){let w=g.get(M[a.targetForeignKey]);if(w==null)continue;if(!h.has(w))h.set(w,[]);h.get(w).push(new I(D,M,!0))}for(let M of r){let w=h.get(M.get(s))||[];M.setRelation(t,a.type==="hasManyThrough"?w:w[0]??null)}}}async get(){let t=N(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new I(this._definition,a,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(i);return i}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let t=await this.first();if(!t)throw Error(`No ${this._definition.name} found`);return t}async find(t){let r=this._definition.primaryKey||"id";return this.where(r,t).first()}async findOrFail(t){let r=await this.find(t);if(!r)throw Error(`${this._definition.name} with id ${t} not found`);return r}async last(){let t=this._definition.primaryKey||"id";return this._orderBy=[{column:t,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let t=N(),r=[],o=`SELECT COUNT(*) as count FROM ${this._definition.table}`,s=this.composeWhere(r);if(s)o+=` WHERE ${s}`;let i=await t.get(o,r);return Number(i?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let t=await this.get();if(t.length===0)throw Error(`No ${this._definition.name} found`);if(t.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return t[0]}async increment(t,r=1){Q(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=N(),s=[r],i=U(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(Z(this._definition))a+=", updated_at = ?",s.push(Y());let d=this.composeWhere(s);if(d)a+=` WHERE ${d}`;return(await o.run(a,s)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let o=0;while(!0){let s=new x(this._definition);s._wheres=[...this._wheres],s._orderBy=[...this._orderBy],s._select=[...this._select],s._withRelations=[...this._withRelations],s._trashed=this._trashed,s._limit=t,s._offset=o*t;let i=await s.get();if(i.length===0)break;if(await r(i)===!1)break;if(i.length<t)break;o++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let a=t;r=a.perPage??15,t=a.page??1}let o=await this.count(),s=Math.ceil(o/r);this._limit=r,this._offset=(t-1)*r;let i=await this.get();return{data:i,total:o,page:t,perPage:r,lastPage:s,hasMorePages:t<s,isEmpty:i.length===0,from:i.length>0?(t-1)*r+1:null,to:i.length>0?(t-1)*r+i.length:null,meta:{perPage:r,page:t,total:o,lastPage:s}}}async pluck(t){Q(t,"pluck(column)");let r=N(),o=[],s=U(t),i=`SELECT ${s} FROM ${this._definition.table}`,a=this.composeWhere(o);if(a)i+=` WHERE ${a}`;if(this._orderBy.length>0)i+=` ORDER BY ${this._orderBy.map((u)=>`${U(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)i+=` LIMIT ${this._limit}`;if(this._offset!==void 0)i+=` OFFSET ${this._offset}`;return(await r.all(i,o)).map((u)=>u[s])}async aggregate(t,r){Q(r,`${t}(column)`);let o=N(),s=[],i=`SELECT ${t}(${U(r)}) as v FROM ${this._definition.table}`,a=this.composeWhere(s);if(a)i+=` WHERE ${a}`;let u=(await o.get(i,s))?.v;if(u==null)return null;if(typeof u==="string"){let c=Number(u);return u.trim()!==""&&!Number.isNaN(c)?c:u}return u}max(t){return this.aggregate("MAX",t)}min(t){return this.aggregate("MIN",t)}async avg(t){return Number(await this.aggregate("AVG",t)??0)||0}async sum(t){return Number(await this.aggregate("SUM",t)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let t=te(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=N(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${F} IS NULL`:`${F} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Y():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${F} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let c=this._definition.primaryKey||"id",f=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((k)=>new I(this._definition,k,!0)),g=f.map((k)=>k._attributes[c]);if(g.some((k)=>k==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let k of f)await s.beforeDelete?.(k);let K=0;for(let k=0;k<g.length;k+=ve){let R=g.slice(k,k+ve),_=`${c} IN (${R.map(()=>"?").join(", ")})`;K+=t?(await r.run(`UPDATE ${o} SET ${F} = ? WHERE ${_}`,[u,...R])).changes:(await r.run(`DELETE FROM ${o} WHERE ${_}`,R)).changes}for(let k of f){if(t)k._attributes[F]=u;await s.afterDelete?.(k)}return K}async update(t){this.assertNoUnappliedClauses("update");let r=N(),o=Object.entries(t),s=o.map(([u])=>`${U(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(Z(this._definition))i.push(Y());let a=`UPDATE ${this._definition.table} SET ${s}${Z(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function nt(t){let r={query:()=>new x(t),where(o,s,i){return new x(t).where(o,s,i)},orWhere(o,s,i){return new x(t).orWhere(o,s,i)},whereIn(o,s){return new x(t).whereIn(o,s)},whereNotIn(o,s){return new x(t).whereNotIn(o,s)},whereNull(o){return new x(t).whereNull(o)},whereNotNull(o){return new x(t).whereNotNull(o)},whereLike(o,s){return new x(t).whereLike(o,s)},orderBy(o,s="asc"){return new x(t).orderBy(o,s)},orderByDesc(o){return new x(t).orderByDesc(o)},select(...o){return new x(t).select(...o)},with(...o){return new x(t).with(...o)},limit:(o)=>new x(t).limit(o),take:(o)=>new x(t).take(o),skip:(o)=>new x(t).skip(o),withTrashed:()=>new x(t).withTrashed(),onlyTrashed:()=>new x(t).onlyTrashed(),async find(o){let s=N(),i=t.primaryKey||"id",a=te(t)?` AND ${F} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new I(t,d,!0):void 0},async findOrFail(o){let s=await r.find(o);if(!s)throw Error(`${t.name} with id ${o} not found`);return s},async findMany(o){let s=N(),i=t.primaryKey||"id",a=te(t)?` AND ${F} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new I(t,u,!0))},all:()=>new x(t).get(),first:()=>new x(t).first(),firstOrFail:()=>new x(t).firstOrFail(),last:()=>new x(t).last(),count:()=>new x(t).count(),exists:()=>new x(t).exists(),doesntExist:()=>new x(t).doesntExist(),paginate:(o,s)=>new x(t).paginate(o,s),whereBetween(o,s){return new x(t).whereBetween(o,s)},whereNotBetween(o,s){return new x(t).whereNotBetween(o,s)},async create(o){let s=new I(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((c)=>new I(t,c,!1));if(!s.length)return[];let i=N(),a=t.primaryKey||"id",d=[];for(let c of s)d.push(await c._prepareInsert());let u=new Map;d.forEach((c,b)=>{let f=Object.keys(c).join("\x00"),g=u.get(f);if(g)g.push(b);else u.set(f,[b])});for(let[c,b]of u){let f=c?c.split("\x00"):[],g=!f.includes(a);if(!f.length||g&&i.dialect==="mysql"){for(let k of b){let R=d[k],_=Object.keys(R),D=await i.insert(_.length?`INSERT INTO ${t.table} (${_.join(", ")}) VALUES (${_.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(R),a);await s[k]._markInserted(R,g?D.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&ze(t,f,b.map((k)=>d[k]))){let k=t.table,R=f.join(", "),_=`INSERT INTO ${k} (${R}) SELECT ${R} FROM jsonb_populate_recordset(NULL::${k}, (?::text)::jsonb)`;for(let D=0;D<b.length;D+=Ae){let h=b.slice(D,D+Ae),M=JSON.stringify(h.map((A)=>Object.fromEntries(f.map((S)=>[S,d[A][S]??null]))),Ge);if(!g){await i.run(_,[M]);for(let A of h)await s[A]._markInserted(d[A]);continue}let w=(await i.all(`${_} RETURNING ${a}`,[M])).map((A)=>A[a]),y=w.every((A)=>typeof A==="number"||typeof A==="bigint")?[...w].sort((A,S)=>A<S?-1:A>S?1:0):w;for(let A=0;A<h.length;A++)await s[h[A]]._markInserted(d[h[A]],y[A])}continue}let K=Ee(Math.max(1,Math.floor(Qe/f.length)));for(let k=0;k<b.length;){let R=Math.min(K,Ee(b.length-k)),_=b.slice(k,k+R);k+=R;let D=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${_.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=_.flatMap((y)=>f.map((A)=>d[y][A]));if(!g){await i.run(D,h);for(let y of _)await s[y]._markInserted(d[y]);continue}let M=(await i.all(`${D} RETURNING ${a}`,h)).map((y)=>y[a]),w=M.every((y)=>typeof y==="number"||typeof y==="bigint")?[...M].sort((y,A)=>y<A?-1:y>A?1:0):M;for(let y=0;y<_.length;y++)await s[_[y]]._markInserted(d[_[y]],w[y])}}return s},async updateOrCreate(o,s){let i=new x(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);let a=await i.first();if(a)return await a.update(s),a;return this.create({...o,...s})},async firstOrCreate(o,s){let i=new x(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);return await i.first()||this.create({...o,...s})},async update(o,s){let i=await r.findOrFail(o);return await i.update(s),i},async delete(o){let s=await r.find(o);return s?s.delete():!1},destroy(o){return r.delete(o)},async forceDelete(o){let s=await r.withTrashed().find(o);return s?s.forceDelete():!1},remove(o){return r.forceDelete(o)},async truncate(){await N().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new I(t,o,!1)},latest:(o="created_at")=>new x(t).orderByDesc(o),oldest:(o="created_at")=>new x(t).orderBy(o,"asc"),max:(o)=>new x(t).max(o),min:(o)=>new x(t).min(o),avg:(o)=>new x(t).avg(o),sum:(o)=>new x(t).sum(o),pluck(o){return new x(t).pluck(o)}};return new Proxy(r,{get(o,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let i=s.slice(5),a=i.charAt(0).toLowerCase()+i.slice(1);if(a in t.attributes||a==="id"||a===t.primaryKey)return(d)=>new x(t).where(a,d)}return Reflect.get(o,s)}})}function jt(t){let r=nt(t);if(t?.name)Ue(t.name,r);return r}async function Wn(t){let r=N(),o=v(t.primaryKey||"id"),s=[],i=new Set([o]);if(s.push(t.autoIncrement!==!1?`${o} INTEGER PRIMARY KEY AUTOINCREMENT`:`${o} INTEGER PRIMARY KEY`),t.traits?.useUuid)s.push("uuid TEXT UNIQUE"),i.add("uuid");for(let[a,d]of Object.entries(t.attributes)){let u=v(a);if(i.has(u))continue;i.add(u);let c=ke(d.type),b=_e(c);if(u.endsWith("_id")&&(c===void 0||O(c)))b="INTEGER";let f=`${u} ${b}`;if(d.unique)f+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let g=d.foreignKey;if(f+=` REFERENCES ${g.table}(${g.column??"id"})`,g.onDelete)f+=` ON DELETE ${g.onDelete.toUpperCase()}`;if(g.onUpdate)f+=` ON UPDATE ${g.onUpdate.toUpperCase()}`}s.push(f)}for(let a of P(t.belongsTo)){let d=a.foreignKey??`${v(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(Z(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(te(t)&&!i.has("deleted_at"))i.add("deleted_at"),s.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${s.join(", ")})`,[])}async function Un(t,r,o){let s=N(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=_t(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<a;d++){let u={};for(let[b,f]of Object.entries(t.attributes))if(f.factory)u[v(b)]=f.factory(o);if(Z(t)){let b=Y();u.created_at=b,u.updated_at=b}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let c=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${c.join(", ")}) VALUES (${c.map(()=>"?").join(", ")})`,Object.values(u))}}var se=new Map;function an(t){return se.get(t)}function on(){return[...se.values()]}function ln(){return Object.fromEntries(se)}function cn(t){return se.has(t)}function un(){se.clear(),It()}function qt(t,r){return se.set(t,r),r}function rt(){return typeof window<"u"&&typeof document<"u"}function dn(t){let r;if(rt())r=Ve(t);else{let o=jt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return qt(t.name,r),r}function fn(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
3
3
  export{O,_e,_t,Ie,P,It,Lt,Kt,Fn,jn,qn,Ft,jt,Wn,Un,an,on,ln,cn,un,qt,dn,fn};