bun-query-builder 0.3.4 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +18 -18
- package/dist/chunk-5b51gpqw.js +67 -0
- package/dist/chunk-7cgq9r40.js +383 -0
- package/dist/chunk-cfswsgdh.js +3 -0
- package/dist/chunk-gcbgbkrf.js +2 -0
- package/dist/{chunk-mbt007va.js → chunk-vxh8ktv7.js} +5 -5
- package/dist/chunk-wfk6y67h.js +3 -0
- package/dist/{chunk-jwwbnv83.js → chunk-xk3qn91x.js} +2 -2
- package/dist/chunk-yzqfbfat.js +2 -0
- package/dist/client.d.ts +2 -2
- package/dist/config.d.ts +9 -0
- package/dist/db.d.ts +10 -0
- package/dist/index.d.ts +1 -0
- package/dist/libsql.d.ts +169 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/runtime.js +1 -1
- package/dist/types.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-afbb8bx3.js +0 -384
- package/dist/chunk-cwf5anrk.js +0 -2
- package/dist/chunk-ne1tyjpr.js +0 -2
- package/dist/chunk-qa7wq5xr.js +0 -67
- package/dist/chunk-wq450xdk.js +0 -3
- package/dist/chunk-yr0kc2zt.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{qe}from"./chunk-xk3qn91x.js";import{n,e,k,_,b,Ke,m,D,l,nt,Y}from"./chunk-5b51gpqw.js";function N(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function De(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 Oe(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 Te}from"bun:sqlite";function te(t){if(typeof t==="number")return{length:t};return t}function me(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 ke(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function z(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 At(t){let r=(f)=>{let g=Array.isArray(f)?f:[],R=Math.floor(Math.random()*g.length);return g[R]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=z(t.string,{alpha:(f)=>o()?.alpha?.(te(f)),alphanumeric:(f)=>o()?.alphanumeric?.(te(f)),numeric:(f)=>o()?.numeric?.(te(f)),sample:(f)=>o()?.sample?.(te(f)),hexadecimal:(f)=>o()?.hexadecimal?.(te(f))}),d=z(t.number,{int:(f)=>s()?.int?.(me(f)),float:(f)=>{let g=me(f);return ke(Number(s()?.float?.(g)??0),g)}}),u=z(t.helpers,{arrayElement:r,arrayElements:(f,g)=>{let R=[...Array.isArray(f)?f:[]],M=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*R.length));for(let x=R.length-1;x>0;x-=1){let A=Math.floor(Math.random()*(x+1));[R[x],R[A]]=[R[A],R[x]]}return R.slice(0,Math.min(M,R.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let R=g.length-1;R>0;R-=1){let M=Math.floor(Math.random()*(R+1));[g[R],g[M]]=[g[M],g[R]]}return g},maybe:(f,g)=>{let R=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<R?f():void 0},slugify:(f)=>String(f??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),T={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?.(me(f))??0),float:(f)=>ke(Number(s()?.float?.(f)??0),f),uuid:()=>crypto.randomUUID(),string:(f)=>String(o()?.alphanumeric?.({length:f??10})??""),hexadecimal:(f)=>String(o()?.hexadecimal?.(te(f))??""),array:(f)=>Array.from({length:f??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:z(t.address),address:z(t.address),vehicle:z(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:z(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(f,g){if(g in T)return T[g];let R=f[g];if(R&&typeof R==="object")return z(R);return R}})}function Be(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 O(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Be).filter((o)=>o!==null)}function X(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var Se=/^[A-Z_][A-Z0-9_]*$/i;function H(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(!Se.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Pe(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||!Se.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 Me(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&Y(t)===0)return[];return r}var ae=null,we=new Map;function Ue(t,r){we.set(t,r),re.clear()}function Mt(){we.clear(),re.clear()}function j(t){if(!ae)try{ae=import.meta.require("./chunk-gcbgbkrf.js").getModel}catch{ae=()=>{return}}return ae(t)??we.get(t)}var le=new Map,He=500;function Re(t){let r=le.get(t);if(r!==void 0)return r;let o=nt(t,"postgres");if(le.size>=He)le.clear();return le.set(t,o),o}function Nt(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 Ot(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 pe{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...r))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...r)??void 0)}run(t,r){let o=this.sqliteDb.run(t,r);return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class be{dialect;constructor(t){this.dialect=t}conn(){return b()}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:Nt(o),lastInsertId:Ot(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=Ot(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:Nt(s)||1,lastInsertId:i}}}var Q=null,ce=!1,U=null,ne=null,ue=null,de=null;function On(t){if(t.database instanceof Te)Q=t.database,ce=!1;else Q=new Te(t.database||":memory:",{create:!0}),ce=!0,k(Q);U=null,ne=null}function Bn(){let t=ce,r=Q;if(Q=null,ce=!1,U=null,ne=null,ue=null,de=null,t&&r)try{r.close()}catch{}}var _e=!1;function S(){if(Q){if(!U||ne!==Q)U=new pe(Q),ne=Q,ue="sqlite",de=null;return U}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${_()?.url??""}`;if(U&&ne===null&&ue===t&&de===o)return U;if(ne=null,ue=t,de=o,t==="sqlite"&&_())U=new be(t);else if(t==="sqlite"){if(!r&&!_e)_e=!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 Te(r||":memory:",{create:!0});k(s),U=new pe(s)}else U=new be(t);return U}function Pn(){let t=S();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,xe=1000;function Ve(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[C(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 ze(t,r){return typeof r==="bigint"?r.toString():r}function Ae(t){return 2**Math.floor(Math.log2(t))}var L="deleted_at",Ee=500,ye="__btm_rel__";function ee(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 ve=new WeakMap;function Ge(t){let r=ve.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 ve.set(t,o),o}function Ie(t){let r={};for(let[o,s]of Object.entries(t))r[C(o)]=s;return r}function Xe(t){for(let r in t)if(C(r)!==r)return Ie(t);return t}function Ye(t,r){if(t[r])return t[r];let o=C(r);if(t[o])return t[o];for(let s of Object.keys(t))if(C(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=Xe({...r}),this._original=null;let s=Ge(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 T=j(c.relatedModelName),f=T?.getDefinition?.()||T?.definition;if(!f)throw Error(`[orm] related model '${c.relatedModelName}' is not registered`);return new Bt(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[C(t)]}getAttribute(t){return this._attributes[C(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[C(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[C(o)];return r}except(t){let r=new Set(t.map((s)=>C(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=C(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()[C(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=Ye(r,o),a=!i&&C(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[C(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Ie(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(C(u)))continue;let T=C(u);if(this._attributes[T]!==void 0)s[T]=this._attributes[T]}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=X(),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[C(r)]=o(this._attributes)}async save(){let t=S(),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=X();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=S(),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=S(),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),ee(this._definition)){let i=X();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[L]=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 S().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!ee(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 S().run(`UPDATE ${this._definition.table} SET ${L} = ? WHERE ${t} = ?`,[null,r]),this._attributes[L]=null,this._original=null,this}trashed(){return this._attributes[L]!=null}async refresh(){let t=S(),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 Ne=new Map,Ce=new Map,re=new Map,Je=1000;function W(t){return C(t)}function C(t){let r=Ne.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),Ne.set(t,r),r}function G(t){let r=Ce.get(t);if(r!==void 0)return r;return r=Ke(t),Ce.set(t,r),r}var fe=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ze=[...fe,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function $e(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 et(t,r){let o=t.name??t.table??"model",i=Ze.filter((d)=>$e(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!fe.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${fe.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=fe.flatMap((d)=>$e(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(w){if(!w)return null;if(Array.isArray(w)){for(let h of w){let K=typeof h==="string"?h:h?.model||"";if(K&&K.toLowerCase()===r.toLowerCase())return K}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||h}return null}function d(){let w=t.belongsTo;if(!w)return null;let h=r.toLowerCase(),K=(p)=>{if(typeof p==="string")return{model:p};if(p&&typeof p==="object"&&typeof p.model==="string")return{model:p.model,foreignKey:p.foreignKey};return null};if(Array.isArray(w)){for(let p of w){let y=K(p);if(y&&y.model.toLowerCase()===h)return y}return null}if(typeof w==="object"){for(let[p,y]of Object.entries(w))if(p===r||p.toLowerCase()===h)return K(y)}return null}function u(){let w=t.belongsToMany;if(!w)return null;if(Array.isArray(w)){for(let h of w)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 w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:K}}return null}function c(w){let h=t[w];if(!h)return null;let K=r.toLowerCase();if(Array.isArray(h)){for(let p of h){let y=typeof p==="string"?p:String(p?.model??"");if(!y||y.toLowerCase()!==K)continue;let v=typeof p==="object"?p?.morphName:void 0;return{model:y,morphName:String(v??`${C(o)}able`)}}return null}if(typeof h==="object")for(let[p,y]of Object.entries(h)){let v=typeof y==="string"?y:String(y?.model??"");if(p.toLowerCase()!==K&&v.toLowerCase()!==K)continue;let P=typeof y==="object"?y?.morphName:void 0;return{model:v,morphName:String(P??p)}}return null}for(let w of["morphMany","morphOne"]){let h=c(w);if(!h)continue;let p=j(h.model)?.getTable?.()||G(h.model);return{type:w,relatedModelName:h.model,relatedTable:p,foreignKey:`${h.morphName}_id`,localKey:i,morphTypeColumn:`${h.morphName}_type`,morphTypeValue:s}}let T=a(t.hasMany);if(T){let h=j(T)?.getTable?.()||G(T),K=C(o)+"_id";return{type:"hasMany",relatedModelName:T,relatedTable:h,foreignKey:K,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||G(f),K=C(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:K,localKey:i}}let g=d();if(g){let w=g.model,h=j(w),K=h?.getTable?.()||G(w),p=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${C(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:K,foreignKey:y,localKey:p}}let R=u();if(R){let w=typeof R.entry==="object",h=w?R.entry.model:R.entry,p=j(h)?.getTable?.()||G(h),y=w?R.entry:null,v,P;if(y?.table)v=y.table;else if(y?.through){P=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.`);v=B.getTable?.()||B.getDefinition?.()?.table||G(y.through)}else{let B=ie(s),q=ie(p);v=[B,q].sort().join("_")}let F=y?.foreignKey||`${ie(s)}_id`,J=y?.relatedKey||`${ie(p)}_id`,V=[];if(y?.pivot?.columns)for(let B of Object.keys(y.pivot.columns))V.push(B);if(P){let B=j(P),q=B?.getDefinition?.()||B?.definition,he=q?.attributes??{},Le=q?.primaryKey??"id";for(let se of Object.keys(he)){if(se===F||se===J||se===Le)continue;if(!V.includes(se))V.push(se)}}return{type:"belongsToMany",relatedModelName:h,relatedTable:p,foreignKey:F,localKey:i,pivotTable:v,pivotFkParent:F,pivotFkRelated:J,pivotColumns:V,pivotModelName:P,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let M=(w,h)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let K=w[r]??w[Object.keys(w).find((q)=>q.toLowerCase()===r.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:p,target:y}=K;if(!p||!y)return null;let v=j(p),P=v?.getDefinition?.()||v?.definition,F=v?.getTable?.()||P?.table||G(p),J=P?.primaryKey||"id",B=j(y)?.getTable?.()||G(y);return{type:h,relatedModelName:y,relatedTable:B,foreignKey:`${C(o)}_id`,localKey:i,throughTable:F,throughForeignKey:`${C(o)}_id`,throughLocalKey:J,targetForeignKey:`${ie(F)}_id`}},x=M(t.hasManyThrough,"hasManyThrough");if(x)return x;let A=M(t.hasOneThrough,"hasOneThrough");if(A)return A;return null}function ge(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 ie(t){return m(e.relations?.singularizeStrategy)(t)}class Bt{_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(Pe(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 ${ye}${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(ye))i[u.slice(ye.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=S(),{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=S(),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 X()}async attach(t,r={}){let o=S(),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),T=c.map(()=>"?").join(", "),f=`INSERT INTO ${this.pivotTable} (${c.join(", ")}) VALUES (${T})`,g=c.map((R)=>u[R]);await o.run(f,g),a++}return a}async detach(t){let r=S(),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=S(),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=S(),o=new Map;for(let T of t)if(T!=null&&typeof T==="object"&&"id"in T){let{id:f,...g}=T;o.set(f,g)}else o.set(T,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((T)=>T[this.fkRelated])),a=[],d=[],u=[],c=[...i].filter((T)=>!o.has(T));if(c.length>0)await this.detach(c),d.push(...c);for(let[T,f]of o)if(!i.has(T))await this.attach(T,f),a.push(T);else if(Object.keys(f).length>0)await this.updateExistingPivot(T,f),u.push(T);return{attached:a,detached:d,updated:u}}async toggle(t){let r=S(),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 E{_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 H(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return H(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return H(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return H(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:Me(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(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 E(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 H(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){H(t,"whereNotBetween(column)");let o=W(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(Pe(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=W(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(W(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${W(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return D(r)}softDeleteClause(){if(this._trashed==="include"||!ee(this._definition))return"";return this._trashed==="only"?`${L} IS NOT NULL`:`${L} 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:W(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)=>`${W(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=S(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=re.get(i);if(a===void 0){if(a=je(this._definition,t),re.size>=Je)re.clear();re.set(i,a)}if(!a)throw Error(et(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=ge(r,s);if(u.length===0)return;let c=u.map(()=>"?").join(", "),T=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${c})${T}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,[]);M.get(A).push(x)}for(let x of r){let A=M.get(x.get(s))||[];x.setRelation(t,A.map((w)=>new I(R,w,!0)))}}else{let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,x)}for(let x of r){let A=M.get(x.get(s));x.setRelation(t,A?new I(R,A,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let x of r){let A=x._attributes[a.foreignKey];if(A!=null)u.add(A)}let c=[...u];if(c.length===0)return;let T=c.map(()=>"?").join(", "),f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${T})`,c),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition,M=new Map;for(let x of f)M.set(x[a.localKey],x);for(let x of r){let A=x._attributes[a.foreignKey],w=M.get(A);x.setRelation(t,w?new I(R,w,!0):null)}}if(a.type==="belongsToMany"){let u=ge(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let c=u.map(()=>"?").join(", "),T=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${c})`,u);if(T.length===0){for(let p of r)p.setRelation(t,[]);return}let f=new Set;for(let p of T){let y=p[a.pivotFkRelated];if(y!=null)f.add(y)}let g=[...f],R=j(a.relatedModelName),M=R?.getDefinition?.()||R?.definition||this._definition,x=M?.primaryKey||"id",A=[];if(g.length>0){let p=g.map(()=>"?").join(", ");A=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${x} IN (${p})`,g)}let w=new Map;for(let p of A)w.set(p[x],p);let h=new Map;for(let p of T){let y=p[a.pivotFkParent];if(!h.has(y))h.set(y,[]);h.get(y).push(p)}let K=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let p of r){let y=p.get(s),P=(h.get(y)||[]).map((F)=>{let J=w.get(F[a.pivotFkRelated]);if(!J)return null;let V=new I(M,J,!0),B={};for(let[q,he]of Object.entries(F))if(!K.has(q))B[q]=he;return V.pivot=B,V}).filter((F)=>F!==null);p.setRelation(t,P)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=ge(r,s);if(u.length===0)return;let c=a.throughLocalKey||"id",T=u.map(()=>"?").join(", "),f=await o.all(`SELECT ${c}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${T})`,u);if(f.length===0){for(let K of r)K.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let K of f)g.set(K[c],K[a.throughForeignKey]);let R=[...new Set(f.map((K)=>K[c]))],M=R.map(()=>"?").join(", "),x=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${M})`,R),A=j(a.relatedModelName),w=A?.getDefinition?.()||A?.definition||this._definition,h=new Map;for(let K of x){let p=g.get(K[a.targetForeignKey]);if(p==null)continue;if(!h.has(p))h.set(p,[]);h.get(p).push(new I(w,K,!0))}for(let K of r){let p=h.get(K.get(s))||[];K.setRelation(t,a.type==="hasManyThrough"?p:p[0]??null)}}}async get(){let t=S(),{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=S(),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){H(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=S(),s=[r],i=W(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(Z(this._definition))a+=", updated_at = ?",s.push(X());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 E(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){H(t,"pluck(column)");let r=S(),o=[],s=W(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)=>`${W(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){H(r,`${t}(column)`);let o=S(),s=[],i=`SELECT ${t}(${W(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=ee(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=S(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${L} IS NULL`:`${L} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?X():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${L} = ?${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((M)=>new I(this._definition,M,!0)),g=f.map((M)=>M._attributes[c]);if(g.some((M)=>M==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let M of f)await s.beforeDelete?.(M);let R=0;for(let M=0;M<g.length;M+=Ee){let x=g.slice(M,M+Ee),A=`${c} IN (${x.map(()=>"?").join(", ")})`;R+=t?(await r.run(`UPDATE ${o} SET ${L} = ? WHERE ${A}`,[u,...x])).changes:(await r.run(`DELETE FROM ${o} WHERE ${A}`,x)).changes}for(let M of f){if(t)M._attributes[L]=u;await s.afterDelete?.(M)}return R}async update(t){this.assertNoUnappliedClauses("update");let r=S(),o=Object.entries(t),s=o.map(([u])=>`${W(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(Z(this._definition))i.push(X());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 tt(t){let r={query:()=>new E(t),where(o,s,i){return new E(t).where(o,s,i)},orWhere(o,s,i){return new E(t).orWhere(o,s,i)},whereIn(o,s){return new E(t).whereIn(o,s)},whereNotIn(o,s){return new E(t).whereNotIn(o,s)},whereNull(o){return new E(t).whereNull(o)},whereNotNull(o){return new E(t).whereNotNull(o)},whereLike(o,s){return new E(t).whereLike(o,s)},orderBy(o,s="asc"){return new E(t).orderBy(o,s)},orderByDesc(o){return new E(t).orderByDesc(o)},select(...o){return new E(t).select(...o)},with(...o){return new E(t).with(...o)},limit:(o)=>new E(t).limit(o),take:(o)=>new E(t).take(o),skip:(o)=>new E(t).skip(o),withTrashed:()=>new E(t).withTrashed(),onlyTrashed:()=>new E(t).onlyTrashed(),async find(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} 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=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} 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 E(t).get(),first:()=>new E(t).first(),firstOrFail:()=>new E(t).firstOrFail(),last:()=>new E(t).last(),count:()=>new E(t).count(),exists:()=>new E(t).exists(),doesntExist:()=>new E(t).doesntExist(),paginate:(o,s)=>new E(t).paginate(o,s),whereBetween(o,s){return new E(t).whereBetween(o,s)},whereNotBetween(o,s){return new E(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=S(),a=t.primaryKey||"id",d=[];for(let c of s)d.push(await c._prepareInsert());let u=new Map;d.forEach((c,T)=>{let f=Object.keys(c).join("\x00"),g=u.get(f);if(g)g.push(T);else u.set(f,[T])});for(let[c,T]of u){let f=c?c.split("\x00"):[],g=!f.includes(a);if(!f.length||g&&i.dialect==="mysql"){for(let M of T){let x=d[M],A=Object.keys(x),w=await i.insert(A.length?`INSERT INTO ${t.table} (${A.join(", ")}) VALUES (${A.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(x),a);await s[M]._markInserted(x,g?w.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&Ve(t,f,T.map((M)=>d[M]))){let M=t.table,x=f.join(", "),A=`INSERT INTO ${M} (${x}) SELECT ${x} FROM jsonb_populate_recordset(NULL::${M}, (?::text)::jsonb)`;for(let w=0;w<T.length;w+=xe){let h=T.slice(w,w+xe),K=JSON.stringify(h.map((v)=>Object.fromEntries(f.map((P)=>[P,d[v][P]??null]))),ze);if(!g){await i.run(A,[K]);for(let v of h)await s[v]._markInserted(d[v]);continue}let p=(await i.all(`${A} RETURNING ${a}`,[K])).map((v)=>v[a]),y=p.every((v)=>typeof v==="number"||typeof v==="bigint")?[...p].sort((v,P)=>v<P?-1:v>P?1:0):p;for(let v=0;v<h.length;v++)await s[h[v]]._markInserted(d[h[v]],y[v])}continue}let R=Ae(Math.max(1,Math.floor(Qe/f.length)));for(let M=0;M<T.length;){let x=Math.min(R,Ae(T.length-M)),A=T.slice(M,M+x);M+=x;let w=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${A.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=A.flatMap((y)=>f.map((v)=>d[y][v]));if(!g){await i.run(w,h);for(let y of A)await s[y]._markInserted(d[y]);continue}let K=(await i.all(`${w} RETURNING ${a}`,h)).map((y)=>y[a]),p=K.every((y)=>typeof y==="number"||typeof y==="bigint")?[...K].sort((y,v)=>y<v?-1:y>v?1:0):K;for(let y=0;y<A.length;y++)await s[A[y]]._markInserted(d[A[y]],p[y])}}return s},async updateOrCreate(o,s){let i=new E(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 E(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 S().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new I(t,o,!1)},latest:(o="created_at")=>new E(t).orderByDesc(o),oldest:(o="created_at")=>new E(t).orderBy(o,"asc"),max:(o)=>new E(t).max(o),min:(o)=>new E(t).min(o),avg:(o)=>new E(t).avg(o),sum:(o)=>new E(t).sum(o),pluck(o){return new E(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 E(t).where(a,d)}return Reflect.get(o,s)}})}function Pt(t){let r=tt(t);if(t?.name)Ue(t.name,r);return r}async function _n(t){let r=S(),o=C(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=C(a);if(i.has(u))continue;i.add(u);let c=De(d.type),T=Oe(c);if(u.endsWith("_id")&&(c===void 0||N(c)))T="INTEGER";let f=`${u} ${T}`;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 O(t.belongsTo)){let d=a.foreignKey??`${C(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(ee(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 In(t,r,o){let s=S(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=At(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[T,f]of Object.entries(t.attributes))if(f.factory)u[C(T)]=f.factory(o);if(Z(t)){let T=X();u.created_at=T,u.updated_at=T}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 oe=new Map;function Xt(t){return oe.get(t)}function Zt(){return[...oe.values()]}function en(){return Object.fromEntries(oe)}function tn(t){return oe.has(t)}function nn(){oe.clear(),Mt()}function _t(t,r){return oe.set(t,r),r}function rt(){return typeof window<"u"&&typeof document<"u"}function rn(t){let r;if(rt())r=qe(t);else{let o=Pt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return _t(t.name,r),r}function sn(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
|
|
3
|
+
export{N,Oe,At,Be,O,Mt,Nt,Ot,On,Bn,Pn,Bt,Pt,_n,In,Xt,Zt,en,tn,nn,_t,rn,sn};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var n={baseUrl:""};function en(e){n={...n,...e}}function tn(){return n}function nn(){return typeof window<"u"&&typeof document<"u"}async function w(){if(n.getToken){let e=n.getToken();return e instanceof Promise?e:e}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function l(){let e={"Content-Type":"application/json",Accept:"application/json",...n.headers},t=await w();if(t)e.Authorization=`Bearer ${t}`;return e}async function u(e){if(e.status===401)throw n.onUnauthorized?.(),new g("Unauthorized",401);if(!e.ok){let r=await e.json().catch(()=>({message:"Request failed"}));throw new g(r.message||`HTTP ${e.status}`,e.status)}let t=await e.json();if(n.transformResponse)return n.transformResponse(t);return t}class g extends Error{status;constructor(e,t){super(e);this.name="BrowserQueryError",this.status=t}}class Ye{state;constructor(e){this.state={table:e,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...e){return this.state.selectColumns=e,this}where(e,t,r){if(r===void 0)this.state.wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this.state.wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}andWhere(e,t,r){return r===void 0?this.where(e,t):this.where(e,t,r)}whereNull(e){return this.where(e,"is",null)}whereNotNull(e){return this.where(e,"is not",null)}whereIn(e,t){return this.where(e,"in",t)}whereNotIn(e,t){return this.where(e,"not in",t)}orderBy(e,t="asc"){return this.state.orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}latest(e="created_at"){return this.orderBy(e,"desc")}oldest(e="created_at"){return this.orderBy(e,"asc")}limit(e){return this.state.limitValue=e,this}offset(e){return this.state.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}with(...e){return this.state.withRelations.push(...e),this}buildQueryParams(){let e=new URLSearchParams;for(let t of this.state.wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this.state.orderBy.length>0){let t=this.state.orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this.state.limitValue!==void 0)e.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)e.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))e.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)e.append("include",this.state.withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.state.table}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return Array.isArray(r)?r:r.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new g(`No ${this.state.table} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r);return"data"in s&&!Array.isArray(s.data)?s.data:s}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new g(`${this.state.table} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.state.table}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async create(e){let t=`${n.baseUrl}/${this.state.table}`,r=n.transformRequest?n.transformRequest(e):e,s=await fetch(t,{method:"POST",headers:await l(),body:JSON.stringify(r)}),a=await u(s);return"data"in a&&!Array.isArray(a.data)?a.data:a}async insert(e){return this.create(e)}async update(e,t){let r=`${n.baseUrl}/${this.state.table}/${e}`,s=n.transformRequest?n.transformRequest(t):t,a=await fetch(r,{method:"PATCH",headers:await l(),body:JSON.stringify(s)}),i=await u(a);return"data"in i&&!Array.isArray(i.data)?i.data:i}async delete(e){let t=`${n.baseUrl}/${this.state.table}/${e}`;return(await fetch(t,{method:"DELETE",headers:await l()})).ok}async destroy(e){return this.delete(e)}async paginate(e=1,t=15){this.limit(t).offset((e-1)*t);let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.state.table}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()});return u(a)}toState(){return{...this.state}}}function Xe(e){return new Ye(e)}function rn(){return new Proxy({},{get:(e,t)=>()=>Xe(t)})}class h{_attributes;_definition;constructor(e,t={}){this._definition=e,this._attributes={...t}}get(e){return this._attributes[e]}set(e,t){this._attributes[e]=t}get attributes(){return{...this._attributes}}get id(){let e=this._definition.primaryKey||"id";return this._attributes[e]}toJSON(){let e=new Set;for(let[r,s]of Object.entries(this._definition.attributes))if(s.hidden)e.add(r);let t={};for(let[r,s]of Object.entries(this._attributes))if(!e.has(r))t[r]=s;return t}}class o{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(e){this._definition=e}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(e,t,r){if(r===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this._wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}whereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"and"}),this}whereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"and"}),this}whereNull(e){return this._wheres.push({column:e,operator:"is",value:null,boolean:"and"}),this}whereNotNull(e){return this._wheres.push({column:e,operator:"is not",value:null,boolean:"and"}),this}whereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"and"}),this}orderBy(e,t="asc"){return this._orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}orderByAsc(e){return this.orderBy(e,"asc")}limit(e){return this._limit=e,this}take(e){return this.limit(e)}offset(e){return this._offset=e,this}skip(e){return this.offset(e)}select(...e){return this._select=e,this}with(...e){return this._withRelations.push(...e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderByAsc(e)}buildQueryParams(){let e=new URLSearchParams;for(let t of this._wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this._orderBy.length>0){let t=this._orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this._limit!==void 0)e.append("limit",String(this._limit));if(this._offset!==void 0)e.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))e.append("fields",this._select.join(","));if(this._withRelations.length>0)e.append("include",this._withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.getTablePath()}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return(Array.isArray(r)?r:r.data).map((a)=>new h(this._definition,a))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new g(`No ${this._definition.name} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r),a="data"in s&&!Array.isArray(s.data)?s.data:s;return new h(this._definition,a)}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new g(`${this._definition.name} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.getTablePath()}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async pluck(e){return this._select=[e],(await this.get()).map((r)=>r.get(e))}async paginate(e=1,t=15){this._limit=t,this._offset=(e-1)*t;let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.getTablePath()}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()}),i=await u(a);return{...i,data:i.data.map((d)=>new h(this._definition,d))}}}function Le(e){return new Proxy({query:()=>new o(e),where(r,s,a){return new o(e).where(r,s,a)},orWhere(r,s,a){return new o(e).orWhere(r,s,a)},whereIn(r,s){return new o(e).whereIn(r,s)},whereNotIn(r,s){return new o(e).whereNotIn(r,s)},whereNull(r){return new o(e).whereNull(r)},whereNotNull(r){return new o(e).whereNotNull(r)},whereLike(r,s){return new o(e).whereLike(r,s)},orderBy(r,s="asc"){return new o(e).orderBy(r,s)},orderByDesc(r){return new o(e).orderByDesc(r)},select(...r){return new o(e).select(...r)},limit:(r)=>new o(e).limit(r),take:(r)=>new o(e).take(r),skip:(r)=>new o(e).skip(r),latest:(r="created_at")=>new o(e).latest(r),oldest:(r="created_at")=>new o(e).oldest(r),async find(r){return new o(e).find(r)},async findOrFail(r){return new o(e).findOrFail(r)},async all(){return new o(e).get()},async first(){return new o(e).first()},async firstOrFail(){return new o(e).firstOrFail()},async count(){return new o(e).count()},async exists(){return new o(e).exists()},async paginate(r,s){return new o(e).paginate(r,s)},async pluck(r){return new o(e).pluck(r)},async create(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}`,i=n.transformRequest?n.transformRequest(r):r,d=await fetch(a,{method:"POST",headers:await l(),body:JSON.stringify(i)}),c=await u(d),f="data"in c&&!Array.isArray(c.data)?c.data:c;return new h(e,f)},async update(r,s){let a=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,i=`${n.baseUrl}/${a}/${r}`,d=n.transformRequest?n.transformRequest(s):s,c=await fetch(i,{method:"PATCH",headers:await l(),body:JSON.stringify(d)}),f=await u(c),y="data"in f&&!Array.isArray(f.data)?f.data:f;return new h(e,y)},async delete(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}/${r}`;return(await fetch(a,{method:"DELETE",headers:await l()})).ok},async destroy(r){return this.delete(r)},getDefinition:()=>e,getTable:()=>e.table},{get(r,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let a=s.slice(5),i=a.charAt(0).toLowerCase()+a.slice(1);if(i in e.attributes||i==="id"||i===e.primaryKey)return(d)=>new o(e).where(i,d)}return Reflect.get(r,s)}})}var sn={async login(e){let t=await fetch(`${n.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Login failed"}));throw new g(a.message||"Login failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async register(e){let t=await fetch(`${n.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Registration failed"}));throw new g(a.message||"Registration failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async logout(){if(await w())try{await fetch(`${n.baseUrl}/logout`,{method:"POST",headers:await l()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await w())return null;try{let t=await fetch(`${n.baseUrl}/user`,{method:"GET",headers:await l()});if(t.status===401)return n.onUnauthorized?.(),null;if(!t.ok)return null;let r=await t.json();return r.user||r}catch{return null}},async check(){return await this.user()!==null},getToken:w},kn=Xe;
|
|
3
|
-
export{
|
|
2
|
+
var n={baseUrl:""};function fn(e){n={...n,...e}}function mn(){return n}function hn(){return typeof window<"u"&&typeof document<"u"}async function w(){if(n.getToken){let e=n.getToken();return e instanceof Promise?e:e}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function l(){let e={"Content-Type":"application/json",Accept:"application/json",...n.headers},t=await w();if(t)e.Authorization=`Bearer ${t}`;return e}async function u(e){if(e.status===401)throw n.onUnauthorized?.(),new p("Unauthorized",401);if(!e.ok){let r=await e.json().catch(()=>({message:"Request failed"}));throw new p(r.message||`HTTP ${e.status}`,e.status)}let t=await e.json();if(n.transformResponse)return n.transformResponse(t);return t}class p extends Error{status;constructor(e,t){super(e);this.name="BrowserQueryError",this.status=t}}class rt{state;constructor(e){this.state={table:e,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...e){return this.state.selectColumns=e,this}where(e,t,r){if(r===void 0)this.state.wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this.state.wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}andWhere(e,t,r){return r===void 0?this.where(e,t):this.where(e,t,r)}whereNull(e){return this.where(e,"is",null)}whereNotNull(e){return this.where(e,"is not",null)}whereIn(e,t){return this.where(e,"in",t)}whereNotIn(e,t){return this.where(e,"not in",t)}orderBy(e,t="asc"){return this.state.orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}latest(e="created_at"){return this.orderBy(e,"desc")}oldest(e="created_at"){return this.orderBy(e,"asc")}limit(e){return this.state.limitValue=e,this}offset(e){return this.state.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}with(...e){return this.state.withRelations.push(...e),this}buildQueryParams(){let e=new URLSearchParams;for(let t of this.state.wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this.state.orderBy.length>0){let t=this.state.orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this.state.limitValue!==void 0)e.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)e.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))e.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)e.append("include",this.state.withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.state.table}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return Array.isArray(r)?r:r.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new p(`No ${this.state.table} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r);return"data"in s&&!Array.isArray(s.data)?s.data:s}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new p(`${this.state.table} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.state.table}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async create(e){let t=`${n.baseUrl}/${this.state.table}`,r=n.transformRequest?n.transformRequest(e):e,s=await fetch(t,{method:"POST",headers:await l(),body:JSON.stringify(r)}),a=await u(s);return"data"in a&&!Array.isArray(a.data)?a.data:a}async insert(e){return this.create(e)}async update(e,t){let r=`${n.baseUrl}/${this.state.table}/${e}`,s=n.transformRequest?n.transformRequest(t):t,a=await fetch(r,{method:"PATCH",headers:await l(),body:JSON.stringify(s)}),i=await u(a);return"data"in i&&!Array.isArray(i.data)?i.data:i}async delete(e){let t=`${n.baseUrl}/${this.state.table}/${e}`;return(await fetch(t,{method:"DELETE",headers:await l()})).ok}async destroy(e){return this.delete(e)}async paginate(e=1,t=15){this.limit(t).offset((e-1)*t);let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.state.table}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()});return u(a)}toState(){return{...this.state}}}function it(e){return new rt(e)}function gn(){return new Proxy({},{get:(e,t)=>()=>it(t)})}class h{_attributes;_definition;constructor(e,t={}){this._definition=e,this._attributes={...t}}get(e){return this._attributes[e]}set(e,t){this._attributes[e]=t}get attributes(){return{...this._attributes}}get id(){let e=this._definition.primaryKey||"id";return this._attributes[e]}toJSON(){let e=new Set;for(let[r,s]of Object.entries(this._definition.attributes))if(s.hidden)e.add(r);let t={};for(let[r,s]of Object.entries(this._attributes))if(!e.has(r))t[r]=s;return t}}class o{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(e){this._definition=e}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(e,t,r){if(r===void 0)this._wheres.push({column:e,operator:"=",value:t,boolean:"and"});else this._wheres.push({column:e,operator:t,value:r,boolean:"and"});return this}orWhere(e,t,r){throw TypeError("[browser] orWhere() is not supported by this client. The query-param format it builds has no spelling for a disjunction, so the term would be sent as a plain filter and the server would read it as AND \u2014 silently returning a superset of the rows you asked for. Express the alternatives as a single filter (whereIn), or issue one request per branch and merge the results.")}whereIn(e,t){return this._wheres.push({column:e,operator:"in",value:t,boolean:"and"}),this}whereNotIn(e,t){return this._wheres.push({column:e,operator:"not in",value:t,boolean:"and"}),this}whereNull(e){return this._wheres.push({column:e,operator:"is",value:null,boolean:"and"}),this}whereNotNull(e){return this._wheres.push({column:e,operator:"is not",value:null,boolean:"and"}),this}whereLike(e,t){return this._wheres.push({column:e,operator:"like",value:t,boolean:"and"}),this}orderBy(e,t="asc"){return this._orderBy.push({column:e,direction:t}),this}orderByDesc(e){return this.orderBy(e,"desc")}orderByAsc(e){return this.orderBy(e,"asc")}limit(e){return this._limit=e,this}take(e){return this.limit(e)}offset(e){return this._offset=e,this}skip(e){return this.offset(e)}select(...e){return this._select=e,this}with(...e){return this._withRelations.push(...e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderByAsc(e)}buildQueryParams(){let e=new URLSearchParams;for(let t of this._wheres)if(t.operator==="=")e.append(t.column,String(t.value));else if(t.operator==="in"&&Array.isArray(t.value))e.append(`${t.column}[]`,t.value.join(","));else if(t.operator==="is"&&t.value===null)e.append(`filter[${t.column}][is]`,"null");else if(t.operator==="is not"&&t.value===null)e.append(`filter[${t.column}][is_not]`,"null");else e.append(`filter[${t.column}][${t.operator}]`,String(t.value));if(this._orderBy.length>0){let t=this._orderBy.map((r)=>`${r.direction==="desc"?"-":""}${r.column}`).join(",");e.append("sort",t)}if(this._limit!==void 0)e.append("limit",String(this._limit));if(this._offset!==void 0)e.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))e.append("fields",this._select.join(","));if(this._withRelations.length>0)e.append("include",this._withRelations.join(","));return e}buildUrl(e){let t=`${n.baseUrl}/${this.getTablePath()}`;if(e!==void 0)return`${t}/${e}`;let s=this.buildQueryParams().toString();return s?`${t}?${s}`:t}async get(){let e=this.buildUrl(),t=await fetch(e,{method:"GET",headers:await l()}),r=await u(t);return(Array.isArray(r)?r:r.data).map((a)=>new h(this._definition,a))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new p(`No ${this._definition.name} found`,404);return e}async find(e){let t=this.buildUrl(e);try{let r=await fetch(t,{method:"GET",headers:await l()});if(r.status===404)return null;let s=await u(r),a="data"in s&&!Array.isArray(s.data)?s.data:s;return new h(this._definition,a)}catch{return null}}async findOrFail(e){let t=await this.find(e);if(!t)throw new p(`${this._definition.name} with id ${e} not found`,404);return t}async count(){let e=this.buildQueryParams();e.append("count","true");let t=`${n.baseUrl}/${this.getTablePath()}?${e.toString()}`,r=await fetch(t,{method:"GET",headers:await l()});return(await u(r)).count}async exists(){return await this.count()>0}async pluck(e){return this._select=[e],(await this.get()).map((r)=>r.get(e))}async paginate(e=1,t=15){this._limit=t,this._offset=(e-1)*t;let r=this.buildQueryParams();r.append("paginate","true");let s=`${n.baseUrl}/${this.getTablePath()}?${r.toString()}`,a=await fetch(s,{method:"GET",headers:await l()}),i=await u(a);return{...i,data:i.data.map((d)=>new h(this._definition,d))}}}function qe(e){return new Proxy({query:()=>new o(e),where(r,s,a){return new o(e).where(r,s,a)},orWhere(r,s,a){return new o(e).orWhere(r,s,a)},whereIn(r,s){return new o(e).whereIn(r,s)},whereNotIn(r,s){return new o(e).whereNotIn(r,s)},whereNull(r){return new o(e).whereNull(r)},whereNotNull(r){return new o(e).whereNotNull(r)},whereLike(r,s){return new o(e).whereLike(r,s)},orderBy(r,s="asc"){return new o(e).orderBy(r,s)},orderByDesc(r){return new o(e).orderByDesc(r)},select(...r){return new o(e).select(...r)},limit:(r)=>new o(e).limit(r),take:(r)=>new o(e).take(r),skip:(r)=>new o(e).skip(r),latest:(r="created_at")=>new o(e).latest(r),oldest:(r="created_at")=>new o(e).oldest(r),async find(r){return new o(e).find(r)},async findOrFail(r){return new o(e).findOrFail(r)},async all(){return new o(e).get()},async first(){return new o(e).first()},async firstOrFail(){return new o(e).firstOrFail()},async count(){return new o(e).count()},async exists(){return new o(e).exists()},async paginate(r,s){return new o(e).paginate(r,s)},async pluck(r){return new o(e).pluck(r)},async create(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}`,i=n.transformRequest?n.transformRequest(r):r,d=await fetch(a,{method:"POST",headers:await l(),body:JSON.stringify(i)}),c=await u(d),f="data"in c&&!Array.isArray(c.data)?c.data:c;return new h(e,f)},async update(r,s){let a=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,i=`${n.baseUrl}/${a}/${r}`,d=n.transformRequest?n.transformRequest(s):s,c=await fetch(i,{method:"PATCH",headers:await l(),body:JSON.stringify(d)}),f=await u(c),y="data"in f&&!Array.isArray(f.data)?f.data:f;return new h(e,y)},async delete(r){let s=typeof e.traits?.useApi==="object"&&e.traits.useApi?.uri||e.table,a=`${n.baseUrl}/${s}/${r}`;return(await fetch(a,{method:"DELETE",headers:await l()})).ok},async destroy(r){return this.delete(r)},getDefinition:()=>e,getTable:()=>e.table},{get(r,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let a=s.slice(5),i=a.charAt(0).toLowerCase()+a.slice(1);if(i in e.attributes||i==="id"||i===e.primaryKey)return(d)=>new o(e).where(i,d)}return Reflect.get(r,s)}})}var pn={async login(e){let t=await fetch(`${n.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Login failed"}));throw new p(a.message||"Login failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async register(e){let t=await fetch(`${n.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...n.headers},body:JSON.stringify(e)});if(!t.ok){let a=await t.json().catch(()=>({message:"Registration failed"}));throw new p(a.message||"Registration failed",t.status)}let r=await t.json(),s=r.data||r;if(typeof localStorage<"u"&&s.token)localStorage.setItem("auth_token",s.token);return s},async logout(){if(await w())try{await fetch(`${n.baseUrl}/logout`,{method:"POST",headers:await l()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await w())return null;try{let t=await fetch(`${n.baseUrl}/user`,{method:"GET",headers:await l()});if(t.status===401)return n.onUnauthorized?.(),null;if(!t.ok)return null;let r=await t.json();return r.user||r}catch{return null}},async check(){return await this.user()!==null},getToken:w},Kn=it;
|
|
3
|
+
export{fn,mn,hn,p,rt,it,gn,qe,pn,Kn};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ot,w,R,A}from"./chunk-7cgq9r40.js";import"./chunk-cfswsgdh.js";import"./chunk-vxh8ktv7.js";import"./chunk-wfk6y67h.js";import"./chunk-5b51gpqw.js";import"./chunk-xk3qn91x.js";export{R as executeMigration,w as generateMigration,A as resetDatabase,ot as saveMigrationSnapshot};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { config } from './config';
|
|
2
|
-
import { resetConnection } from './db';
|
|
2
|
+
import { resetConnection, resolveLibSQLTarget } from './db';
|
|
3
3
|
import type { AnyDatabaseSchema } from './schema';
|
|
4
4
|
import type { DeferredInsert } from './sqlite-deferred-inserts';
|
|
5
5
|
import type { DriverConnection } from './db';
|
|
@@ -731,4 +731,4 @@ declare class QueryCache {
|
|
|
731
731
|
clear(): void;
|
|
732
732
|
setMaxSize(size: number): void;
|
|
733
733
|
}
|
|
734
|
-
export { resetConnection };
|
|
734
|
+
export { resetConnection, resolveLibSQLTarget };
|
package/dist/config.d.ts
CHANGED
|
@@ -70,6 +70,15 @@ declare function mergeObject(target: Record<string, unknown>, source: Record<str
|
|
|
70
70
|
* carried were unreachable.
|
|
71
71
|
*/
|
|
72
72
|
export declare function resolveDialect(explicit?: string | null): SupportedDialect;
|
|
73
|
+
/**
|
|
74
|
+
* Collapse a connection name onto the dialect whose SQL it speaks.
|
|
75
|
+
*
|
|
76
|
+
* `turso` and `libsql` are SQLite behind a network transport (see
|
|
77
|
+
* `src/libsql.ts`): they render SQLite SQL and are reached through
|
|
78
|
+
* `database.url`, so as a DIALECT they are `sqlite`. `DB_CONNECTION=turso`
|
|
79
|
+
* otherwise arrived here verbatim and every dialect switch fell through.
|
|
80
|
+
*/
|
|
81
|
+
export declare function normalizeDialectName(name: string): SupportedDialect;
|
|
73
82
|
/**
|
|
74
83
|
* Get the placeholder format for the current dialect.
|
|
75
84
|
* PostgreSQL uses $1, $2, $3... while MySQL and SQLite use ?
|
package/dist/db.d.ts
CHANGED
|
@@ -85,6 +85,16 @@ export declare function resolvePoolOptions(pool?: PoolConfig): {
|
|
|
85
85
|
* For SQLite, uses bun:sqlite directly for better compiled binary support.
|
|
86
86
|
* Handles connection errors gracefully by falling back to in-memory SQLite.
|
|
87
87
|
*/
|
|
88
|
+
/**
|
|
89
|
+
* The libSQL server a sqlite-dialect config points at, or null for a file.
|
|
90
|
+
*
|
|
91
|
+
* libSQL is SQLite's SQL behind a network transport, so it is selected by the
|
|
92
|
+
* URL rather than by a dialect of its own: every grammar branch keyed on
|
|
93
|
+
* `sqlite` stays correct, and only the connection differs. `database.url`
|
|
94
|
+
* is the documented place; a URL in `database.database` is accepted too,
|
|
95
|
+
* since that slot is the "where is it" field for sqlite.
|
|
96
|
+
*/
|
|
97
|
+
export declare function resolveLibSQLTarget(dbConfig?: DatabaseConfig, dialect?: SupportedDialect): { url: string, authToken?: string } | null;
|
|
88
98
|
export declare function getBunSql(): SQL;
|
|
89
99
|
export declare function getOrCreateBunSql(forceNew?: boolean): SQL;
|
|
90
100
|
/**
|
package/dist/index.d.ts
CHANGED
package/dist/libsql.d.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import type { SQL } from 'bun';
|
|
2
|
+
/** True when a URL names a libSQL server rather than a local SQLite file. */
|
|
3
|
+
export declare function isLibSQLUrl(url: unknown): url is string;
|
|
4
|
+
/**
|
|
5
|
+
* Where the pipeline endpoint is, and the token a URL carried, if any.
|
|
6
|
+
*
|
|
7
|
+
* Exported for tests. The returned `baseUrl` has no credentials and no query
|
|
8
|
+
* string, so it is safe to put in an error message.
|
|
9
|
+
*/
|
|
10
|
+
export declare function resolveLibSQLEndpoint(url: string): { baseUrl: string, authToken?: string };
|
|
11
|
+
/** Turn a statement-level Hrana error into a SQLite-shaped `LibSQLError`. */
|
|
12
|
+
export declare function toLibSQLError(error: HranaError): LibSQLError;
|
|
13
|
+
/**
|
|
14
|
+
* Encode one bound value for Hrana.
|
|
15
|
+
*
|
|
16
|
+
* Matches what `bun:sqlite` binds, with two deliberate differences, both of
|
|
17
|
+
* which turn silent data loss into something visible:
|
|
18
|
+
* - a `Date` is sent as its ISO-8601 string (`bun:sqlite` binds NULL);
|
|
19
|
+
* - any other object throws (`bun:sqlite` binds NULL).
|
|
20
|
+
*/
|
|
21
|
+
export declare function encodeLibSQLValue(value: unknown): HranaValue;
|
|
22
|
+
/** Decode one Hrana value into what `bun:sqlite` would have returned. */
|
|
23
|
+
export declare function decodeLibSQLValue(value: HranaValue, largeIntegers?: LibSQLLargeIntegerMode): unknown;
|
|
24
|
+
export declare function toLibSQLRows(result: HranaStatementResult, largeIntegers?: LibSQLLargeIntegerMode): LibSQLRows;
|
|
25
|
+
/** Build a Hrana statement, rewriting `$n` to SQLite's positional `?`. */
|
|
26
|
+
export declare function toHranaStatement(sql: string, params?: LibSQLParams): HranaStatement;
|
|
27
|
+
/**
|
|
28
|
+
* Build a connection to a libSQL server with the surface of Bun's `SQL`.
|
|
29
|
+
*
|
|
30
|
+
* Nothing is sent until the first query.
|
|
31
|
+
*/
|
|
32
|
+
export declare function createLibSQLSQL(options: LibSQLConnectionOptions): SQL;
|
|
33
|
+
/** Whether a connection object was built by {@link createLibSQLSQL}. */
|
|
34
|
+
export declare function isLibSQLConnection(connection: unknown): boolean;
|
|
35
|
+
/** A statement as Hrana expects it. */
|
|
36
|
+
export declare interface HranaStatement {
|
|
37
|
+
sql: string
|
|
38
|
+
args?: HranaValue[]
|
|
39
|
+
named_args?: Array<{ name: string, value: HranaValue }>
|
|
40
|
+
want_rows?: boolean
|
|
41
|
+
}
|
|
42
|
+
declare interface HranaColumn {
|
|
43
|
+
name: string | null
|
|
44
|
+
decltype?: string | null
|
|
45
|
+
}
|
|
46
|
+
/** The result of one executed statement. */
|
|
47
|
+
export declare interface HranaStatementResult {
|
|
48
|
+
cols: HranaColumn[]
|
|
49
|
+
rows: HranaValue[][]
|
|
50
|
+
affected_row_count: number
|
|
51
|
+
last_insert_rowid: string | null
|
|
52
|
+
}
|
|
53
|
+
declare interface HranaError {
|
|
54
|
+
message: string
|
|
55
|
+
code?: string | null
|
|
56
|
+
}
|
|
57
|
+
declare interface HranaPipelineResponse {
|
|
58
|
+
baton: string | null
|
|
59
|
+
base_url: string | null
|
|
60
|
+
results: HranaStreamResult[]
|
|
61
|
+
}
|
|
62
|
+
export declare interface LibSQLConnectionOptions {
|
|
63
|
+
url: string
|
|
64
|
+
authToken?: string
|
|
65
|
+
timeoutMs?: number
|
|
66
|
+
largeIntegers?: LibSQLLargeIntegerMode
|
|
67
|
+
fetch?: typeof fetch
|
|
68
|
+
}
|
|
69
|
+
export declare interface LibSQLErrorDetails {
|
|
70
|
+
code: string
|
|
71
|
+
errno?: number
|
|
72
|
+
libsqlCode?: string
|
|
73
|
+
status?: number
|
|
74
|
+
cause?: unknown
|
|
75
|
+
}
|
|
76
|
+
/** One statement in a `batch()`. */
|
|
77
|
+
export declare interface LibSQLBatchStatement {
|
|
78
|
+
sql: string
|
|
79
|
+
args?: LibSQLParams
|
|
80
|
+
}
|
|
81
|
+
/** A Hrana value, as it appears on the wire. */
|
|
82
|
+
export type HranaValue = | { type: 'null' }
|
|
83
|
+
| { type: 'integer', value: string }
|
|
84
|
+
| { type: 'float', value: number }
|
|
85
|
+
| { type: 'text', value: string }
|
|
86
|
+
| { type: 'blob', base64: string }
|
|
87
|
+
declare type HranaRequest = | { type: 'execute', stmt: HranaStatement }
|
|
88
|
+
| { type: 'batch', batch: { steps: Array<{ stmt: HranaStatement, condition?: HranaCondition | null }> } }
|
|
89
|
+
| { type: 'get_autocommit' }
|
|
90
|
+
| { type: 'close' }
|
|
91
|
+
declare type HranaCondition = | { type: 'ok', step: number }
|
|
92
|
+
| { type: 'error', step: number }
|
|
93
|
+
| { type: 'not', cond: HranaCondition }
|
|
94
|
+
declare type HranaResponse = | { type: 'execute', result: HranaStatementResult }
|
|
95
|
+
| { type: 'batch', result: { step_results: Array<HranaStatementResult | null>, step_errors: Array<HranaError | null> } }
|
|
96
|
+
| { type: 'get_autocommit', is_autocommit: boolean }
|
|
97
|
+
| { type: 'close' }
|
|
98
|
+
declare type HranaStreamResult = | { type: 'ok', response: HranaResponse }
|
|
99
|
+
| { type: 'error', error: HranaError }
|
|
100
|
+
/** How integers beyond `Number.MAX_SAFE_INTEGER` are returned. */
|
|
101
|
+
export type LibSQLLargeIntegerMode = 'bigint' | 'string';
|
|
102
|
+
/**
|
|
103
|
+
* A query result in the shape the sqlite code paths read.
|
|
104
|
+
*
|
|
105
|
+
* Always an array of rows - empty for a statement that returns none - so a
|
|
106
|
+
* caller that destructures rows never gets a non-iterable. The write metadata
|
|
107
|
+
* rides along under every name a caller looks for it: `changes` and
|
|
108
|
+
* `lastInsertRowid` (bun:sqlite's `run()`), `count` (Bun's network drivers).
|
|
109
|
+
*/
|
|
110
|
+
export type LibSQLRows = Array<Record<string, unknown>> & {
|
|
111
|
+
changes: number
|
|
112
|
+
count: number
|
|
113
|
+
lastInsertRowid: number | bigint | string | null
|
|
114
|
+
columns: string[]
|
|
115
|
+
}
|
|
116
|
+
/** Positional or named parameters, as callers pass them. */
|
|
117
|
+
export type LibSQLParams = readonly unknown[] | Record<string, unknown>;
|
|
118
|
+
/**
|
|
119
|
+
* An error from a libSQL server or the transport to it.
|
|
120
|
+
*
|
|
121
|
+
* Carries `code`/`errno` in the shape `bun:sqlite`'s `SQLiteError` does, so a
|
|
122
|
+
* unique-violation check written for SQLite matches here too. Never carries
|
|
123
|
+
* the auth token: messages are built from the server's reply and the host.
|
|
124
|
+
*/
|
|
125
|
+
export declare class LibSQLError extends Error {
|
|
126
|
+
readonly code: string;
|
|
127
|
+
readonly errno?: number;
|
|
128
|
+
readonly libsqlCode?: string;
|
|
129
|
+
readonly status?: number;
|
|
130
|
+
constructor(message: string, details: LibSQLErrorDetails);
|
|
131
|
+
}
|
|
132
|
+
/** The HTTP side: one POST per pipeline, with transport errors made legible. */
|
|
133
|
+
declare class HranaHttp {
|
|
134
|
+
readonly baseUrl: string;
|
|
135
|
+
constructor(options: LibSQLConnectionOptions);
|
|
136
|
+
pipeline(baseUrl: string, baton: string | null, requests: HranaRequest[]): Promise<HranaPipelineResponse>;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* A server-side connection kept open across requests by its baton.
|
|
140
|
+
*
|
|
141
|
+
* A baton is good for exactly one request, so requests are chained: each waits
|
|
142
|
+
* for the previous reply. That also makes concurrent queries on one transaction
|
|
143
|
+
* handle safe - they queue instead of racing for the baton.
|
|
144
|
+
*/
|
|
145
|
+
declare class HranaStream {
|
|
146
|
+
closed: boolean;
|
|
147
|
+
constructor(http: HranaHttp, prelude: () => HranaRequest[]);
|
|
148
|
+
send(requests: HranaRequest[], options?: { close?: boolean }): Promise<HranaStreamResult[]>;
|
|
149
|
+
close(): Promise<void>;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Shared, per-connection state: the HTTP client, the session pragma, and the
|
|
153
|
+
* stream a raw BEGIN pinned the connection to.
|
|
154
|
+
*/
|
|
155
|
+
declare class LibSQLSession {
|
|
156
|
+
readonly http: HranaHttp;
|
|
157
|
+
readonly largeIntegers: LibSQLLargeIntegerMode;
|
|
158
|
+
foreignKeys: string | null;
|
|
159
|
+
pinned: HranaStream | null;
|
|
160
|
+
closed: boolean;
|
|
161
|
+
constructor(options: LibSQLConnectionOptions);
|
|
162
|
+
prelude: unknown;
|
|
163
|
+
openStream(): HranaStream;
|
|
164
|
+
assertOpen(): void;
|
|
165
|
+
rows(result: HranaStatementResult): LibSQLRows;
|
|
166
|
+
notePragma(sql: string): void;
|
|
167
|
+
execute(stmt: HranaStatement): Promise<LibSQLRows>;
|
|
168
|
+
close(): Promise<void>;
|
|
169
|
+
}
|
package/dist/src/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{fn,mn,hn,p,rt,it,gn,qe,pn,Kn}from"../chunk-xk3qn91x.js";export{rt as BrowserQueryBuilder,p as BrowserQueryError,pn as browserAuth,it as browserQuery,fn as configureBrowser,gn as createBrowserDb,qe as createBrowserModel,Kn as default,mn as getBrowserConfig,hn as isBrowser};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{J,x,kt,Qe,v,Ae,Ge,Je,Me,Ct,f,z,Ne,ze,Rt,Ye,zt,Yt}from"../../chunk-vxh8ktv7.js";export{J as DynamoDBClient,Ne as DynamoDBMigrationDriver,z as DynamoDBMigrationTracker,Ye as EntityQueryBuilder,f as MIGRATIONS_TABLE,Qe as Model,Me as buildDynamoDBMigrationPlan,kt as configureModels,Je as convertSchemaToDefinition,x as createClient,Yt as createDynamo,ze as createMigrationDriver,zt as dynamo,Ge as extractModelSchema,Ae as extractTableDefinition,v as hashTableDefinition,Ct as isDefinitionEqual,Rt as migrateModels};
|
package/dist/src/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{X,Z,ee,te,I,ne,re,ie,se,L,ae,K,F,oe,le,j,ce,ue,st,We,at,C,de,o,fe,me,he,ge,h,ot,w,R,A,pe,ye,q,be,W,Te,U,V,M,H,we,Se,De,Ee,Q,$e,xe,S,g,yn,bn,Tn,lt,ct,ut,dt,ft,wn,mt,Wt,Sn,Dn,En,$n,ht,xn,vn,kn,ve,d,gt,pt,yt,bt,Tt,Ut,G,ke,Cn,Rn,wt,Ue,y,Ve,He,Vt,An,Ht,Mn,St,Dt,Et,Qt,Gt}from"../chunk-7cgq9r40.js";import{E,Nn,Jt,c,$t,xt,i,Ce,Re}from"../chunk-cfswsgdh.js";import{vt,u,J,x,kt,Qe,v,Ae,Ge,Je,Me,Ct,f,z,Ne,ze,Rt,Ye,zt,Yt}from"../chunk-vxh8ktv7.js";import{At,Mt,Nt,Ot,On,Bn,Pn,Bt,Pt,_n,In,Xt,Zt,en,tn,nn,_t,rn,sn}from"../chunk-wfk6y67h.js";import{n,Xe,e,B,Ze,t,s,P,Pe,an,et,on,a,_e,It,Lt,ln,Ie,Kt,Ln,Ft,jt,k,_,cn,Ke,T,un,dn,m,nt}from"../chunk-5b51gpqw.js";import{fn,mn,hn,p,rt,it,gn,qe,pn}from"../chunk-xk3qn91x.js";export{Bt as BelongsToManyRelationBuilder,rt as BrowserQueryBuilder,p as BrowserQueryError,Ft as DEFAULT_SQLITE_PRAGMAS,J as DynamoDBClient,vt as DynamoDBDriverImpl,g as DynamoDBItemBuilder,Ne as DynamoDBMigrationDriver,z as DynamoDBMigrationTracker,S as DynamoDBQueryBuilder,ht as DynamoDBToolingAdapter,Ye as EntityQueryBuilder,yt as GENERATED_MARKER,a as LibSQLError,f as MIGRATIONS_TABLE,Qe as Model,o as MySQLDriver,fe as PostgresDriver,ge as SQLiteDriver,Ht as Seeder,me as SingleStoreDriver,lt as SingleTableManager,wn as SingleTablePatterns,ut as SingleTableQueryBuilder,ct as SingleTableRepository,y as UTC_CLOCK_DEFAULT,he as VitessDriver,k as applySqliteBootstrapPragmas,Qt as auditSchemaDrift,pn as browserAuth,it as browserQuery,ve as buildDatabaseSchema,Me as buildDynamoDBMigrationPlan,G as buildMigrationPlan,gt as buildSchemaMeta,Z as cacheClear,te as cacheConfig,ee as cacheStats,Ue as canonicalStorageType,Ve as canonicalizeDefault,$e as checkSchema,Mt as clearLocalModels,nn as clearModelRegistry,Ce as clearQueryCache,e as config,fn as configureBrowser,kt as configureModels,On as configureOrm,Je as convertSchemaToDefinition,gn as createBrowserDb,qe as createBrowserModel,x as createClient,Yt as createDynamo,Tn as createDynamoDBClient,u as createDynamoDBDriver,bn as createDynamoDBItemBuilder,yn as createDynamoDBQueryBuilder,xn as createDynamoDBToolingAdapter,At as createFakerCompatLayer,Kt as createLibSQLSQL,ze as createMigrationDriver,Pt as createModel,i as createQueryBuilder,ft as createRepository,dt as createSingleTableManager,_n as createTableFromModel,L as dbInfo,K as dbOptimize,ae as dbStats,F as dbWipe,Lt as decodeLibSQLValue,Xe as defaultConfig,an as defineConfig,rn as defineModel,An as defineModels,Mn as defineSeeder,se as dumpDatabase,zt as dynamo,It as encodeLibSQLValue,xt as escapeStringLiteral,R as executeMigration,oe as explain,U as explainAllQueries,re as exportData,Nt as extractChanges,Ot as extractInsertId,Ge as extractModelSchema,Ae as extractTableDefinition,St as familyOfDeclared,Dt as familyOfSqlType,le as file,Gt as formatSchemaDrift,Se as freshDatabase,vn as generateAccessPatterns,V as generateDiagram,He as generateDiffOperations,Vt as generateDiffSql,Rn as generateDiffSqlString,w as generateMigration,at as generateModelSource,ke as generateSql,Cn as generateSqlString,Zt as getAllModels,mn as getBrowserConfig,P as getConfig,Pn as getDatabase,h as getDialectDriver,Xt as getModel,en as getModelRegistry,t as getPlaceholder,s as getPlaceholders,tn as hasModel,wt as hashMigrationPlan,v as hashTableDefinition,ie as importData,dn as inflectSingular,j as inspectTable,ue as introspect,C as introspectDatabase,hn as isBrowser,Ct as isDefinitionEqual,bt as isGeneratedMigrationSql,Ln as isLibSQLConnection,et as isLibSQLUrl,Ut as isLosslessTypeChange,n as isMysqlLike,Nn as iterateAllPivots,pt as lastCreatedMigrationFiles,d as loadModels,de as makeModel,we as makeSeeder,En as marshallObject,pe as migrateGenerate,be as migrateList,Rt as migrateModels,ye as migrateRollback,q as migrateStatus,Tt as migrationBody,We as modelNameForTable,W as modelShow,Ze as normalizeDialectName,K as optimizeDatabase,Wt as parseStacksModels,Te as ping,U as queryExplainAll,c as quoteColumnForDialect,Jt as raw,sn as registerBrowserModels,_t as registerModel,V as relationDiagram,Bn as releaseOrm,cn as resetConnection,A as resetDatabase,B as resolveDialect,mt as resolveKeyPattern,on as resolveLibSQLEndpoint,_ as resolveLibSQLTarget,E as resolvePivot,jt as resolveSqlitePragmas,X as runBenchmark,H as runSeeder,M as runSeeders,Et as satisfies,ot as saveMigrationSnapshot,In as seedModel,Pe as setConfig,Re as setQueryCacheMaxSize,W as showModel,m as singularizerFor,De as sql,st as sqlTypeToAttr,kn as stacksModelToEntity,I as startConsole,un as stripTrailingS,ce as tableInfo,T as tableNameFor,$t as temporalLiteral,ne as tinker,nt as toDialectPlaceholders,Sn as toDynamoDBItem,Ie as toHranaStatement,_e as toLibSQLError,ln as toLibSQLRows,Dn as toModelInstance,Ke as toTableName,$n as unmarshallItem,Ee as unsafe,Q as validateSchema,xe as waitReady,F as wipeDatabase};
|
package/dist/src/runtime.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{n,
|
|
2
|
+
import{n,Xe,e,B,Ze,t,s,P,Pe,an,Ft,jt,k,_,cn}from"../chunk-5b51gpqw.js";import{Jt,c,$t,xt,i,Ce,Re}from"../chunk-cfswsgdh.js";export{Ft as DEFAULT_SQLITE_PRAGMAS,k as applySqliteBootstrapPragmas,Ce as clearQueryCache,e as config,i as createQueryBuilder,Xe as defaultConfig,an as defineConfig,xt as escapeStringLiteral,P as getConfig,t as getPlaceholder,s as getPlaceholders,n as isMysqlLike,Ze as normalizeDialectName,c as quoteColumnForDialect,Jt as raw,cn as resetConnection,B as resolveDialect,_ as resolveLibSQLTarget,jt as resolveSqlitePragmas,Pe as setConfig,Re as setQueryCacheMaxSize,$t as temporalLiteral};
|
package/dist/types.d.ts
CHANGED
package/package.json
CHANGED