bun-query-builder 0.3.3 → 0.3.5

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.
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{n,e,t,s,Pe,b,r,m,qt,D,l,Y,Fe,je}from"./chunk-455vt4nn.js";function Qt(p){return m(e.relations?.singularizeStrategy)(p)}function E(p,B,w,H={}){let re=H.singularize??Qt,ae=p.relations?.[B]?.belongsToMany?.[w];if(ae==null)return null;let Ee=typeof ae==="object",pe=Ee?ae:null,me=Ee?pe.model:ae,Ue=p.modelToTable[me]||me,He,Ze;if(pe?.table)He=pe.table;else if(pe?.through){if(Ze=pe.through,He=p.modelToTable[pe.through],!He)throw Error(`[query-builder] belongsToMany relation '${w}' on '${B}' references unknown through model '${pe.through}'. Make sure '${pe.through}' is registered via defineModels({...}).`)}else{let Je=re(B),T=re(Ue);He=[Je,T].sort().join("_")}let et=pe?.foreignKey??`${re(B)}_id`,lt=pe?.relatedKey??`${re(Ue)}_id`,te={};if(pe?.pivot?.columns)Object.assign(te,pe.pivot.columns);if(Ze&&H.models){let Je=H.models[Ze],T=Je?.definition??Je?.getDefinition?.()??Je,g=T?.attributes??{};for(let[d,y]of Object.entries(g)){if(d===et||d===lt||d===(T?.primaryKey??"id"))continue;te[d]={default:y?.default,nullable:y?.nullable,validation:y?.validation}}}let Le=Boolean(pe?.pivot?.timestamps),Ie=Object.keys(te);return{pivotTable:He,fkParent:et,fkRelated:lt,pivotColumns:Ie,pivotColumnDefs:te,pivotModelName:Ze,timestamps:Le,relatedModelName:me,relatedTable:Ue,hasConfig:Ee}}function*Nn(p,B={}){let w=p.relations;if(!w)return;for(let[H,re]of Object.entries(w)){let A=re?.belongsToMany;if(!A)continue;for(let ae of Object.keys(A)){let Ee=E(p,H,ae,B);if(Ee)yield{parentTable:H,relationKey:ae,resolved:Ee}}}}import{Buffer as pt}from"buffer";import{serialize as vt}from"v8";function We(p){return typeof p==="object"&&p!==null&&"raw"in p&&typeof p.raw==="string"}function bt(p,B,w){if(Array.isArray(B)){let re=s(B.length,w.length+1),A=l(p,B,!1,re);return w.push(...B),A}let H=`${p} = ${t(w.length+1)}`;return w.push(B),H}function Ve(p){return typeof p==="object"&&p!==null&&"sql"in p&&typeof p.sql==="string"&&(!("parameters"in p)||Array.isArray(p.parameters))}function Mt(p,B){let[w,...H]=B;if(H.length>0||w!==void 0&&!Array.isArray(w))throw TypeError("[query-builder] db.raw(sql, bindings): pass the bindings as one array, db.raw('a = ? AND b = ?', [a, b]).");let re={sql:p,parameters:[...w??[]]};return Object.defineProperty(re,"then",{enumerable:!1,value:(A,ae)=>{let Ee=TypeError("[query-builder] db.raw(sql, bindings) builds a fragment for set() or where(), not a query. Run SQL with db.unsafe(sql, params).");if(typeof ae==="function")return ae(Ee);throw Ee}}),re}function at(p){return p instanceof Promise&&typeof p.execute==="function"&&typeof p.cancel==="function"}function ot(p){throw TypeError(`[query-builder] ${p}: a Bun \`sql\`...\`\` query cannot be used as a fragment, because its SQL text is not readable. Bind values with db.raw('name = ?', [value]) or { sql, parameters }, or use the exported \`raw\` tagged template.`)}function Ge(p,B){let w=p.parameters??(Array.isArray(p.values)?p.values:[]);if(e.dialect!=="postgres"||w.length===0)return{text:p.sql,parameters:w};let H=0,{text:re}=Fe(p.sql,()=>H<w.length?t(B+H++):void 0);if(H!==w.length)throw TypeError(`[query-builder] SQL expression declares ${w.length} parameters but contains only ${H} placeholders`);return{text:re,parameters:w}}function Et(p,B){if(B.length===2){let[w,H]=B;if(Array.isArray(H)&&typeof w==="number"&&H[w]===p)return!1;if(H instanceof Set&&w===p&&H.has(p))return!1;if(H instanceof Map&&H.get(w)===p)return!1}return B.some((w)=>w!==void 0&&!(Array.isArray(w)&&w.length===0))}function Jt(p,...B){if(typeof p==="string"){if(!(B.length===1&&Number.isInteger(B[0])&&B[0]>=0&&!p.includes("?"))&&Et(p,B))throw TypeError("[query-builder] raw(string) takes no values, so the argument(s) after the string would be dropped. Use raw as a tagged template instead, which interpolates each value as an escaped literal.");return{raw:p}}let w=p[0];for(let H=0;H<B.length;H++)w+=_e(B[H])+p[H+1];return{raw:w}}function De(p){return n(e.dialect)?`\`${p.replace(/`/g,"``")}\``:`"${p.replace(/"/g,'""')}"`}function ht(p,B=1){let w=Object.keys(p[0]??{}),H=[],re=B,A=p.map((ae)=>`(${w.map((pe)=>(H.push(ae[pe]),t(re++))).join(", ")})`);return{colsSql:w.map(De).join(", "),valuesSql:A.join(", "),params:H,nextIndex:re}}function it(p){return Boolean(p&&(p.onSlowQuery||p.slowQueryThresholdMs!=null&&p.slowQueryThresholdMs>=0))}function c(p,B=e.dialect){if(!n(B))return p;let w=/^([A-Z_][\w$]*)(?:\.([A-Z_][\w$]*))?(?:\s+as\s+([A-Z_][\w$]*))?$/i.exec(p.trim());if(!w)return p;let[,H,re,A]=w,ae=re?`\`${H}\`.\`${re}\``:`\`${H}\``;return A?`${ae} AS \`${A}\``:ae}function $t(p,B=e.dialect){if(!n(B)||p===null||p===void 0)return p;if(typeof p==="string"){let w=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(p);if(!w)return p;let[,H,re]=w;return`${H} ${re.length===5?`${re}:00`:re}`}if(!(p instanceof Date)||Number.isNaN(p.getTime()))return p;return p.toISOString().replace("T"," ").replace(/\.\d+Z$/,"")}function wt(p){if(typeof p==="string")return c(p);if(We(p))return p.raw;if(p&&typeof p==="object"){let B=p;if(typeof B.raw==="function")return String(B.raw());if(typeof B.sql==="string")return B.sql;let w=String(p);if(w!=="[object Object]")return w}throw TypeError(`[query-builder] select(): unsupported column ${String(p)} \u2014 pass a column name, a string[], or a SQL fragment (e.g. sql\`count(*) as c\`)`)}function Wt(p){let B=/\(|\)|\bORDER\s+BY\b/gi,w=0,H;while(H=B.exec(p))if(H[0]==="(")w++;else if(H[0]===")")w=Math.max(0,w-1);else if(w===0)return!0;return!1}var ye={SELECT_STAR:/^SELECT\s+\*/i,SELECT:/^SELECT\s+/i,SELECT_FROM:/^SELECT\s+(.+?)\s+FROM/i,WHERE:/\bWHERE\b/i,ORDER_BY:/\bORDER\s+BY\b/i,GROUP_BY:/\bGROUP\s+BY\b/i,LIMIT:/\sLIMIT\s+\d+/i,OFFSET:/\sOFFSET\s+\d+/i,IDENTIFIER:/^[A-Z_][\w.]*$/i,DELETED_AT:/\bdeleted_at\b/i},St=new Set(["=","!=","<>","<","<=",">",">=","like","not like","ilike","not ilike","in","not in","is","is not","between","not between"]);function F(p,B){if(!ye.IDENTIFIER.test(p)){let w=B?` in ${B}`:"";throw Error(`[query-builder] Invalid identifier${w}: '${p}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`)}}function $e(p,B){if(typeof p!=="string")throw TypeError(`[query-builder] ${B}: operator must be a string, got ${typeof p}`);let w=p.toLowerCase();if(!St.has(w))throw TypeError(`[query-builder] ${B}: refusing to use '${p}' as a SQL operator \u2014 not in the allowed set (${[...St].join(", ")})`);return p}function xe(p,B){if(typeof p!=="string"||p.length===0)throw TypeError(`[query-builder] ${B}: identifier must be a non-empty string, got ${typeof p}`);if(p.length>129)throw TypeError(`[query-builder] ${B}: identifier '${p}' too long`);let w=p.split(".");if(w.length>2)throw TypeError(`[query-builder] ${B}: identifier '${p}' has more than one dot \u2014 only \`table.column\` is allowed`);for(let H of w)if(!/^[A-Z_][A-Z0-9_]*$/i.test(H))throw TypeError(`[query-builder] ${B}: identifier segment '${H}' contains characters outside [A-Za-z0-9_]`)}function Ye(p,B,w=[]){let H=typeof p==="object"&&p!==null?p.parameters??p.values:void 0;if(Et(p,w)||Array.isArray(H)&&H.length>0){let re=B.startsWith("whereRaw(")?", or use where(). Model.query().whereRaw(sql, ...bindings) is the builder that binds `?` values.":B.startsWith("orWhereRaw(")?", or use orWhere(). Model.query().orWhereRaw(sql, ...bindings) is the builder that binds `?` values.":".";throw TypeError(`[query-builder] ${B}: this method takes a single fragment and no bindings, so the argument(s) after it would be dropped. Interpolate values with the exported \`raw\` tagged template, which inlines them as escaped literals${re}`)}if(typeof p==="string")return Kt(B),p;if(p===null||p===void 0)throw TypeError(`[query-builder] ${B}: fragment must be a SqlFragment, got ${p}`);if(We(p))return p.raw;if(typeof p==="object"){let re=p;if(typeof re.raw==="string")return re.raw;if(typeof re.raw==="function"){let ae=re.raw();if(typeof ae==="string")return ae}if(typeof re.sql==="string")return re.sql;let A=String(p);if(A!=="[object Object]"&&A!=="[object Promise]")return A}throw TypeError(`[query-builder] ${B}: cannot render this value as a SQL fragment. `+"A Bun `sql`...`` query object cannot be converted to SQL text \u2014 pass a "+"string, or use the exported `raw` helper: raw`count(*) as c` / raw('age > 18').")}function Ft(p,B){if(!B||B.length===0)return;if(e.dialect!=="postgres")return;if(/\$\d/.test(p))return;let w=Y(p),H=`${B.length} binding${B.length===1?"":"s"}`,re=w>0?`the query binds them with ${w} \`?\` placeholder${w===1?"":"s"}, which Postgres reads as an operator rather than a parameter`:"the query contains no $n placeholder for them to bind to";throw TypeError(`[query-builder] unsafe(): ${H} supplied, but ${re}. Postgres numbers `+"its parameters, so write $1, $2 \u2026 in the order the bindings should bind: "+"unsafe('SELECT * FROM users WHERE email = $1 LIMIT 1', [email]). `?` is correct on SQLite and MySQL, which is why this call may work there.")}var Bt=new Set;function Kt(p){if(Bt.has(p))return;Bt.add(p),console.warn(`[query-builder] ${p}: bare string passed to a *Raw method. Prefer the \`raw\`...\`\` tagged template, which escapes interpolated `+"values for the configured dialect \u2014 concatenating request input into SQL "+"is an injection vector. This will become a hard error in a future release.")}function xt(p,B=e.dialect){return n(B)?p.replace(/\\/g,"\\\\").replace(/'/g,"''"):p.replace(/'/g,"''")}function _e(p){if(p===null)return"NULL";if(typeof p==="number"&&Number.isFinite(p))return String(p);if(typeof p==="boolean")return p?"1":"0";if(typeof p==="string")return`'${xt(p)}'`;if(p instanceof Date)return`'${p.toISOString()}'`;throw TypeError(`[query-builder] subquery condition: refusing to interpolate value of type ${typeof p}`)}function _t(p,B){let w=Array.isArray(p)?p:p?[p]:[],H=[];if(w.length)H.push(`PARTITION BY ${w.join(", ")}`);if(B&&B.length)H.push(`ORDER BY ${B.map(([re,A])=>`${re} ${A==="desc"?"DESC":"ASC"}`).join(", ")}`);return H.length?`OVER (${H.join(" ")})`:"OVER ()"}class Rt{cache=new Map;maxSize=100;get(p){let B=this.cache.get(p);if(!B)return null;if(Date.now()>B.expiresAt)return this.cache.delete(p),null;return this.cache.delete(p),this.cache.set(p,B),B.data}set(p,B,w){if(this.cache.has(p))this.cache.delete(p);if(this.cache.size>=this.maxSize){let H=Date.now(),re=!1;for(let[A,ae]of this.cache)if(H>ae.expiresAt){if(this.cache.delete(A),re=!0,this.cache.size<this.maxSize)break}if(!re){let A=this.cache.keys().next().value;if(A!==void 0)this.cache.delete(A)}}this.cache.set(p,{data:B,expiresAt:Date.now()+w})}clear(){this.cache.clear()}setMaxSize(p){this.maxSize=Math.max(0,Math.floor(p));while(this.cache.size>this.maxSize){let B=this.cache.keys().next().value;if(B===void 0)break;this.cache.delete(B)}}}var ft=new Rt,Dt=new WeakMap,jt=0;function Ut(p,B,w){let H=Dt.get(p);if(H===void 0)H=++jt,Dt.set(p,H);let re=w.map((A)=>ArrayBuffer.isView(A)?["view",pt.isBuffer(A)?"Buffer":Object.prototype.toString.call(A),pt.from(A.buffer,A.byteOffset,A.byteLength).toString("base64")]:["value",vt(A).toString("base64")]);return`${H}\x00${B}\x00${JSON.stringify(re)}`}function Ht(p){let B=String(p?.message||"").toLowerCase();return B.includes("deadlock")||B.includes("serialization failure")||B.includes("could not serialize access")||B.includes("deadlock found when trying to get lock")||B.includes("lock wait timeout exceeded")||B.includes("database is locked")||B.includes("busy")}function Vt(p,B){if(!B||B.length===0)return!1;let w=p&&(p.code||p.sqlState||p.sqlstate);if(!w)return!1;return B.includes(w)}function Gt(p){return new Promise((B)=>setTimeout(B,p))}var gt=new Map,Yt=500,zt=[{key:"GROUP_BY",pattern:/GROUP\s+BY\b/iy},{key:"ORDER_BY",pattern:/ORDER\s+BY\b/iy},{key:"HAVING",pattern:/HAVING\b/iy},{key:"OFFSET",pattern:/OFFSET\b/iy},{key:"LIMIT",pattern:/LIMIT\b/iy},{key:"WHERE",pattern:/WHERE\b/iy}],Xt=[{key:"tail",pattern:/GROUP\s+BY\b/iy},{key:"tail",pattern:/ORDER\s+BY\b/iy},{key:"tail",pattern:/HAVING\b/iy},{key:"tail",pattern:/LIMIT\b/iy},{key:"tail",pattern:/OFFSET\b/iy},{key:"tail",pattern:/WINDOW\b/iy},{key:"tail",pattern:/UNION\b/iy},{key:"tail",pattern:/INTERSECT\b/iy},{key:"tail",pattern:/EXCEPT\b/iy},{key:"tail",pattern:/FOR\s+UPDATE\b/iy},{key:"tail",pattern:/FOR\s+SHARE\b/iy},{key:"tail",pattern:/LOCK\s+IN\s+SHARE\s+MODE\b/iy}],Zt=[{key:"cut",pattern:/GROUP\s+BY\b/iy},{key:"cut",pattern:/ORDER\s+BY\b/iy},{key:"cut",pattern:/WHERE\b/iy},{key:"cut",pattern:/HAVING\b/iy},{key:"cut",pattern:/LIMIT\b/iy},{key:"cut",pattern:/OFFSET\b/iy},{key:"cut",pattern:/UNION\b/iy}];function Xe(p){let B=gt.get(p);if(B!==void 0)return B;let w=en(p);if(gt.size>=Yt)gt.clear();return gt.set(p,w),w}function en(p){let B=je(p,zt);if(B.length<=1)return p;let w=p.slice(0,B[0].start).trimEnd(),H={};for(let ae=0;ae<B.length;ae++){let Ee=B[ae].start,pe=ae+1<B.length?B[ae+1].start:p.length,me=p.slice(Ee,pe).trim();if(!H[B[ae].key])H[B[ae].key]=[];H[B[ae].key].push(me)}let A=["WHERE","GROUP_BY","HAVING","ORDER_BY","LIMIT","OFFSET"].filter((ae)=>H[ae]).map((ae)=>H[ae].join(" ")).join(" ");return A?`${w} ${A}`:w}function tn(p,B){let w=Math.max(1,B?.baseMs??50),H=Math.max(1,B?.factor??2),re=Math.max(w,B?.maxMs??2000),A=Math.min(re,w*H**Math.max(0,p-1));if(B?.jitter)A=Math.min(re,A*(0.9+Math.random()*0.2));return Math.floor(A)}function i(p){let B=p?.sql??b(),w=p?.meta,H=p?.schema,re;function A(T,g){let d=B.unsafe(T,g);if(typeof d.sql!=="string")re??=new WeakMap,re.set(d,{sql:T,params:g?.slice()});return d}let ae,Ee=(T,g)=>{let d=w?.temporalColumns?.[T];if(!d||d.length===0||!n(e.dialect))return g;return g.map((y)=>{let I=null;for(let f of d){if(!(f in y))continue;let z=$t(y[f]);if(z!==y[f])I=I??{...y},I[f]=z}return I??y})};function pe(T){if(typeof T==="number")return T;let g=String(T),d=7;for(let y=0;y<g.length;y++)d=d*31+g.charCodeAt(y)|0;return Math.abs(d)}function me(){if(!p?.hooks)return e.hooks;return{...e.hooks,...p.hooks}}let Ue=new Map;function He(T){if(Array.isArray(T)){let[f,z,v]=T;F(f,"where(column)");let K=String(f);switch(z){case"in":if(Array.isArray(v)){let q=s(v.length);return A(`${K} IN (${q})`,v)}return A(`${K} IN (${t(1)})`,[v]);case"not in":if(Array.isArray(v)){let q=s(v.length);return A(`${K} NOT IN (${q})`,v)}return A(`${K} NOT IN (${t(1)})`,[v]);case"like":return A(`${K} LIKE ${t(1)}`,[v]);case"is":case"is not":{if(v!==null&&v!==void 0)throw TypeError(`[query-builder] where(..., '${z}', ?): operator '${z}' only accepts NULL/undefined as value, got ${typeof v} (${String(v)})`);return A(`${K} IS ${z==="is not"?"NOT ":""}NULL`)}case"!=":return A(`${K} <> ${t(1)}`,[v]);case"<":case">":case"<=":case">=":case"=":return A(`${K} ${z} ${t(1)}`,[v]);default:throw TypeError(`[query-builder] where(..., '${String(z)}', ?): unsupported operator. Allowed: =, !=, <>, <, <=, >, >=, like, in, not in, is, is not`)}}if("raw"in T)return T.raw;let g=Object.keys(T);if(g.length===0)return A("");let d=[],y=[],I=1;for(let f of g){F(f,"where(object key)");let z=T[f];if(Array.isArray(z)){let v=s(z.length,I);d.push(`${f} IN (${v})`),y.push(...z),I+=z.length}else d.push(`${f} = ${t(I++)}`),y.push(z)}return A(d.join(" AND "),y)}function Ze(T,g,d){if(!d)return g;let y=He(d);return B`${g} WHERE ${y}`}function et(T){let g=re?.get(T);if(g)return g.sql;let d=e.debug?.captureText;if(e.debug)e.debug.captureText=!0;let y=String(T);if(e.debug)e.debug.captureText=d;return y}function lt(T){let g=re?.get(T);if(g)return g.params;if(!T||typeof T!=="object")return;if(Array.isArray(T.values))return T.values;if(Array.isArray(T.parameters))return T.parameters;if(Array.isArray(T.params))return T.params;return}function te(T,g,d){let y=me(),I=y?.slowQueryThresholdMs,f=I!=null&&I>=0,z=Boolean(y?.onSlowQuery||f),v=y&&(y.onQueryStart||y.onQueryEnd||y.onQueryError||y.startSpan||z),K=d?.timeoutMs&&d.timeoutMs>0||d?.signal;if(!v&&!K)return T.execute();let q=et(T),R=lt(T),J=Date.now(),k;try{if(y?.onQueryStart?.({sql:q,params:R,kind:g}),y?.startSpan)k=y.startSpan({sql:q,params:R,kind:g})}catch{}let N=!1,V=(_,G,Q=Boolean(_))=>{if(N)return;N=!0;let j=Date.now()-J;try{if(Q)y?.onQueryError?.({sql:q,params:R,error:_,durationMs:j,kind:g});else if(y?.onQueryEnd?.({sql:q,params:R,durationMs:j,rowCount:G,kind:g}),f&&j>=I)if(y?.onSlowQuery)y.onSlowQuery({sql:q,params:R,durationMs:j,kind:g});else console.warn(`[query-builder] slow query (${j}ms >= ${I}ms): ${q}`)}catch{}try{k?.end(_)}catch{}};if(typeof T.executeSync==="function"){let _,G,Q=!1;try{_=T.executeSync()}catch(ee){G=ee,Q=!0}if(d?.signal?.aborted){try{T.cancel?.()}catch{}G=Object.assign(Error("Query aborted"),{code:"EBQBABORT"}),Q=!0}if(Q)return V(G,void 0,!0),Promise.reject(G);let j=Array.isArray(_)?_.length:typeof _==="number"?_:void 0;return V(void 0,j),Promise.resolve(_)}let W=T.execute(),U=[W],X;if(d?.timeoutMs&&d.timeoutMs>0){let _=new Promise((G,Q)=>{X=setTimeout(()=>{try{T.cancel?.()}catch{}let j=Error(`Query timed out after ${d.timeoutMs}ms`);j.code="EBQBTIMEOUT",Q(j)},d.timeoutMs)});U.push(_)}if(d?.signal){if(d.signal.aborted){try{T.cancel?.()}catch{}let G=Error("Query aborted");return G.code="EBQBABORT",V(G),Promise.reject(G)}let _=()=>{try{T.cancel?.()}catch{}};d.signal.addEventListener("abort",_,{once:!0}),W.finally(()=>{d.signal?.removeEventListener("abort",_)})}return Promise.race(U).then((_)=>{clearTimeout(X);let G=Array.isArray(_)?_.length:typeof _==="number"?_:void 0;return V(void 0,G),_}).catch((_)=>{throw clearTimeout(X),V(_),_})}function Le(T){if(typeof T==="number")return Number.isFinite(T)?T:0;if(typeof T==="bigint")return Number(T);if(!T||typeof T!=="object")return 0;let g=T;for(let d of["changes","affectedRows","count","rowCount","numAffectedRows","numUpdatedRows","numDeletedRows","numInsertedOrUpdatedRows"])if(g[d]!==void 0&&g[d]!==null)return Le(g[d]);if(Array.isArray(T))return T.reduce((d,y)=>d+Le(y),0);return 0}function Ie(T,g){let d=g??et(T);return{sql:d,toString:()=>d,execute:()=>T.execute(),values:()=>T.values(),raw:()=>T.raw()}}function Je(T,g){let d=B,y=g&&g.length>0?`SELECT ${g.join(", ")} FROM ${String(T)}`:`SELECT * FROM ${String(T)}`,I=[],f=[],z=!1,v=!1,K=!1,q=null,R=()=>{if(q===null){let a=Xe(W());q=f.length>0?A(a,f):A(a)}return q},J=(a="",o="",u=[])=>A(`${a}${Xe(W())}${o}`,[...f,...u]),k=(a,o)=>{I.push({conn:a,sql:o}),q=null},N=(a,o)=>{k(a==="OR"?"OR":"AND",o)},V=(a)=>{let o=je(a,Xt,1);return o.length>0?o[0].start:-1},W=(a)=>{let o=D(a?[...I,a]:I);if(!o)return y;if(z)return`${y} ${v?"AND":"WHERE"} ${o}`;let u=V(y);return u>=0?`${y.slice(0,u)}WHERE ${o} ${y.slice(u)}`:`${y} WHERE ${o}`},U=(a,o)=>{let u=Je(T);o(u);let h=u.__whereState?.();if(!h||!h.body)throw TypeError("[query-builder] whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");let S=f.length,O=S>0&&e.dialect==="postgres"?h.body.replace(/\$(\d+)/g,(P,L)=>`$${Number(L)+S}`):h.body;f.push(...h.params),k(a,`(${O})`)},X=(a,o,u,h,S,O)=>{if(typeof h==="string"&&S!==void 0){F(String(h),`${u}(column)`),$e(S,`${u}(operator)`);let P=f.length+1;return f.push(O),k(o,`${String(h)} ${String(S)} ${t(P)}`),a}if(Array.isArray(h)){let[P,L,M]=h,x=String(P);F(x,`${u}(column)`);let C=$e(L,`${u}(operator)`);if(C==="in"||C==="not in"){let Z=Array.isArray(M)?M:[M],oe=s(Z.length,f.length+1),we=l(c(x),Z,C==="not in",oe);f.push(...Z),k(o,we)}else{let Z=f.length+1;f.push(M),k(o,`${x} ${C} ${t(Z)}`)}return a}if(typeof h==="function")return U(o,h),a;if(at(h))ot(`${u}(expr)`);if(Ve(h)){let P=Ge(h,f.length+1);return f.push(...P.parameters),k(o,P.text),a}if(h&&typeof h==="object"&&!("raw"in h)){let P=[];for(let L of Object.keys(h)){F(L,`${u}(column)`);let M=h[L];if(Array.isArray(M)){let x=s(M.length,f.length+1);P.push(l(c(L),M,!1,x)),f.push(...M)}else{let x=f.length+1;P.push(`${L} = ${t(x)}`),f.push(M)}}if(P.length>0)k(o,P.length>1?`(${P.join(" AND ")})`:P[0]);return a}if(h&&typeof h.raw<"u")return k(o,h.raw),a;return a},_=(a,o)=>{if(I.length>0)y=W(),I.length=0;z=!0;let u=o.__rawState?.();if(u){let h=f.length,S=e.dialect==="postgres"?u.sql.replace(/\$(\d+)/g,(O,P)=>`$${Number(P)+h}`):u.sql;y+=` ${a} ${S}`,f.push(...u.params),v=o.__hasPredicate?.()??ye.WHERE.test(S)}else{let h=String(o.toSQL());y+=` ${a} ${h}`,v=o.__hasPredicate?.()??ye.WHERE.test(h)}q=null},G=(a)=>{let o=je(y,Zt,1),u=o.length>0?o[0].start:-1;y=u>=0?`${y.slice(0,u)}${a} ${y.slice(u)}`:`${y} ${a}`,q=null},Q=new Set,j,ee,se=!1,ce=!1,Te=!1,qe=new Map,ke=new Set,ut=60000,ge=(a)=>m(e.relations.singularizeStrategy)(a),Qe=(a)=>{if(!w)return null;return E(w,String(T),a,{singularize:ge,models:w.models})},Ke=(a)=>{if(!a||typeof a!=="object"||ke.size===0)return a;let o;for(let u of Object.keys(a))if(u.startsWith("pivot_")){if(!o)o={};o[u.slice(6)]=a[u],delete a[u]}if(o)a.pivot=o;return a},tt=(a)=>{if(ke.size===0||!a)return a;if(Array.isArray(a))for(let o=0;o<a.length;o++)Ke(a[o]);else Ke(a);return a},nt=(a)=>{if(!w)return;if(Q.has(a.pivotTable))return;let o=String(T),u=w.primaryKeys[o]??"id";F(a.pivotTable,"wherePivot auto-join (pivot table)"),F(a.fkParent,"wherePivot auto-join (parent FK)"),F(o,"wherePivot auto-join (parent table)"),F(u,"wherePivot auto-join (parent PK)"),q=d`${R()} LEFT JOIN ${d(a.pivotTable)} ON ${d(`${a.pivotTable}.${a.fkParent}`)} = ${d(`${o}.${u}`)}`,y=`${y} LEFT JOIN ${a.pivotTable} ON ${a.pivotTable}.${a.fkParent} = ${o}.${u}`,Q.add(a.pivotTable)},rt=(a)=>{if(ye.SELECT_STAR.test(y))y=y.replace(ye.SELECT_STAR,`SELECT *, ${a}`);else if(ye.SELECT.test(y))y=y.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);let o=String(R());if(ye.SELECT_STAR.test(o)){let u=o.replace(ye.SELECT_STAR,`SELECT *, ${a}`);q=A(u)}else if(ye.SELECT.test(o)){if(ye.SELECT_FROM.exec(o)){let h=o.replace(ye.SELECT_FROM,`SELECT $1, ${a} FROM`);q=A(h)}}},ve=(a,o,u,h)=>{rt(`${a} ${_t(u,h)} AS ${o}`)},ct=(a,o,u,h)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${a.endsWith("s")?a.slice(0,-1):a}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${S} = ${a}.${u}`;if(h){let L=h({where:(M,x,C)=>(F(M,"relationship subquery condition"),`${o}.${M} ${$e(x,"whereHas callback")} ${_e(C)}`)});if(L)O+=` AND ${L}`}return O},dt=(a,o,u,h)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)");let S=`${o.endsWith("s")?o.slice(0,-1):o}_id`;F(S,"relationship subquery (foreign key)");let O=`SELECT 1 FROM ${o} WHERE ${o}.${u} = ${a}.${S}`;if(h){let L=h({where:(M,x,C)=>(F(M,"relationship subquery condition"),`${o}.${M} ${$e(x,"whereHas callback")} ${_e(C)}`)});if(L)O+=` AND ${L}`}return O},yt=(a,o,u,h,S,O)=>{F(a,"relationship subquery (parent table)"),F(o,"relationship subquery (target table)"),F(u,"relationship subquery (primary key)"),F(h,"relationship subquery (target primary key)");let P=O&&w?E(w,a,O,{singularize:ge,models:w.models}):null,L=ge(a),M=ge(o),x=P?.pivotTable??[L,M].sort().join("_"),C=P?.fkParent??`${L}_id`,Z=P?.fkRelated??`${M}_id`;F(x,"relationship subquery (pivot table)"),F(C,"relationship subquery (foreign key A)"),F(Z,"relationship subquery (foreign key B)");let oe=`SELECT 1 FROM ${x} JOIN ${o} ON ${o}.${h} = ${x}.${Z} WHERE ${x}.${C} = ${a}.${u}`;if(S){let ne=S({where:(Se,Oe,Ne)=>(F(Se,"relationship subquery condition"),`${o}.${Se} ${$e(Oe,"whereHas callback")} ${_e(Ne)}`)});if(ne)oe+=` AND ${ne}`}return oe},kt=(a,o,u)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let h=`${a.endsWith("s")?a.slice(0,-1):a}_id`;return F(h,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${o} WHERE ${o}.${h} = ${a}.${u})`},Ot=(a,o,u,h)=>{F(a,"withCount (parent table)"),F(o,"withCount (target table)"),F(u,"withCount (primary key)");let S=h&&w?E(w,a,h,{singularize:ge,models:w.models}):null,O=ge(a),P=ge(o),L=S?.pivotTable??[O,P].sort().join("_"),M=S?.fkParent??`${O}_id`;return F(L,"withCount (pivot table)"),F(M,"withCount (foreign key)"),`(SELECT COUNT(*) FROM ${L} WHERE ${L}.${M} = ${a}.${u})`},Tt=(a,o,u)=>{if(!w)return;F(u,`with${a[0]}${a.slice(1).toLowerCase()} (column)`);let h=String(T),S=w.relations?.[h];if(!S)return;let O=Object.entries(S).find(([ne,Se])=>Se&&typeof Se==="object"&&(o in Se));if(!O)return;let[P,L]=O,M=L[o],x=typeof M==="string"?M:M?.model||M?.target||M,C=w.modelToTable[x]||x,Z=w.primaryKeys[h]??"id";F(C,`with${a} (target table)`);let oe=`${a}(${C}.${u})`,we;if(P==="hasMany"||P==="hasOne"){let ne=`${h.endsWith("s")?h.slice(0,-1):h}_id`;F(ne,`with${a} (foreign key)`),we=`(SELECT ${oe} FROM ${C} WHERE ${C}.${ne} = ${h}.${Z})`}else if(P==="belongsToMany"){let ne=w?E(w,h,o,{singularize:ge,models:w.models}):null,Se=ge(h),Oe=ge(C),Ne=ne?.pivotTable??[Se,Oe].sort().join("_"),Be=ne?.fkParent??`${Se}_id`,ie=ne?.fkRelated??`${Oe}_id`,st=w.primaryKeys[C]??"id";F(Ne,`with${a} (pivot table)`),F(Be,`with${a} (foreign key)`),F(ie,`with${a} (related key)`),we=`(SELECT ${oe} FROM ${Ne} JOIN ${C} ON ${C}.${st} = ${Ne}.${ie} WHERE ${Ne}.${Be} = ${h}.${Z})`}else return;rt(`${we} AS ${o}_${a.toLowerCase()}_${u}`)},mt=()=>{if(qe.size===0)return;let a=[];for(let[o,u]of qe.entries()){let h=Qe(o);if(!h)continue;for(let O of u)F(O,"withPivot");let S=u.map((O)=>`${h.pivotTable}.${O} AS pivot_${O}`);a.push(...S)}if(a.length>0){let o=a.join(", ");rt(o)}};return new Proxy({distinct(){return y=y.replace(/^SELECT\s+/i,"SELECT DISTINCT "),q=null,this},distinctOn(...a){let o=a.map(String).join(", ");return y=y.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${o}) `),q=null,this},selectRaw(a,...o){let u=Ye(a,"selectRaw(fragment)",o),h=y.indexOf(" FROM ");if(h!==-1)y=`${y.substring(0,h)}, ${u}${y.substring(h)}`;else y+=`, ${u}`;return q=null,this},rowNumber(a="row_number",o,u){let h=[];if(o){let L=Array.isArray(o)?o:[o];h.push(`PARTITION BY ${L.join(", ")}`)}if(u&&u.length)h.push(`ORDER BY ${u.map(([L,M])=>`${L} ${M==="desc"?"DESC":"ASC"}`).join(", ")}`);let O=`ROW_NUMBER() ${h.length?`OVER (${h.join(" ")})`:"OVER ()"} AS ${a}`,P=y.indexOf(" FROM ");if(P!==-1)y=`${y.substring(0,P)}, ${O}${y.substring(P)}`;else y+=`, ${O}`;return q=null,this},denseRank(a="dense_rank",o,u){let h=Array.isArray(o)?o:o?[o]:[],S=[];if(h.length)S.push(`PARTITION BY ${h.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([M,x])=>`${M} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let P=`DENSE_RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${P}${y.substring(L)}`;else y+=`, ${P}`;return q=null,this},rank(a="rank",o,u){let h=Array.isArray(o)?o:o?[o]:[],S=[];if(h.length)S.push(`PARTITION BY ${h.join(", ")}`);if(u&&u.length)S.push(`ORDER BY ${u.map(([M,x])=>`${M} ${x==="desc"?"DESC":"ASC"}`).join(", ")}`);let P=`RANK() ${S.length?`OVER (${S.join(" ")})`:"OVER ()"} AS ${a}`,L=y.indexOf(" FROM ");if(L!==-1)y=`${y.substring(0,L)}, ${P}${y.substring(L)}`;else y+=`, ${P}`;return q=null,this},over(a,o,u={}){return ve(a,o,u.partitionBy,u.orderBy),this},lag(a,o={}){let u=[a,String(o.offset??1)];if(o.defaultValue!==void 0)u.push(String(o.defaultValue));return ve(`LAG(${u.join(", ")})`,o.alias??`${a}_lag`,o.partitionBy,o.orderBy),this},lead(a,o={}){let u=[a,String(o.offset??1)];if(o.defaultValue!==void 0)u.push(String(o.defaultValue));return ve(`LEAD(${u.join(", ")})`,o.alias??`${a}_lead`,o.partitionBy,o.orderBy),this},sumOver(a,o={}){return ve(`SUM(${a})`,o.alias??`${a}_sum`,o.partitionBy,o.orderBy),this},avgOver(a,o={}){return ve(`AVG(${a})`,o.alias??`${a}_avg`,o.partitionBy,o.orderBy),this},countOver(a="*",o={}){return ve(`COUNT(${a})`,o.alias??"count_over",o.partitionBy,o.orderBy),this},minOver(a,o={}){return ve(`MIN(${a})`,o.alias??`${a}_min`,o.partitionBy,o.orderBy),this},maxOver(a,o={}){return ve(`MAX(${a})`,o.alias??`${a}_max`,o.partitionBy,o.orderBy),this},firstValue(a,o={}){return ve(`FIRST_VALUE(${a})`,o.alias??`${a}_first`,o.partitionBy,o.orderBy),this},lastValue(a,o={}){return ve(`LAST_VALUE(${a})`,o.alias??`${a}_last`,o.partitionBy,o.orderBy),this},selectAll(){return this},select(a){if(!a)return this;let o=Array.isArray(a)?a:[a];if(o.length===0)return this;let u=o.map(wt),h=/^SELECT\s+(DISTINCT(?:\s+ON\s+\([^)]*\))?\s+)/i.exec(y),S=h?h[1]:"",O=y.indexOf(" FROM ");if(O!==-1)y=`SELECT ${S}${u.join(", ")}${y.substring(O)}`;else y=`SELECT ${S}${u.join(", ")} FROM ${T}`;return q=null,this},addSelect(...a){if(!a.length)return this;let o=a.map(wt),u=y.indexOf(" FROM ");if(u!==-1)y=`${y.substring(0,u)}, ${o.join(", ")}${y.substring(u)}`;else y+=`, ${o.join(", ")}`;return q=null,this},with(...a){if(!w||!a||a.length===0)return this;let o=[];for(let x of a){if(!x)continue;if(typeof x==="string")o.push({name:x});else if(typeof x==="object"&&!Array.isArray(x))for(let[C,Z]of Object.entries(x))if(typeof Z==="function")o.push({name:C,callback:Z});else o.push({name:C})}if(o.length===0)return this;let u=e.relations.maxEagerLoad??50;if(o.length>u)throw Error(`[query-builder] Too many relationships to eager load (${o.length}). Maximum allowed: ${u}`);let h=String(T),S=new Set,O=new Set,P=new Map,L=(x)=>{let C=w.relations?.[x];if(!C)return[];return[...Object.keys(C.hasOne||{}),...Object.keys(C.hasMany||{}),...Object.keys(C.belongsTo||{}),...Object.keys(C.belongsToMany||{}),...Object.keys(C.hasOneThrough||{}),...Object.keys(C.hasManyThrough||{}),...Object.keys(C.morphOne||{}),...Object.keys(C.morphMany||{}),...Object.keys(C.morphToMany||{}),...Object.keys(C.morphedByMany||{})]},M=(x,C,Z=0,oe)=>{let we=e.relations.maxDepth??10;if(Z>=we)throw Error(`[query-builder] Maximum relationship depth (${we}) exceeded at '${C}'. Consider using separate queries or increasing maxDepth.`);let ne=w.relations?.[x];if(!ne)return x;let Se=(le)=>{if(e.softDeletes?.enabled&&e.softDeletes?.defaultFilter){let ue=e.softDeletes.column||"deleted_at";return` AND ${le}.${ue} IS NULL`}return""},Oe=(le)=>{if(!oe)return"";let ue=[],fe=(de,Ae,Me)=>{F(String(de),"with() constraint column");let ze=$e(Ae,"with() constraint operator");ue.push(`${le}.${String(de)} ${ze} ${_e(Me)}`)},he=(de)=>()=>{throw Error(`[query-builder] with('${C}', ...): ${de} is not supported inside a constraint callback on the JOIN-based builder \u2014 apply it to the outer query, or use the model layer's eager loading. (Silently ignoring it would return wrong data.)`)},be={where:(de,Ae,Me)=>{if(Array.isArray(de))fe(de[0],de[1],de[2]);else if(de&&typeof de==="object")for(let ze of Object.keys(de))fe(ze,"=",de[ze]);else if(Ae!==void 0&&Me!==void 0)fe(de,Ae,Me);else if(Ae!==void 0)fe(de,"=",Ae);return be},whereIn:(de,Ae)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IN (${Ae.map(_e).join(", ")})`),be),whereNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NULL`),be),whereNotNull:(de)=>(F(String(de),"with() constraint column"),ue.push(`${le}.${String(de)} IS NOT NULL`),be),orderBy:he("orderBy()"),limit:he("limit()"),offset:he("offset()"),take:he("take()")};return oe(be),ue.length?` AND ${ue.join(" AND ")}`:""},Ne=()=>{let le=(he)=>{let be=he?.[C];return be?w.modelToTable[be]:void 0},ue=(he)=>{let be=he?.[C],de=typeof be==="string"?be:be?.model;return de?w.modelToTable[de]:void 0},fe=(he)=>{let be=he?.[C];return be?.target?w.modelToTable[be.target]:void 0};return le(ne?.hasOne)||le(ne?.hasMany)||le(ne?.belongsTo)||ue(ne?.belongsToMany)||fe(ne?.hasOneThrough)||fe(ne?.hasManyThrough)||le(ne?.morphOne)||le(ne?.morphMany)||le(ne?.morphToMany)||le(ne?.morphedByMany)},Be=Ne()??(w.modelToTable[C]||w.tableToModel[C]?w.modelToTable[C]??C:C),ie=String(Be);if(!Be||!Ne()&&!w.modelToTable[C]&&!w.tableToModel[C]){let le=L(x);if(le.length>0&&!le.includes(C)){let ue=` Available relationships: ${le.join(", ")}`;throw Error(`[query-builder] Relationship '${C}' not found on table '${x}'.${ue}`)}}if(e.relations.detectCycles!==!1){let le=`${x}->${ie}`;if(S.has(le))throw Error(`[query-builder] Circular relationship detected: ${le}. This would cause an infinite loop.`);S.add(le)}if(!ie||ie===x)return x;let st=ne?.hasOneThrough?.[C]||ne?.hasManyThrough?.[C];if(st){let{through:le,target:ue}=st,fe=w.modelToTable[le]||le,he=w.modelToTable[ue]||ue,be=w.primaryKeys[x]??"id",de=w.primaryKeys[fe]??"id",Ae=`${ge(x)}_id`,Me=`${ge(fe)}_id`;return G(`LEFT JOIN ${fe} ON ${fe}.${Ae} = ${x}.${be} LEFT JOIN ${he} ON ${he}.${Me} = ${fe}.${de}`),Q.add(fe),Q.add(he),he}if(Boolean(ne?.belongsToMany?.[C])){let le=E(w,x,C,{singularize:ge,models:w.models}),ue=le?.pivotTable??[ge(x),ge(ie)].sort().join("_"),fe=w.primaryKeys[x]??"id",he=w.primaryKeys[ie]??"id",be=le?.fkParent??`${ge(x)}_id`,de=le?.fkRelated??`${ge(ie)}_id`;return G(`LEFT JOIN ${ue} ON ${ue}.${be} = ${x}.${fe} LEFT JOIN ${ie} ON ${ie}.${he} = ${ue}.${de}${Oe(ie)}`),Q.add(ue),Q.add(ie),ie}if(Boolean(ne?.morphToMany?.[C])){let le=C,ue=`${ge(ie)}_${le}`,fe=w.primaryKeys[x]??"id",he=w.primaryKeys[ie]??"id",be=`${le}_type`,de=`${le}_id`,Ae=`${ge(ie)}_id`,Me=_e(w.tableToModel[x]||x);return G(`LEFT JOIN ${ue} ON ${ue}.${de} = ${x}.${fe} AND ${ue}.${be} = ${Me} LEFT JOIN ${ie} ON ${ie}.${he} = ${ue}.${Ae}`),Q.add(ue),Q.add(ie),ie}if(Boolean(ne?.morphedByMany?.[C])){let le=ne.morphedByMany?.[C]||C,ue=w.modelToTable[le]||le,fe=ge(x),he=`${ge(ue)}_${fe}`,be=w.primaryKeys[x]??"id",de=w.primaryKeys[ue]??"id",Ae=`${fe}_type`,Me=`${fe}_id`,ze=`${ge(ue)}_id`,Pt=_e(w.tableToModel[ue]||ue);return G(`LEFT JOIN ${he} ON ${he}.${ze} = ${x}.${be} LEFT JOIN ${ue} ON ${ue}.${de} = ${he}.${Me} AND ${he}.${Ae} = ${Pt}`),Q.add(he),Q.add(ue),ue}if(Boolean(ne?.belongsTo?.[C])){let le=`${ge(ie)}_id`,ue=w.primaryKeys[ie]??"id";return G(`LEFT JOIN ${ie} ON ${x}.${le} = ${ie}.${ue}${Oe(ie)}`),Q.add(ie),ie}let Nt=Boolean(ne?.morphOne?.[C]),At=Boolean(ne?.morphMany?.[C]);if(Nt||At){let le=`${C}_type`,ue=`${C}_id`,fe=w.primaryKeys[x]??"id",he=_e(w.tableToModel[x]||x);return G(`LEFT JOIN ${ie} ON ${ie}.${ue} = ${x}.${fe} AND ${ie}.${le} = ${he}`),Q.add(ie),ie}let It=`${ge(x)}_id`,Lt=w.primaryKeys[x]??"id",Ct=`${Se(ie)}${Oe(ie)}`;return G(`LEFT JOIN ${ie} ON ${ie}.${It} = ${x}.${Lt}${Ct}`),Q.add(ie),ie};for(let x of o){let C=x.name.trim();if(x.callback)P.set(C,x.callback);let Z=C.split("."),oe=h,we=0;for(let ne of Z){if(!ne||ne.trim().length===0)continue;let Se=ne.trim(),Oe=P.get(Se);oe=M(oe,Se,we,Oe)||oe,we++}O.add(C)}if(qe.size>0){let x=[];for(let[C,Z]of qe.entries()){let oe=Qe(C);if(!oe)continue;let we=Z.map((ne)=>`${oe.pivotTable}.${ne} AS pivot_${ne}`);x.push(...we)}if(x.length>0){let C=x.join(", ");rt(C)}}return q=null,this},whereHas(a,o){if(!w)return this;let u=String(T),h=w.relations?.[u];if(!h)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(h).find(([Z,oe])=>oe&&typeof oe==="object"&&(a in oe));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,P]=S,L=P[a],M=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[M]||M,C;if(O==="hasMany"||O==="hasOne"){let Z=w.primaryKeys[u]??"id";C=ct(u,x,Z,o)}else if(O==="belongsTo"){let Z=w.primaryKeys[x]??"id";C=dt(u,x,Z,o)}else if(O==="belongsToMany"){let Z=w.primaryKeys[u]??"id",oe=w.primaryKeys[x]??"id";C=yt(u,x,Z,oe,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereHas`);return N("WHERE",`EXISTS (${C})`),this},whereDoesntHave(a,o){if(!w)return this;let u=String(T),h=w.relations?.[u];if(!h)throw Error(`[query-builder] No relationships defined for table '${u}'`);let S=Object.entries(h).find(([Z,oe])=>oe&&typeof oe==="object"&&(a in oe));if(!S)throw Error(`[query-builder] Relationship '${a}' not found on table '${u}'`);let[O,P]=S,L=P[a],M=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[M]||M,C;if(O==="hasMany"||O==="hasOne"){let Z=w.primaryKeys[u]??"id";C=ct(u,x,Z,o)}else if(O==="belongsTo"){let Z=w.primaryKeys[x]??"id";C=dt(u,x,Z,o)}else if(O==="belongsToMany"){let Z=w.primaryKeys[u]??"id",oe=w.primaryKeys[x]??"id";C=yt(u,x,Z,oe,o,a)}else throw Error(`[query-builder] Unsupported relationship type '${O}' for whereDoesntHave`);return N("WHERE",`NOT EXISTS (${C})`),this},has(a){if(!w)return this;let o=String(T),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let h=Object.entries(u).find(([C,Z])=>Z&&typeof Z==="object"&&(a in Z));if(!h)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=h,P=O[a],L=typeof P==="string"?P:P?.model||P?.target||P,M=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let C=w.primaryKeys[o]??"id";x=ct(o,M,C)}else if(S==="belongsTo"){let C=w.primaryKeys[M]??"id";x=dt(o,M,C)}else if(S==="belongsToMany"){let C=w.primaryKeys[o]??"id",Z=w.primaryKeys[M]??"id";x=yt(o,M,C,Z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for has`);return N("WHERE",`EXISTS (${x})`),this},doesntHave(a){if(!w)return this;let o=String(T),u=w.relations?.[o];if(!u)throw Error(`[query-builder] No relationships defined for table '${o}'`);let h=Object.entries(u).find(([C,Z])=>Z&&typeof Z==="object"&&(a in Z));if(!h)throw Error(`[query-builder] Relationship '${a}' not found on table '${o}'`);let[S,O]=h,P=O[a],L=typeof P==="string"?P:P?.model||P?.target||P,M=w.modelToTable[L]||L,x;if(S==="hasMany"||S==="hasOne"){let C=w.primaryKeys[o]??"id";x=ct(o,M,C)}else if(S==="belongsTo"){let C=w.primaryKeys[M]??"id";x=dt(o,M,C)}else if(S==="belongsToMany"){let C=w.primaryKeys[o]??"id",Z=w.primaryKeys[M]??"id";x=yt(o,M,C,Z,void 0,a)}else throw Error(`[query-builder] Unsupported relationship type '${S}' for doesntHave`);return N("WHERE",`NOT EXISTS (${x})`),this},withCount(...a){if(!w||!a||a.length===0)return this;let o=String(T);for(let u of a){let h=w.relations?.[o];if(!h)continue;let S=Object.entries(h).find(([we,ne])=>ne&&typeof ne==="object"&&(u in ne));if(!S)continue;let[O,P]=S,L=P[u],M=typeof L==="string"?L:L?.model||L?.target||L,x=w.modelToTable[M]||M,C=w.primaryKeys[o]??"id",Z;if(O==="hasMany"||O==="hasOne")Z=kt(o,x,C);else if(O==="belongsToMany")Z=Ot(o,x,C,u);else continue;let oe=`${u}_count`;rt(`${Z} AS ${oe}`)}return this},withSum(a,o){return Tt("SUM",a,o),this},withAvg(a,o){return Tt("AVG",a,o),this},withMax(a,o){return Tt("MAX",a,o),this},withMin(a,o){return Tt("MIN",a,o),this},applyPivotColumns(){return mt(),this},withPivot(a,...o){if(!w)return this;let u=String(T),h=Qe(a);if(!h)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${u}'`);let S=o&&o.length>0?o:h.hasConfig?h.pivotColumns:[];if(S.length===0)return this;if(qe.set(a,S),h.hasConfig)ke.add(a);return mt(),this},wherePivot(a,o,u,h){if(!w)return this;let S=Qe(a);if(!S)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(T)}'`);F(S.pivotTable,"wherePivot (pivot table)"),F(o,"wherePivot (column)"),nt(S);let O=h===void 0?"=":String(u),P=h===void 0?u:h,L=f.length+1,M=`${S.pivotTable}.${o} ${O} ${t(L)}`;if(f.push(P),k("AND",M),S.hasConfig)ke.add(a);return this},wherePivotIn(a,o,u){if(!w||!Array.isArray(u))return this;let h=Qe(a);if(!h)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(T)}'`);F(h.pivotTable,"wherePivotIn (pivot table)"),F(o,"wherePivotIn (column)"),nt(h);let S=s(u.length,f.length+1),O=l(`${h.pivotTable}.${o}`,u,!1,S);if(f.push(...u),k("AND",O),h.hasConfig)ke.add(a);return this},wherePivotNotIn(a,o,u){if(!w||!Array.isArray(u)||u.length===0)return this;let h=Qe(a);if(!h)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(T)}'`);F(h.pivotTable,"wherePivotNotIn (pivot table)"),F(o,"wherePivotNotIn (column)"),nt(h);let S=s(u.length,f.length+1),O=`${h.pivotTable}.${o} NOT IN (${S})`;if(f.push(...u),k("AND",O),h.hasConfig)ke.add(a);return this},wherePivotNull(a,o){if(!w)return this;let u=Qe(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(T)}'`);if(F(u.pivotTable,"wherePivotNull (pivot table)"),F(o,"wherePivotNull (column)"),nt(u),k("AND",`${u.pivotTable}.${o} IS NULL`),u.hasConfig)ke.add(a);return this},wherePivotNotNull(a,o){if(!w)return this;let u=Qe(a);if(!u)throw Error(`[query-builder] Relationship '${a}' is not a belongsToMany relationship on table '${String(T)}'`);if(F(u.pivotTable,"wherePivotNotNull (pivot table)"),F(o,"wherePivotNotNull (column)"),nt(u),k("AND",`${u.pivotTable}.${o} IS NOT NULL`),u.hasConfig)ke.add(a);return this},where(a,o,u){if(typeof a==="string"&&o!==void 0){F(String(a),"where(column)"),$e(o,"where(operator)");let h=String(o).toLowerCase();if(h==="in"||h==="not in"){let O=Array.isArray(u)?u:[u],P=s(O.length,f.length+1),L=l(c(String(a)),O,h==="not in",P);return f.push(...O),k("AND",L),this}let S=f.length+1;return f.push(u),k("AND",`${c(String(a))} ${String(o)} ${t(S)}`),this}if(Array.isArray(a)){let[h,S,O]=a,P=String(h);F(P,"where(column)");let L=$e(S,"where(operator)");if(L==="in"||L==="not in"){let M=Array.isArray(O)?O:[O],x=s(M.length,f.length+1),C=l(c(P),M,L==="not in",x);f.push(...M),k("AND",C)}else{let M=f.length+1;f.push(O),k("AND",`${c(P)} ${L} ${t(M)}`)}return this}if(at(a))ot("where(expr)");if(Ve(a)){let h=Ge(a,f.length+1);return f.push(...h.parameters),k("AND",h.text),this}if(a&&typeof a==="object"&&!We(a)){let h=a,S=Object.keys(h),O=[];for(let P of S){F(P,"where(column)");let L=h[P];if(Array.isArray(L)){let M=s(L.length,f.length+1);O.push(l(c(P),L,!1,M)),f.push(...L)}else{let M=f.length+1;O.push(`${c(P)} = ${t(M)}`),f.push(L)}}if(O.length>0)k("AND",O.length>1?`(${O.join(" AND ")})`:O[0]);return this}if(We(a))return k("AND",a.raw),this;if(typeof a==="function")return U("AND",a),this;if(a===void 0||a===null)throw TypeError("where() was called with no condition.");if(typeof a==="string")throw TypeError(`where(${JSON.stringify(a)}) is missing an operator and a value. Pass where(column, operator, value), or whereRaw() for a raw fragment.`);throw TypeError(`where() does not understand a condition of type ${typeof a}.`)},whereNull(a){return F(String(a),"whereNull(column)"),k("AND",`${String(a)} IS NULL`),this},whereNotNull(a){return F(String(a),"whereNotNull(column)"),k("AND",`${String(a)} IS NOT NULL`),this},orWhereNull(a){return F(String(a),"orWhereNull(column)"),k("OR",`${String(a)} IS NULL`),this},orWhereNotNull(a){return F(String(a),"orWhereNotNull(column)"),k("OR",`${String(a)} IS NOT NULL`),this},whereBetween(a,o,u){F(String(a),"whereBetween(column)");let h=f.length+1;return f.push(o,u),k("AND",`${String(a)} BETWEEN ${t(h)} AND ${t(h+1)}`),this},orWhereBetween(a,o,u){F(String(a),"orWhereBetween(column)");let h=f.length+1;return f.push(o,u),k("OR",`${String(a)} BETWEEN ${t(h)} AND ${t(h+1)}`),this},whereExists(a){return k("AND",`EXISTS (${a.toSQL()})`),this},orWhereExists(a){return k("OR",`EXISTS (${a.toSQL()})`),this},whereGroup(a){return U("AND",a),this},orWhereGroup(a){return U("OR",a),this},__whereState(){return{body:D(I),params:[...f]}},whereJsonContains(a,o){F(String(a),"whereJsonContains(column)");let u=e.dialect,h=f.length+1;if(u==="postgres"){let O=typeof o==="number"||typeof o==="boolean"?`to_jsonb(${t(h)})`:t(h);if(e.sql?.jsonContainsMode==="function")k("AND",`jsonb_contains(${a}, ${O})`);else k("AND",`${a} @> ${O}`);f.push(o)}else if(n(u))k("AND",`JSON_CONTAINS(${a}, ${t(h)})`),f.push(JSON.stringify(o));else if(Array.isArray(o)){let S=o.map((O,P)=>`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(h+P)})`);k("AND",`(${S.join(" AND ")})`);for(let O of o)f.push(O)}else if(o!==null&&typeof o==="object")throw Error("[query-builder] whereJsonContains: object containment is not supported on SQLite \u2014 pass a scalar or array, or use whereJsonPath.");else k("AND",`EXISTS (SELECT 1 FROM json_each(${a}) WHERE json_each.value = ${t(h)})`),f.push(o);return this},whereJsonPath(a,o,u){if($e(o,"whereJsonPath(op)"),typeof a!=="string"||a.length===0||a.length>256)throw TypeError(`[query-builder] whereJsonPath(path): expected non-empty string up to 256 chars, got ${typeof a==="string"?`'${a.slice(0,32)}...'`:typeof a}`);if(!/^[A-Za-z0-9_.[\]$'\->* ,]+$/.test(a))throw TypeError(`[query-builder] whereJsonPath(path): refusing to use '${a}' \u2014 contains characters outside the allowed JSON-path set`);let h=e.dialect,S=f.length+1;if(h==="postgres")k("AND",`${a} ${o} ${t(S)}`);else if(n(h))k("AND",`JSON_EXTRACT(${a}) ${o} ${t(S)}`);else k("AND",`json_extract(${a}) ${o} ${t(S)}`);return f.push(u),this},whereLike(a,o,u=!1){let h=t(f.length+1);return N("WHERE",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?h:`LOWER(${h})`}`),f.push(o),q=null,this},whereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")N("WHERE",`${String(a)} ILIKE ${u}`);else N("WHERE",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereLike(a,o,u=!1){let h=t(f.length+1);return N("OR",`${u?String(a):`LOWER(${String(a)})`} LIKE ${u?h:`LOWER(${h})`}`),f.push(o),q=null,this},orWhereILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")N("OR",`${String(a)} ILIKE ${u}`);else N("OR",`LOWER(${String(a)}) LIKE LOWER(${u})`);return f.push(o),q=null,this},whereNotLike(a,o,u=!1){let h=t(f.length+1);return N("WHERE",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?h:`LOWER(${h})`}`),f.push(o),q=null,this},whereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")N("WHERE",`${String(a)} NOT ILIKE ${u}`);else N("WHERE",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},orWhereNotLike(a,o,u=!1){let h=t(f.length+1);return N("OR",`${u?String(a):`LOWER(${String(a)})`} NOT LIKE ${u?h:`LOWER(${h})`}`),f.push(o),q=null,this},orWhereNotILike(a,o){let u=t(f.length+1);if(e.dialect==="postgres")N("OR",`${String(a)} NOT ILIKE ${u}`);else N("OR",`LOWER(${String(a)}) NOT LIKE LOWER(${u})`);return f.push(o),q=null,this},whereAny(a,o,u){if(a.length===0)return k("AND",`(${qt})`),this;let h=f.length+1,S=a.map((O,P)=>`${O} ${o} ${t(h+P)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`(${S.join(" OR ")})`),this},whereAll(a,o,u){if(a.length===0)return this;let h=f.length+1,S=a.map((O,P)=>`${O} ${o} ${t(h+P)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`(${S.join(" AND ")})`),this},whereNone(a,o,u){if(a.length===0)return this;let h=f.length+1,S=a.map((O,P)=>`${O} ${o} ${t(h+P)}`);for(let O=0;O<a.length;O++)f.push(u);return k("AND",`NOT (${S.join(" OR ")})`),this},whereNotBetween(a,o,u){F(String(a),"whereNotBetween(column)");let h=f.length+1;return f.push(o,u),k("AND",`${a} NOT BETWEEN ${t(h)} AND ${t(h+1)}`),this},whereDate(a,o,u){F(a,"whereDate(column)");let h=u instanceof Date?u.toISOString():typeof u==="string"?u:(()=>{throw TypeError(`[query-builder] whereDate(date): expected string or Date, got ${typeof u}`)})(),S=f.length+1;return f.push(h),k("AND",`${a} ${o} ${t(S)}`),this},whereRaw(a,...o){return k("AND",Ye(a,"whereRaw(fragment)",o)),this},orWhereRaw(a,...o){return k("OR",Ye(a,"orWhereRaw(fragment)",o)),this},whereColumn(a,o,u){return F(a,"whereColumn(left)"),F(u,"whereColumn(right)"),k("AND",`${a} ${o} ${u}`),this},orWhereColumn(a,o,u){return F(a,"orWhereColumn(left)"),F(u,"orWhereColumn(right)"),k("OR",`${a} ${o} ${u}`),this},whereIn(a,o){if(F(String(a),"whereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),h=l(a,o,!1,u);f.push(...o),k("AND",h)}else k("AND",`${a} IN (${String(o.toSQL())})`);return this},orWhereIn(a,o){if(F(String(a),"orWhereIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),h=l(a,o,!1,u);f.push(...o),k("OR",h)}else k("OR",`${a} IN (${String(o.toSQL())})`);return this},whereNotIn(a,o){if(F(String(a),"whereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),h=l(a,o,!0,u);f.push(...o),k("AND",h)}else k("AND",`${a} NOT IN (${String(o.toSQL())})`);return this},orWhereNotIn(a,o){if(F(String(a),"orWhereNotIn(column)"),Array.isArray(o)){let u=s(o.length,f.length+1),h=l(a,o,!0,u);f.push(...o),k("OR",h)}else k("OR",`${a} NOT IN (${String(o.toSQL())})`);return this},whereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return k("AND",`(${o})`),this},orWhereNested(a){let o=a.toSQL?String(a.toSQL()):String(a);return k("OR",`(${o})`),this},andWhere(a,o,u){return X(this,"AND","andWhere",a,o,u)},orWhere(a,o,u){return X(this,"OR","orWhere",a,o,u)},orderBy(a,o="asc"){let u=o==="asc"?"ASC":"DESC",h=c(String(a));return y=ye.ORDER_BY.test(y)?`${y}, ${h} ${u}`:`${y} ORDER BY ${h} ${u}`,q=null,this},orderByDesc(a){return y=ye.ORDER_BY.test(y)?`${y}, ${a} DESC`:`${y} ORDER BY ${a} DESC`,q=null,this},inRandomOrder(){let a=e.sql.randomFunction==="RAND()"?"RAND()":"RANDOM()";return y=ye.ORDER_BY.test(y)?`${y}, ${a}`:`${y} ORDER BY ${a}`,q=null,this},reorder(a,o="asc"){return y=y.replace(/ORDER BY[\s\S]*$/i,""),y+=` ORDER BY ${a} ${o==="asc"?"ASC":"DESC"}`,q=null,this},latest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} DESC`:`${y} ORDER BY ${o} DESC`,q=null,this},oldest(a){let o=a??e.timestamps.defaultOrderColumn;return y=ye.ORDER_BY.test(y)?`${y}, ${o} ASC`:`${y} ORDER BY ${o} ASC`,q=null,this},limit(a){if(!Number.isFinite(a)||a<0||!Number.isInteger(a))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${a}`);return y=ye.LIMIT.test(y)?y.replace(ye.LIMIT,` LIMIT ${a}`):`${y} LIMIT ${a}`,q=null,this},offset(a){if(!Number.isFinite(a)||a<0||!Number.isInteger(a))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${a}`);return y=ye.OFFSET.test(y)?y.replace(ye.OFFSET,` OFFSET ${a}`):`${y} OFFSET ${a}`,q=null,this},join(a,o,u,h){return F(a,"join(table)"),xe(o,"join(onLeft)"),xe(h,"join(onRight)"),$e(u,"join(operator)"),G(`JOIN ${a} ON ${o} ${u} ${h}`),Q.add(a),this},joinSub(a,o,u,h,S){return F(o,"joinSub(alias)"),xe(u,"joinSub(onLeft)"),xe(S,"joinSub(onRight)"),$e(h,"joinSub(operator)"),G(`JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${h} ${S}`),Q.add(o),this},innerJoin(a,o,u,h){return F(a,"innerJoin(table)"),xe(o,"innerJoin(onLeft)"),xe(h,"innerJoin(onRight)"),$e(u,"innerJoin(operator)"),G(`INNER JOIN ${a} ON ${o} ${u} ${h}`),Q.add(a),this},leftJoin(a,o,u,h){return F(a,"leftJoin(table)"),xe(o,"leftJoin(onLeft)"),xe(h,"leftJoin(onRight)"),$e(u,"leftJoin(operator)"),G(`LEFT JOIN ${a} ON ${o} ${u} ${h}`),Q.add(a),this},leftJoinSub(a,o,u,h,S){return F(o,"leftJoinSub(alias)"),xe(u,"leftJoinSub(onLeft)"),xe(S,"leftJoinSub(onRight)"),$e(h,"leftJoinSub(operator)"),G(`LEFT JOIN (${String(a.toSQL())}) AS ${o} ON ${u} ${h} ${S}`),Q.add(o),this},rightJoin(a,o,u,h){return F(a,"rightJoin(table)"),xe(o,"rightJoin(onLeft)"),xe(h,"rightJoin(onRight)"),$e(u,"rightJoin(operator)"),G(`RIGHT JOIN ${a} ON ${o} ${u} ${h}`),Q.add(a),this},crossJoin(a){return F(a,"crossJoin(table)"),G(`CROSS JOIN ${a}`),Q.add(a),this},crossJoinSub(a,o){return F(o,"crossJoinSub(alias)"),G(`CROSS JOIN (${String(a.toSQL())}) AS ${o}`),Q.add(o),this},selectAllRelations(){if(!H)return this;let a=String(T),o=Object.keys(H[a]?.columns??{}),u=[];if(o.length>0)u.push(d`${d(a)}.*`);for(let h of Q){let S=Object.keys(H[h]?.columns??{});for(let O of S){let P=e.aliasing.relationColumnAliasFormat==="camelCase"?`${h}_${O}`.replace(/_([a-z])/g,(L,M)=>M.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${h}.${O}`:`${h}_${O}`;u.push(d`${d(`${h}.${O}`)} AS ${d(P)}`)}}if(u.length>0){let h=o.length>0?`${a}.*`:"",S=[];for(let L of Q){let M=Object.keys(H[L]?.columns??{});for(let x of M){let C=e.aliasing.relationColumnAliasFormat==="camelCase"?`${L}_${x}`.replace(/_([a-z])/g,(Z,oe)=>oe.toUpperCase()):e.aliasing.relationColumnAliasFormat==="table.dot.column"?`${L}.${x}`:`${L}_${x}`;S.push(`${L}.${x} AS ${C}`)}}let O=[h,...S].filter(Boolean).join(", "),P=y.indexOf(" FROM ");if(P!==-1)y=`SELECT ${O}${y.substring(P)}`;else y=`SELECT ${O} FROM ${a}`;q=null}return this},groupBy(...a){if(a.length)y=ye.GROUP_BY.test(y)?`${y}, ${a.map((o)=>c(String(o))).join(", ")}`:`${y} GROUP BY ${a.map((o)=>c(String(o))).join(", ")}`,q=null;return this},groupByRaw(a,...o){let u=Ye(a,"groupByRaw(fragment)",o);return y=ye.GROUP_BY.test(y)?`${y}, ${u}`:`${y} GROUP BY ${u}`,q=null,this},having(a){let o=K?"AND":"HAVING";if(Array.isArray(a)){let u=f.length+1;y=`${y} ${o} ${a[0]} ${a[1]} ${t(u)}`,f.push(a[2]),K=!0,q=null}else if(a&&typeof a==="object"&&!("raw"in a)){let u=Object.keys(a),h=u.length;if(h){let S=f.length,O=Array.from({length:h});for(let P=0;P<h;P++){let L=u[P];O[P]=`${L} = ${t(S+P+1)}`,f.push(a[L])}y=`${y} ${o} ${O.join(" AND ")}`,K=!0,q=null}}else if(a&&typeof a.raw<"u")y+=` ${o} ${a.raw}`,K=!0,q=null;return this},havingRaw(a,...o){let u=Ye(a,"havingRaw(fragment)",o);return y+=` ${K?"AND":"HAVING"} ${u}`,K=!0,q=null,this},orderByRaw(a,...o){let u=Ye(a,"orderByRaw(fragment)",o);return y=ye.ORDER_BY.test(y)?`${y}, ${u}`:`${y} ORDER BY ${u}`,q=null,this},$call(a){return a(this),this},union(a){return _("UNION",a),this},unionAll(a){return _("UNION ALL",a),this},intersect(a){return _("INTERSECT",a),this},intersectAll(a){return _("INTERSECT ALL",a),this},except(a){return _("EXCEPT",a),this},exceptAll(a){return _("EXCEPT ALL",a),this},forPage(a,o){let u=Math.max(1,Math.floor(a)),h=Math.max(1,Math.floor(o));return y+=` LIMIT ${h} OFFSET ${(u-1)*h}`,q=null,this},toSQL(){let a=Xe(W());return{sql:a,toString:()=>a,execute:()=>R().execute(),values:()=>R().values(),raw:()=>R().raw()}},async value(a){let o=J(""," LIMIT 1"),u=await te(o,"select",{signal:ee,timeoutMs:j}),[h]=u;return h?.[a]},async pluck(a,o){let u=await te(R(),"select",{signal:ee,timeoutMs:j});if(o){let h={};for(let S of u){let O=String(S?.[o]);if(Object.prototype.hasOwnProperty.call(h,O))throw Error(`[query-builder] pluck(${a}, ${o}): duplicate key '${O}' \u2014 multiple rows share this value, so the resulting map would silently drop data. Use a unique key column or pluck without a key to get an array.`);h[O]=S?.[a]}return h}return u.map((h)=>h?.[a])},async exists(){let a=J("SELECT EXISTS (",") as e"),o=await te(a,"select",{signal:ee,timeoutMs:j}),[u]=o;return Boolean(u?.e)},async doesntExist(){return!await this.exists()},async paginate(a,o=1,u={}){if(typeof a==="object"&&a!==null){let Z=a;o=Z.page??1,u=Z.tx?{tx:Z.tx}:{},a=Z.perPage??10}if(!Number.isFinite(a)||a<=0||!Number.isInteger(a))throw TypeError(`[query-builder] paginate(perPage): expected positive integer, got ${a}`);if(!Number.isFinite(o)||o<1||!Number.isInteger(o))throw TypeError(`[query-builder] paginate(page): expected integer >= 1, got ${o}`);if(u.tx){let Z=Xe(W()),oe=[...f],we=await u.tx.unsafe(`SELECT COUNT(*) as c FROM (${Z}) as sub`,oe),ne=Number(we?.[0]?.c??0),Se=Math.max(1,Math.ceil(ne/a)),Oe=Math.max(1,Math.min(o,Se)),Ne=(Oe-1)*a;return{data:await u.tx.unsafe(`${Z} LIMIT ${a} OFFSET ${Ne}`,oe),meta:{perPage:a,page:Oe,total:ne,lastPage:Se}}}let h=J("SELECT COUNT(*) as c FROM (",") as sub"),S=await te(h,"select",{signal:ee,timeoutMs:j}),[O]=S,P=Number(O?.c??0),L=Math.max(1,Math.ceil(P/a)),M=Math.max(1,Math.min(o,L)),x=(M-1)*a;return{data:await te(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a,x]),"select",{signal:ee,timeoutMs:j}),meta:{perPage:a,page:M,total:P,lastPage:L}}},async simplePaginate(a,o=1){let u=Math.max(1,o),h=(u-1)*a,S=await te(J("",` LIMIT ${t(f.length+1)} OFFSET ${t(f.length+2)}`,[a+1,h]),"select",{signal:ee,timeoutMs:j}),O=S.length>a;return{data:O?S.slice(0,a):S,meta:{perPage:a,page:u,hasMore:O}}},async cursorPaginate(a,o,u="id",h="asc"){if(!Number.isInteger(a)||a<=0)throw TypeError(`[query-builder] cursorPaginate(perPage): expected positive integer, got ${a}`);let S=(Array.isArray(u)?u:[u]).map(String);for(let Be of S)F(Be,"cursorPaginate(column)");let O=h==="asc"?">":"<",P=h==="asc"?"ASC":"DESC",L=[...f],M="";if(o!==void 0&&o!==null)if(Array.isArray(u)){let Be=o.map((ie)=>(L.push(ie),t(L.length)));M=`(${S.join(", ")}) ${O} (${Be.join(", ")})`}else L.push(o),M=`${S[0]} ${O} ${t(L.length)}`;let x=Xe(M?W({conn:"AND",sql:M}):W()),C=S.map((Be)=>`${Be} ${P}`).join(", ");if(Wt(x))throw TypeError("[query-builder] cursorPaginate() cannot be combined with orderBy() \u2014 it orders by "+`${C} itself, and a cursor is only meaningful in that order. Remove the orderBy(), or pass the column and direction to cursorPaginate().`);let Z=L.length>0?A(`${x} ORDER BY ${C} LIMIT ${a+1}`,L):A(`${x} ORDER BY ${C} LIMIT ${a+1}`),oe=await te(Z,"select",{signal:ee,timeoutMs:j}),we=oe.length>a,ne=oe.slice(0,a),Se=ne[ne.length-1],Oe=we&&Se?Array.isArray(u)?u.map((Be)=>Se[Be]):Se[u]:null,Ne=ne.length?Array.isArray(u)?u.map((Be)=>ne[0]?.[Be]):ne[0]?.[u]:null;return{data:ne,meta:{perPage:a,nextCursor:Oe??null,prevCursor:Ne}}},async chunk(a,o){let u=1;while(!0){let{data:h,meta:S}=await this.paginate(a,u);if(h.length===0)break;if(await o(h),u>=S.lastPage)break;u+=1}},async chunkById(a,o="id",u){let h;while(!0){let{data:S,meta:O}=await this.cursorPaginate(a,h,o,"asc");if(S.length===0)break;if(u)await u(S);if(h=O.nextCursor,!h)break}},async eachById(a,o="id",u){await this.chunkById(a,o,async(h)=>{for(let S of h)await u?.(S)})},withTimeout(a){return j=Math.max(1,Math.floor(a)),this},abort(a){return ee=a,this},withTrashed(){return se=!0,ce=!1,this},onlyTrashed(){se=!0,ce=!0;let a=e.softDeletes?.column||"deleted_at";return k("AND",`${T}.${a} IS NOT NULL`),this},scope(a,o){let u=String(T),S=w?.scopes?.[u]?.[a];if(S)return S(this,o);return this},when(a,o,u){if(a)return o(this);if(u)return u(this);return this},tap(a){return a(this),this},dump(){return console.log(String(R())),this},dd(){throw console.log(String(R())),Error("Dump and Die")},cache(a=60000){return ut=a,Te=!0,this},async explain(){let a=J("EXPLAIN ");return await te(a,"select",{signal:ee,timeoutMs:j})},simple(){return R().simple()},toText(){return W()},async get(){let a=me(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||it(a));if(!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!o){let L=B._prepareStatement;if(L){let M=L(W());return tt(f.length>0?M.all(...f):M.all())}}let u=W();if(q=f.length>0?A(u,f):A(u),!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!o){let L=R()._stmt,M=R()._params;if(L)return tt(M&&M.length>0?L.all(...M):L.all());return tt(await R().execute())}if(!e.softDeletes?.enabled&&!Te&&!j&&!ee)return tt(await te(R(),"select"));let h=R();if(e.softDeletes?.enabled&&e.softDeletes.defaultFilter&&!se){let L=e.softDeletes.column,M=String(T);if((H?Boolean(H[M]?.columns?.[L]):!0)&&!ye.DELETED_AT.test(W()))N("WHERE",`${String(L)} IS ${ce?"NOT ":""}NULL`),h=R()}let S=Te&&!p?.inTransaction,O=S?Ut(B,W(),f):"";if(S){let L=ft.get(O);if(L)return L}let P=await te(h,"select",{signal:ee,timeoutMs:j});if(S)ft.set(O,P,ut);return tt(P)},async executeTakeFirst(){let a=await te(R(),"select",{signal:ee,timeoutMs:j});return Ke(Array.isArray(a)?a[0]:a)},async executeTakeFirstOrThrow(){let a=await this.executeTakeFirst();if(!a)throw Error("Record not found");return a},async first(){let a=me(),o=a&&(a.onQueryStart||a.onQueryEnd||a.onQueryError||a.startSpan||it(a));if(!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!o){let S=B._prepareStatement;if(S){let O=W(),P=O.includes(" LIMIT ")?O:`${O} LIMIT 1`,L=S(P),M=f.length>0?L.all(...f):L.all();return Ke(M[0])}}let u=await te(J(""," LIMIT 1"),"select",{signal:ee,timeoutMs:j}),[h]=u;return Ke(h)},async firstOrFail(){let a=await this.first();if(!a)throw Error("Record not found");return a},async find(a){let o=w?.primaryKeys[String(T)]??"id",u=await te(J("",` WHERE ${De(o)} = ${t(f.length+1)} LIMIT 1`,[a]),"select",{signal:ee,timeoutMs:j}),[h]=u;return h},async findOrFail(a){let o=await this.find(a);if(!o)throw Error("Record not found");return o},async findMany(a){let o=w?.primaryKeys[String(T)]??"id";return await te(J("",` WHERE ${l(De(String(o)),a,!1,s(a.length,f.length+1))}`,a),"select",{signal:ee,timeoutMs:j})},async*lazy(){let a,o=w?.primaryKeys[String(T)]??"id";while(!0){let h=await(a==null?d`${R()} ORDER BY ${d(String(o))} ASC LIMIT 100`:d`${R()} WHERE ${d(String(o))} > ${a} ORDER BY ${d(String(o))} ASC LIMIT 100`).execute();if(h.length===0)break;for(let S of h)yield S;if(a=h[h.length-1]?.[o],a==null)break}},async*lazyById(){let a=w?.primaryKeys[String(T)]??"id",o;while(!0){let h=await(o==null?d`${R()} ORDER BY ${d(String(a))} ASC LIMIT 100`:d`${R()} WHERE ${d(String(a))} > ${o} ORDER BY ${d(String(a))} ASC LIMIT 100`).execute();if(h.length===0)break;for(let S of h)yield S;if(o=h[h.length-1]?.[a],o==null)break}},pipe(a){return a(this)},async count(){let a=W(),o=a.indexOf(" FROM "),u=/ GROUP BY /i.test(a),h;if(u)h=`SELECT COUNT(*) as c FROM (${a}) AS _bqb_count_sub`;else if(o!==-1)h=`SELECT COUNT(*) as c${a.substring(o)}`;else h=`SELECT COUNT(*) as c FROM ${T}`;let S=me(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||it(S));if(!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!O){let x=B._prepareStatement;if(x){let C=x(h),Z=f.length>0?C.all(...f):C.all();return Number(Z[0]?.c??0)}}let P=f.length>0?A(h,f):A(h),L=await te(P,"select",{signal:ee,timeoutMs:j}),[M]=L;return Number(M?.c??0)},async avg(a){let o=W(),u=o.indexOf(" FROM "),h=u!==-1?`SELECT AVG(${a}) as a${o.substring(u)}`:`SELECT AVG(${a}) as a FROM ${T}`,S=me(),O=S&&(S.onQueryStart||S.onQueryEnd||S.onQueryError||S.startSpan||it(S));if(!e.softDeletes?.enabled&&!Te&&!j&&!ee&&!O){let x=B._prepareStatement;if(x){let C=x(h),Z=f.length>0?C.all(...f):C.all();return Number(Z[0]?.a??0)}}let P=f.length>0?A(h,f):A(h),L=await te(P,"select",{signal:ee,timeoutMs:j}),[M]=L;return Number(M?.a??0)},async sum(a){let o=W(),u=o.indexOf(" FROM "),h=u!==-1?`SELECT SUM(${a}) as s${o.substring(u)}`:`SELECT SUM(${a}) as s FROM ${T}`,S=f.length>0?A(h,f):A(h),O=await te(S,"select",{signal:ee,timeoutMs:j}),[P]=O;return Number(P?.s??0)},async max(a){let o=W(),u=o.indexOf(" FROM "),h=u!==-1?`SELECT MAX(${a}) as m${o.substring(u)}`:`SELECT MAX(${a}) as m FROM ${T}`,S=f.length>0?A(h,f):A(h),O=await te(S,"select",{signal:ee,timeoutMs:j}),[P]=O;return P?.m},async min(a){let o=W(),u=o.indexOf(" FROM "),h=u!==-1?`SELECT MIN(${a}) as m${o.substring(u)}`:`SELECT MIN(${a}) as m FROM ${T}`,S=f.length>0?A(h,f):A(h),O=await te(S,"select",{signal:ee,timeoutMs:j}),[P]=O;return P?.m},lockForUpdate(){return y+=" FOR UPDATE",q=null,this},sharedLock(){let a=e.sql.sharedLockSyntax==="LOCK IN SHARE MODE"?"LOCK IN SHARE MODE":"FOR SHARE";return y+=` ${a}`,q=null,this},withCTE(a,o){return F(a,"withCTE(name)"),y=`WITH ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},withRecursive(a,o){return F(a,"withRecursive(name)"),y=`WITH RECURSIVE ${a} AS (${String(o.toSQL())}) ${y}`,q=null,this},execute(){return te(R(),"select",{signal:ee,timeoutMs:j})},values(){return R().values()},toParams(){return[...f]},__rawState(){return{sql:Xe(W()),params:[...f]}},__hasPredicate(){return I.length>0||v},raw(){return R().raw()},get rows(){return},get row(){return},cancel(){try{R().cancel()}catch{}}},{get(a,o,u){let h=Reflect.get(a,o,u);if(h!==void 0)return h;if(typeof o==="string"&&(o.startsWith("where")||o.startsWith("orWhere")||o.startsWith("andWhere"))){let S=o.startsWith("orWhere"),O=o.startsWith("andWhere"),P=`${String(T)}|${o}`,L=Ue.get(P);if(L===void 0){let x=o.replace(/^(?:or|and)?where/i,"");if(!x)Ue.set(P,""),L="";else{let C=x.charAt(0).toLowerCase()+x.slice(1),Z=x.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),oe=H?Object.keys(H[String(T)]?.columns??{}):[];L=[Z,C,C.toLowerCase()].find((we)=>oe.includes(we))??Z,Ue.set(P,L)}}if(L==="")return()=>u;let M=L;return(x)=>{if(Array.isArray(x)){let C=s(x.length,f.length+1);N(S?"OR":O?"AND":"WHERE",`${M} IN (${C})`),f.push(...x)}else{let C=t(f.length+1);N(S?"OR":O?"AND":"WHERE",`${M} = ${C}`),f.push(x)}return u}}return Reflect.get(a,o,u)}})}return{configure(T){return Pe(T),this},id(T){if(!ye.IDENTIFIER.test(T))throw Error(`[query-builder] Invalid identifier: '${T}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return B(String(T))},ids(...T){for(let g of T)if(!ye.IDENTIFIER.test(g))throw Error(`[query-builder] Invalid identifier: '${g}'. Identifiers must start with a letter or underscore and contain only alphanumeric characters, underscores, and dots.`);return B(T)},select(T,...g){return Je(T,g)},selectFrom(T){return Je(T)},selectFromSub(T,g){function d(R){return()=>{throw Error(`[query-builder] selectFromSub(...).${R}() is not supported. Apply ${R}() to the underlying subquery BEFORE passing it to selectFromSub, or use the regular selectFrom(...) builder. This previously silently returned without `+"affecting the SQL, producing wrong results \u2014 see stacksjs/stacks#1862 #11.")}}F(String(g),"selectFromSub(alias)");let y=typeof T.__rawState==="function"?T.__rawState():null,I=T.toSQL(),f=y?.sql??(typeof I==="string"?I:I?.sql??String(I)),z=y?.params??(Array.isArray(I?.values)?I.values:[]),v=`SELECT * FROM (${f}) AS ${String(g)}`,K=(R,J,k,N)=>{let V=[...R],W=(X,_,G)=>{F(X,"selectFromSub where(column)");let Q=$e(_,"selectFromSub where(operator)");if(Q==="in"||Q==="not in"){let ee=Array.isArray(G)?G:[G],se=s(ee.length,V.length+1);return V.push(...ee),`${X} ${Q.toUpperCase()} (${se})`}let j=t(V.length+1);return V.push(G),`${X} ${Q} ${j}`},U;if(typeof J==="string"&&k!==void 0)U=W(J,k,N);else if(Array.isArray(J)&&J.length===3)U=W(J[0],J[1],J[2]);else if(J&&typeof J==="object"){let X=Object.entries(J).map(([_,G])=>W(_,"=",G));U=X.length>1?`(${X.join(" AND ")})`:X[0]}else return{clause:null,params:R};return{clause:U,params:V}};function q(R,J,k,N=""){let V=D(J),W=V?`${R} WHERE ${V}${N}`:`${R}${N}`,U=()=>k.length>0?A(W,k):A(W),X=(Q,j,ee,se)=>{let ce=K(k,j,ee,se);return ce.clause===null?q(R,J,k,N):q(R,[...J,{conn:Q,sql:ce.clause}],ce.params,N)},_=(Q,j)=>{let ee=[],se=[...k],ce=(ke)=>(ut,ge,Qe)=>{let Ke=K(se,ut,ge,Qe);if(Ke.clause!==null)ee.push({conn:ke,sql:Ke.clause}),se=Ke.params;return Te},Te={where:ce("AND"),andWhere:ce("AND"),orWhere:ce("OR")};j(Te);let qe=D(ee);if(!qe)throw TypeError("[query-builder] selectFromSub.whereGroup(callback): the callback added no conditions. Add at least one where()/orWhere() to the builder it receives.");return q(R,[...J,{conn:Q,sql:`(${qe})`}],se,N)},G={distinct(){return q(R.replace(/^SELECT\s+/i,"SELECT DISTINCT "),J,k,N)},distinctOn(...Q){let j=Q.map(String).join(", ");return q(R.replace(/^SELECT\s+/i,`SELECT DISTINCT ON (${j}) `),J,k,N)},selectRaw(Q,...j){let ee=Ye(Q,"selectFromSub.selectRaw(fragment)",j),se=R.indexOf(" FROM "),ce=se!==-1?`${R.slice(0,se)}, ${ee}${R.slice(se)}`:`${R}, ${ee}`;return q(ce,J,k,N)},$call(Q){return Q(this)??this},where(Q,j,ee){return X("AND",Q,j,ee)},andWhere(Q,j,ee){return X("AND",Q,j,ee)},orWhere(Q,j,ee){return X("OR",Q,j,ee)},whereGroup(Q){return _("AND",Q)},orWhereGroup(Q){return _("OR",Q)},orderBy(Q,j="asc"){F(String(Q),"selectFromSub.orderBy(column)");let ee=j==="asc"?"ASC":"DESC",se=ye.ORDER_BY.test(N)?`${N}, ${Q} ${ee}`:`${N} ORDER BY ${Q} ${ee}`;return q(R,J,k,se)},limit(Q){if(!Number.isInteger(Q)||Q<0)throw TypeError(`[query-builder] selectFromSub.limit(n): expected non-negative integer, got ${Q}`);let j=ye.LIMIT.test(N)?N.replace(ye.LIMIT,` LIMIT ${Q}`):`${N} LIMIT ${Q}`;return q(R,J,k,j)},offset(Q){if(!Number.isInteger(Q)||Q<0)throw TypeError(`[query-builder] selectFromSub.offset(n): expected non-negative integer, got ${Q}`);let j=ye.OFFSET.test(N)?N.replace(ye.OFFSET,` OFFSET ${Q}`):`${N} OFFSET ${Q}`;return q(R,J,k,j)},toSQL(){return Ie(U(),W)},async execute(){return te(U(),"select")},async executeTakeFirst(){let Q=await te(U(),"select");return Array.isArray(Q)?Q[0]:Q},async executeTakeFirstOrThrow(){let Q=await te(U(),"select"),j=Array.isArray(Q)?Q[0]:Q;if(!j)throw Error("Record not found");return j},async get(){return te(U(),"select")},async first(){let Q=await te(U(),"select");return Array.isArray(Q)?Q[0]:Q},async firstOrFail(){let Q=await te(U(),"select"),j=Array.isArray(Q)?Q[0]:Q;if(!j)throw Error("No rows found");return j},async count(){let Q=k.length>0?A(`SELECT COUNT(*) as c FROM (${W}) as sub`,k):A(`SELECT COUNT(*) as c FROM (${W}) as sub`),j=await te(Q,"select");return Number(j?.[0]?.c??0)},async exists(){let Q=k.length>0?A(`SELECT EXISTS(${W}) as e`,k):A(`SELECT EXISTS(${W}) as e`),j=await te(Q,"select");return Boolean(j?.[0]?.e)},async doesntExist(){return!await G.exists()},values(){return U().values()},raw(){return U().raw()},cancel(){try{U().cancel()}catch{}},whereRaw:d("whereRaw"),whereColumn:d("whereColumn"),orWhereColumn:d("orWhereColumn"),whereIn:d("whereIn"),orWhereIn:d("orWhereIn"),whereNotIn:d("whereNotIn"),orWhereNotIn:d("orWhereNotIn"),whereLike:d("whereLike"),whereILike:d("whereILike"),orWhereLike:d("orWhereLike"),orWhereILike:d("orWhereILike"),whereNotLike:d("whereNotLike"),whereNotILike:d("whereNotILike"),orWhereNotLike:d("orWhereNotLike"),orWhereNotILike:d("orWhereNotILike"),whereAny:d("whereAny"),whereAll:d("whereAll"),whereNone:d("whereNone"),whereNested:d("whereNested"),orWhereNested:d("orWhereNested"),whereDate:d("whereDate"),whereBetween:d("whereBetween"),whereNotBetween:d("whereNotBetween"),whereJsonContains:d("whereJsonContains"),whereJsonPath:d("whereJsonPath"),whereNull:d("whereNull"),orWhereNull:d("orWhereNull"),whereNotNull:d("whereNotNull"),orWhereNotNull:d("orWhereNotNull"),whereExists:d("whereExists"),orWhereExists:d("orWhereExists"),orWhereBetween:d("orWhereBetween"),orWhereRaw:d("orWhereRaw"),whereJsonDoesntContain:d("whereJsonDoesntContain"),whereJsonContainsKey:d("whereJsonContainsKey"),whereJsonDoesntContainKey:d("whereJsonDoesntContainKey"),whereJsonLength:d("whereJsonLength"),join:d("join"),joinSub:d("joinSub"),innerJoin:d("innerJoin"),leftJoin:d("leftJoin"),leftJoinSub:d("leftJoinSub"),rightJoin:d("rightJoin"),crossJoin:d("crossJoin"),crossJoinSub:d("crossJoinSub"),groupBy:d("groupBy"),groupByRaw:d("groupByRaw"),having:d("having"),havingRaw:d("havingRaw"),addSelect:d("addSelect"),select:d("select"),selectAll:d("selectAll"),orderByDesc:d("orderByDesc"),inRandomOrder:d("inRandomOrder"),reorder:d("reorder"),orderByRaw:d("orderByRaw"),union:d("union"),unionAll:d("unionAll"),forPage:d("forPage"),selectAllRelations:d("selectAllRelations"),with:d("with"),value:d("value"),pluck:d("pluck"),cursorPaginate:d("cursorPaginate"),paginate:d("paginate"),simplePaginate:d("simplePaginate"),chunk:d("chunk"),chunkById:d("chunkById"),eachById:d("eachById"),avg:d("avg"),sum:d("sum"),max:d("max"),min:d("min"),find:d("find"),findOrFail:d("findOrFail"),findMany:d("findMany"),latest:d("latest"),oldest:d("oldest"),lazy:d("lazy"),lazyById:d("lazyById"),pipe:(Q)=>Q(G),when:d("when"),tap:()=>G,dump:()=>G,dd:()=>{throw Error("Dump and Die")},explain:()=>Promise.resolve([]),simple:()=>U().simple(),toText:()=>W,toParams:()=>[...k],withTimeout:()=>G,abort:()=>G,lockForUpdate:()=>G,sharedLock:()=>G,withCTE:()=>G,withRecursive:()=>G,cache:()=>G,clone:()=>G,withTrashed:()=>G,onlyTrashed:()=>G,scope:()=>G,get rows(){return[]},get row(){return}};return G}return q(v,[],z)},insertInto(T){let g,d="",y=[],I=[],f=!1,z=()=>K?[]:{changes:0,lastInsertRowid:0},v=()=>{let N=async()=>{return},V=async()=>{throw Error("Insert with RETURNING returned no rows")};return{where:()=>v(),andWhere:()=>v(),orWhere:()=>v(),orderBy:()=>v(),limit:()=>v(),offset:()=>v(),toSQL:()=>Ie(null,""),execute:async()=>[],get:async()=>[],first:N,executeTakeFirst:N,firstOrFail:V,executeTakeFirstOrThrow:V}},K=e.dialect==="postgres",q=(N)=>{let W=N.flat(2).map(String).filter(Boolean),U=W.length>0&&!W.includes("*")?W.map((G)=>R(G)).join(", "):"*",X=async()=>{let G=await te(A(d,y),"insert"),Q=Number(G?.lastInsertRowid??0),j=Math.max(1,Number(G?.affectedRows??1)),ee=I.filter((Te)=>Te!==void 0&&Te!==null),se=Q>0?A(`SELECT ${U} FROM ${R(String(T))} WHERE ${R("id")} >= ? AND ${R("id")} < ? ORDER BY ${R("id")} ASC`,[Q,Q+j]):ee.length>0?A(`SELECT ${U} FROM ${R(String(T))} WHERE ${R("id")} IN (${ee.map(()=>"?").join(", ")}) ORDER BY ${R("id")} ASC`,ee):null;if(!se)return[];let ce=await se.execute();return Array.isArray(ce)?ce:[]},_=async()=>(await X())[0];return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>Ie(A(d,y),d),execute:X,get:X,first:_,executeTakeFirst:_,async firstOrFail(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G},async executeTakeFirstOrThrow(){let G=await _();if(!G)throw Error("Insert with RETURNING returned no rows");return G}}},R=K?(N)=>`"${String(N).replace(/"/g,'""')}"`:n(e.dialect)?(N)=>`\`${String(N).replace(/`/g,"``")}\``:(N)=>`"${String(N).replace(/"/g,'""')}"`,J=K?"postgres":n(e.dialect)?"mysql":"sqlite",k=K?(N)=>`$${N+1}`:(N)=>"?";return{values(N){let V=Ee(String(T),Array.isArray(N)?N:[N]),W=V.length;if(I=V.map((se)=>se?.id),W===0)return f=!0,g=null,d="",y.length=0,this;f=!1;let U=V[0],X=Object.keys(U),_=X.length,G=W*_;y.length=G;let Q=W===1&&_>0&&typeof T==="string",j=Q?ae?.get(T):void 0,ee=j?.quoteStyle===J&&j.columns.length===_;if(ee){for(let se=0;se<_;se++)if(j.columns[se]!==X[se]){ee=!1;break}}if(ee){d=j.sql;for(let se=0;se<_;se++)y[se]=U[X[se]]}else if(W===1)if(!K){let se=R(X[0]),ce="?";y[0]=U[X[0]];for(let Te=1;Te<_;Te++)se+=`,${R(X[Te])}`,ce+=",?",y[Te]=U[X[Te]];d=`INSERT INTO ${R(T)}(${se})VALUES(${ce})`}else{let se=X.map((ce)=>R(ce)).join(",");d=`INSERT INTO ${R(T)}(${se})VALUES(`;for(let ce=0;ce<_;ce++){if(ce>0)d+=",";d+=k(ce),y[ce]=U[X[ce]]}d+=")"}else{let se=X.map((Te)=>R(Te)).join(",");d=`INSERT INTO ${R(T)}(${se})VALUES`;let ce=0;for(let Te=0;Te<W;Te++){let qe=V[Te];if(Te===0)d+="(";else d+="),(";for(let ke=0;ke<_;ke++){if(ke>0)d+=",";d+=k(ce),y[ce++]=qe[X[ke]]}}d+=")"}if(Q&&!ee&&d.length<=8192){if(ae??=new Map,ae.size>=32&&!ae.has(T)){let se=ae.keys().next().value;if(se!==void 0)ae.delete(se)}ae.set(T,{columns:X,quoteStyle:J,sql:d})}if(!B._prepareStatement)g=A(d,y);return this},returning(...N){if(f)return v();if(n(e.dialect))return q(N);let V=`${d} RETURNING ${N.join(", ")}`,W=A(V,y),U=async()=>{let X=await te(W,"insert");return Array.isArray(X)?X[0]:X};return{where:()=>this,andWhere:()=>this,orWhere:()=>this,orderBy:()=>this,limit:()=>this,offset:()=>this,toSQL:()=>Ie(W,V),execute:()=>te(W,"insert"),get:()=>te(W,"insert"),first:U,executeTakeFirst:U,async firstOrFail(){let X=await U();if(!X)throw Error("Insert with RETURNING returned no rows");return X},async executeTakeFirstOrThrow(){let X=await U();if(!X)throw Error("Insert with RETURNING returned no rows");return X}}},toSQL(){if(f)return Ie(null,"");if(!g)g=A(d,y);return Ie(g,d)},execute(){if(f)return Promise.resolve(z());let N=me();if(!(N&&(N.onQueryStart||N.onQueryEnd||N.onQueryError||N.startSpan||N.beforeCreate||N.afterCreate||it(N)))){let W=B._prepareStatement;if(W){let U=W(d);return y.length>0?U.run(...y):U.run()}}if(!g)g=A(d,y);return te(g,"insert")},async executeTakeFirst(){if(f)return z();if(!g)g=A(d,y);return await te(g,"insert")},async executeTakeFirstOrThrow(){if(f)throw Error("Insert failed");if(!g)g=A(d,y);let N=await te(g,"insert");if(!N)throw Error("Insert failed");return N},returningAll(){return this.returning("*")}}},updateTable(T){let g,d=[],y=(v)=>{let K=String(v);if(n(e.dialect))return`\`${K.replace(/`/g,"``")}\``;return`"${K.replace(/"/g,'""')}"`},I=`UPDATE ${y(String(T))}`,f=!1,z=(v)=>{I=`${I} ${f?"AND":"WHERE"} ${v}`,f=!0};return{set(v){let K=Ee(String(T),[v])[0],q=Object.keys(K),R=q.length,J=Array.from({length:R});for(let k=0;k<R;k++){let N=q[k],V=K[N];if(at(V))ot(`set(${N})`);if(We(V))J[k]=`${y(N)} = ${V.raw}`;else if(Ve(V)){let W=Ge(V,d.length+1);J[k]=`${y(N)} = ${W.text}`,d.push(...W.parameters)}else J[k]=`${y(N)} = ${t(d.length+1)}`,d.push(V)}return I=`${I} SET ${J.join(", ")}`,g=A(I,d),this},where(v,K,q){if(K!==void 0&&(typeof v==="string"||We(v)||Ve(v))){let R=$e(K,"updateTable.where"),J;if(typeof v==="string")J=y(v);else if(We(v))J=v.raw;else{let N=Ge(v,d.length+1);J=N.text,d.push(...N.parameters)}if(R.toLowerCase()==="in"||R.toLowerCase()==="not in"){let N=Array.isArray(q)?q:[q],V=s(N.length,d.length+1);return z(`${J} ${R.toUpperCase()} (${V})`),d.push(...N),g=A(I,d),this}let k=d.length+1;return z(`${J} ${R} ${t(k)}`),d.push(q),g=A(I,d),this}if(Array.isArray(v)){let[R,J,k]=v,N=$e(J,"updateTable.where");if(N.toLowerCase()==="in"||N.toLowerCase()==="not in"){let W=Array.isArray(k)?k:[k],U=s(W.length,d.length+1);return z(`${y(String(R))} ${N.toUpperCase()} (${U})`),d.push(...W),g=A(I,d),this}let V=d.length+1;return z(`${y(String(R))} ${N} ${t(V)}`),d.push(k),g=A(I,d),this}if(at(v))ot("updateTable.where(expr)");if(We(v))return z(v.raw),g=A(I,d),this;if(Ve(v)){let R=Ge(v,d.length+1);return z(R.text),d.push(...R.parameters),g=A(I,d),this}if(v&&typeof v==="object"){let R=Object.keys(v);if(R.length===0)throw TypeError("[query-builder] updateTable.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if updating every row is intended.");let J=R.map((k)=>bt(y(k),v[k],d));return z(J.join(" AND ")),g=A(I,d),this}throw TypeError(`[query-builder] updateTable.where(): expected a condition, got ${v===null?"null":typeof v}. Refusing to run an UPDATE with no WHERE \u2014 drop the where() call if updating every row is intended.`)},whereNull(v){return z(`${y(String(v))} IS NULL`),g=A(I,d),this},whereNotNull(v){return z(`${y(String(v))} IS NOT NULL`),g=A(I,d),this},returning(...v){let K=this,q=()=>`${I} RETURNING ${v.join(", ")}`,R=()=>d.length>0?A(q(),d):A(q()),J=async()=>{let U=/\sWHERE\s/i.test(I),X=U?I.slice(I.search(/\sWHERE\s/i)+1):"",_=d.slice(d.length-(X.match(/\?|\$\d+/g)?.length??0)),G=y("id"),Q=await(_.length>0?A(`SELECT ${G} FROM ${y(String(T))}${U?` ${X}`:""}`,_):A(`SELECT ${G} FROM ${y(String(T))}${U?` ${X}`:""}`)).execute().catch(()=>[]),j=(Array.isArray(Q)?Q:[]).map((ce)=>ce?.id).filter((ce)=>ce!==void 0&&ce!==null);if(await te(d.length>0?A(I,d):A(I),"update"),j.length===0)return[];let ee=`SELECT ${v.join(", ")} FROM ${y(String(T))} WHERE ${G} IN (${j.map(()=>"?").join(", ")})`,se=await A(ee,j).execute();return Array.isArray(se)?se:[]},k=()=>n(e.dialect)?J():te(R(),"update"),N=async()=>{let U=await k();return Array.isArray(U)?U[0]:U},V=(U)=>()=>{throw TypeError(`[query-builder] updateTable.returning(...).${U}() is not supported \u2014 an UPDATE cannot be ordered or limited through this builder. Apply the filter with where() instead.`)},W={where:(...U)=>(K.where(...U),W),andWhere:(...U)=>(K.where(...U),W),whereNull:(...U)=>(K.whereNull(...U),W),whereNotNull:(...U)=>(K.whereNotNull(...U),W),orWhere:V("orWhere"),orderBy:V("orderBy"),limit:V("limit"),offset:V("offset"),toSQL:()=>Ie(R(),q()),execute:k,get:k,first:N,executeTakeFirst:N,async firstOrFail(){let U=await N();if(!U)throw Error("Update with RETURNING returned no rows");return U},async executeTakeFirstOrThrow(){let U=await N();if(!U)throw Error("Update with RETURNING returned no rows");return U}};return W},toSQL(){if(!g)g=d.length>0?A(I,d):A(I);return Ie(g,I)},async execute(){let v=await te(g,"update");return Le(v)},async executeTakeFirst(){return{numUpdatedRows:Le(await te(g,"update"))}},async executeTakeFirstOrThrow(){let v=Le(await te(g,"update"));if(v===0)throw Error("No rows updated");return{numUpdatedRows:v}},returningAll(){return this.returning("*")}}},deleteFrom(T){let g=(R)=>{let J=String(R);if(n(e.dialect))return`\`${J.replace(/`/g,"``")}\``;return`"${J.replace(/"/g,'""')}"`},y=`DELETE FROM ${g(String(T))}`,I=null,f=[],z=null,v=!1,K=(R)=>{y+=` ${v?"AND":"WHERE"} ${R}`,v=!0},q=()=>{if(I===null)I=f.length>0?A(y,f):A(y);return I};return{where(R,J,k){if(z=R,typeof R==="string"&&J!==void 0){let N=$e(J,"deleteFrom.where");if(N.toLowerCase()==="in"||N.toLowerCase()==="not in"){let W=Array.isArray(k)?k:[k],U=s(W.length,f.length+1);return K(`${g(R)} ${N.toUpperCase()} (${U})`),f.push(...W),I=null,this}let V=f.length+1;return K(`${g(R)} ${N} ${t(V)}`),f.push(k),I=null,this}if(Array.isArray(R)){let[N,V,W]=R,U=$e(V,"deleteFrom.where");if(U.toLowerCase()==="in"||U.toLowerCase()==="not in"){let _=Array.isArray(W)?W:[W],G=s(_.length,f.length+1);return K(`${g(String(N))} ${U.toUpperCase()} (${G})`),f.push(..._),I=null,this}let X=f.length+1;return K(`${g(String(N))} ${U} ${t(X)}`),f.push(W),I=null,this}if(at(R))ot("deleteFrom.where(expr)");if(We(R))return K(R.raw),I=null,this;if(Ve(R)){let N=Ge(R,f.length+1);return K(N.text),f.push(...N.parameters),I=null,this}if(R&&typeof R==="object"){let N=Object.keys(R);if(N.length===0)throw TypeError("[query-builder] deleteFrom.where({}): an empty object is not a filter. Pass a condition, or drop the where() call if deleting every row is intended.");let V=N.map((W)=>bt(g(W),R[W],f));return K(V.join(" AND ")),I=null,this}throw TypeError(`[query-builder] deleteFrom.where(): expected a condition, got ${R===null?"null":typeof R}. Refusing to run a DELETE with no WHERE \u2014 drop the where() call if deleting every row is intended.`)},whereNull(R){return K(`${g(String(R))} IS NULL`),I=null,this},whereNotNull(R){return K(`${g(String(R))} IS NOT NULL`),I=null,this},returning(...R){let J=this,k=()=>`${y} RETURNING ${R.join(", ")}`,N=()=>f.length>0?A(k(),f):A(k()),V=async()=>{await me()?.beforeDelete?.({table:String(T),where:z});let _=n(e.dialect)?await(async()=>{let G=y.slice(y.search(/\sFROM\s/i)+1),Q=`SELECT ${R.join(", ")} ${G}`,j=await(f.length>0?A(Q,f):A(Q)).execute();return await te(f.length>0?A(y,f):A(y),"delete"),Array.isArray(j)?j:[]})():await te(N(),"delete");try{await me()?.afterDelete?.({table:String(T),where:z,result:_})}catch{}return _},W=async()=>{let _=await V();return Array.isArray(_)?_[0]:_},U=(_)=>()=>{throw TypeError(`[query-builder] deleteFrom.returning(...).${_}() is not supported \u2014 a DELETE cannot be ordered or limited through this builder. Narrow it with where() instead.`)},X={where:(..._)=>(J.where(..._),X),andWhere:(..._)=>(J.where(..._),X),whereNull:(..._)=>(J.whereNull(..._),X),whereNotNull:(..._)=>(J.whereNotNull(..._),X),orWhere:U("orWhere"),orderBy:U("orderBy"),limit:U("limit"),offset:U("offset"),toSQL:()=>Ie(N(),k()),execute:()=>V(),get:()=>V(),first:W,executeTakeFirst:W,async firstOrFail(){let _=await W();if(!_)throw Error("Delete with RETURNING returned no rows");return _},async executeTakeFirstOrThrow(){let _=await W();if(!_)throw Error("Delete with RETURNING returned no rows");return _}};return X},toSQL(){return Ie(q(),y)},async execute(){try{await me()?.beforeDelete?.({table:String(T),where:z})}catch(J){throw J}let R=Le(await te(q(),"delete"));try{await me()?.afterDelete?.({table:String(T),where:z,result:R})}catch{}return R},async executeTakeFirst(){return{numDeletedRows:Le(await te(q(),"delete"))}},async executeTakeFirstOrThrow(){let R=Le(await te(q(),"delete"));if(R===0)throw Error("No rows deleted");return{numDeletedRows:R}},returningAll(){return this.returning("*")}}},table(T){let g=this;return{insert(d){return g.insertInto(T).values(d)},update(d){return g.updateTable(T).set(d)},delete(){return g.deleteFrom(T)},select(...d){if(d.length===0)return g.selectFrom(T);return g.select(T,...d)}}},sql:B,raw(T,...g){if(typeof T==="string")return Mt(T,g);return B(T,...g)},simple(T,...g){return B(T,...g).simple()},async advisoryLock(T){if(e.dialect==="postgres"){let g=pe(T),d=A("SELECT pg_advisory_lock($1)",[g]);await te(d,"raw");return}if(n(e.dialect)){let g=`bqb:${String(T)}`,d=A("SELECT GET_LOCK(?, -1) AS ok",[g]);await te(d,"raw");return}throw Error("[query-builder] advisoryLock() is not supported on SQLite \u2014 use a Postgres or MySQL deployment for distributed locking.")},async tryAdvisoryLock(T){if(e.dialect==="postgres"){let g=pe(T),d=A("SELECT pg_try_advisory_lock($1) as ok",[g]),y=await te(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(T)}`,d=A("SELECT GET_LOCK(?, 0) AS ok",[g]),y=await te(d,"raw");return Number(y?.[0]?.ok)===1}return!1},async advisoryUnlock(T){if(e.dialect==="postgres"){let g=pe(T),d=A("SELECT pg_advisory_unlock($1) as ok",[g]),y=await te(d,"raw");return Boolean(y?.[0]?.ok)}if(n(e.dialect)){let g=`bqb:${String(T)}`,d=A("SELECT RELEASE_LOCK(?) AS ok",[g]),y=await te(d,"raw");return Number(y?.[0]?.ok)===1}return!1},unsafe(T,g){return Ft(T,g),B.unsafe(T,g)},deferInsert:B.deferInsert?.bind(B),flushDeferredInserts:B.flushDeferredInserts?.bind(B),file(T,g){return B.file(T,g)},async reserve(){let T=await r.reserve(),g=i({sql:T,meta:w,schema:H,hooks:p?.hooks});return g.release=()=>T.release(),g},async close(T){await r.close(T)},async listen(T,g){},async unlisten(T){},async notify(T,g){},async copyTo(T,g){throw Error("COPY TO is not yet supported by Bun.sql; placeholder")},async copyFrom(T,g,d){throw Error("COPY FROM is not yet supported by Bun.sql; placeholder")},async ping(){try{let T=A("SELECT 1");return await te(T,"select"),!0}catch{return!1}},async waitForReady(T){let g=Math.max(1,T?.attempts??10),d=Math.max(10,T?.delayMs??100);for(let y=0;y<g;y++){if(await this.ping())return;await new Promise((I)=>setTimeout(I,d))}throw Error("Database not ready after waiting")},async transaction(T,g){let y={...p?.txDefaults,...g},I=p?.sql??r,f=p?.inTransaction===!0,z=f&&typeof I?.savepoint==="function"?"savepoint":"begin",v=async(J)=>{y.logger?.({type:"start",attempt:J});let k=Date.now();return await I[z](async(N)=>{let V=i({sql:N,meta:w,schema:H,hooks:p?.hooks,inTransaction:!0});if(y?.isolation&&!f){let X=y.isolation,_=X==="read committed"?"READ COMMITTED":X==="repeatable read"?"REPEATABLE READ":"SERIALIZABLE";if(e.dialect==="postgres")await N.unsafe(`SET TRANSACTION ISOLATION LEVEL ${_}`);else if(n(e.dialect))await N.unsafe(`SET TRANSACTION ISOLATION LEVEL ${_}`);else if(X!=="serializable")throw Error(`[query-builder] transaction({ isolation: '${X}' }) not supported on SQLite (only 'serializable'). Use a Postgres or MySQL deployment for finer-grained isolation.`)}if(y?.readOnly)if(e.dialect==="postgres")await N.unsafe("SET TRANSACTION READ ONLY");else if(n(e.dialect))await N.unsafe("SET TRANSACTION READ ONLY");else throw Error("[query-builder] transaction({ readOnly: true }) not supported on SQLite. Use a Postgres or MySQL deployment.");let W=await T(V),U=Date.now()-k;return y.logger?.({type:"commit",attempt:J,durationMs:U}),W})},K=Math.max(0,y?.retries??0),q=0,R;for(;;)try{R=await v(q+1);break}catch(J){let k=Ht(J)||Vt(J,y.sqlStates);if(q<K&&k){q++,y?.onRetry?.(q,J);let N=tn(q,y.backoff);if(N>0)await Gt(N);continue}try{y.onRollback?.(J)}catch{}try{y.afterRollback?.()}catch{}throw J}return await y.afterCommit?.(),R},async savepoint(T){if(p?.inTransaction!==!0)throw Error("savepoint() must be called inside a transaction");let g=B;if(!g||typeof g.savepoint!=="function")throw Error("savepoint() is not supported by the active connection");return await g.savepoint(async(d)=>{let y=i({sql:d,meta:w,schema:H,hooks:p?.hooks,inTransaction:!0});return await T(y)})},async beginDistributed(T,g){return await(p?.sql??r).beginDistributed(T,async(I)=>{let f=i({sql:I,meta:w,schema:H,hooks:p?.hooks});return await g(f)})},async commitDistributed(T){await r.commitDistributed(T)},async rollbackDistributed(T){await r.rollbackDistributed(T)},setTransactionDefaults(T){p={...p,txDefaults:{...p?.txDefaults,...T}}},transactional(T,g){return(...d)=>this.transaction((y)=>T(y,...d),g)},async insertOrIgnore(T,g){let d=Array.isArray(g)?g:[g];if(!d.length)return;let{colsSql:y,valuesSql:I,params:f}=ht(d),z=De(String(T)),v=n(e.dialect)?`INSERT IGNORE INTO ${z} (${y}) VALUES ${I}`:`INSERT INTO ${z} (${y}) VALUES ${I} ON CONFLICT DO NOTHING`;return A(v,f).execute()},async insertGetId(T,g,d="id"){let{colsSql:y,valuesSql:I,params:f}=ht([g]),z=De(String(T));if(n(e.dialect)){await A(`INSERT INTO ${z} (${y}) VALUES ${I}`,f).execute();let[K]=await A("SELECT LAST_INSERT_ID() as id").execute();return K?.id}if(e.dialect==="sqlite"){let K=await A(`INSERT INTO ${z} (${y}) VALUES ${I}`,f).execute();if(K?.lastInsertRowid!=null)return K.lastInsertRowid;let[q]=await A("SELECT last_insert_rowid() as id").execute();return q?.id}let[v]=await A(`INSERT INTO ${z} (${y}) VALUES ${I} RETURNING ${De(String(d))} as id`,f).execute();return v?.id},async updateOrInsert(T,g,d){let y=De(String(T)),I=Object.keys(g),f=1,z=I.map((k)=>`${De(k)} = ${t(f++)}`).join(" AND "),v=I.map((k)=>g[k]);if((await A(`SELECT 1 FROM ${y} WHERE ${z} LIMIT 1`,v).execute()).length){let k=Object.keys(d),N=1,V=k.map((X)=>`${De(X)} = ${t(N++)}`).join(", "),W=I.map((X)=>`${De(X)} = ${t(N++)}`).join(" AND "),U=[...k.map((X)=>d[X]),...I.map((X)=>g[X])];return await A(`UPDATE ${y} SET ${V} WHERE ${W}`,U).execute(),!0}let{colsSql:q,valuesSql:R,params:J}=ht([{...g,...d}]);return await A(`INSERT INTO ${y} (${q}) VALUES ${R}`,J).execute(),!0},async upsert(T,g,d,y){let I=d.map((V)=>String(V)),f=(y??[]).map((V)=>String(V)),z=g;if(!z.length)return;let{colsSql:v,valuesSql:K,params:q}=ht(z),R=De(String(T)),J=`INSERT INTO ${R} (${v}) VALUES ${K}`;if(n(e.dialect)){if(f.length===0)return A(`INSERT IGNORE INTO ${R} (${v}) VALUES ${K}`,q).execute();let V=f.map((W)=>`${De(W)} = VALUES(${De(W)})`).join(", ");return A(`${J} ON DUPLICATE KEY UPDATE ${V}`,q).execute()}let k=I.map(De).join(", ");if(f.length===0)return A(`${J} ON CONFLICT (${k}) DO NOTHING`,q).execute();let N=f.map((V)=>`${De(V)} = EXCLUDED.${De(V)}`).join(", ");return A(`${J} ON CONFLICT (${k}) DO UPDATE SET ${N}`,q).execute()},async save(T,g){let d=w?.primaryKeys[String(T)]??"id",y=g[d];if(y!=null)if(await this.selectFrom(T).find(y)){await this.updateTable(T).set(g).where({[d]:y}).execute();let f=await this.selectFrom(T).find(y);if(!f)throw Error("save() failed to retrieve updated row");return f}else return await this.create(T,g);return await this.create(T,g)},async remove(T,g){return await this.deleteFrom(T).where({id:g}).execute()},async find(T,g){return await this.selectFrom(T).find(g)},async findOrFail(T,g){return await this.selectFrom(T).findOrFail(g)},async findMany(T,g){return await this.selectFrom(T).findMany(g)},async latest(T,g){return await this.selectFrom(T).latest(g).first()},async oldest(T,g){return await this.selectFrom(T).oldest(g).first()},skip(T,g){return this.selectFrom(T).offset(g)},async rawQuery(T){let g=Date.now();try{me()?.onQueryStart?.({sql:T,kind:"raw"});let d=await B.unsafe(T);return me()?.onQueryEnd?.({sql:T,durationMs:Date.now()-g,kind:"raw"}),d}catch(d){throw me()?.onQueryError?.({sql:T,error:d,durationMs:Date.now()-g,kind:"raw"}),d}},async create(T,g){let d=w?.primaryKeys[String(T)]??"id";try{await me()?.beforeCreate?.({table:String(T),data:g})}catch(y){throw y}if(e.dialect==="postgres"){let y=B`INSERT INTO ${B(String(T))} ${B(g)} RETURNING ${B(String(d))} as id`,[I]=await y.execute();if(!I?.id)throw console.error(`create() failed to get insert ID for table ${String(T)}`),console.error("Inserted values:",g),Error(`create() failed to get insert ID for table ${String(T)}`);let f=await this.selectFrom(T).find(I.id);if(!f)throw console.error(`create() failed to retrieve inserted row for table ${String(T)} with id ${I.id}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(T)} with id ${I.id}`);try{await me()?.afterCreate?.({table:String(T),data:g,result:f})}catch{}return f}else{let y=await this.insertGetId(T,g,d);if(y==null)throw Error(`create() failed to get insert ID for table ${String(T)}`);let I=await this.selectFrom(T).find(y);if(!I)throw console.error(`create() failed to retrieve inserted row for table ${String(T)} with id ${y}`),console.error("Inserted values:",g),Error(`create() failed to retrieve inserted row for table ${String(T)} with id ${y}`);try{await me()?.afterCreate?.({table:String(T),data:g,result:I})}catch{}return I}},async createMany(T,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),I=y.length,f=g.length,z=Array.from({length:f*I}),v=n(e.dialect)?(R)=>`\`${String(R).replace(/`/g,"``")}\``:(R)=>`"${String(R).replace(/"/g,'""')}"`,K=`INSERT INTO ${v(String(T))}(${y.map(v).join(",")})VALUES`,q=0;for(let R=0;R<f;R++){if(R>0)K+=",";K+="(";let J=g[R];for(let k=0;k<I;k++){if(k>0)K+=",";K+=t(q+1),z[q++]=J[y[k]]}K+=")"}return A(K,z).execute()},async insertMany(T,g){if(!g?.length)return;let d=g[0],y=Object.keys(d),I=y.length,f=g.length,z=f*I,v=Array(z),K=e.dialect==="postgres",q;if(!K){let k=Array(I);for(let N=0;N<I;N++)k[N]="?";q=`(${k.join(",")})`}else q="";let R=Array(f+2);R[0]=`INSERT INTO ${T}(${y.join(",")})VALUES`;let J=0;if(!K){for(let k=0;k<f;k++){let N=g[k];R[k+1]=q;for(let V=0;V<I;V++)v[J++]=N[y[V]]}return A(R[0]+R.slice(1,f+1).join(","),v).execute()}for(let k=0;k<f;k++){let N=g[k],V=Array(I);for(let W=0;W<I;W++)V[W]=`$${J+1}`,v[J++]=N[y[W]];R[k+1]=`(${V.join(",")})`}return A(R[0]+R.slice(1,f+1).join(","),v).execute()},async updateMany(T,g,d){let y=Object.keys(d),I=y.length;if(I===0)return 0;let f=[],z=Array.from({length:I});for(let K=0;K<I;K++)z[K]=`${y[K]}=${t(K+1)}`,f.push(d[y[K]]);let v=`UPDATE ${T} SET ${z.join(",")}`;if(Array.isArray(g)){let K=$e(String(g[1]),"updateMany");v+=` WHERE ${g[0]} ${K} ${t(f.length+1)}`,f.push(g[2])}else if(We(g))v+=` WHERE ${g.raw}`;else if(Ve(g)){let K=Ge(g,f.length+1);v+=` WHERE ${K.text}`,f.push(...K.parameters)}else if(g&&typeof g==="object"&&Object.keys(g).length>0){let K=Object.keys(g).map((q)=>bt(q,g[q],f));v+=` WHERE ${K.join(" AND ")}`}else if(g&&typeof g==="object")throw TypeError("[query-builder] updateMany(): an empty object is not a filter. Pass a condition, or use updateTable(table).set(data).execute() if updating every row is intended.");else throw TypeError(`[query-builder] updateMany(): expected a condition, got ${g===null?"null":typeof g}. Refusing to run an UPDATE with no WHERE \u2014 use updateTable(table).set(data).execute() if updating every row is intended.`);return A(v,f).execute()},async deleteMany(T,g){if(!Array.isArray(g)||g.length===0)return 0;let d=w?.primaryKeys[String(T)]??"id",y=g.length;if(e.dialect==="postgres"){let f=Array(y);for(let z=0;z<y;z++)f[z]=`$${z+1}`;return A(`DELETE FROM ${T} WHERE ${d} IN (${f.join(",")})`,g).execute()}let I=Array(y);for(let f=0;f<y;f++)I[f]="?";return A(`DELETE FROM ${T} WHERE ${d} IN (${I.join(",")})`,g).execute()},async firstOrCreate(T,g,d){let y=await this.selectFrom(T).where(g).first();if(y)return y;return await this.create(T,{...g,...d})},async updateOrCreate(T,g,d){let y=await this.selectFrom(T).where(g).first();if(y){await this.updateTable(T).set(d).where(g).execute();let I=w?.primaryKeys[String(T)]??"id",f=y[I],z=f!=null?await this.selectFrom(T).find(f):await this.selectFrom(T).where(g).first();if(!z)throw Error("updateOrCreate() failed to retrieve updated row");return z}return await this.create(T,{...g,...d})},async count(T,g){let d=g?B(String(g)):B`*`,y=B`SELECT COUNT(${d}) as c FROM ${B(String(T))}`,[I]=await y.execute();return Number(I?.c??0)},async sum(T,g){let d=B`SELECT SUM(${B(String(g))}) as s FROM ${B(String(T))}`,[y]=await d.execute();return Number(y?.s??0)},async avg(T,g){let d=B`SELECT AVG(${B(String(g))}) as a FROM ${B(String(T))}`,[y]=await d.execute();return Number(y?.a??0)},async min(T,g){let d=B`SELECT MIN(${B(String(g))}) as m FROM ${B(String(T))}`,[y]=await d.execute();return y?.m},async max(T,g){let d=B`SELECT MAX(${B(String(g))}) as m FROM ${B(String(T))}`,[y]=await d.execute();return y?.m},getRelationships(T){if(!w?.relations)return{};let g=w.relations[T];if(!g)return{};let d={};for(let[y,I]of Object.entries(g))if(I&&typeof I==="object"&&Object.keys(I).length>0)d[y]=I;return d},hasRelationship(T,g){if(!w?.relations)return!1;let d=w.relations[T];if(!d)return!1;return Object.values(d).some((y)=>y&&typeof y==="object"&&(g in y))},getRelationshipType(T,g){if(!w?.relations)return null;let d=w.relations[T];if(!d)return null;for(let[y,I]of Object.entries(d))if(I&&typeof I==="object"&&g in I)return y;return null},getRelationshipTarget(T,g){if(!w?.relations)return null;let d=w.relations[T];if(!d)return null;for(let[y,I]of Object.entries(d))if(I&&typeof I==="object"&&g in I){let f=I[g];if(typeof f==="string")return w.modelToTable[f]||f;else if(f&&typeof f==="object"){if("model"in f)return w.modelToTable[f.model]||f.model;if("target"in f)return w.modelToTable[f.target]||f.target}}return null}}}function Ce(){ft.clear()}function Re(p){ft.setMaxSize(p)}
3
+ export{E,Nn,Jt,c,$t,xt,i,Ce,Re};
@@ -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-455vt4nn.js";import{Database as Te}from"bun:sqlite";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"}}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-zkgctd8f.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,7 +1,7 @@
1
1
  // @bun
2
- class Tt{config;entityMappings=new Map;constructor(t){if(this.config=t,t.entityMappings)for(let e of t.entityMappings)this.registerEntity(e)}createTable(t){return{...t,billingMode:t.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable(t){return{tableName:t}}registerEntity(t){this.entityMappings.set(t.entityType,t)}getEntityMapping(t){return this.entityMappings.get(t)}buildPrimaryKey(t,e){let i=this.entityMappings.get(t);if(!i)throw Error(`No entity mapping found for type: ${t}`);let n=this.interpolatePattern(i.pkPattern,e),r=this.interpolatePattern(i.skPattern,e);return{pk:n,sk:r}}parseEntityFromItem(t){let e=t.pk||t.PK;if(!e)return null;for(let[i,n]of this.entityMappings){let r=n.pkPattern.split("${")[0];if(e.startsWith(r))return{entityType:i,data:this.unmarshall(t)}}return null}buildQueryParams(t){return{tableName:t.tableName??this.config.tableName??"",keyConditions:t.keyConditions??[],...t}}buildScanParams(t){return{tableName:t.tableName??this.config.tableName??"",...t}}buildGetItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},...t}}buildPutItemParams(t){return{tableName:t.tableName??this.config.tableName??"",item:t.item??{},...t}}buildUpdateItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},updateExpressions:t.updateExpressions??{},...t}}buildDeleteItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},...t}}buildBatchGetItemParams(t){return{requestItems:t.requestItems??{}}}buildBatchWriteItemParams(t){return{requestItems:t.requestItems??{}}}buildTransactWriteParams(t){return{transactItems:t.transactItems??[],...t}}buildKeyConditionExpression(t){return this.buildExpression(t,"AND")}buildFilterExpression(t){return this.buildExpression(t,"AND")}buildUpdateExpression(t){let e={},i={},n=[],r=0;if(t.set&&Object.keys(t.set).length>0){let a=[];for(let[s,o]of Object.entries(t.set)){let l=`#attr${r}`,u=`:val${r}`;e[l]=s,i[u]=this.marshallValue(o),a.push(`${l} = ${u}`),r++}n.push(`SET ${a.join(", ")}`)}if(t.remove&&t.remove.length>0){let a=[];for(let s of t.remove){let o=`#attr${r}`;e[o]=s,a.push(o),r++}n.push(`REMOVE ${a.join(", ")}`)}if(t.add&&Object.keys(t.add).length>0){let a=[];for(let[s,o]of Object.entries(t.add)){let l=`#attr${r}`,u=`:val${r}`;e[l]=s,i[u]=this.marshallValue(o),a.push(`${l} ${u}`),r++}n.push(`ADD ${a.join(", ")}`)}if(t.delete&&Object.keys(t.delete).length>0){let a=[];for(let[s,o]of Object.entries(t.delete)){let l=`#attr${r}`,u=`:val${r}`;e[l]=s,i[u]=this.marshallValue(o),a.push(`${l} ${u}`),r++}n.push(`DELETE ${a.join(", ")}`)}return{expression:n.join(" "),expressionAttributeNames:e,expressionAttributeValues:i}}buildProjectionExpression(t){let e={},i=[];return t.forEach((n,r)=>{let a=`#proj${r}`;e[a]=n,i.push(a)}),{expression:i.join(", "),expressionAttributeNames:e}}marshall(t){let e={};for(let[i,n]of Object.entries(t))e[i]=this.marshallValue(n);return e}unmarshall(t){let e={};for(let[i,n]of Object.entries(t))e[i]=this.unmarshallValue(n);return e}interpolatePattern(t,e){return t.replace(/\$\{(\w+)\}/g,(i,n)=>{if(!(n in e))throw Error(`Missing value for pattern key: ${n}`);return String(e[n])})}buildExpression(t,e){let i={},n={},r=[];return t.forEach((a,s)=>{let o=`#attr${s}`;i[o]=a.attribute;let l;switch(a.operator){case"=":case"<":case"<=":case">":case">=":{let u=`:val${s}`;n[u]=this.marshallValue(a.value),l=`${o} ${a.operator} ${u}`;break}case"BETWEEN":{let u=`:val${s}a`,y=`:val${s}b`;n[u]=this.marshallValue(a.values?.[0]),n[y]=this.marshallValue(a.values?.[1]),l=`${o} BETWEEN ${u} AND ${y}`;break}case"begins_with":{let u=`:val${s}`;n[u]=this.marshallValue(a.value),l=`begins_with(${o}, ${u})`;break}case"contains":{let u=`:val${s}`;n[u]=this.marshallValue(a.value),l=`contains(${o}, ${u})`;break}case"attribute_exists":l=`attribute_exists(${o})`;break;case"attribute_not_exists":l=`attribute_not_exists(${o})`;break;case"attribute_type":{let u=`:val${s}`;n[u]={S:a.value},l=`attribute_type(${o}, ${u})`;break}case"IN":{let u=(a.values??[]).map((y,p)=>`:val${s}_${p}`);a.values?.forEach((y,p)=>{n[`:val${s}_${p}`]=this.marshallValue(y)}),l=`${o} IN (${u.join(", ")})`;break}default:throw Error(`Unknown operator: ${a.operator}`)}r.push(l)}),{expression:r.join(` ${e} `),expressionAttributeNames:i,expressionAttributeValues:n}}marshallValue(t){if(t===null||t===void 0)return{NULL:!0};if(typeof t==="string")return{S:t};if(typeof t==="number")return{N:String(t)};if(typeof t==="boolean")return{BOOL:t};if(t instanceof Uint8Array||Buffer.isBuffer(t))return{B:t};if(Array.isArray(t)){if(t.length===0)return{L:[]};let e=typeof t[0],i=t.every((r)=>typeof r==="string"),n=t.every((r)=>typeof r==="number");if(i)return{SS:t};if(n)return{NS:t.map(String)};return{L:t.map((r)=>this.marshallValue(r))}}if(typeof t==="object"){let e={};for(let[i,n]of Object.entries(t))e[i]=this.marshallValue(n);return{M:e}}return{S:String(t)}}unmarshallValue(t){if(!t||typeof t!=="object")return t;if("S"in t)return t.S;if("N"in t)return Number(t.N);if("BOOL"in t)return t.BOOL;if("NULL"in t)return null;if("B"in t)return t.B;if("SS"in t)return t.SS;if("NS"in t)return t.NS.map(Number);if("BS"in t)return t.BS;if("L"in t)return t.L.map((e)=>this.unmarshallValue(e));if("M"in t){let e={};for(let[i,n]of Object.entries(t.M))e[i]=this.unmarshallValue(n);return e}return t}}function c(t){return new Tt(t)}async function S(t,e){let i=t instanceof ArrayBuffer?t:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),n=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",n,new TextEncoder().encode(e))}async function w(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(e)).map((i)=>i.toString(16).padStart(2,"0")).join("")}async function W(t,e,i,n){let r=await S(new TextEncoder().encode(`AWS4${t}`),e),a=await S(r,i),s=await S(a,n);return S(s,"aws4_request")}async function q(t,e,i,n,r,a,s){let l=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),u=l.slice(0,8),y=e.pathname,p=e.search.slice(1),m={...i,host:e.host,"x-amz-date":l};if(r.sessionToken)m["x-amz-security-token"]=r.sessionToken;let h=Object.keys(m).sort(),f=h.map((T)=>`${T.toLowerCase()}:${m[T].trim()}`).join(`
2
+ class vt{config;entityMappings=new Map;constructor(t){if(this.config=t,t.entityMappings)for(let e of t.entityMappings)this.registerEntity(e)}createTable(t){return{...t,billingMode:t.billingMode??this.config.defaultBillingMode??"PAY_PER_REQUEST"}}deleteTable(t){return{tableName:t}}registerEntity(t){this.entityMappings.set(t.entityType,t)}getEntityMapping(t){return this.entityMappings.get(t)}buildPrimaryKey(t,e){let i=this.entityMappings.get(t);if(!i)throw Error(`No entity mapping found for type: ${t}`);let n=this.interpolatePattern(i.pkPattern,e),r=this.interpolatePattern(i.skPattern,e);return{pk:n,sk:r}}parseEntityFromItem(t){let e=t.pk||t.PK;if(!e)return null;for(let[i,n]of this.entityMappings){let r=n.pkPattern.split("${")[0];if(e.startsWith(r))return{entityType:i,data:this.unmarshall(t)}}return null}buildQueryParams(t){return{tableName:t.tableName??this.config.tableName??"",keyConditions:t.keyConditions??[],...t}}buildScanParams(t){return{tableName:t.tableName??this.config.tableName??"",...t}}buildGetItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},...t}}buildPutItemParams(t){return{tableName:t.tableName??this.config.tableName??"",item:t.item??{},...t}}buildUpdateItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},updateExpressions:t.updateExpressions??{},...t}}buildDeleteItemParams(t){return{tableName:t.tableName??this.config.tableName??"",key:t.key??{},...t}}buildBatchGetItemParams(t){return{requestItems:t.requestItems??{}}}buildBatchWriteItemParams(t){return{requestItems:t.requestItems??{}}}buildTransactWriteParams(t){return{transactItems:t.transactItems??[],...t}}buildKeyConditionExpression(t){return this.buildExpression(t,"AND")}buildFilterExpression(t){return this.buildExpression(t,"AND")}buildUpdateExpression(t){let e={},i={},n=[],r=0;if(t.set&&Object.keys(t.set).length>0){let a=[];for(let[s,o]of Object.entries(t.set)){let l=`#attr${r}`,c=`:val${r}`;e[l]=s,i[c]=this.marshallValue(o),a.push(`${l} = ${c}`),r++}n.push(`SET ${a.join(", ")}`)}if(t.remove&&t.remove.length>0){let a=[];for(let s of t.remove){let o=`#attr${r}`;e[o]=s,a.push(o),r++}n.push(`REMOVE ${a.join(", ")}`)}if(t.add&&Object.keys(t.add).length>0){let a=[];for(let[s,o]of Object.entries(t.add)){let l=`#attr${r}`,c=`:val${r}`;e[l]=s,i[c]=this.marshallValue(o),a.push(`${l} ${c}`),r++}n.push(`ADD ${a.join(", ")}`)}if(t.delete&&Object.keys(t.delete).length>0){let a=[];for(let[s,o]of Object.entries(t.delete)){let l=`#attr${r}`,c=`:val${r}`;e[l]=s,i[c]=this.marshallValue(o),a.push(`${l} ${c}`),r++}n.push(`DELETE ${a.join(", ")}`)}return{expression:n.join(" "),expressionAttributeNames:e,expressionAttributeValues:i}}buildProjectionExpression(t){let e={},i=[];return t.forEach((n,r)=>{let a=`#proj${r}`;e[a]=n,i.push(a)}),{expression:i.join(", "),expressionAttributeNames:e}}marshall(t){let e={};for(let[i,n]of Object.entries(t))e[i]=this.marshallValue(n);return e}unmarshall(t){let e={};for(let[i,n]of Object.entries(t))e[i]=this.unmarshallValue(n);return e}interpolatePattern(t,e){return t.replace(/\$\{(\w+)\}/g,(i,n)=>{if(!(n in e))throw Error(`Missing value for pattern key: ${n}`);return String(e[n])})}buildExpression(t,e){let i={},n={},r=[];return t.forEach((a,s)=>{let o=`#attr${s}`;i[o]=a.attribute;let l;switch(a.operator){case"=":case"<":case"<=":case">":case">=":{let c=`:val${s}`;n[c]=this.marshallValue(a.value),l=`${o} ${a.operator} ${c}`;break}case"BETWEEN":{let c=`:val${s}a`,y=`:val${s}b`;n[c]=this.marshallValue(a.values?.[0]),n[y]=this.marshallValue(a.values?.[1]),l=`${o} BETWEEN ${c} AND ${y}`;break}case"begins_with":{let c=`:val${s}`;n[c]=this.marshallValue(a.value),l=`begins_with(${o}, ${c})`;break}case"contains":{let c=`:val${s}`;n[c]=this.marshallValue(a.value),l=`contains(${o}, ${c})`;break}case"attribute_exists":l=`attribute_exists(${o})`;break;case"attribute_not_exists":l=`attribute_not_exists(${o})`;break;case"attribute_type":{let c=`:val${s}`;n[c]={S:a.value},l=`attribute_type(${o}, ${c})`;break}case"IN":{let c=(a.values??[]).map((y,d)=>`:val${s}_${d}`);a.values?.forEach((y,d)=>{n[`:val${s}_${d}`]=this.marshallValue(y)}),l=`${o} IN (${c.join(", ")})`;break}default:throw Error(`Unknown operator: ${a.operator}`)}r.push(l)}),{expression:r.join(` ${e} `),expressionAttributeNames:i,expressionAttributeValues:n}}marshallValue(t){if(t===null||t===void 0)return{NULL:!0};if(typeof t==="string")return{S:t};if(typeof t==="number")return{N:String(t)};if(typeof t==="boolean")return{BOOL:t};if(t instanceof Uint8Array||Buffer.isBuffer(t))return{B:t};if(Array.isArray(t)){if(t.length===0)return{L:[]};let e=typeof t[0],i=t.every((r)=>typeof r==="string"),n=t.every((r)=>typeof r==="number");if(i)return{SS:t};if(n)return{NS:t.map(String)};return{L:t.map((r)=>this.marshallValue(r))}}if(typeof t==="object"){let e={};for(let[i,n]of Object.entries(t))e[i]=this.marshallValue(n);return{M:e}}return{S:String(t)}}unmarshallValue(t){if(!t||typeof t!=="object")return t;if("S"in t)return t.S;if("N"in t)return Number(t.N);if("BOOL"in t)return t.BOOL;if("NULL"in t)return null;if("B"in t)return t.B;if("SS"in t)return t.SS;if("NS"in t)return t.NS.map(Number);if("BS"in t)return t.BS;if("L"in t)return t.L.map((e)=>this.unmarshallValue(e));if("M"in t){let e={};for(let[i,n]of Object.entries(t.M))e[i]=this.unmarshallValue(n);return e}return t}}function u(t){return new vt(t)}async function S(t,e){let i=t instanceof ArrayBuffer?t:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),n=await crypto.subtle.importKey("raw",i,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",n,new TextEncoder().encode(e))}async function w(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(e)).map((i)=>i.toString(16).padStart(2,"0")).join("")}async function G(t,e,i,n){let r=await S(new TextEncoder().encode(`AWS4${t}`),e),a=await S(r,i),s=await S(a,n);return S(s,"aws4_request")}async function W(t,e,i,n,r,a,s){let l=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),c=l.slice(0,8),y=e.pathname,d=e.search.slice(1),m={...i,host:e.host,"x-amz-date":l};if(r.sessionToken)m["x-amz-security-token"]=r.sessionToken;let g=Object.keys(m).sort(),D=g.map((T)=>`${T.toLowerCase()}:${m[T].trim()}`).join(`
3
3
  `)+`
4
- `,A=h.map((T)=>T.toLowerCase()).join(";"),B=await w(n),M=[t,y,p,f,A,B].join(`
5
- `),K=await w(M),P="AWS4-HMAC-SHA256",_=`${u}/${a}/${s}/aws4_request`,L=[P,l,_,K].join(`
6
- `),O=await W(r.secretAccessKey,u,a,s),U=await S(O,L),j=Array.from(new Uint8Array(U)).map((T)=>T.toString(16).padStart(2,"0")).join(""),V=`${P} Credential=${r.accessKeyId}/${_}, SignedHeaders=${A}, Signature=${j}`;return{...m,authorization:V}}class Q{config;endpoint;credentials;constructor(t){if(this.config=t,this.endpoint=t.endpoint??`https://dynamodb.${t.region}.amazonaws.com`,this.credentials=t.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute(t,e){let i=new URL(this.endpoint),n=JSON.stringify(e),r={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${t}`},a=await q("POST",i,r,n,this.credentials,this.config.region,"dynamodb"),s=await fetch(i.toString(),{method:"POST",headers:a,body:n});if(!s.ok){let o=await s.text(),l;try{let u=JSON.parse(o);l=u.message??u.Message??o}catch{l=o}throw Error(`DynamoDB ${t} failed: ${s.status} - ${l}`)}return s.json()}async query(t){return this.execute("Query",t)}async scan(t){return this.execute("Scan",t)}async getItem(t){return this.execute("GetItem",t)}async putItem(t){return this.execute("PutItem",t)}async updateItem(t){return this.execute("UpdateItem",t)}async deleteItem(t){return this.execute("DeleteItem",t)}async batchGetItem(t){return this.execute("BatchGetItem",t)}async batchWriteItem(t){return this.execute("BatchWriteItem",t)}async transactWriteItems(t){return this.execute("TransactWriteItems",t)}async describeTable(t){return this.execute("DescribeTable",{TableName:t})}async createTable(t){return this.execute("CreateTable",t)}async deleteTable(t){return this.execute("DeleteTable",{TableName:t})}async listTables(t){return this.execute("ListTables",t??{})}async updateTable(t){return this.execute("UpdateTable",t)}async updateTimeToLive(t){return this.execute("UpdateTimeToLive",t)}async describeTimeToLive(t){return this.execute("DescribeTimeToLive",{TableName:t})}}function E(t){return new Q(t)}var g={region:process.env.AWS_REGION??"us-east-1"},v=null,N=null;function wt(t){g={...g,...t},v=null,N=null}function b(){if(!v)v=E({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return v}function D(){if(!N)N=c({region:g.region??"us-east-1",endpoint:g.endpoint,credentials:g.credentials});return N}class qe{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor(t={}){this._attributes={...t},this._original={...t};for(let[e,i]of Object.entries(t))this[e]=i}static query(){return new R(this)}static async find(t){let e=this,i=b(),n=D(),r=`${e.pkPrefix}${e.keyDelimiter}${t}`,a=e.skPrefix;try{let s=await i.getItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:r,[e.skAttribute]:a})});if(!s.Item)return null;let o=n.unmarshall(s.Item),l=new e(o);return l._exists=!0,l}catch(s){return console.error("Find error:",s),null}}static async findOrFail(t){let e=await this.find(t);if(!e)throw Error(`${this.name} not found with id: ${t}`);return e}static async all(){return this.query().get()}static async create(t){let e=this,i=b(),n=D(),r=t[e.primaryKey];if(!r)throw Error(`${e.primaryKey} is required`);let a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t,[e.pkAttribute]:a,[e.skAttribute]:s,[e.entityTypeAttribute]:e.name};if(e.timestamps)l[e.createdAtField]=o,l[e.updatedAtField]=o;await i.putItem({TableName:e.tableName,Item:n.marshall(l),ConditionExpression:`attribute_not_exists(${e.pkAttribute})`});let u=new e(l);return u._exists=!0,u}static async updateOrCreate(t,e){let i=this,n=t[i.primaryKey],r=await i.find(n);if(r)return await r.update(e),r;return i.create({...t,...e})}static where(t,e,i){return this.query().where(t,e,i)}static wherePk(t){return this.query().wherePk(t)}getKey(){let t=this.constructor;return this[t.primaryKey]}getAttribute(t){return this._attributes[t]}setAttribute(t,e){return this._attributes[t]=e,this[t]=e,this}getAttributes(){return{...this._attributes}}isDirty(t){if(t)return this._attributes[t]!==this._original[t];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let t={};for(let[e,i]of Object.entries(this._attributes))if(i!==this._original[e])t[e]=i;return t}async save(){if(this._exists){let t=this.getDirty();if(Object.keys(t).length>0)await this.update(t)}else{let e=await this.constructor.create(this._attributes);this._attributes=e._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(t){let e=this.constructor,i=b(),n=D(),r=this.getKey(),a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t};if(e.timestamps)l[e.updatedAtField]=o;let u=[],y={},p={},m=0;for(let[h,f]of Object.entries(l)){let A=`#attr${m}`,B=`:val${m}`;y[A]=h,p[B]=n.marshall({v:f}).v,u.push(`${A} = ${B}`),m++}await i.updateItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:a,[e.skAttribute]:s}),UpdateExpression:`SET ${u.join(", ")}`,ExpressionAttributeNames:y,ExpressionAttributeValues:p});for(let[h,f]of Object.entries(l))this._attributes[h]=f,this[h]=f;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=b(),i=D(),n=this.getKey(),r=`${t.pkPrefix}${t.keyDelimiter}${n}`,a=t.skPrefix;return await e.deleteItem({TableName:t.tableName,Key:i.marshall({[t.pkAttribute]:r,[t.skAttribute]:a})}),this._exists=!1,!0}async refresh(){let e=await this.constructor.find(this.getKey());if(e){this._attributes=e._attributes,this._original={...this._attributes};for(let[i,n]of Object.entries(this._attributes))this[i]=n}return this}toObject(){let t=this.constructor,e={...this._attributes};return delete e[t.pkAttribute],delete e[t.skAttribute],delete e[t.entityTypeAttribute],e}toJSON(){return this.toObject()}}class R{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(t){this.ModelClass=t}wherePk(t){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${t}`,this}where(t,e,i){if(i===void 0)this._filterConditions.push({attribute:t,operator:"=",value:e});else this._filterConditions.push({attribute:t,operator:e,value:i});return this}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}whereBetween(t,e,i){return this._filterConditions.push({attribute:t,operator:"BETWEEN",value:e,values:[e,i]}),this}whereBeginsWith(t,e){return this._filterConditions.push({attribute:t,operator:"begins_with",value:e}),this}whereExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_exists"}),this}whereNotExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_not_exists"}),this}orderBy(t){return this._scanForward=t==="asc",this}limit(t){return this._limitValue=t,this}select(...t){return this._projectionAttrs.push(...t),this}index(t){return this._indexName=t,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(t){return this._startKey=t,this}buildRequest(){let t=D(),e={TableName:this.ModelClass.tableName};if(this._indexName)e.IndexName=this._indexName;let i={},n={},r=0,a=[];if(this._pkValue){let s=`#pk${r}`,o=`:pk${r}`;i[s]=this.ModelClass.pkAttribute,n[o]={S:this._pkValue},a.push(`${s} = ${o}`),r++}if(this._skCondition){let s=`#sk${r}`;switch(i[s]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`${s} = ${o}`);break}case"begins_with":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`begins_with(${s}, ${o})`);break}}r++}if(a.length>0)e.KeyConditionExpression=a.join(" AND ");if(this._filterConditions.length>0){let s=[];for(let o of this._filterConditions){let l=`#flt${r}`;if(i[l]=o.attribute,o.operator==="attribute_exists")s.push(`attribute_exists(${l})`);else if(o.operator==="attribute_not_exists")s.push(`attribute_not_exists(${l})`);else if(o.operator==="IN"&&o.values){let u=o.values.map((y,p)=>`:flt${r}_${p}`);o.values.forEach((y,p)=>{n[`:flt${r}_${p}`]=t.marshall({v:y}).v}),s.push(`${l} IN (${u.join(", ")})`)}else if(o.operator==="BETWEEN"&&o.values){let u=`:flt${r}a`,y=`:flt${r}b`;n[u]=t.marshall({v:o.values[0]}).v,n[y]=t.marshall({v:o.values[1]}).v,s.push(`${l} BETWEEN ${u} AND ${y}`)}else if(o.operator==="begins_with"){let u=`:flt${r}`;n[u]=t.marshall({v:o.value}).v,s.push(`begins_with(${l}, ${u})`)}else{let u=`:flt${r}`;n[u]=t.marshall({v:o.value}).v,s.push(`${l} ${o.operator} ${u}`)}r++}e.FilterExpression=s.join(" AND ")}if(this._projectionAttrs.length>0){let s=[];for(let o of this._projectionAttrs){let l=`#proj${r}`;i[l]=o,s.push(l),r++}e.ProjectionExpression=s.join(", ")}if(Object.keys(i).length>0)e.ExpressionAttributeNames=i;if(Object.keys(n).length>0)e.ExpressionAttributeValues=n;if(this._limitValue!==void 0)e.Limit=this._limitValue;if(e.ScanIndexForward=this._scanForward,this._consistentReadValue)e.ConsistentRead=!0;if(this._startKey)e.ExclusiveStartKey=t.marshall(this._startKey);return e}async get(){let t=b(),e=D(),i=this.buildRequest();return((this._pkValue!==void 0?await t.query(i):await t.scan(i)).Items??[]).map((s)=>{let o=e.unmarshall(s),l=new this.ModelClass(o);return l._exists=!0,l})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let t=b(),e=this.buildRequest();return e.Select="COUNT",(this._pkValue!==void 0?await t.query(e):await t.scan(e)).Count??0}async paginate(t,e){let i=D();if(e)this._startKey=e;this._limitValue=t;let n=b(),r=this.buildRequest(),s=this._pkValue!==void 0?await n.query(r):await n.scan(r);return{items:(s.Items??[]).map((l)=>{let u=i.unmarshall(l),y=new this.ModelClass(u);return y._exists=!0,y}),lastKey:s.LastEvaluatedKey?i.unmarshall(s.LastEvaluatedKey):void 0}}}function x(t){let e=JSON.stringify({tableName:t.tableName,keySchema:t.keySchema,attributeDefinitions:[...t.attributeDefinitions||[]].sort((n,r)=>n.name.localeCompare(r.name)),globalSecondaryIndexes:[...t.globalSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),localSecondaryIndexes:[...t.localSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),billingMode:t.billingMode,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamSpecification}),i=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);i=(i<<5)-i+r,i=i&i}return Math.abs(i).toString(16).padStart(8,"0")}function ke(t){let e=We(t);return Ue(e)}function We(t){return{tableName:t.tableName||"",pkAttribute:t.pkAttribute||"pk",skAttribute:t.skAttribute||"sk",pkPrefix:t.pkPrefix||"",skPrefix:t.skPrefix||"METADATA",entityTypeAttribute:t.entityTypeAttribute||"_et",timestamps:t.timestamps!==!1,ttlAttribute:t.ttlAttribute,gsis:t.gsis,lsis:t.lsis,billingMode:t.billingMode||"PAY_PER_REQUEST",provisionedThroughput:t.provisionedThroughput,streamEnabled:t.streamEnabled,streamViewType:t.streamViewType}}function Ue(t){let e=[{name:t.pkAttribute,type:"S"},{name:t.skAttribute,type:"S"}],i=[];if(t.gsis)for(let n of t.gsis){if(!e.some((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.some((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});i.push({indexName:n.indexName,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:Array.isArray(n.projection)?"INCLUDE":n.projection||"ALL",nonKeyAttributes:Array.isArray(n.projection)?n.projection:void 0},provisionedThroughput:n.provisionedThroughput})}return{tableName:t.tableName,keySchema:{partitionKey:t.pkAttribute,sortKey:t.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:i.length>0?i:void 0,billingMode:t.billingMode,provisionedThroughput:t.provisionedThroughput,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamEnabled?{enabled:!0,viewType:t.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function Ce(t,e){let i=[],n=e.tableName;if(!t)i.push({type:"CREATE_TABLE",tableName:n,details:{definition:e}});else{let r=t.keySchema.partitionKey!==e.keySchema.partitionKey,a=t.keySchema.sortKey!==e.keySchema.sortKey;if(r||a)console.warn(`[Migration] Table ${n}: Key schema changes require table recreation. Current: pk=${t.keySchema.partitionKey}, sk=${t.keySchema.sortKey}. Target: pk=${e.keySchema.partitionKey}, sk=${e.keySchema.sortKey}. This operation is not supported automatically.`);let s=t.globalSecondaryIndexes||[],o=e.globalSecondaryIndexes||[],l=new Set(s.map((m)=>m.indexName)),u=new Set(o.map((m)=>m.indexName));for(let m of o)if(!l.has(m.indexName))i.push({type:"ADD_GSI",tableName:n,details:{gsi:m}});for(let m of s)if(!u.has(m.indexName))i.push({type:"DELETE_GSI",tableName:n,details:{indexName:m.indexName}});if(t.billingMode!==e.billingMode&&e.billingMode)i.push({type:"UPDATE_BILLING_MODE",tableName:n,details:{billingMode:e.billingMode,provisionedThroughput:e.provisionedThroughput}});if(t.ttlAttribute!==e.ttlAttribute)i.push({type:"UPDATE_TTL",tableName:n,details:{ttlAttribute:e.ttlAttribute||null,enabled:!!e.ttlAttribute}});let y=t.streamSpecification?.enabled,p=e.streamSpecification?.enabled;if(y!==p)if(p)i.push({type:"ENABLE_STREAM",tableName:n,details:{viewType:e.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else i.push({type:"DISABLE_STREAM",tableName:n,details:{}})}return{tableName:n,operations:i,timestamp:new Date().toISOString(),hash:x(e)}}function St(t,e){return x(t)===x(e)}var d="_qb_migrations",k="MIGRATION",C="VERSION";class G{client;initialized=!1;constructor(t){this.client=t}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(d),this.initialized=!0}catch(t){if(t.message?.includes("ResourceNotFoundException")||t.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${d}`),await this.client.createTable({TableName:d,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(d),this.initialized=!0;else throw t}}async waitForTableActive(t,e=30){for(let i=0;i<e;i++){try{if((await this.client.describeTable(t)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((n)=>setTimeout(n,1000))}throw Error(`Table ${t} did not become active within ${e} seconds`)}async getLatestState(t){await this.ensureMigrationsTable();let e=`${k}#${t}`,i=await this.client.query({TableName:d,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1,Limit:1});if(!i.Items||i.Items.length===0)return null;return this.unmarshallState(i.Items[0])}async getHistory(t){await this.ensureMigrationsTable();let e=`${k}#${t}`,i=await this.client.query({TableName:d,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1});if(!i.Items)return[];return i.Items.map((n)=>this.unmarshallState(n))}async recordMigration(t,e,i){await this.ensureMigrationsTable();let n=await this.getLatestState(t),r=i??(n?n.version+1:1),a=`${k}#${t}`,s=`${C}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:x(e),definition:e,appliedAt:new Date().toISOString(),version:r};return await this.client.putItem({TableName:d,Item:this.marshallState(o,a,s)}),console.log(`[Migration] Recorded migration for ${t} (version ${r})`),o}async listTrackedTables(){await this.ensureMigrationsTable();let t=await this.client.scan({TableName:d,ProjectionExpression:"pk"});if(!t.Items)return[];let e=new Set;for(let i of t.Items){let r=(i.pk?.S||"").replace(`${k}#`,"");if(r)e.add(r)}return Array.from(e)}async hasMigrations(t){return await this.getLatestState(t)!==null}async deleteMigrationHistory(t){await this.ensureMigrationsTable();let e=await this.getHistory(t),i=`${k}#${t}`;for(let n of e){let r=`${C}#${String(n.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:d,Key:{pk:{S:i},sk:{S:r}}})}console.log(`[Migration] Deleted migration history for ${t}`)}marshallState(t,e,i){return{pk:{S:e},sk:{S:i},tableName:{S:t.tableName},hash:{S:t.hash},definition:{S:JSON.stringify(t.definition)},appliedAt:{S:t.appliedAt},version:{N:String(t.version)}}}unmarshallState(t){return{tableName:t.tableName?.S||"",hash:t.hash?.S||"",definition:JSON.parse(t.definition?.S||"{}"),appliedAt:t.appliedAt?.S||"",version:Number(t.version?.N||0)}}}class Re{client;tracker;config;constructor(t){this.config=t,this.client=E({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new G(this.client)}async execute(t){let e={tableName:t.tableName,success:!0,operations:[]};if(t.operations.length===0)return this.log(`[Migration] No changes needed for ${t.tableName}`),e;this.log(`[Migration] Executing ${t.operations.length} operations for ${t.tableName}`);try{for(let i of t.operations)await this.executeOperation(i),e.operations.push(i.type);this.log(`[Migration] Successfully applied ${e.operations.length} operations to ${t.tableName}`)}catch(i){e.success=!1,e.error=i.message,console.error(`[Migration] Failed to execute migration for ${t.tableName}:`,i)}return e}async executeOperation(t){if(this.log(`[Migration] Executing ${t.type} on ${t.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${t.type}`,t.details);return}switch(t.type){case"CREATE_TABLE":await this.createTable(t.details.definition);break;case"DELETE_TABLE":await this.deleteTable(t.tableName);break;case"ADD_GSI":await this.addGSI(t.tableName,t.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(t.tableName,t.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(t.tableName,t.details.ttlAttribute,t.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(t.tableName,t.details.billingMode,t.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(t.tableName,t.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(t.tableName);break;default:throw Error(`Unknown migration operation type: ${t.type}`)}}async createTable(t){let e={TableName:t.tableName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:t.attributeDefinitions.map((i)=>({AttributeName:i.name,AttributeType:i.type})),BillingMode:t.billingMode||"PAY_PER_REQUEST"};if(t.keySchema.sortKey)e.KeySchema.push({AttributeName:t.keySchema.sortKey,KeyType:"RANGE"});if(t.billingMode==="PROVISIONED"&&t.provisionedThroughput)e.ProvisionedThroughput={ReadCapacityUnits:t.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:t.provisionedThroughput.writeCapacityUnits};if(t.globalSecondaryIndexes&&t.globalSecondaryIndexes.length>0)e.GlobalSecondaryIndexes=t.globalSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:i.keySchema.partitionKey,KeyType:"HASH"},...i.keySchema.sortKey?[{AttributeName:i.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}},...i.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:i.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:i.provisionedThroughput.writeCapacityUnits}}:{}}));if(t.localSecondaryIndexes&&t.localSecondaryIndexes.length>0)e.LocalSecondaryIndexes=t.localSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:i.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}}}));if(t.streamSpecification?.enabled)e.StreamSpecification={StreamEnabled:!0,StreamViewType:t.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${t.tableName}`),await this.client.createTable(e),await this.waitForTableActive(t.tableName),t.ttlAttribute)await this.updateTTL(t.tableName,t.ttlAttribute,!0);this.log(`[Migration] Table created: ${t.tableName}`)}async deleteTable(t){this.log(`[Migration] Deleting table: ${t}`),await this.client.deleteTable(t),this.log(`[Migration] Table deleted: ${t}`)}async addGSI(t,e){this.log(`[Migration] Adding GSI ${e.indexName} to ${t}`);let i=await this.client.describeTable(t),n=new Set(i.Table?.AttributeDefinitions?.map((s)=>s.AttributeName)||[]),r=[];if(!n.has(e.keySchema.partitionKey))r.push({AttributeName:e.keySchema.partitionKey,AttributeType:"S"});if(e.keySchema.sortKey&&!n.has(e.keySchema.sortKey))r.push({AttributeName:e.keySchema.sortKey,AttributeType:"S"});let a={TableName:t,AttributeDefinitions:r.length>0?r:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:e.indexName,KeySchema:[{AttributeName:e.keySchema.partitionKey,KeyType:"HASH"},...e.keySchema.sortKey?[{AttributeName:e.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:e.projection.type,...e.projection.nonKeyAttributes?{NonKeyAttributes:e.projection.nonKeyAttributes}:{}},...e.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:e.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:e.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(a),await this.waitForGSIActive(t,e.indexName),this.log(`[Migration] GSI ${e.indexName} added to ${t}`)}async deleteGSI(t,e){this.log(`[Migration] Deleting GSI ${e} from ${t}`);let i={TableName:t,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:e}}]};await this.executeUpdateTable(i),this.log(`[Migration] GSI ${e} deleted from ${t}`)}async updateTTL(t,e,i){this.log(`[Migration] Updating TTL on ${t}: ${i?e:"disabled"}`);let n={TableName:t,TimeToLiveSpecification:{Enabled:i,AttributeName:e||"ttl"}};await this.executeUpdateTimeToLive(n),this.log(`[Migration] TTL updated on ${t}`)}async updateBillingMode(t,e,i){this.log(`[Migration] Updating billing mode on ${t} to ${e}`);let n={TableName:t,BillingMode:e};if(e==="PROVISIONED"&&i)n.ProvisionedThroughput={ReadCapacityUnits:i.readCapacityUnits,WriteCapacityUnits:i.writeCapacityUnits};await this.executeUpdateTable(n),await this.waitForTableActive(t),this.log(`[Migration] Billing mode updated on ${t}`)}async enableStream(t,e){this.log(`[Migration] Enabling stream on ${t} with view type ${e}`);let i={TableName:t,StreamSpecification:{StreamEnabled:!0,StreamViewType:e}};await this.executeUpdateTable(i),await this.waitForTableActive(t),this.log(`[Migration] Stream enabled on ${t}`)}async disableStream(t){this.log(`[Migration] Disabling stream on ${t}`);let e={TableName:t,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(e),await this.waitForTableActive(t),this.log(`[Migration] Stream disabled on ${t}`)}async executeUpdateTable(t){await this.client.updateTable(t)}async executeUpdateTimeToLive(t){await this.client.updateTimeToLive(t)}async waitForTableActive(t,e=60){this.log(`[Migration] Waiting for table ${t} to become active...`);for(let i=0;i<e;i++){try{let r=(await this.client.describeTable(t)).Table?.TableStatus;if(r==="ACTIVE")return;this.log(`[Migration] Table status: ${r}, waiting...`)}catch{}await new Promise((n)=>setTimeout(n,2000))}throw Error(`Table ${t} did not become active within ${e*2} seconds`)}async waitForGSIActive(t,e,i=120){this.log(`[Migration] Waiting for GSI ${e} to become active...`);for(let n=0;n<i;n++){try{let a=(await this.client.describeTable(t)).Table?.GlobalSecondaryIndexes?.find((o)=>o.IndexName===e);if(a?.IndexStatus==="ACTIVE")return;let s=a?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${s}, waiting...`)}catch{}await new Promise((r)=>setTimeout(r,5000))}throw Error(`GSI ${e} did not become active within ${i*5} seconds`)}async migrateModel(t){let e=ke(t),i=null;try{let a=await this.client.describeTable(e.tableName);if(a.Table)i=this.tableInfoToDefinition(a.Table)}catch(a){if(!a.message?.includes("ResourceNotFoundException")&&!a.message?.includes("not found"))throw a}let n=Ce(i,e),r=await this.execute(n);if(r.success&&!this.config.dryRun)r.state=await this.tracker.recordMigration(e.tableName,e);return r}async migrateModels(t){let e=[];for(let i of t)try{let n=await this.migrateModel(i);e.push(n)}catch(n){e.push({tableName:i.tableName||"unknown",success:!1,operations:[],error:n.message})}return e}async getStatus(){let t=new Map,e=await this.tracker.listTrackedTables();for(let i of e){let n=await this.tracker.getLatestState(i);t.set(i,n)}return t}tableInfoToDefinition(t){let e={partitionKey:"",sortKey:void 0};for(let r of t.KeySchema||[])if(r.KeyType==="HASH")e.partitionKey=r.AttributeName;else if(r.KeyType==="RANGE")e.sortKey=r.AttributeName;let i=(t.AttributeDefinitions||[]).map((r)=>({name:r.AttributeName,type:r.AttributeType})),n=(t.GlobalSecondaryIndexes||[]).map((r)=>{let a={partitionKey:"",sortKey:void 0};for(let s of r.KeySchema||[])if(s.KeyType==="HASH")a.partitionKey=s.AttributeName;else if(s.KeyType==="RANGE")a.sortKey=s.AttributeName;return{indexName:r.IndexName,keySchema:a,projection:{type:r.Projection?.ProjectionType||"ALL",nonKeyAttributes:r.Projection?.NonKeyAttributes},provisionedThroughput:r.ProvisionedThroughput?{readCapacityUnits:r.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:r.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:t.TableName,keySchema:e,attributeDefinitions:i,globalSecondaryIndexes:n.length>0?n:void 0,billingMode:t.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:t.ProvisionedThroughput?{readCapacityUnits:t.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:t.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:t.TimeToLiveDescription?.AttributeName,streamSpecification:t.StreamSpecification?{enabled:t.StreamSpecification.StreamEnabled,viewType:t.StreamSpecification.StreamViewType}:void 0}}log(...t){if(this.config.verbose||this.config.dryRun)console.log(...t)}}function Ve(t){return new Re(t)}async function Dt(t,e){return Ve(e).migrateModels(t)}class He{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(t,e,i,n){this.driver=t,this.client=e,this.tableName=i,this.pkAttribute=n.pkAttribute,this.skAttribute=n.skAttribute,this.entityTypeAttr=n.entityTypeAttribute,this.delimiter=n.keyDelimiter}entity(t){return this._entityType=t,this}pk(t){return this._pkValue=t,this}get sk(){let t=this;return{equals(e){return t._skCondition={type:"eq",value:e},t},beginsWith(e){return t._skCondition={type:"begins_with",value:e},t},between(e,i){return t._skCondition={type:"between",value:e,value2:i},t},lt(e){return t._skCondition={type:"lt",value:e},t},lte(e){return t._skCondition={type:"lte",value:e},t},gt(e){return t._skCondition={type:"gt",value:e},t},gte(e){return t._skCondition={type:"gte",value:e},t}}}index(t){return this._indexName=t,this}project(...t){return this._projectionAttrs.push(...t),this}filter(t,e,i){return this._filterConditions.push({attribute:t,operator:e,value:i}),this}where(t,e){return this.filter(t,"=",e)}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}limit(t){return this._limitValue=t,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(t){return this._startKey=t,this}toRequest(){let t={TableName:this.tableName};if(this._indexName)t.IndexName=this._indexName;let e=[],i={},n={},r=0;if(this._pkValue){let a=`#pk${r}`,s=`:pk${r}`;i[a]=this.pkAttribute,n[s]={S:this._pkValue},e.push(`${a} = ${s}`),r++}if(this._skCondition){let a=`#sk${r}`;switch(i[a]=this.skAttribute,this._skCondition.type){case"eq":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} = ${s}`);break}case"begins_with":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`begins_with(${a}, ${s})`);break}case"between":{let s=`:sk${r}a`,o=`:sk${r}b`;n[s]={S:this._skCondition.value},n[o]={S:this._skCondition.value2},e.push(`${a} BETWEEN ${s} AND ${o}`);break}case"lt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} < ${s}`);break}case"lte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} <= ${s}`);break}case"gt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} > ${s}`);break}case"gte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} >= ${s}`);break}}r++}if(e.length>0)t.KeyConditionExpression=e.join(" AND ");if(this._filterConditions.length>0){let a=[];for(let s of this._filterConditions){let o=`#flt${r}`;if(i[o]=s.attribute,s.operator==="IN"&&s.values){let l=s.values.map((u,y)=>`:flt${r}_${y}`);s.values.forEach((u,y)=>{n[`:flt${r}_${y}`]=this.driver.marshall({v:u}).v}),a.push(`${o} IN (${l.join(", ")})`)}else{let l=`:flt${r}`;n[l]=this.driver.marshall({v:s.value}).v,a.push(`${o} ${s.operator} ${l}`)}r++}t.FilterExpression=a.join(" AND ")}if(this._projectionAttrs.length>0){let a=[];for(let s of this._projectionAttrs){let o=`#proj${r}`;i[o]=s,a.push(o),r++}t.ProjectionExpression=a.join(", ")}if(Object.keys(i).length>0)t.ExpressionAttributeNames=i;if(Object.keys(n).length>0)t.ExpressionAttributeValues=n;if(this._limitValue!==void 0)t.Limit=this._limitValue;if(t.ScanIndexForward=this._scanForward,this._consistentRead)t.ConsistentRead=!0;if(this._startKey)t.ExclusiveStartKey=this.driver.marshall(this._startKey);return t}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return((this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Items??[]).map((n)=>this.driver.unmarshall(n))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let t=[],e;do{if(e)this._startKey=e;let i=this.toRequest(),r=this._pkValue!==void 0?await this.client.query(i):await this.client.scan(i),a=(r.Items??[]).map((s)=>this.driver.unmarshall(s));t.push(...a),e=r.LastEvaluatedKey?this.driver.unmarshall(r.LastEvaluatedKey):void 0}while(e);return t}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return t.Select="COUNT",(this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Count??0}}class I{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(t){let e={region:t.region,tableName:t.table,endpoint:t.endpoint,credentials:t.credentials};return this.driver=c(e),this.tableName=t.table,this.pkAttribute=t.pkAttribute??"pk",this.skAttribute=t.skAttribute??"sk",this.entityTypeAttr=t.entityTypeAttribute??"_et",this.delimiter=t.keyDelimiter??"#",this}setClient(t){return this.client=t,this}registerEntity(t){if(this.entityMappings.set(t.entityType,t),this.driver)this.driver.registerEntity(t);return this}entity(t){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new He(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(t)}async batchWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity};e.push({PutRequest:{Item:this.driver.marshall(n)}})}else if(i.delete)e.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}});if(e.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:e}})}async transactWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity},r={Put:{TableName:this.tableName,Item:this.driver.marshall(n)}};if(i.put.condition)r.Put.ConditionExpression=i.put.condition;e.push(r)}else if(i.update){let n={[this.pkAttribute]:i.update.pk};if(i.update.sk)n[this.skAttribute]=i.update.sk;let r=[],a={},s={},o=0;if(i.update.set){let l=[];for(let[u,y]of Object.entries(i.update.set)){let p=`#set${o}`,m=`:set${o}`;a[p]=u,s[m]=this.driver.marshall({v:y}).v,l.push(`${p} = ${m}`),o++}if(l.length>0)r.push(`SET ${l.join(", ")}`)}if(i.update.add){let l=[];for(let[u,y]of Object.entries(i.update.add)){let p=`#add${o}`,m=`:add${o}`;a[p]=u,s[m]={N:String(y)},l.push(`${p} ${m}`),o++}if(l.length>0)r.push(`ADD ${l.join(", ")}`)}if(i.update.remove&&i.update.remove.length>0){let l=[];for(let u of i.update.remove){let y=`#rem${o}`;a[y]=u,l.push(y),o++}r.push(`REMOVE ${l.join(", ")}`)}e.push({Update:{TableName:this.tableName,Key:this.driver.marshall(n),UpdateExpression:r.join(" "),ExpressionAttributeNames:a,ExpressionAttributeValues:s}})}else if(i.delete){let n={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}};if(i.delete.condition)n.Delete.ConditionExpression=i.delete.condition;e.push(n)}else if(i.conditionCheck)e.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.conditionCheck.pk,[this.skAttribute]:i.conditionCheck.sk}),ConditionExpression:i.conditionCheck.condition}});if(e.length>0)await this.client.transactWriteItems({TransactItems:e})}getDriver(){return this.driver}}var jt=new I;function qt(){return new I}
7
- export{Tt,c,Q,E,wt,qe,x,ke,We,Ue,Ce,St,d,G,Re,Ve,Dt,He,jt,qt};
4
+ `,A=g.map((T)=>T.toLowerCase()).join(";"),k=await w(n),M=[t,y,d,D,A,k].join(`
5
+ `),K=await w(M),P="AWS4-HMAC-SHA256",_=`${c}/${a}/${s}/aws4_request`,L=[P,l,_,K].join(`
6
+ `),O=await G(r.secretAccessKey,c,a,s),U=await S(O,L),j=Array.from(new Uint8Array(U)).map((T)=>T.toString(16).padStart(2,"0")).join(""),V=`${P} Credential=${r.accessKeyId}/${_}, SignedHeaders=${A}, Signature=${j}`;return{...m,authorization:V}}class J{config;endpoint;credentials;constructor(t){if(this.config=t,this.endpoint=t.endpoint??`https://dynamodb.${t.region}.amazonaws.com`,this.credentials=t.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute(t,e){let i=new URL(this.endpoint),n=JSON.stringify(e),r={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${t}`},a=await W("POST",i,r,n,this.credentials,this.config.region,"dynamodb"),s=await fetch(i.toString(),{method:"POST",headers:a,body:n});if(!s.ok){let o=await s.text(),l;try{let c=JSON.parse(o);l=c.message??c.Message??o}catch{l=o}throw Error(`DynamoDB ${t} failed: ${s.status} - ${l}`)}return s.json()}async query(t){return this.execute("Query",t)}async scan(t){return this.execute("Scan",t)}async getItem(t){return this.execute("GetItem",t)}async putItem(t){return this.execute("PutItem",t)}async updateItem(t){return this.execute("UpdateItem",t)}async deleteItem(t){return this.execute("DeleteItem",t)}async batchGetItem(t){return this.execute("BatchGetItem",t)}async batchWriteItem(t){return this.execute("BatchWriteItem",t)}async transactWriteItems(t){return this.execute("TransactWriteItems",t)}async describeTable(t){return this.execute("DescribeTable",{TableName:t})}async createTable(t){return this.execute("CreateTable",t)}async deleteTable(t){return this.execute("DeleteTable",{TableName:t})}async listTables(t){return this.execute("ListTables",t??{})}async updateTable(t){return this.execute("UpdateTable",t)}async updateTimeToLive(t){return this.execute("UpdateTimeToLive",t)}async describeTimeToLive(t){return this.execute("DescribeTimeToLive",{TableName:t})}}function x(t){return new J(t)}var p={region:process.env.AWS_REGION??"us-east-1"},B=null,N=null;function kt(t){p={...p,...t},B=null,N=null}function h(){if(!B)B=x({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return B}function b(){if(!N)N=u({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return N}class Qe{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor(t={}){this._attributes={...t},this._original={...t};for(let[e,i]of Object.entries(t))this[e]=i}static query(){return new R(this)}static async find(t){let e=this,i=h(),n=b(),r=`${e.pkPrefix}${e.keyDelimiter}${t}`,a=e.skPrefix;try{let s=await i.getItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:r,[e.skAttribute]:a})});if(!s.Item)return null;let o=n.unmarshall(s.Item),l=new e(o);return l._exists=!0,l}catch(s){return console.error("Find error:",s),null}}static async findOrFail(t){let e=await this.find(t);if(!e)throw Error(`${this.name} not found with id: ${t}`);return e}static async all(){return this.query().get()}static async create(t){let e=this,i=h(),n=b(),r=t[e.primaryKey];if(!r)throw Error(`${e.primaryKey} is required`);let a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t,[e.pkAttribute]:a,[e.skAttribute]:s,[e.entityTypeAttribute]:e.name};if(e.timestamps)l[e.createdAtField]=o,l[e.updatedAtField]=o;await i.putItem({TableName:e.tableName,Item:n.marshall(l),ConditionExpression:`attribute_not_exists(${e.pkAttribute})`});let c=new e(l);return c._exists=!0,c}static async updateOrCreate(t,e){let i=this,n=t[i.primaryKey],r=await i.find(n);if(r)return await r.update(e),r;return i.create({...t,...e})}static where(t,e,i){return this.query().where(t,e,i)}static wherePk(t){return this.query().wherePk(t)}getKey(){let t=this.constructor;return this[t.primaryKey]}getAttribute(t){return this._attributes[t]}setAttribute(t,e){return this._attributes[t]=e,this[t]=e,this}getAttributes(){return{...this._attributes}}isDirty(t){if(t)return this._attributes[t]!==this._original[t];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let t={};for(let[e,i]of Object.entries(this._attributes))if(i!==this._original[e])t[e]=i;return t}async save(){if(this._exists){let t=this.getDirty();if(Object.keys(t).length>0)await this.update(t)}else{let e=await this.constructor.create(this._attributes);this._attributes=e._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(t){let e=this.constructor,i=h(),n=b(),r=this.getKey(),a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t};if(e.timestamps)l[e.updatedAtField]=o;let c=[],y={},d={},m=0;for(let[g,D]of Object.entries(l)){let A=`#attr${m}`,k=`:val${m}`;y[A]=g,d[k]=n.marshall({v:D}).v,c.push(`${A} = ${k}`),m++}await i.updateItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:a,[e.skAttribute]:s}),UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:y,ExpressionAttributeValues:d});for(let[g,D]of Object.entries(l))this._attributes[g]=D,this[g]=D;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=h(),i=b(),n=this.getKey(),r=`${t.pkPrefix}${t.keyDelimiter}${n}`,a=t.skPrefix;return await e.deleteItem({TableName:t.tableName,Key:i.marshall({[t.pkAttribute]:r,[t.skAttribute]:a})}),this._exists=!1,!0}async refresh(){let e=await this.constructor.find(this.getKey());if(e){this._attributes=e._attributes,this._original={...this._attributes};for(let[i,n]of Object.entries(this._attributes))this[i]=n}return this}toObject(){let t=this.constructor,e={...this._attributes};return delete e[t.pkAttribute],delete e[t.skAttribute],delete e[t.entityTypeAttribute],e}toJSON(){return this.toObject()}}class R{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(t){this.ModelClass=t}wherePk(t){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${t}`,this}where(t,e,i){if(i===void 0)this._filterConditions.push({attribute:t,operator:"=",value:e});else this._filterConditions.push({attribute:t,operator:e,value:i});return this}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}whereBetween(t,e,i){return this._filterConditions.push({attribute:t,operator:"BETWEEN",value:e,values:[e,i]}),this}whereBeginsWith(t,e){return this._filterConditions.push({attribute:t,operator:"begins_with",value:e}),this}whereExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_exists"}),this}whereNotExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_not_exists"}),this}orderBy(t){return this._scanForward=t==="asc",this}limit(t){return this._limitValue=t,this}select(...t){return this._projectionAttrs.push(...t),this}index(t){return this._indexName=t,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(t){return this._startKey=t,this}buildRequest(){let t=b(),e={TableName:this.ModelClass.tableName};if(this._indexName)e.IndexName=this._indexName;let i={},n={},r=0,a=[];if(this._pkValue){let s=`#pk${r}`,o=`:pk${r}`;i[s]=this.ModelClass.pkAttribute,n[o]={S:this._pkValue},a.push(`${s} = ${o}`),r++}if(this._skCondition){let s=`#sk${r}`;switch(i[s]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`${s} = ${o}`);break}case"begins_with":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`begins_with(${s}, ${o})`);break}}r++}if(a.length>0)e.KeyConditionExpression=a.join(" AND ");if(this._filterConditions.length>0){let s=[];for(let o of this._filterConditions){let l=`#flt${r}`;if(i[l]=o.attribute,o.operator==="attribute_exists")s.push(`attribute_exists(${l})`);else if(o.operator==="attribute_not_exists")s.push(`attribute_not_exists(${l})`);else if(o.operator==="IN"&&o.values){let c=o.values.map((y,d)=>`:flt${r}_${d}`);o.values.forEach((y,d)=>{n[`:flt${r}_${d}`]=t.marshall({v:y}).v}),s.push(`${l} IN (${c.join(", ")})`)}else if(o.operator==="BETWEEN"&&o.values){let c=`:flt${r}a`,y=`:flt${r}b`;n[c]=t.marshall({v:o.values[0]}).v,n[y]=t.marshall({v:o.values[1]}).v,s.push(`${l} BETWEEN ${c} AND ${y}`)}else if(o.operator==="begins_with"){let c=`:flt${r}`;n[c]=t.marshall({v:o.value}).v,s.push(`begins_with(${l}, ${c})`)}else{let c=`:flt${r}`;n[c]=t.marshall({v:o.value}).v,s.push(`${l} ${o.operator} ${c}`)}r++}e.FilterExpression=s.join(" AND ")}if(this._projectionAttrs.length>0){let s=[];for(let o of this._projectionAttrs){let l=`#proj${r}`;i[l]=o,s.push(l),r++}e.ProjectionExpression=s.join(", ")}if(Object.keys(i).length>0)e.ExpressionAttributeNames=i;if(Object.keys(n).length>0)e.ExpressionAttributeValues=n;if(this._limitValue!==void 0)e.Limit=this._limitValue;if(e.ScanIndexForward=this._scanForward,this._consistentReadValue)e.ConsistentRead=!0;if(this._startKey)e.ExclusiveStartKey=t.marshall(this._startKey);return e}async get(){let t=h(),e=b(),i=this.buildRequest();return((this._pkValue!==void 0?await t.query(i):await t.scan(i)).Items??[]).map((s)=>{let o=e.unmarshall(s),l=new this.ModelClass(o);return l._exists=!0,l})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let t=h(),e=this.buildRequest();return e.Select="COUNT",(this._pkValue!==void 0?await t.query(e):await t.scan(e)).Count??0}async paginate(t,e){let i=b();if(e)this._startKey=e;this._limitValue=t;let n=h(),r=this.buildRequest(),s=this._pkValue!==void 0?await n.query(r):await n.scan(r);return{items:(s.Items??[]).map((l)=>{let c=i.unmarshall(l),y=new this.ModelClass(c);return y._exists=!0,y}),lastKey:s.LastEvaluatedKey?i.unmarshall(s.LastEvaluatedKey):void 0}}}function v(t){let e=JSON.stringify({tableName:t.tableName,keySchema:t.keySchema,attributeDefinitions:[...t.attributeDefinitions||[]].sort((n,r)=>n.name.localeCompare(r.name)),globalSecondaryIndexes:[...t.globalSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),localSecondaryIndexes:[...t.localSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),billingMode:t.billingMode,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamSpecification}),i=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);i=(i<<5)-i+r,i=i&i}return Math.abs(i).toString(16).padStart(8,"0")}function Ae(t){let e=Ge(t);return Je(e)}function Ge(t){return{tableName:t.tableName||"",pkAttribute:t.pkAttribute||"pk",skAttribute:t.skAttribute||"sk",pkPrefix:t.pkPrefix||"",skPrefix:t.skPrefix||"METADATA",entityTypeAttribute:t.entityTypeAttribute||"_et",timestamps:t.timestamps!==!1,ttlAttribute:t.ttlAttribute,gsis:t.gsis,lsis:t.lsis,billingMode:t.billingMode||"PAY_PER_REQUEST",provisionedThroughput:t.provisionedThroughput,streamEnabled:t.streamEnabled,streamViewType:t.streamViewType}}function Je(t){let e=[{name:t.pkAttribute,type:"S"},{name:t.skAttribute,type:"S"}],i=[];if(t.gsis)for(let n of t.gsis){if(!e.some((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.some((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});i.push({indexName:n.indexName,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:Array.isArray(n.projection)?"INCLUDE":n.projection||"ALL",nonKeyAttributes:Array.isArray(n.projection)?n.projection:void 0},provisionedThroughput:n.provisionedThroughput})}return{tableName:t.tableName,keySchema:{partitionKey:t.pkAttribute,sortKey:t.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:i.length>0?i:void 0,billingMode:t.billingMode,provisionedThroughput:t.provisionedThroughput,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamEnabled?{enabled:!0,viewType:t.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function Me(t,e){let i=[],n=e.tableName;if(!t)i.push({type:"CREATE_TABLE",tableName:n,details:{definition:e}});else{let r=t.keySchema.partitionKey!==e.keySchema.partitionKey,a=t.keySchema.sortKey!==e.keySchema.sortKey;if(r||a)console.warn(`[Migration] Table ${n}: Key schema changes require table recreation. Current: pk=${t.keySchema.partitionKey}, sk=${t.keySchema.sortKey}. Target: pk=${e.keySchema.partitionKey}, sk=${e.keySchema.sortKey}. This operation is not supported automatically.`);let s=t.globalSecondaryIndexes||[],o=e.globalSecondaryIndexes||[],l=new Set(s.map((m)=>m.indexName)),c=new Set(o.map((m)=>m.indexName));for(let m of o)if(!l.has(m.indexName))i.push({type:"ADD_GSI",tableName:n,details:{gsi:m}});for(let m of s)if(!c.has(m.indexName))i.push({type:"DELETE_GSI",tableName:n,details:{indexName:m.indexName}});if(t.billingMode!==e.billingMode&&e.billingMode)i.push({type:"UPDATE_BILLING_MODE",tableName:n,details:{billingMode:e.billingMode,provisionedThroughput:e.provisionedThroughput}});if(t.ttlAttribute!==e.ttlAttribute)i.push({type:"UPDATE_TTL",tableName:n,details:{ttlAttribute:e.ttlAttribute||null,enabled:!!e.ttlAttribute}});let y=t.streamSpecification?.enabled,d=e.streamSpecification?.enabled;if(y!==d)if(d)i.push({type:"ENABLE_STREAM",tableName:n,details:{viewType:e.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else i.push({type:"DISABLE_STREAM",tableName:n,details:{}})}return{tableName:n,operations:i,timestamp:new Date().toISOString(),hash:v(e)}}function Ct(t,e){return v(t)===v(e)}var f="_qb_migrations",E="MIGRATION",C="VERSION";class z{client;initialized=!1;constructor(t){this.client=t}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(f),this.initialized=!0}catch(t){if(t.message?.includes("ResourceNotFoundException")||t.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${f}`),await this.client.createTable({TableName:f,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(f),this.initialized=!0;else throw t}}async waitForTableActive(t,e=30){for(let i=0;i<e;i++){try{if((await this.client.describeTable(t)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((n)=>setTimeout(n,1000))}throw Error(`Table ${t} did not become active within ${e} seconds`)}async getLatestState(t){await this.ensureMigrationsTable();let e=`${E}#${t}`,i=await this.client.query({TableName:f,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1,Limit:1});if(!i.Items||i.Items.length===0)return null;return this.unmarshallState(i.Items[0])}async getHistory(t){await this.ensureMigrationsTable();let e=`${E}#${t}`,i=await this.client.query({TableName:f,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1});if(!i.Items)return[];return i.Items.map((n)=>this.unmarshallState(n))}async recordMigration(t,e,i){await this.ensureMigrationsTable();let n=await this.getLatestState(t),r=i??(n?n.version+1:1),a=`${E}#${t}`,s=`${C}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:v(e),definition:e,appliedAt:new Date().toISOString(),version:r};return await this.client.putItem({TableName:f,Item:this.marshallState(o,a,s)}),console.log(`[Migration] Recorded migration for ${t} (version ${r})`),o}async listTrackedTables(){await this.ensureMigrationsTable();let t=await this.client.scan({TableName:f,ProjectionExpression:"pk"});if(!t.Items)return[];let e=new Set;for(let i of t.Items){let r=(i.pk?.S||"").replace(`${E}#`,"");if(r)e.add(r)}return Array.from(e)}async hasMigrations(t){return await this.getLatestState(t)!==null}async deleteMigrationHistory(t){await this.ensureMigrationsTable();let e=await this.getHistory(t),i=`${E}#${t}`;for(let n of e){let r=`${C}#${String(n.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:f,Key:{pk:{S:i},sk:{S:r}}})}console.log(`[Migration] Deleted migration history for ${t}`)}marshallState(t,e,i){return{pk:{S:e},sk:{S:i},tableName:{S:t.tableName},hash:{S:t.hash},definition:{S:JSON.stringify(t.definition)},appliedAt:{S:t.appliedAt},version:{N:String(t.version)}}}unmarshallState(t){return{tableName:t.tableName?.S||"",hash:t.hash?.S||"",definition:JSON.parse(t.definition?.S||"{}"),appliedAt:t.appliedAt?.S||"",version:Number(t.version?.N||0)}}}class Ne{client;tracker;config;constructor(t){this.config=t,this.client=x({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new z(this.client)}async execute(t){let e={tableName:t.tableName,success:!0,operations:[]};if(t.operations.length===0)return this.log(`[Migration] No changes needed for ${t.tableName}`),e;this.log(`[Migration] Executing ${t.operations.length} operations for ${t.tableName}`);try{for(let i of t.operations)await this.executeOperation(i),e.operations.push(i.type);this.log(`[Migration] Successfully applied ${e.operations.length} operations to ${t.tableName}`)}catch(i){e.success=!1,e.error=i.message,console.error(`[Migration] Failed to execute migration for ${t.tableName}:`,i)}return e}async executeOperation(t){if(this.log(`[Migration] Executing ${t.type} on ${t.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${t.type}`,t.details);return}switch(t.type){case"CREATE_TABLE":await this.createTable(t.details.definition);break;case"DELETE_TABLE":await this.deleteTable(t.tableName);break;case"ADD_GSI":await this.addGSI(t.tableName,t.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(t.tableName,t.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(t.tableName,t.details.ttlAttribute,t.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(t.tableName,t.details.billingMode,t.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(t.tableName,t.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(t.tableName);break;default:throw Error(`Unknown migration operation type: ${t.type}`)}}async createTable(t){let e={TableName:t.tableName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:t.attributeDefinitions.map((i)=>({AttributeName:i.name,AttributeType:i.type})),BillingMode:t.billingMode||"PAY_PER_REQUEST"};if(t.keySchema.sortKey)e.KeySchema.push({AttributeName:t.keySchema.sortKey,KeyType:"RANGE"});if(t.billingMode==="PROVISIONED"&&t.provisionedThroughput)e.ProvisionedThroughput={ReadCapacityUnits:t.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:t.provisionedThroughput.writeCapacityUnits};if(t.globalSecondaryIndexes&&t.globalSecondaryIndexes.length>0)e.GlobalSecondaryIndexes=t.globalSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:i.keySchema.partitionKey,KeyType:"HASH"},...i.keySchema.sortKey?[{AttributeName:i.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}},...i.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:i.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:i.provisionedThroughput.writeCapacityUnits}}:{}}));if(t.localSecondaryIndexes&&t.localSecondaryIndexes.length>0)e.LocalSecondaryIndexes=t.localSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:i.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}}}));if(t.streamSpecification?.enabled)e.StreamSpecification={StreamEnabled:!0,StreamViewType:t.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${t.tableName}`),await this.client.createTable(e),await this.waitForTableActive(t.tableName),t.ttlAttribute)await this.updateTTL(t.tableName,t.ttlAttribute,!0);this.log(`[Migration] Table created: ${t.tableName}`)}async deleteTable(t){this.log(`[Migration] Deleting table: ${t}`),await this.client.deleteTable(t),this.log(`[Migration] Table deleted: ${t}`)}async addGSI(t,e){this.log(`[Migration] Adding GSI ${e.indexName} to ${t}`);let i=await this.client.describeTable(t),n=new Set(i.Table?.AttributeDefinitions?.map((s)=>s.AttributeName)||[]),r=[];if(!n.has(e.keySchema.partitionKey))r.push({AttributeName:e.keySchema.partitionKey,AttributeType:"S"});if(e.keySchema.sortKey&&!n.has(e.keySchema.sortKey))r.push({AttributeName:e.keySchema.sortKey,AttributeType:"S"});let a={TableName:t,AttributeDefinitions:r.length>0?r:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:e.indexName,KeySchema:[{AttributeName:e.keySchema.partitionKey,KeyType:"HASH"},...e.keySchema.sortKey?[{AttributeName:e.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:e.projection.type,...e.projection.nonKeyAttributes?{NonKeyAttributes:e.projection.nonKeyAttributes}:{}},...e.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:e.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:e.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(a),await this.waitForGSIActive(t,e.indexName),this.log(`[Migration] GSI ${e.indexName} added to ${t}`)}async deleteGSI(t,e){this.log(`[Migration] Deleting GSI ${e} from ${t}`);let i={TableName:t,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:e}}]};await this.executeUpdateTable(i),this.log(`[Migration] GSI ${e} deleted from ${t}`)}async updateTTL(t,e,i){this.log(`[Migration] Updating TTL on ${t}: ${i?e:"disabled"}`);let n={TableName:t,TimeToLiveSpecification:{Enabled:i,AttributeName:e||"ttl"}};await this.executeUpdateTimeToLive(n),this.log(`[Migration] TTL updated on ${t}`)}async updateBillingMode(t,e,i){this.log(`[Migration] Updating billing mode on ${t} to ${e}`);let n={TableName:t,BillingMode:e};if(e==="PROVISIONED"&&i)n.ProvisionedThroughput={ReadCapacityUnits:i.readCapacityUnits,WriteCapacityUnits:i.writeCapacityUnits};await this.executeUpdateTable(n),await this.waitForTableActive(t),this.log(`[Migration] Billing mode updated on ${t}`)}async enableStream(t,e){this.log(`[Migration] Enabling stream on ${t} with view type ${e}`);let i={TableName:t,StreamSpecification:{StreamEnabled:!0,StreamViewType:e}};await this.executeUpdateTable(i),await this.waitForTableActive(t),this.log(`[Migration] Stream enabled on ${t}`)}async disableStream(t){this.log(`[Migration] Disabling stream on ${t}`);let e={TableName:t,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(e),await this.waitForTableActive(t),this.log(`[Migration] Stream disabled on ${t}`)}async executeUpdateTable(t){await this.client.updateTable(t)}async executeUpdateTimeToLive(t){await this.client.updateTimeToLive(t)}async waitForTableActive(t,e=60){this.log(`[Migration] Waiting for table ${t} to become active...`);for(let i=0;i<e;i++){try{let r=(await this.client.describeTable(t)).Table?.TableStatus;if(r==="ACTIVE")return;this.log(`[Migration] Table status: ${r}, waiting...`)}catch{}await new Promise((n)=>setTimeout(n,2000))}throw Error(`Table ${t} did not become active within ${e*2} seconds`)}async waitForGSIActive(t,e,i=120){this.log(`[Migration] Waiting for GSI ${e} to become active...`);for(let n=0;n<i;n++){try{let a=(await this.client.describeTable(t)).Table?.GlobalSecondaryIndexes?.find((o)=>o.IndexName===e);if(a?.IndexStatus==="ACTIVE")return;let s=a?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${s}, waiting...`)}catch{}await new Promise((r)=>setTimeout(r,5000))}throw Error(`GSI ${e} did not become active within ${i*5} seconds`)}async migrateModel(t){let e=Ae(t),i=null;try{let a=await this.client.describeTable(e.tableName);if(a.Table)i=this.tableInfoToDefinition(a.Table)}catch(a){if(!a.message?.includes("ResourceNotFoundException")&&!a.message?.includes("not found"))throw a}let n=Me(i,e),r=await this.execute(n);if(r.success&&!this.config.dryRun)r.state=await this.tracker.recordMigration(e.tableName,e);return r}async migrateModels(t){let e=[];for(let i of t)try{let n=await this.migrateModel(i);e.push(n)}catch(n){e.push({tableName:i.tableName||"unknown",success:!1,operations:[],error:n.message})}return e}async getStatus(){let t=new Map,e=await this.tracker.listTrackedTables();for(let i of e){let n=await this.tracker.getLatestState(i);t.set(i,n)}return t}tableInfoToDefinition(t){let e={partitionKey:"",sortKey:void 0};for(let r of t.KeySchema||[])if(r.KeyType==="HASH")e.partitionKey=r.AttributeName;else if(r.KeyType==="RANGE")e.sortKey=r.AttributeName;let i=(t.AttributeDefinitions||[]).map((r)=>({name:r.AttributeName,type:r.AttributeType})),n=(t.GlobalSecondaryIndexes||[]).map((r)=>{let a={partitionKey:"",sortKey:void 0};for(let s of r.KeySchema||[])if(s.KeyType==="HASH")a.partitionKey=s.AttributeName;else if(s.KeyType==="RANGE")a.sortKey=s.AttributeName;return{indexName:r.IndexName,keySchema:a,projection:{type:r.Projection?.ProjectionType||"ALL",nonKeyAttributes:r.Projection?.NonKeyAttributes},provisionedThroughput:r.ProvisionedThroughput?{readCapacityUnits:r.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:r.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:t.TableName,keySchema:e,attributeDefinitions:i,globalSecondaryIndexes:n.length>0?n:void 0,billingMode:t.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:t.ProvisionedThroughput?{readCapacityUnits:t.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:t.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:t.TimeToLiveDescription?.AttributeName,streamSpecification:t.StreamSpecification?{enabled:t.StreamSpecification.StreamEnabled,viewType:t.StreamSpecification.StreamViewType}:void 0}}log(...t){if(this.config.verbose||this.config.dryRun)console.log(...t)}}function ze(t){return new Ne(t)}async function Rt(t,e){return ze(e).migrateModels(t)}class Ye{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(t,e,i,n){this.driver=t,this.client=e,this.tableName=i,this.pkAttribute=n.pkAttribute,this.skAttribute=n.skAttribute,this.entityTypeAttr=n.entityTypeAttribute,this.delimiter=n.keyDelimiter}entity(t){return this._entityType=t,this}pk(t){return this._pkValue=t,this}get sk(){let t=this;return{equals(e){return t._skCondition={type:"eq",value:e},t},beginsWith(e){return t._skCondition={type:"begins_with",value:e},t},between(e,i){return t._skCondition={type:"between",value:e,value2:i},t},lt(e){return t._skCondition={type:"lt",value:e},t},lte(e){return t._skCondition={type:"lte",value:e},t},gt(e){return t._skCondition={type:"gt",value:e},t},gte(e){return t._skCondition={type:"gte",value:e},t}}}index(t){return this._indexName=t,this}project(...t){return this._projectionAttrs.push(...t),this}filter(t,e,i){return this._filterConditions.push({attribute:t,operator:e,value:i}),this}where(t,e){return this.filter(t,"=",e)}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}limit(t){return this._limitValue=t,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(t){return this._startKey=t,this}toRequest(){let t={TableName:this.tableName};if(this._indexName)t.IndexName=this._indexName;let e=[],i={},n={},r=0;if(this._pkValue){let a=`#pk${r}`,s=`:pk${r}`;i[a]=this.pkAttribute,n[s]={S:this._pkValue},e.push(`${a} = ${s}`),r++}if(this._skCondition){let a=`#sk${r}`;switch(i[a]=this.skAttribute,this._skCondition.type){case"eq":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} = ${s}`);break}case"begins_with":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`begins_with(${a}, ${s})`);break}case"between":{let s=`:sk${r}a`,o=`:sk${r}b`;n[s]={S:this._skCondition.value},n[o]={S:this._skCondition.value2},e.push(`${a} BETWEEN ${s} AND ${o}`);break}case"lt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} < ${s}`);break}case"lte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} <= ${s}`);break}case"gt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} > ${s}`);break}case"gte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} >= ${s}`);break}}r++}if(e.length>0)t.KeyConditionExpression=e.join(" AND ");if(this._filterConditions.length>0){let a=[];for(let s of this._filterConditions){let o=`#flt${r}`;if(i[o]=s.attribute,s.operator==="IN"&&s.values){let l=s.values.map((c,y)=>`:flt${r}_${y}`);s.values.forEach((c,y)=>{n[`:flt${r}_${y}`]=this.driver.marshall({v:c}).v}),a.push(`${o} IN (${l.join(", ")})`)}else{let l=`:flt${r}`;n[l]=this.driver.marshall({v:s.value}).v,a.push(`${o} ${s.operator} ${l}`)}r++}t.FilterExpression=a.join(" AND ")}if(this._projectionAttrs.length>0){let a=[];for(let s of this._projectionAttrs){let o=`#proj${r}`;i[o]=s,a.push(o),r++}t.ProjectionExpression=a.join(", ")}if(Object.keys(i).length>0)t.ExpressionAttributeNames=i;if(Object.keys(n).length>0)t.ExpressionAttributeValues=n;if(this._limitValue!==void 0)t.Limit=this._limitValue;if(t.ScanIndexForward=this._scanForward,this._consistentRead)t.ConsistentRead=!0;if(this._startKey)t.ExclusiveStartKey=this.driver.marshall(this._startKey);return t}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return((this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Items??[]).map((n)=>this.driver.unmarshall(n))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let t=[],e;do{if(e)this._startKey=e;let i=this.toRequest(),r=this._pkValue!==void 0?await this.client.query(i):await this.client.scan(i),a=(r.Items??[]).map((s)=>this.driver.unmarshall(s));t.push(...a),e=r.LastEvaluatedKey?this.driver.unmarshall(r.LastEvaluatedKey):void 0}while(e);return t}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return t.Select="COUNT",(this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Count??0}}class I{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(t){let e={region:t.region,tableName:t.table,endpoint:t.endpoint,credentials:t.credentials};return this.driver=u(e),this.tableName=t.table,this.pkAttribute=t.pkAttribute??"pk",this.skAttribute=t.skAttribute??"sk",this.entityTypeAttr=t.entityTypeAttribute??"_et",this.delimiter=t.keyDelimiter??"#",this}setClient(t){return this.client=t,this}registerEntity(t){if(this.entityMappings.set(t.entityType,t),this.driver)this.driver.registerEntity(t);return this}entity(t){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new Ye(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(t)}async batchWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity};e.push({PutRequest:{Item:this.driver.marshall(n)}})}else if(i.delete)e.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}});if(e.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:e}})}async transactWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity},r={Put:{TableName:this.tableName,Item:this.driver.marshall(n)}};if(i.put.condition)r.Put.ConditionExpression=i.put.condition;e.push(r)}else if(i.update){let n={[this.pkAttribute]:i.update.pk};if(i.update.sk)n[this.skAttribute]=i.update.sk;let r=[],a={},s={},o=0;if(i.update.set){let l=[];for(let[c,y]of Object.entries(i.update.set)){let d=`#set${o}`,m=`:set${o}`;a[d]=c,s[m]=this.driver.marshall({v:y}).v,l.push(`${d} = ${m}`),o++}if(l.length>0)r.push(`SET ${l.join(", ")}`)}if(i.update.add){let l=[];for(let[c,y]of Object.entries(i.update.add)){let d=`#add${o}`,m=`:add${o}`;a[d]=c,s[m]={N:String(y)},l.push(`${d} ${m}`),o++}if(l.length>0)r.push(`ADD ${l.join(", ")}`)}if(i.update.remove&&i.update.remove.length>0){let l=[];for(let c of i.update.remove){let y=`#rem${o}`;a[y]=c,l.push(y),o++}r.push(`REMOVE ${l.join(", ")}`)}e.push({Update:{TableName:this.tableName,Key:this.driver.marshall(n),UpdateExpression:r.join(" "),ExpressionAttributeNames:a,ExpressionAttributeValues:s}})}else if(i.delete){let n={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}};if(i.delete.condition)n.Delete.ConditionExpression=i.delete.condition;e.push(n)}else if(i.conditionCheck)e.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.conditionCheck.pk,[this.skAttribute]:i.conditionCheck.sk}),ConditionExpression:i.conditionCheck.condition}});if(e.length>0)await this.client.transactWriteItems({TransactItems:e})}getDriver(){return this.driver}}var zt=new I;function Yt(){return new I}
7
+ export{vt,u,J,x,kt,Qe,v,Ae,Ge,Je,Me,Ct,f,z,Ne,ze,Rt,Ye,zt,Yt};