@xwxfox/foxdb 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,45 +1,45 @@
1
1
  // @bun
2
- import{Database as Nt,constants as kt}from"bun:sqlite";class we{timers=new Set;timersByName=new Map;tasks=new Map;schedule(e,t,n){this.clear(e),this.tasks.set(e,n);let r=setInterval(()=>{try{n()}catch(s){console.error(`[foxdb] scheduler task "${e}" failed:`,s)}},t);this.timers.add(r),this.timersByName.set(e,r)}clear(e){let t=this.timersByName.get(e);if(t)clearInterval(t),this.timers.delete(t),this.timersByName.delete(e);this.tasks.delete(e)}clearAll(){for(let e of this.timers)clearInterval(e);this.timers.clear(),this.timersByName.clear(),this.tasks.clear()}}import{existsSync as Ct,unlinkSync as At}from"fs";class K{db;scheduler=new we;constructor(e={}){let t=e.path??":memory:";this.db=new Nt(t,{create:!0}),this.db.run("PRAGMA journal_mode = WAL;");let n=e.synchronous??"NORMAL",r=e.cacheSize??-64000,s=e.busyTimeout??5000,a=e.mmapSize??268435456;this.db.run(`PRAGMA synchronous = ${n};`),this.db.run(`PRAGMA cache_size = ${r};`),this.db.run(`PRAGMA busy_timeout = ${s};`),this.db.run(`PRAGMA mmap_size = ${a};`),this.db.run("PRAGMA foreign_keys = ON;"),this.db.run("PRAGMA temp_store = MEMORY;");let o=e.autoVacuum??!1;if(o)this.db.run(`PRAGMA auto_vacuum = ${o.toUpperCase()};`)}exec(e){this.db.run(e)}transaction(e){return this.db.transaction(e)()}close(){this.scheduler.clearAll();for(let e of this._stmtCache.values())try{e.finalize()}catch{}this._stmtCache.clear();try{this.db.fileControl(kt.SQLITE_FCNTL_PERSIST_WAL,0),this.db.run("PRAGMA wal_checkpoint(TRUNCATE);")}catch{}this.db.close()}static _MAX_CACHE_SIZE=256;_stmtCache=new Map;prepare(e){let t=this._stmtCache.get(e);if(!t){if(t=this.db.prepare(e),this._stmtCache.size>=K._MAX_CACHE_SIZE){let n=this._stmtCache.keys().next().value;if(n!==void 0){let r=this._stmtCache.get(n);try{r?.finalize()}catch{}this._stmtCache.delete(n)}}this._stmtCache.set(e,t)}return t}setSynchronous(e){this.db.run(`PRAGMA synchronous = ${e};`)}clearCache(){for(let e of this._stmtCache.values())try{e.finalize()}catch{}this._stmtCache.clear()}}function $t(e){if(e===":memory:")return[];return[e,`${e}-wal`,`${e}-shm`,`${e}-journal`].filter((t)=>Ct(t))}function ae(e){for(let t of $t(e))try{At(t)}catch{}}import{Compile as Ht}from"typebox/compile";class le{db;tableName;metricsHook;stmtCache=new Map;constructor(e){this.db=e.db,this.tableName=e.tableName,this.metricsHook=e.metricsHook}_getStmt(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.db.prepare(e);return this.stmtCache.set(e,n),n}exec(e,t,n="raw"){let r=performance.now(),s=this._getStmt(e).run(...t??[]);return this._emit(n,e,performance.now()-r,s.changes),s}all(e,t,n="read"){let r=performance.now(),s=this._getStmt(e).all(...t??[]);return this._emit(n,e,performance.now()-r,s.length),s}get(e,t,n="read"){let r=performance.now(),s=this._getStmt(e).get(...t??[]);return this._emit(n,e,performance.now()-r,s?1:0),s??null}*iterate(e,t,n="read"){let r=performance.now(),s=this._getStmt(e).iterate(...t??[]),a=0;for(let o of s)a++,yield o;this._emit(n,e,performance.now()-r,a)}_emit(e,t,n,r){if(!this.metricsHook)return;this.metricsHook({table:this.tableName,operation:e,sql:t,durationMs:n,rowCount:r})}}class G extends Error{code;trace;context;constructor(e,t){super(e);this.name="ORMError",this.code=t.code,this.trace=t.trace,this.context=t.context??{}}}var xe=[];function Ee(e,t){xe.push({label:e,time:Date.now(),details:t})}function Oe(){xe.pop()}function _e(){return xe.slice()}function C(e,t,n){Ee(e,t);try{return n()}finally{Oe()}}function O(e,t,n){throw new G(t,{code:e,trace:_e(),context:n})}import{IsObject as W,IsArray as ue,IsString as Je,IsNumber as Xe,IsInteger as Ye,IsBoolean as Ce,IsLiteral as ze,IsOptional as Mt}from"typebox";function Ne(e){if(Mt(e))return{schema:e,optional:!0};return{schema:e,optional:!1}}function Ae(e){let t=e;if(t.anyOf&&Array.isArray(t.anyOf))return t.anyOf;return null}function It(e){return e.const}function vt(e){let t=e;if(t.properties&&typeof t.properties==="object"&&t.properties!==null)return t.properties;return null}function $e(e){let t=Ae(e);if(t)return t.some((n)=>n.type==="null");return!1}function Me(e){if(Ye(e))return"INTEGER";if(Xe(e))return"REAL";if(Ce(e))return"INTEGER";if(Je(e))return"TEXT";if(ze(e)){let t=It(e);if(typeof t==="number")return Number.isInteger(t)?"INTEGER":"REAL";if(typeof t==="boolean")return"INTEGER";return"TEXT"}if($e(e)){let t=Ae(e);if(t){let n=t.find((r)=>r.type!=="null");if(n)return Me(n)}}return"TEXT"}function Ze(e){if(Je(e)||Xe(e)||Ye(e)||Ce(e)||ze(e))return!0;if($e(e)){let t=Ae(e);if(t){let n=t.find((r)=>r.type!=="null");if(!n)return!1;return Ze(n)}}return!1}function Lt(e){if(!W(e))return!1;let t=vt(e);if(!t)return!1;for(let n of Object.values(t)){if(ue(n)||W(n))continue;let{schema:r}=Ne(n);if(ue(r)||W(r))continue;if(Ze(r))continue;return!1}return!0}function ke(e,t=[],n=0,r=!1){let s=[];for(let[a,o]of Object.entries(e)){if(ue(o)){let{optional:c}=Ne(o);if(r&&n===0&&W(o.items))continue;let d=t.length>0?[...t,a].join("__"):a;s.push({name:d,sqlType:"TEXT",nullable:c,optional:c,path:t.length>0?[...t,a]:void 0});continue}if(W(o)&&n<2&&Lt(o)){s.push(...ke(o.properties,[...t,a],n+1,r));continue}let{schema:i,optional:l}=Ne(o),u=l||$e(i),m=t.length>0?[...t,a].join("__"):a;s.push({name:m,sqlType:W(i)?"TEXT":Me(i),nullable:u,optional:u,path:t.length>0?[...t,a]:void 0,isBoolean:Ce(i)})}return s}function ne(e){if(!e)return;let t=[];for(let[n,r]of Object.entries(e))t.push({name:n,expr:r.expr,sqlType:Me(r.type)});return t}function J(e,t,n){let r=[];for(let[i,l]of Object.entries(t.properties))if(ue(l)&&W(l.items)){let u=l.items,m=`${e}__${i}`,c=ke(u.properties,[],0,!1),d=new Map,p=new Map;for(let h of c)if(d.set(h.name,h),h.path)p.set(h.path.join("."),h);r.push({fieldName:i,tableName:m,itemSchema:u,columns:c,columnByName:d,columnByPath:p})}let s=ke(t.properties,[],0,!0);if(n)for(let i of n)s.push({name:i.name,sqlType:i.sqlType??"TEXT",nullable:!0,optional:!0,generated:!0,generatedExpr:i.expr});let a=new Map,o=new Map;for(let i of s)if(o.set(i.name,i),i.path)a.set(i.path.join("."),i);return{tableName:e,columns:s,subTables:r,columnByPath:a,columnByName:o}}function Ie(e,t){let n=[],r=e.columns.map((s)=>{let a=!s.nullable?" NOT NULL":"",o=s.name===t?" PRIMARY KEY":"",i=s.generated&&s.generatedExpr?` GENERATED ALWAYS AS (${s.generatedExpr}) STORED`:"";return` "${s.name}" ${s.sqlType}${o}${a}${i}`});n.push(`CREATE TABLE IF NOT EXISTS "${e.tableName}" (
3
- ${r.join(`,
2
+ import{Database as fn,constants as pn}from"bun:sqlite";class Ze{timers=new Set;timersByName=new Map;tasks=new Map;schedule(e,t,n){this.clear(e),this.tasks.set(e,n);let r=setInterval(()=>{try{n()}catch(s){console.error(`[foxdb] scheduler task "${e}" failed:`,s)}},t);this.timers.add(r),this.timersByName.set(e,r)}clear(e){let t=this.timersByName.get(e);if(t)clearInterval(t),this.timers.delete(t),this.timersByName.delete(e);this.tasks.delete(e)}clearAll(){for(let e of this.timers)clearInterval(e);this.timers.clear(),this.timersByName.clear(),this.tasks.clear()}}import{existsSync as hn,unlinkSync as yn}from"fs";class ge{db;scheduler=new Ze;extensionStatus="NOT_NEEDED";_txDepth=0;constructor(e={}){let t=e.path??":memory:";this.db=new fn(t,{create:!0}),this.db.run("PRAGMA journal_mode = WAL;");let n=e.synchronous??"NORMAL",r=e.cacheSize??-64000,s=e.busyTimeout??5000,o=e.mmapSize??268435456;this.db.run(`PRAGMA synchronous = ${n};`),this.db.run(`PRAGMA cache_size = ${r};`),this.db.run(`PRAGMA busy_timeout = ${s};`),this.db.run(`PRAGMA mmap_size = ${o};`),this.db.run("PRAGMA foreign_keys = ON;"),this.db.run("PRAGMA temp_store = MEMORY;");let i=e.autoVacuum??!1;if(i)this.db.run(`PRAGMA auto_vacuum = ${i.toUpperCase()};`)}exec(e){this.db.run(e)}transaction(e){return this.db.transaction(e)()}close(){this.scheduler.clearAll();for(let e of this._stmtCache.values())try{e.finalize()}catch{}this._stmtCache.clear();try{this.db.fileControl(pn.SQLITE_FCNTL_PERSIST_WAL,0),this.db.run("PRAGMA wal_checkpoint(TRUNCATE);")}catch{}this.db.close()}static _MAX_CACHE_SIZE=256;_stmtCache=new Map;prepare(e){let t=this._stmtCache.get(e);if(!t){if(t=this.db.prepare(e),this._stmtCache.size>=ge._MAX_CACHE_SIZE){let n=this._stmtCache.keys().next().value;if(n!==void 0)this._stmtCache.delete(n)}this._stmtCache.set(e,t)}return t}setSynchronous(e){this.db.run(`PRAGMA synchronous = ${e};`)}dropCached(e){this._stmtCache.delete(e)}clearCache(){for(let e of this._stmtCache.values())try{e.finalize()}catch{}this._stmtCache.clear()}getStmtStats(e){if(this.extensionStatus=="OK")return this.db.prepare("SELECT stmt_stats(?) AS stats").get(e);else return[]}}function gn(e){if(e===":memory:")return[];return[e,`${e}-wal`,`${e}-shm`,`${e}-journal`].filter((t)=>hn(t))}function Fe(e){for(let t of gn(e))try{yn(t)}catch{}}import{Compile as qn}from"typebox/schema";function Q(e,t){}function D(e){}function j(e,t){}var ne=null,$t="";function Dt(){if(!ne)try{ne=Bun.file("./foxdb-queries.sql").writer()}catch{}}function At(e){return}function Qe(e,t){return}function Mt(){return}function bn(e){if(!e?.stats)return null;let t=e.stats.replace(/("sql"\s*:\s*")([\s\S]*?)("\s*,\s*"exec_count")/g,(n,r,s,o)=>{let i=s.replace(/"/g,"'");return`${r}${i}${o}`});try{return JSON.parse(t)}catch(n){return console.error("Failed to parse SQL stats JSON:",n),null}}function Tn(e,t,n){let r=0,s=[],o=e.map((i)=>i.detail).join(" ");if(o.includes("SCAN")&&!o.includes("USING INDEX"))r+=50,s.push("Full table scan detected");if(o.includes("TEMP B-TREE"))r+=25,s.push("Sorting requires temporary B-tree (ORDER BY cost)");if(o.includes("IN ("))r+=20,s.push("Large IN clause may cause execution fanout");if(t?.cost?.fullscan_steps>1e5)r+=30,s.push("High fullscan_steps detected (execution pressure)");return{score:Math.min(100,r),hints:s}}class Ce{db;tableName;metricsHook;stmtCache=new Map;constructor(e){this.db=e.db,this.tableName=e.tableName,this.metricsHook=e.metricsHook}_getStmt(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.db.prepare(e);return this.stmtCache.set(e,n),n}static _isFinalizedError(e){return e instanceof Error&&e.message.includes("has finalized")}_withStmt(e,t){try{return t(this._getStmt(e))}catch(n){if(!Ce._isFinalizedError(n))throw n;return this.stmtCache.delete(e),this.db.dropCached(e),t(this._getStmt(e))}}_debugQueryPlan(e,t){return}exec(e,t,n="raw"){let r=performance.now(),s=this._withStmt(e,(o)=>o.run(...t??[]));return this._emit(n,e,performance.now()-r,s.changes),s}all(e,t,n="read"){let r=performance.now(),s=this._withStmt(e,(o)=>o.all(...t??[]));return this._emit(n,e,performance.now()-r,s.length),s}get(e,t,n="read"){let r=performance.now(),s=this._withStmt(e,(o)=>o.get(...t??[]));return this._emit(n,e,performance.now()-r,s?1:0),s??null}*iterate(e,t,n="read"){let r=performance.now(),s=this._getStmt(e).iterate(...t??[]),o=0;for(let i of s)o++,yield i;this._emit(n,e,performance.now()-r,o)}_emit(e,t,n,r){if(!this.metricsHook)return;this.metricsHook({table:this.tableName,operation:e,sql:t,durationMs:n,rowCount:r})}}class we extends Error{code;trace;context;constructor(e,t){super(e);this.name="ORMError",this.code=t.code,this.trace=t.trace,this.context=t.context??{}}}var Le=[],et=[],tt=[];function Sn(e,t){Le.push(e),et.push(Date.now()),tt.push(t)}function _n(){Le.pop(),et.pop(),tt.pop()}function nt(){let e=[];for(let t=0;t<Le.length;t++)e.push({label:Le[t],time:et[t],details:tt[t]});return e}function V(e,t,n){Sn(e,t);try{return n()}finally{_n()}}function v(e,t,n){throw new we(t,{code:e,trace:nt(),context:n})}import{IsObject as le,IsArray as Pe,IsString as Ft,IsNumber as Qt,IsInteger as Lt,IsBoolean as st,IsLiteral as Pt,IsOptional as wn}from"typebox";function Te(e){return e}function rt(e){if(wn(e))return{schema:e,optional:!0};return{schema:e,optional:!1}}function ve(e){let t=Te(e);if(t.anyOf&&Array.isArray(t.anyOf))return t.anyOf;return null}function En(e){return Te(e).const}function Rn(e){let t=ve(e);if(!t)return null;let n=t.filter((r)=>Te(r).type!=="null");return n.length===1?n[0]:null}function Nn(e){let t=Te(e);if(t.properties&&typeof t.properties==="object"&&t.properties!==null)return t.properties;return null}function it(e){let t=ve(e);if(t)return t.some((n)=>Te(n).type==="null");return!1}function ot(e){if(Lt(e))return"INTEGER";if(Qt(e))return"REAL";if(st(e))return"INTEGER";if(Ft(e))return"TEXT";if(Pt(e)){let t=En(e);if(typeof t==="number")return Number.isInteger(t)?"INTEGER":"REAL";if(typeof t==="boolean")return"INTEGER";return"TEXT"}if(it(e)){let t=ve(e);if(t){let n=t.find((r)=>Te(r).type!=="null");if(n)return ot(n)}}return"TEXT"}function vt(e){if(Ft(e)||Qt(e)||Lt(e)||st(e)||Pt(e))return!0;if(it(e)){let t=ve(e);if(t){let n=t.find((r)=>Te(r).type!=="null");if(!n)return!1;return vt(n)}}return!1}function xn(e){if(!le(e))return!1;let t=Nn(e);if(!t)return!1;for(let n of Object.values(t)){if(Pe(n)||le(n))continue;let{schema:r}=rt(n);if(Pe(r)||le(r))continue;if(vt(r))continue;return!1}return!0}function Ie(e,t=[],n=0,r=!1){let s=[];for(let[o,i]of Object.entries(e)){if(Pe(i)){let{optional:y}=rt(i);if(r&&n===0&&le(i.items)){j(`buildColumns skip array ${o}`,{depth:n,reason:"top-level object array \u2192 handled as sub-table"});continue}let _=t.length>0?[...t,o].join("__"):o,g=t.length>0?[...t,o]:void 0;s.push({name:_,sqlType:"TEXT",nullable:y,optional:y,path:g,decode:1,_targetKey:g?g.length===1?g[0]:void 0:_}),j(`buildColumns array ${o} \u2192 ${_}`,{depth:n,sqlType:"TEXT",reason:n===0?"top-level array not of objects \u2192 scalar sub-table or JSON TEXT":"nested array \u2192 JSON TEXT"});continue}if(le(i)&&n<2&&xn(i)){j(`buildColumns flatten ${o}`,{depth:n,reason:"nested object at depth < 2 with only scalar children \u2192 flatten columns"}),s.push(...Ie(i.properties,[...t,o],n+1,r));continue}if(le(i)){let y=n>=2?`depth ${n} >= 2 \u2192 store as JSON TEXT`:"contains non-scalar children or arrays \u2192 store as JSON TEXT";j(`buildColumns object ${o} \u2192 JSON TEXT`,{depth:n,reason:y})}let{schema:l,optional:m}=rt(i),a=m||it(l),u=t.length>0?[...t,o].join("__"):o,c=t.length>0?[...t,o]:void 0,d=le(l)?"TEXT":ot(l),f=st(l),p=Rn(l)??l,h=f?2:le(l)||le(p)?1:0;if(s.push({name:u,sqlType:d,nullable:a,optional:a,path:c,isBoolean:f,decode:h,_targetKey:c?c.length===1?c[0]:void 0:u}),t.length>0)j(`buildColumns scalar ${o} \u2192 ${u}`,{depth:n,sqlType:d,nullable:a,path:[...t,o]})}return s}function Be(e){if(!e)return;let t=[];for(let[n,r]of Object.entries(e))t.push({name:n,expr:r.expr,sqlType:ot(r.type)});return t}function ke(e,t,n,r){let s=[],o=new Set;j(`introspect.${e} start`,{fieldCount:Object.keys(t.properties).length,fields:Object.keys(t.properties),generatedColumns:n?.map((d)=>d.name)});for(let[d,f]of Object.entries(t.properties))if(Pe(f)&&le(f.items)){o.add(d);let p=f.items,h=`${e}__${d}`,y=Ie(p.properties,[],0,!1);j(`introspect.${e} field ${d} \u2192 sub-table`,{subTableName:h,columnCount:y.length,columns:y.map((x)=>({name:x.name,sqlType:x.sqlType,path:x.path})),reason:"top-level array of objects \u2192 separate sub-table with FK back to owner"});let _=new Map,g=new Map;for(let x of y)if(_.set(x.name,x),x.path)g.set(x.path.join("."),x);let S=["_owner_id","_index",...y.map((x)=>x.name)],E=S.map((x)=>`"${x}"`).join(", "),C=`(${S.map(()=>"?").join(", ")})`;s.push({fieldName:d,tableName:h,itemSchema:p,columns:y,columnByName:_,columnByPath:g,insertColsSql:E,insertValueGroup:C,insertColumnNames:S})}let i=Ie(t.properties,[],0,!0);if(j(`introspect.${e} columns built`,{totalScalar:i.length,columnNames:i.map((d)=>d.name),flatColumns:i.filter((d)=>!d.path).length,pathColumns:i.filter((d)=>d.path).length,textJsonColumns:i.filter((d)=>d.sqlType==="TEXT"&&!d.path).length,subTables:s.map((d)=>({fieldName:d.fieldName,tableName:d.tableName,columns:d.columns.length}))}),n)for(let d of n)i.push({name:d.name,sqlType:d.sqlType??"TEXT",nullable:!0,optional:!0,generated:!0,generatedExpr:d.expr});let l=new Map,m=new Map;for(let d of i)if(m.set(d.name,d),d.path)l.set(d.path.join("."),d);let a=i.filter((d)=>!d.generated),u=a.map((d)=>d.name),c={tableName:e,columns:i,subTables:s,columnByPath:l,columnByName:m,primaryKey:r,insertColumns:a,insertColumnNames:u};for(let d of s)for(let f of d.columns){if(f.decode===void 0)f.decode=f.isBoolean?2:f.sqlType==="TEXT"?0:0;if(f._targetKey===void 0)f._targetKey=f.path?f.path.length===1?f.path[0]:void 0:f.name}return c._hydrateFast=at(c),c}function at(e,t){let n=e.columns,r=n.length,s=Array(r),o=Array(r),i=!1;for(let m=0;m<r;m++){let a=n[m],u=a.decode??0;if(a._targetKey)s[m]={src:a.name,dst:a._targetKey,decode:u};else if(a.path)o[m]={src:a.name,path:a.path,decode:u},i=!0;else s[m]={src:a.name,dst:a.name,decode:u}}if(t?.size){let m=t;if(i)return function(u){let c={};for(let d=0;d<r;d++){let f=s[d];if(f){let p=u[f.src],h=m.get(f.src);if(h)p=h.decode(p);if(f.decode===1){if(typeof p==="string")try{p=JSON.parse(p)}catch{}}else if(f.decode===2)p=p==null?null:p===1;c[f.dst]=p??null}else{let p=o[d],h=u[p.src],y=m.get(p.src);if(y)h=y.decode(h);if(p.decode===1){if(typeof h==="string")try{h=JSON.parse(h)}catch{}}else if(p.decode===2)h=h==null?null:h===1;be(c,p.path,h??null)}}return c};return function(u){let c={};for(let d=0;d<r;d++){let f=s[d],p=u[f.src],h=m.get(f.src);if(h)p=h.decode(p);if(f.decode===1){if(typeof p==="string")try{p=JSON.parse(p)}catch{}}else if(f.decode===2)p=p==null?null:p===1;c[f.dst]=p??null}return c}}if(i)return function(a){let u={};for(let c=0;c<r;c++){let d=s[c];if(d){let f=a[d.src];if(d.decode===1){if(typeof f==="string")try{f=JSON.parse(f)}catch{}}else if(d.decode===2)f=f==null?null:f===1;u[d.dst]=f??null}else{let f=o[c],p=a[f.src];if(f.decode===1){if(typeof p==="string")try{p=JSON.parse(p)}catch{}}else if(f.decode===2)p=p==null?null:p===1;be(u,f.path,p??null)}}return u};return function(a){let u={};for(let c=0;c<r;c++){let d=s[c],f=a[d.src];if(d.decode===1){if(typeof f==="string")try{f=JSON.parse(f)}catch{}}else if(d.decode===2)f=f==null?null:f===1;u[d.dst]=f??null}return u}}function lt(e,t,n=!1,r="native"){let s=[];j(`ddl.mainTable building ${e.tableName}`,{totalColumns:e.columns.length,primaryKey:t,scalarColumns:e.columns.filter((l)=>!l.generated).length,generatedColumns:e.columns.filter((l)=>l.generated).length,subTables:e.subTables.map((l)=>l.fieldName)});let o=e.columns.map((l)=>{let m=!l.nullable?" NOT NULL":"",a=l.name===t?" PRIMARY KEY":"",u=l.generated&&l.generatedExpr?` GENERATED ALWAYS AS (${l.generatedExpr}) STORED`:"";return` "${l.name}" ${l.sqlType}${a}${m}${u}`}),i=`CREATE TABLE IF NOT EXISTS "${e.tableName}" (
3
+ ${o.join(`,
4
4
  `)}
5
- )`);for(let s of e.subTables){let a=[' "_id" INTEGER PRIMARY KEY AUTOINCREMENT',` "_owner_id" ${e.columns.find((o)=>o.name===t)?.sqlType??"TEXT"} NOT NULL`,' "_index" INTEGER NOT NULL',...s.columns.map((o)=>{let i=!o.nullable?" NOT NULL":"";return` "${o.name}" ${o.sqlType}${i}`})];n.push(`CREATE TABLE IF NOT EXISTS "${s.tableName}" (
6
- ${a.join(`,
5
+ )`;s.push(i),j(`ddl.mainTable SQL for ${e.tableName}`,{sql:i});for(let l of e.subTables){let a=e.columns.find((p)=>p.name===t)?.sqlType??"TEXT",u=r==="native"?`REFERENCES "${e.tableName}"("${t}") ON DELETE CASCADE`:"",c=[' "_id" INTEGER PRIMARY KEY AUTOINCREMENT',` "_owner_id" ${a} NOT NULL ${u}`.trim(),' "_index" INTEGER NOT NULL',...l.columns.map((p)=>{let h=!p.nullable?" NOT NULL":"";return` "${p.name}" ${p.sqlType}${h}`})],d=`CREATE TABLE IF NOT EXISTS "${l.tableName}" (
6
+ ${c.join(`,
7
7
  `)}
8
- )`),n.push(`CREATE INDEX IF NOT EXISTS "idx_${s.tableName}__owner" ON "${s.tableName}" ("_owner_id")`)}return n}function et(e,t,n,r,s,a){let o=r??`idx_${e}__${t.join("_")}`,i=n?"UNIQUE ":"",l=t.map((m)=>`"${m}"`).join(", "),u=s?` WHERE ${s}`:"";return`CREATE ${i}INDEX IF NOT EXISTS "${o}" ON "${e}" (${l})${u}`}function ee(e,t){if(e===void 0||e===null)return null;if(t==="TEXT"&&typeof e==="object")return JSON.stringify(e);if(t==="INTEGER"&&typeof e==="boolean")return e?1:0;return Bt(e)}function te(e,t){let n=e;for(let r of t){if(n===null||n===void 0)return;if(typeof n!=="object")return;n=n[r]}return n}function Z(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let a=t[s];if(!(a in r))r[a]={};r=r[a]}r[t[t.length-1]]=n}function U(e,t,n){let r={};if(!n?.size)for(let s of t.columns){if(s.generated)continue;let a=s.path?te(e,s.path):e[s.name];r[s.name]=ee(a,s.sqlType)}else for(let s of t.columns){if(s.generated)continue;let a=s.path?te(e,s.path):e[s.name],o=ee(a,s.sqlType),i=n.get(s.name);if(i)o=i.encode(o);r[s.name]=o}return r}function tt(e,t,n){let r={};for(let s of t.columns){if(s.generated)continue;if(!(s.name in e)&&!s.path)continue;let a;if(s.path)a=te(e,s.path);else a=e[s.name];if(a===void 0)continue;let o=ee(a,s.sqlType),i=n?.get(s.name);if(i)o=i.encode(o);r[s.name]=o}return r}function X(e,t,n,r){let s=Array(t.length);if(!r?.size)for(let a=0;a<t.length;a++){let o=t[a];if(o===null||typeof o!=="object")throw TypeError("Sub-table item must be an object");let i=o,l={_owner_id:e,_index:a};for(let u of n.columns){let m=u.path?te(i,u.path):i[u.name];l[u.name]=ee(m,u.sqlType)}s[a]=l}else for(let a=0;a<t.length;a++){let o=t[a];if(o===null||typeof o!=="object")throw TypeError("Sub-table item must be an object");let i=o,l={_owner_id:e,_index:a};for(let u of n.columns){let m=u.path?te(i,u.path):i[u.name],c=ee(m,u.sqlType),d=r.get(u.name);if(d)c=d.encode(c);l[u.name]=c}s[a]=l}return s}function Bt(e){if(e===null||e===void 0)return null;if(typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint")return e;if(typeof e==="object")return JSON.stringify(e);return String(e)}function ce(e,t,n){if(t==="TEXT"&&typeof e==="string"){let r=e.charCodeAt(0);if(r===123||r===91)try{let s=JSON.parse(e);return typeof s==="object"?s:e}catch{return e}return e}if(t==="INTEGER"&&typeof e==="number")return n?e===1:e;return e??null}function Dt(e,t){let n={};for(let r of t.columns){let s=ce(e[r.name],r.sqlType,r.isBoolean);if(r.path)if(r.path.length===1)n[r.path[0]]=s;else Z(n,r.path,s);else n[r.name]=s}return n}function de(e,t,n,r,s,a){if(!r?.size&&!s&&!t.subTables.length)return Dt(e,t);let o={};if(!s)if(!r?.size)for(let i of t.columns){let l=ce(e[i.name],i.sqlType,i.isBoolean);if(i.path)if(i.path.length===1)o[i.path[0]]=l;else Z(o,i.path,l);else o[i.name]=l}else for(let i of t.columns){let l=e[i.name],u=r.get(i.name);if(u)l=u.decode(l);let m=ce(l,i.sqlType,i.isBoolean);if(i.path)if(i.path.length===1)o[i.path[0]]=m;else Z(o,i.path,m);else o[i.name]=m}else{let i=new Set;for(let l of s)if(i.add(l),!l.includes(".")){for(let u of t.columns)if(u.path&&u.path[0]===l)i.add(u.name)}else{let u=t.columnByPath.get(l);if(u)i.add(u.name)}for(let l of t.columns){if(!i.has(l.name))continue;let u=e[l.name],m=r?.get(l.name);if(m)u=m.decode(u);let c=ce(u,l.sqlType,l.isBoolean);if(l.path)if(l.path.length===1)o[l.path[0]]=c;else Z(o,l.path,c);else o[l.name]=c}for(let l of Object.keys(e)){if(i.has(l))continue;if(l.includes("__")){let u=l.split("__"),m=e[l];if(typeof m==="string"){let c=m.charCodeAt(0);if(c===123||c===91)try{let d=JSON.parse(m);if(typeof d==="object")m=d}catch{}}Z(o,u,m)}}}for(let i of t.subTables)if(a&&!a.includes(i.fieldName))o[i.fieldName]=[];else o[i.fieldName]=n.get(i.tableName)??[];return o}var nt={encode(e){if(typeof e!=="string")return e;let t=new TextEncoder().encode(e);return Bun.gzipSync(t.buffer)},decode(e){if(!(e instanceof Uint8Array))return e;return new TextDecoder().decode(Bun.gunzipSync(e.buffer))}};function Pt(e){return typeof e==="object"&&e!==null}function ve(e){return e.replace(/'/g,"''")}function Qt(e,t){let n=e.split(".");if(n.length<2)return null;if(t){let o=t.columnByPath.get(e);if(o)return{sql:`"${o.name}"`};for(let i=n.length-1;i>=1;i--){let l=n.slice(0,i).join("."),u=n.slice(i).join("."),m=t.columnByPath.get(l);if(m&&m.sqlType==="TEXT")return{sql:`JSON_EXTRACT("${m.name.replace(/"/g,'""')}", '$.${ve(u)}')`}}}let r=n[0],s=n.slice(1).join(".");return{sql:`JSON_EXTRACT("${r.replace(/"/g,'""')}", '$.${ve(s)}')`}}function B(e){if(e!==null&&typeof e==="object")return JSON.stringify(e);return e}function Le(e,t,n){let r=Qt(e,n),s=r?r.sql:`"${e}"`,a=[],o=[];if("eq"in t)a.push(`${s} = ?`),o.push(B(t.eq));if("ne"in t)a.push(`${s} != ?`),o.push(B(t.ne));if("gt"in t)a.push(`${s} > ?`),o.push(B(t.gt));if("gte"in t)a.push(`${s} >= ?`),o.push(B(t.gte));if("lt"in t)a.push(`${s} < ?`),o.push(B(t.lt));if("lte"in t)a.push(`${s} <= ?`),o.push(B(t.lte));if("like"in t)a.push(`${s} LIKE ?`),o.push(B(t.like));if("between"in t){let[i,l]=t.between;a.push(`${s} BETWEEN ? AND ?`),o.push(B(i),B(l))}if("in"in t){let i=t.in,l=i.map(()=>"?").join(", ");a.push(`${s} IN (${l})`),o.push(...i.map(B))}if("notIn"in t){let i=t.notIn,l=i.map(()=>"?").join(", ");a.push(`${s} NOT IN (${l})`),o.push(...i.map(B))}if("isNull"in t)a.push(`${s} IS NULL`);if("isNotNull"in t)a.push(`${s} IS NOT NULL`);if("arraySome"in t)a.push(`EXISTS (SELECT 1 FROM json_each(${s}) WHERE value = ?)`),o.push(B(t.arraySome));if("arrayNot"in t)a.push(`NOT EXISTS (SELECT 1 FROM json_each(${s}) WHERE value = ?)`),o.push(B(t.arrayNot));if("isEmpty"in t)if(t.isEmpty)a.push(`(json_array_length(${s}) = 0 OR ${s} IS NULL)`);else a.push(`json_array_length(${s}) > 0`);if("fastArrayIsEmpty"in t)if(t.fastArrayIsEmpty)a.push(`(${s} = '[]' OR ${s} IS NULL)`);else a.push(`(${s} != '[]' AND ${s} IS NOT NULL)`);if("fastArraySome"in t){let i=JSON.stringify([t.fastArraySome]),l=i.substring(1,i.length-1);a.push(`(',' || REPLACE(REPLACE(${s}, '[', ''), ']', '') || ',') LIKE ?`),o.push(`%,${l},%`)}if("fastArrayNot"in t){let i=JSON.stringify([t.fastArrayNot]),l=i.substring(1,i.length-1);a.push(`(',' || REPLACE(REPLACE(${s}, '[', ''), ']', '') || ',') NOT LIKE ?`),o.push(`%,${l},%`)}if(a.length===0)O("UNKNOWN_FILTER",`foxdb: unknown filter operator for column "${e}"`,{column:e});return{sql:a.join(" AND "),params:o}}function jt(e){if(typeof e!=="object"||e===null)return!1;let t=e;if("AND"in t&&Array.isArray(t.AND))return!0;if("OR"in t&&Array.isArray(t.OR))return!0;if("NOT"in t&&typeof t.NOT==="object"&&t.NOT!==null)return!0;return!1}function Y(e){if(!e||typeof e!=="object"||Object.keys(e).length===0)return!0;let t=e,n=Object.keys(t);if(n.length===1&&n[0]==="AND"&&Array.isArray(t.AND)&&t.AND.length===0)return!0;if(n.length===1&&n[0]==="OR"&&Array.isArray(t.OR)&&t.OR.some(Y))return!0;if(n.length===1&&n[0]==="NOT"&&re(t.NOT))return!0;return!1}function re(e){if(!e||typeof e!=="object")return!1;let t=e,n=Object.keys(t);if(n.length===1&&n[0]==="OR"&&Array.isArray(t.OR)&&t.OR.length===0)return!0;if(n.length===1&&n[0]==="AND"&&Array.isArray(t.AND)&&t.AND.some(re))return!0;if(n.length===1&&n[0]==="NOT"&&Y(t.NOT))return!0;return!1}function me(e,t,n){let r=[],s=[];if(t)r.push(`"${t}" IS NULL`);if(!e||Object.keys(e).length===0){if(r.length===0)return{sql:"",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}if(jt(e)){let o=e;if(o.AND)for(let i of o.AND){if(Y(i))continue;if(re(i)){if(r.push("1=0"),r.length===1)return{sql:"WHERE 1=0",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}let l=me(i,void 0,n);if(l.sql)r.push(`(${l.sql.replace(/^WHERE\s+/,"")})`),s.push(...l.params)}if(o.OR){let i=[],l=[];for(let u of o.OR){if(Y(u)){i.length=0;break}if(re(u))continue;let m=me(u,void 0,n);if(m.sql)i.push(m.sql.replace(/^WHERE\s+/,"")),l.push(...m.params)}if(i.length>0)r.push(`(${i.join(" OR ")})`),s.push(...l);else if(!o.OR.some(Y))r.push("1=0")}if(o.NOT){if(Y(o.NOT))r.push("1=0");else if(!re(o.NOT)){let i=me(o.NOT,void 0,n);if(i.sql)r.push(`NOT (${i.sql.replace(/^WHERE\s+/,"")})`),s.push(...i.params)}}}let a=e._raw;if(a&&typeof a==="object"&&"sql"in a){let o=a;r.push(`(${o.sql})`),s.push(...o.params??[])}for(let[o,i]of Object.entries(e)){if(o==="AND"||o==="OR"||o==="NOT"||o==="_raw")continue;if(!Pt(i))continue;let l=Le(o,i,n);r.push(l.sql),s.push(...l.params)}if(r.length===0)return{sql:"",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}function P(e,t,n){return me(e,t,n)}function Q(e,t){if(!t)return`"${e}"`;let n=t.columnByPath.get(e);if(n)return`"${n.name}"`;let r=e.split(".");for(let s=r.length-1;s>=1;s--){let a=r.slice(0,s).join("."),o=r.slice(s).join("."),i=t.columnByPath.get(a);if(i&&i.sqlType==="TEXT")return`JSON_EXTRACT("${i.name.replace(/"/g,'""')}", '$.${ve(o)}')`}return`"${e}"`}function qt(e,t){if(!e)return"";let n=globalThis.Array.isArray(e)?e:[e];if(n.length===0)return"";return`ORDER BY ${n.map((s)=>`${Q(s.column,t)} ${s.direction??"ASC"}`).join(", ")}`}function Ft(e,t){let n=[],r=[];if(e!==void 0)n.push("LIMIT ?"),r.push(e);if(t!==void 0)n.push("OFFSET ?"),r.push(t);return{sql:n.join(" "),params:r}}function Kt(e,t){let n=t.columnByName.get(e)||t.columnByPath.get(e);if(n)return[`"${n.name}"`];let r=[];for(let a of t.columns)if(a.path&&a.path[0]===e)r.push(`"${a.name}"`);if(r.length>0)return r;let s=e.split(".");for(let a=s.length-1;a>=1;a--){let o=s.slice(0,a).join("."),i=s.slice(a).join("."),l=t.columnByPath.get(o);if(l&&l.sqlType==="TEXT"){let u=s.join("__");return[`JSON_EXTRACT("${l.name}", '$.${i.replace(/'/g,"''")}') as "${u}"`]}}return[`"${e}"`]}function Be(e,t,n,r){let{sql:s,params:a}=P(t.where,t.includeDeleted?void 0:n,r),o=qt(t.orderBy,r),{sql:i,params:l}=Ft(t.limit,t.offset),u=t.select&&r?t.select.flatMap((p)=>Kt(p,r)).join(", "):"*";if(t.distinctOn&&t.distinctOn.length>0){let p=t.distinctOn.map((k)=>Q(k,r)).join(", "),h=[`SELECT ${u} FROM "${e}"`,s,`GROUP BY ${p}`,o,i].filter(Boolean).join(" "),T=[`SELECT COUNT(*) as "_count" FROM (SELECT 1 FROM "${e}"`,s,`GROUP BY ${p})`].filter(Boolean).join(" ");return{sql:h,params:[...a,...l],countSql:T,countParams:a}}let c=[`SELECT ${t.distinct?"DISTINCT ":""}${u} FROM "${e}"`,s,o,i].filter(Boolean).join(" "),d;if(t.distinct)d=[`SELECT COUNT(*) as "_count" FROM (SELECT DISTINCT ${u} FROM "${e}"`,s,")"];else d=[`SELECT COUNT(*) as "_count" FROM "${e}"`,s];return{sql:c,params:[...a,...l],countSql:d.filter(Boolean).join(" "),countParams:a}}function se(e,t,n,r){return Be(e,t,n,r)}function H(e,t){let n=Object.keys(t),r=n.map((a)=>`"${a}"`).join(", "),s=n.map(()=>"?").join(", ");return{sql:`INSERT INTO "${e}" (${r}) VALUES (${s})`,params:n.map((a)=>t[a])}}function pe(e,t,n=999){if(t.length===0)return[];let r=t[0],s=Object.keys(r),a=s.length,o=Math.floor(n/a);if(o<=0)O("TOO_MANY_COLUMNS",`foxdb: table "${e}" has too many columns for multi-value insert`);let i=[];for(let l=0;l<t.length;l+=o){let u=t.slice(l,l+o),m=s.map((p)=>`"${p}"`).join(", "),c=u.map(()=>`(${s.map(()=>"?").join(", ")})`).join(", "),d=u.flatMap((p)=>s.map((h)=>p[h]));i.push({sql:`INSERT INTO "${e}" (${m}) VALUES ${c}`,params:d})}return i}function rt(e,t,n,r){let s=Object.keys(t),a=s.map((u)=>`"${u}"`).join(", "),o=s.map(()=>"?").join(", "),i=n.map((u)=>`"${u}"`).join(", "),l=r.map((u)=>`"${u}" = excluded."${u}"`).join(", ");return{sql:`INSERT INTO "${e}" (${a}) VALUES (${o}) ON CONFLICT (${i}) DO UPDATE SET ${l}`,params:s.map((u)=>t[u])}}function st(e,t,n,r,s=999){if(t.length===0)return[];let a=t[0],o=Object.keys(a),i=o.length,l=Math.floor(s/i);if(l<=0)O("TOO_MANY_COLUMNS",`foxdb: table "${e}" has too many columns for multi-value upsert`);let u=n.map((d)=>`"${d}"`).join(", "),m=r.map((d)=>`"${d}" = excluded."${d}"`).join(", "),c=[];for(let d=0;d<t.length;d+=l){let p=t.slice(d,d+l),h=o.map((D)=>`"${D}"`).join(", "),T=p.map(()=>`(${o.map(()=>"?").join(", ")})`).join(", "),k=p.flatMap((D)=>o.map((oe)=>D[oe]));c.push({sql:`INSERT INTO "${e}" (${h}) VALUES ${T} ON CONFLICT (${u}) DO UPDATE SET ${m}`,params:k})}return c}function ot(e,t,n,r){let s=Object.entries(r).filter(([o])=>o!==t);if(s.length===0)O("NO_COLUMNS_TO_UPDATE","foxdb: no columns to update",{table:e});let a=s.map(([o])=>`"${o}" = ?`).join(", ");return{sql:`UPDATE "${e}" SET ${a} WHERE "${t}" = ?`,params:[...s.map(([,o])=>o),n]}}function it(e,t,n,r,s){let a=Object.entries(t);if(a.length===0)O("NO_COLUMNS_TO_UPDATE","foxdb: no columns to update",{table:e});let o=a.map(([u])=>`"${u}" = ?`).join(", "),{sql:i,params:l}=P(n,r,s);return{sql:`UPDATE "${e}" SET ${o} ${i}`.trim(),params:[...a.map(([,u])=>u),...l]}}function Wt(e){return e.replace(/'/g,"''")}function V(e,t){if(!t)return`"${e}"`;let n=t.columnByPath.get(e);if(n)return`"${n.name}"`;let r=e.split(".");for(let s=r.length-1;s>=1;s--){let a=r.slice(0,s).join("."),o=r.slice(s).join("."),i=t.columnByPath.get(a);if(i&&i.sqlType==="TEXT")return`JSON_EXTRACT("${i.name.replace(/"/g,'""')}", '$.${Wt(o)}')`}return`"${e}"`}function at(e,t,n,r){let{sql:s,params:a}=P(t.where,t.includeDeleted?void 0:n,r),o=[];if(t.groupBy)for(let d of t.groupBy){let p=V(d,r);o.push(`${p} as "${d.replace(/"/g,'""')}"`)}for(let[d,p]of Object.entries(t.aggregations))if("sum"in p&&p.sum)o.push(`SUM(${V(p.sum,r)}) as "${d}"`);else if("count"in p&&p.count)o.push(`COUNT(${p.count==="*"?"*":V(p.count,r)}) as "${d}"`);else if("avg"in p&&p.avg)o.push(`AVG(${V(p.avg,r)}) as "${d}"`);else if("min"in p&&p.min)o.push(`MIN(${V(p.min,r)}) as "${d}"`);else if("max"in p&&p.max)o.push(`MAX(${V(p.max,r)}) as "${d}"`);let i=t.groupBy?`GROUP BY ${t.groupBy.map((d)=>V(d,r)).join(", ")}`:"",l=[],u=[];if(t.having){for(let[d,p]of Object.entries(t.having))if(p&&typeof p==="object"&&!Array.isArray(p)){let h=Le(d,p,r);l.push(h.sql),u.push(...h.params)}}let m=l.length>0?`HAVING ${l.join(" AND ")}`:"";return{sql:`SELECT ${o.join(", ")} FROM "${e}" ${s} ${i} ${m}`.trim(),params:[...a,...u]}}function Ut(e,t,n,r){if("rowNumber"in t)return`ROW_NUMBER() OVER (${n}) as "${e}"`;if("rank"in t)return`RANK() OVER (${n}) as "${e}"`;if("denseRank"in t)return`DENSE_RANK() OVER (${n}) as "${e}"`;if("lead"in t){let s=Q(t.lead,r),a=t.offset??1;return`LEAD(${s}, ${a}) OVER (${n}) as "${e}"`}if("lag"in t){let s=Q(t.lag,r),a=t.offset??1;return`LAG(${s}, ${a}) OVER (${n}) as "${e}"`}return`"${e}"`}function lt(e,t,n,r){let{sql:s,params:a}=P(t.where,n,r),o=t.partitionBy&&t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map((h)=>Q(h,r)).join(", ")}`:"",i=t.orderBy?(Array.isArray(t.orderBy)?t.orderBy:[t.orderBy]).map((h)=>`${Q(h.column,r)} ${h.direction??"ASC"}`):[],l=i.length>0?`ORDER BY ${i.join(", ")}`:"",u=[o,l].filter(Boolean).join(" "),m=u?u:"ORDER BY (SELECT NULL)",c=[];for(let[h,T]of Object.entries(t.select))c.push(Ut(h,T,m,r));let d=t.limit!==void 0?`LIMIT ${t.limit}`:"";return{sql:[`SELECT ${c.join(", ")} FROM "${e}"`,s,d].filter(Boolean).join(" "),params:a}}class fe{buffer=[];maxBuffer;tableName;db;prepare;onFlush;timer;constructor(e,t,n={},r){if(this.tableName=e,this.db=t,this.maxBuffer=n.maxBuffer??1000,this.prepare=r.prepare,this.onFlush=r.onFlush,n.flushIntervalMs)this.timer=setInterval(()=>this.flush(),n.flushIntervalMs)}insert(e){let t=this.prepare(e);if(this.buffer.push(t),this.buffer.length>=this.maxBuffer)this.flush()}flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0,this.buffer.length);this.db.transaction(()=>{let t=pe(this.tableName,e);for(let{sql:n,params:r}of t)this.db.prepare(n).run(...r)}),this.onFlush?.(e)}close(){if(this.timer)clearInterval(this.timer);this.flush()}}var De={createdAt:"createdAt",updatedAt:"updatedAt"};function Pe(e,t){if(e===!1||!e)return{createdAt:null,updatedAt:null};let n=typeof e==="object"&&e.createdAt!==void 0?e.createdAt:De.createdAt,r=typeof e==="object"&&e.updatedAt!==void 0?e.updatedAt:De.updatedAt,s=new Set(t.columns.map((a)=>a.name));return{createdAt:s.has(n)?n:null,updatedAt:s.has(r)?r:null}}class he{tableName;meta;validator;db;descriptor;_entityProto=null;_timestampNames;_materialize;_materializeMany;_events;_executor;_codecs;setEventBus(e){this._events=e}setMetricsHook(e){this._executor=new le({db:this.db,tableName:this.tableName,metricsHook:e})}constructor(e,t,n){this.tableName=e,this.descriptor=t,this.db=n,this._executor=new le({db:n,tableName:this.tableName}),this.meta=J(e,t.schema,ne(t.generated)),this._timestampNames=Pe(t.timestamps,this.meta),this.validator=Ht(t.schema);let r=new Map;if(t.compression?.algorithm==="gzip")for(let s of t.compression.columns)r.set(s.name,nt);this._codecs=r;for(let s of this.meta.columns)if(this._codecs.has(s.name))s.sqlType="BLOB";if(this._migrate(),t.eviction){if(n.scheduler.schedule(`evict:${e}`,30000,()=>this._runEviction()),t.eviction.maxRows&&!t.eviction.lruColumn)console.warn(`[foxdb] table "${e}" has eviction.maxRows without lruColumn. Eviction will use PK order, which is not true LRU.`)}}_ensureSelectPk(e){let t=this.descriptor.primaryKey.name;if(e.select&&e.include&&!e.select.includes(t))return{...e,select:[...e.select,t]};return e}_fetchRows(e,t){let n=this.descriptor.primaryKey.name,r=this.descriptor.softDelete?.column;if(!(!e.select&&e.where&&Object.keys(e.where).length>0)){let{sql:h,params:T}=se(this.tableName,e,r,this.meta);return this._executor.all(h,T,t)}let a={...e,select:[n],include:void 0},{sql:o,params:i}=se(this.tableName,a,r,this.meta),u=this._executor.all(o,i,t).map((h)=>h[n]).filter((h)=>typeof h==="string"||typeof h==="number");if(u.length===0)return[];if(u.length>500){let{sql:h,params:T}=se(this.tableName,e,r,this.meta);return this._executor.all(h,T,t)}let m=u.map(()=>"?").join(", "),c=`SELECT * FROM "${this.tableName}" WHERE "${n}" IN (${m})`,d=this._executor.all(c,u,t),p=new Map(u.map((h,T)=>[h,T]));return d.sort((h,T)=>{let k=h[n],D=T[n],oe=p.get(k)??0,ie=p.get(D)??0;return oe-ie}),d}setMaterializer(e,t){this._materialize=e,this._materializeMany=t;let n=Object.create(null);Object.defineProperty(n,"materialize",{value:function(){return e(this)},writable:!1,enumerable:!1,configurable:!1}),this._entityProto=n}_wrap(e){if(!this._entityProto)return e;let t=Object.create(this._entityProto);return Object.assign(t,e),t}_record(e){return Object.fromEntries(Object.entries(e))}_assertPk(e){if(e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint")return e;O("INSERT_INVALID_PK",`Primary key must be a scalar, got ${typeof e}`,{table:this.tableName})}_emit(e,t){if(!this._events)return;let n=Date.now(),s={...{table:this.tableName,operation:e,timestamp:n},...t},a=`${this.tableName}.${e}`;if(this._events.has(a))this._events.emit(a,s);let o;if(e.startsWith("find")||e==="count")o="read";else if(e==="delete"||e==="deleteWhere"||e==="flush")o="delete";else o="write";let i=`${this.tableName}.${o}`;if(this._events.has(i))this._events.emit(i,{...s,operation:o})}_migrate(){let e=this.descriptor.primaryKey.name,t=Ie(this.meta,e);this.db.transaction(()=>{for(let n of t)this.db.exec(n);for(let n of this.descriptor.indexes??[])this.db.exec(et(this.tableName,n.columns.map((r)=>r.name),n.unique??!1,n.name,n.where,n.include?.map((r)=>r.name)))}),this.db.clearCache()}_runEviction(){let e=this.descriptor.eviction;if(!e)return;let t=Date.now();if(e.ttlColumn&&e.ttlMs){let n=t-e.ttlMs;this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${e.ttlColumn}" < ?`,[n],"evict")}if(e.maxRows){let n=e.lruColumn??this.descriptor.primaryKey.name,s=this.db.prepare(`SELECT COUNT(*) as c FROM "${this.tableName}"`).get().c;if(s<=e.maxRows)return;let a=s-e.maxRows;this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${this.descriptor.primaryKey.name}" IN (
8
+ )`;s.push(d),j(`ddl.subTable SQL for ${l.tableName}`,{sql:d});let f=`CREATE INDEX IF NOT EXISTS "idx_${l.tableName}__owner" ON "${l.tableName}" ("_owner_id")`;if(s.push(f),j(`ddl.index for ${l.tableName}`,{sql:f,reason:"FK index for hydration + CASCADE lookups"}),n){let h=0,y=l.columns.filter((E)=>E.sqlType==="TEXT"),_=y.filter((E)=>!E.nullable),g=y.filter((E)=>E.nullable),S=[..._,...g];for(let E of S){if(h>=3)break;let C=E.name.toUpperCase();if(C.endsWith("DATE")||C.endsWith("AT")||C.endsWith("TIME"))continue;let x=`CREATE INDEX IF NOT EXISTS "idx_${l.tableName}__${E.name}" ON "${l.tableName}" ("${E.name}")`;s.push(x),h++,j(`ddl.index for ${l.tableName}`,{sql:x,reason:`auto-index TEXT column "${E.name}" for WHERE / ORDER BY`})}j(`ddl.autoIndex summary for ${l.tableName}`,{autoIndexed:h,totalCandidates:y.length,capped:h>=3,note:h>0?"TEXT columns auto-indexed (max 3). Set autoIndex: false in table() to disable.":"no suitable TEXT columns to auto-index"})}else j(`ddl.autoIndex summary for ${l.tableName}`,{autoIndexed:0,note:"autoIndex disabled. only _owner_id indexed."})}return s}function qt(e,t,n,r,s,o){let i=r??`idx_${e}__${t.join("_")}`,l=n?"UNIQUE ":"",m=t.map((u)=>`"${u}"`).join(", "),a=s?` WHERE ${s}`:"";return`CREATE ${l}INDEX IF NOT EXISTS "${i}" ON "${e}" (${m})${a}`}function ct(e,t){if(e===void 0||e===null)return null;if(t==="TEXT"&&typeof e==="object")return JSON.stringify(e);if(t==="INTEGER"&&typeof e==="boolean")return e?1:0;return On(e)}function ut(e){return e}function dt(e,t){let n=e;for(let r of t){if(n===null||n===void 0)return;if(typeof n!=="object")return;n=ut(n)[r]}return n}function be(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let o=t[s];if(!(o in r))r[o]={};r=ut(r[o])}r[t[t.length-1]]=n}function Ee(e,t,n){let r=t.insertColumns,s=r.length,o=n?.size,i=Object.create(null);for(let l=0;l<s;l++){let m=r[l],a=m.path?dt(e,m.path):e[m.name],u=ct(a,m.sqlType);if(o){let c=n.get(m.name);i[m.name]=c?c.encode(u):u}else i[m.name]=u}return i}function mt(e,t,n){let r=t.insertColumns,s=r.length,o=n?.size,i={};for(let l=0;l<s;l++){let m=r[l];if(!(m.name in e)&&!m.path)continue;let a;if(m.path)a=dt(e,m.path);else a=e[m.name];if(a===void 0)continue;let u=ct(a,m.sqlType);if(o){let c=n.get(m.name);i[m.name]=c?c.encode(u):u}else i[m.name]=u}return i}function Re(e,t,n,r){let s=n.columns,o=s.length,i=Array(t.length),l=r?.size;for(let m=0;m<t.length;m++){let a=t[m];if(a===null||typeof a!=="object")throw TypeError("Sub-table item must be an object");let u=ut(a),c={_owner_id:e,_index:m};for(let d=0;d<o;d++){let f=s[d],p=f.path?dt(u,f.path):u[f.name],h=ct(p,f.sqlType);if(l){let y=r.get(f.name);c[f.name]=y?y.encode(h):h}else c[f.name]=h}i[m]=c}return i}function On(e){if(e===null||e===void 0)return null;if(typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint")return e;if(typeof e==="object")return JSON.stringify(e);return String(e)}function qe(e,t,n){if(t==="TEXT"&&typeof e==="string"){let r=e.charCodeAt(0);if(r===123||r===91)try{let s=JSON.parse(e);return typeof s==="object"?s:e}catch{return e}return e}if(t==="INTEGER"&&typeof e==="number")return n?e===1:e;return e??null}function Cn(e,t){let n={};for(let r of t.columns){let s=qe(e[r.name],r.sqlType,r.isBoolean);if(r.path)if(r.path.length===1)n[r.path[0]]=s;else be(n,r.path,s);else n[r.name]=s}return n}var se=Object.freeze(new Map);function re(e,t,n,r,s,o){if(!r?.size&&!s&&!t.subTables.length){if(t._hydrateFast)return t._hydrateFast(e);return Cn(e,t)}let i=r?.size,l={};if(!s)if(!i){if(t._hydrateFast){let m=t._hydrateFast(e);for(let a of t.subTables)if(o&&!o.includes(a.fieldName))m[a.fieldName]=[];else{let u=n.get(a.tableName);if(o||u)m[a.fieldName]=u??[]}return m}In(e,t,l)}else Bn(e,t,r,l);else{let m=new Set;for(let a of s)if(m.add(a),!a.includes(".")){for(let u of t.columns)if(u.path&&u.path[0]===a)m.add(u.name)}else{let u=t.columnByPath.get(a);if(u)m.add(u.name)}for(let a of t.columns){if(!m.has(a.name))continue;let u=e[a.name];if(i){let d=r.get(a.name);if(d)u=d.decode(u)}let c=qe(u,a.sqlType,a.isBoolean);if(a.path)if(a.path.length===1)l[a.path[0]]=c;else be(l,a.path,c);else l[a.name]=c}for(let a of Object.keys(e)){if(m.has(a))continue;if(a.includes("__")){let u=a.split("__"),c=e[a];if(typeof c==="string"){let d=c.charCodeAt(0);if(d===123||d===91)try{let f=JSON.parse(c);if(typeof f==="object")c=f}catch{}}be(l,u,c)}}}for(let m of t.subTables)if(o&&!o.includes(m.fieldName))l[m.fieldName]=[];else{let a=n.get(m.tableName);if(o||a)l[m.fieldName]=a??[]}return l}function In(e,t,n){for(let r of t.columns){let s=qe(e[r.name],r.sqlType,r.isBoolean);if(r.path)if(r.path.length===1)n[r.path[0]]=s;else be(n,r.path,s);else n[r.name]=s}}function Bn(e,t,n,r){for(let s of t.columns){let o=e[s.name],i=n.get(s.name);if(i)o=i.decode(o);let l=qe(o,s.sqlType,s.isBoolean);if(s.path)if(s.path.length===1)r[s.path[0]]=l;else be(r,s.path,l);else r[s.name]=l}}var Ut={encode(e){if(typeof e!=="string")return e;let t=new TextEncoder().encode(e);return Bun.gzipSync(t.buffer)},decode(e){if(!(e instanceof Uint8Array))return e;return new TextDecoder().decode(Bun.gunzipSync(e.buffer))}};function kn(e){return typeof e==="object"&&e!==null}function ft(e){return e.replace(/'/g,"''")}function $n(e,t){if(!t)return null;let n=e.split(".");if(n.length<2)return null;let r=n[0],s=t.subTables.find((l)=>l.fieldName===r);if(!s)return null;let o=n.slice(1).join("."),i=s.columnByPath.get(o);if(!i&&n.length===2){let l=s.columnByName.get(o);if(l)return{subTableName:s.tableName,subColumn:l.name,ownerPk:t.primaryKey};return null}if(i)return{subTableName:s.tableName,subColumn:i.name,ownerPk:t.primaryKey};return null}function Dn(e,t){let n=e.split(".");if(n.length<2)return null;if(t){let i=t.columnByPath.get(e);if(i)return{sql:`"${i.name}"`};for(let l=n.length-1;l>=1;l--){let m=n.slice(0,l).join("."),a=n.slice(l).join("."),u=t.columnByPath.get(m);if(u&&u.sqlType==="TEXT")return{sql:`JSON_EXTRACT("${u.name.replace(/"/g,'""')}", '$.${ft(a)}')`}}}let r=n[0],s=n.slice(1).join(".");return{sql:`JSON_EXTRACT("${r.replace(/"/g,'""')}", '$.${ft(s)}')`}}function ce(e){if(e===null)return null;if(typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint")return e;if(e instanceof Uint8Array)return e;if(typeof e==="object")return JSON.stringify(e);return String(e)}function K(e){return ce(e)}function De(e,t,n){let r=e.indexOf(".")!==-1?$n(e,n):null;if(r){let a=[],u=[],c=`"${r.subColumn}"`;if("eq"in t)a.push(`${c} = ?`),u.push(K(t.eq));if("ne"in t)a.push(`${c} != ?`),u.push(K(t.ne));if("gt"in t)a.push(`${c} > ?`),u.push(K(t.gt));if("gte"in t)a.push(`${c} >= ?`),u.push(K(t.gte));if("lt"in t)a.push(`${c} < ?`),u.push(K(t.lt));if("lte"in t)a.push(`${c} <= ?`),u.push(K(t.lte));if("like"in t)a.push(`${c} LIKE ?`),u.push(K(t.like));if("between"in t){let[f,p]=t.between;a.push(`${c} BETWEEN ? AND ?`),u.push(K(f),K(p))}if("in"in t){let f=t.in,p=f.map(()=>"?").join(", ");a.push(`${c} IN (${p})`),u.push(...f.map(K))}if("notIn"in t){let f=t.notIn,p=f.map(()=>"?").join(", ");a.push(`${c} NOT IN (${p})`),u.push(...f.map(K))}if("isNull"in t)a.push(`${c} IS NULL`);if("isNotNull"in t)a.push(`${c} IS NOT NULL`);if(a.length>0){let f=a.join(" AND ");return{sql:`EXISTS (SELECT 1 FROM "${r.subTableName}" WHERE "${r.subTableName}"."_owner_id" = "${n.tableName}"."${r.ownerPk}" AND ${f})`,params:u}}return{sql:"1=0",params:[]}}let s=Dn(e,n),o=s?s.sql:`"${e}"`,i=[],l=[];if("eq"in t)i.push(`${o} = ?`),l.push(K(t.eq));if("ne"in t)i.push(`${o} != ?`),l.push(K(t.ne));if("gt"in t)i.push(`${o} > ?`),l.push(K(t.gt));if("gte"in t)i.push(`${o} >= ?`),l.push(K(t.gte));if("lt"in t)i.push(`${o} < ?`),l.push(K(t.lt));if("lte"in t)i.push(`${o} <= ?`),l.push(K(t.lte));if("like"in t)i.push(`${o} LIKE ?`),l.push(K(t.like));if("between"in t){let[a,u]=t.between;i.push(`${o} BETWEEN ? AND ?`),l.push(K(a),K(u))}if("in"in t){let a=t.in,u=a.map(()=>"?").join(", ");i.push(`${o} IN (${u})`),l.push(...a.map(K))}if("notIn"in t){let a=t.notIn,u=a.map(()=>"?").join(", ");i.push(`${o} NOT IN (${u})`),l.push(...a.map(K))}if("isNull"in t)i.push(`${o} IS NULL`);if("isNotNull"in t)i.push(`${o} IS NOT NULL`);if("arraySome"in t){let a=n?.subTables.find((c)=>c.fieldName===e&&c.isScalar);if(Boolean(a&&n?.primaryKey))i.push(`"${n.primaryKey}" IN (SELECT "_owner_id" FROM "${a.tableName}" WHERE "_value" = ?)`);else i.push(`EXISTS (SELECT 1 FROM json_each(${o}) WHERE value = ?)`);l.push(K(t.arraySome))}if("arrayNot"in t){let a=n?.subTables.find((c)=>c.fieldName===e&&c.isScalar);if(Boolean(a&&n?.primaryKey))i.push(`"${n.primaryKey}" NOT IN (SELECT "_owner_id" FROM "${a.tableName}" WHERE "_value" = ?)`);else i.push(`NOT EXISTS (SELECT 1 FROM json_each(${o}) WHERE value = ?)`);l.push(K(t.arrayNot))}if("isEmpty"in t){let a=n?.subTables.find((c)=>c.fieldName===e&&c.isScalar);if(Boolean(a&&n?.primaryKey))if(t.isEmpty)i.push(`"${n.primaryKey}" NOT IN (SELECT DISTINCT "_owner_id" FROM "${a.tableName}")`);else i.push(`"${n.primaryKey}" IN (SELECT DISTINCT "_owner_id" FROM "${a.tableName}")`);else if(t.isEmpty)i.push(`(json_array_length(${o}) = 0 OR ${o} IS NULL)`);else i.push(`json_array_length(${o}) > 0`)}if("fastArrayIsEmpty"in t)if(t.fastArrayIsEmpty)i.push(`(${o} = '[]' OR ${o} IS NULL)`);else i.push(`(${o} != '[]' AND ${o} IS NOT NULL)`);if("fastArraySome"in t){let a=JSON.stringify([t.fastArraySome]),u=a.substring(1,a.length-1);i.push(`(',' || REPLACE(REPLACE(${o}, '[', ''), ']', '') || ',') LIKE ?`),l.push(`%,${u},%`)}if("fastArrayNot"in t){let a=JSON.stringify([t.fastArrayNot]),u=a.substring(1,a.length-1);i.push(`(',' || REPLACE(REPLACE(${o}, '[', ''), ']', '') || ',') NOT LIKE ?`),l.push(`%,${u},%`)}if(i.length===0)v("UNKNOWN_FILTER",`foxdb: unknown filter operator for column "${e}"`,{column:e});return{sql:i.join(" AND "),params:l}}function An(e){if(typeof e!=="object"||e===null)return!1;let t=e;if("AND"in t&&Array.isArray(t.AND))return!0;if("OR"in t&&Array.isArray(t.OR))return!0;if("NOT"in t&&typeof t.NOT==="object"&&t.NOT!==null)return!0;return!1}function Ne(e){if(!e||typeof e!=="object"||Object.keys(e).length===0)return!0;let t=e,n=Object.keys(t);if(n.length===1&&n[0]==="AND"&&Array.isArray(t.AND)&&t.AND.length===0)return!0;if(n.length===1&&n[0]==="OR"&&Array.isArray(t.OR)&&t.OR.some(Ne))return!0;if(n.length===1&&n[0]==="NOT"&&$e(t.NOT))return!0;return!1}function $e(e){if(!e||typeof e!=="object")return!1;let t=e,n=Object.keys(t);if(n.length===1&&n[0]==="OR"&&Array.isArray(t.OR)&&t.OR.length===0)return!0;if(n.length===1&&n[0]==="AND"&&Array.isArray(t.AND)&&t.AND.some($e))return!0;if(n.length===1&&n[0]==="NOT"&&Ne(t.NOT))return!0;return!1}function Ue(e,t,n){let r=[],s=[];if(t)r.push(`"${t}" IS NULL`);if(!e||Object.keys(e).length===0){if(r.length===0)return{sql:"",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}if(An(e)){let i=e;if(i.AND)for(let l of i.AND){if(Ne(l))continue;if($e(l)){if(r.push("1=0"),r.length===1)return{sql:"WHERE 1=0",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}let m=Ue(l,void 0,n);if(m.sql)r.push(`(${m.sql.replace(/^WHERE\s+/,"")})`),s.push(...m.params)}if(i.OR){let l=[],m=[];for(let a of i.OR){if(Ne(a)){l.length=0;break}if($e(a))continue;let u=Ue(a,void 0,n);if(u.sql)l.push(u.sql.replace(/^WHERE\s+/,"")),m.push(...u.params)}if(l.length>0)r.push(`(${l.join(" OR ")})`),s.push(...m);else if(!i.OR.some(Ne))r.push("1=0")}if(i.NOT){if(Ne(i.NOT))r.push("1=0");else if(!$e(i.NOT)){let l=Ue(i.NOT,void 0,n);if(l.sql)r.push(`NOT (${l.sql.replace(/^WHERE\s+/,"")})`),s.push(...l.params)}}}let o=e._raw;if(o&&typeof o==="object"&&"sql"in o){let i=o;r.push(`(${i.sql})`),s.push(...i.params??[])}for(let[i,l]of Object.entries(e)){if(i==="AND"||i==="OR"||i==="NOT"||i==="_raw")continue;if(!kn(l))continue;let m=De(i,l,n);r.push(m.sql),s.push(...m.params)}if(r.length===0)return{sql:"",params:[]};return{sql:`WHERE ${r.join(" AND ")}`,params:s}}function ie(e,t,n){return Ue(e,t,n)}function H(e,t){if(!t)return`"${e}"`;let n=t.columnByPath.get(e);if(n)return`"${n.name}"`;let r=e.split(".");for(let s=r.length-1;s>=1;s--){let o=r.slice(0,s).join("."),i=r.slice(s).join("."),l=t.columnByPath.get(o);if(l&&l.sqlType==="TEXT")return`JSON_EXTRACT("${l.name.replace(/"/g,'""')}", '$.${ft(i)}')`}return`"${e}"`}function Mn(e,t){if(!e)return"";let n=globalThis.Array.isArray(e)?e:[e];if(n.length===0)return"";return`ORDER BY ${n.map((o)=>`${H(o.column,t)} ${o.direction??"ASC"}`).join(", ")}`}function Fn(e,t){let n=[],r=[];if(e!==void 0)n.push("LIMIT ?"),r.push(e);if(t!==void 0)n.push("OFFSET ?"),r.push(t);return{sql:n.join(" "),params:r}}function Qn(e,t){let n=t.columnByName.get(e)||t.columnByPath.get(e);if(n)return[`"${n.name}"`];let r=[];for(let o of t.columns)if(o.path&&o.path[0]===e)r.push(`"${o.name}"`);if(r.length>0)return r;let s=e.split(".");for(let o=s.length-1;o>=1;o--){let i=s.slice(0,o).join("."),l=s.slice(o).join("."),m=t.columnByPath.get(i);if(m&&m.sqlType==="TEXT"){let a=s.join("__");return[`JSON_EXTRACT("${m.name}", '$.${l.replace(/'/g,"''")}') as "${a}"`]}}return[`"${e}"`]}function pt(e,t,n,r){let{sql:s,params:o}=ie(t.where,t.includeDeleted?void 0:n,r),i=Mn(t.orderBy,r),{sql:l,params:m}=Fn(t.limit,t.offset),a=t.select&&r?t.select.flatMap((p)=>Qn(p,r)).join(", "):"*";if(t.distinctOn&&t.distinctOn.length>0){let p=t.distinctOn.map((g)=>H(g,r)).join(", "),h=[`SELECT ${a} FROM "${e}"`,s,`GROUP BY ${p}`,i,l].filter(Boolean).join(" "),y=[`SELECT COUNT(*) as "_count" FROM (SELECT 1 FROM "${e}"`,s,`GROUP BY ${p})`].filter(Boolean).join(" ");return{sql:h,params:[...o,...m],countSql:y,countParams:o}}let c=[`SELECT ${t.distinct?"DISTINCT ":""}${a} FROM "${e}"`,s,i,l].filter(Boolean).join(" "),d;if(t.distinct)d=[`SELECT COUNT(*) as "_count" FROM (SELECT DISTINCT ${a} FROM "${e}"`,s,")"];else d=[`SELECT COUNT(*) as "_count" FROM "${e}"`,s];return{sql:c,params:[...o,...m],countSql:d.filter(Boolean).join(" "),countParams:o}}function fe(e,t,n,r){return pt(e,t,n,r)}function de(e,t,n=999,r,s,o){if(t.length===0)return[];let i=o??Object.keys(t[0]),l=i.length,m=Math.floor(n/l);if(m<=0)v("TOO_MANY_COLUMNS",`foxdb: table "${e}" has too many columns for multi-value insert`);let a=r??i.map((d)=>`"${d}"`).join(", "),u=s??`(${i.map(()=>"?").join(", ")})`,c=[];for(let d=0;d<t.length;d+=m){let f=t.slice(d,d+m),p=f.map(()=>u).join(", "),h=o?f.flatMap((_)=>i.map((g)=>_[g])):f.flatMap((_)=>i.map((g)=>ce(_[g]))),y=`INSERT INTO "${e}" (${a}) VALUES ${p}`;c.push({sql:y,params:h})}return c}function Gt(e,t,n,r){let s=Object.keys(t),o=s.map((u)=>`"${u}"`).join(", "),i=s.map(()=>"?").join(", "),l=n.map((u)=>`"${u}"`).join(", "),m=r.map((u)=>`"${u}" = excluded."${u}"`).join(", ");return{sql:`INSERT INTO "${e}" (${o}) VALUES (${i}) ON CONFLICT (${l}) DO UPDATE SET ${m}`,params:s.map((u)=>ce(t[u]))}}function jt(e,t,n,r,s=999){if(t.length===0)return[];let o=t[0],i=Object.keys(o),l=i.length,m=Math.floor(s/l);if(m<=0)v("TOO_MANY_COLUMNS",`foxdb: table "${e}" has too many columns for multi-value upsert`);let a=n.map((d)=>`"${d}"`).join(", "),u=r.map((d)=>`"${d}" = excluded."${d}"`).join(", "),c=[];for(let d=0;d<t.length;d+=m){let f=t.slice(d,d+m),p=i.map((g)=>`"${g}"`).join(", "),h=f.map(()=>`(${i.map(()=>"?").join(", ")})`).join(", "),y=f.flatMap((g)=>i.map((S)=>ce(g[S]))),_=`INSERT INTO "${e}" (${p}) VALUES ${h} ON CONFLICT (${a}) DO UPDATE SET ${u}`;c.push({sql:_,params:y})}return c}function Kt(e,t,n,r){let s=Object.entries(r).filter(([l])=>l!==t);if(s.length===0)v("NO_COLUMNS_TO_UPDATE","foxdb: no columns to update",{table:e});let o=s.map(([l])=>`"${l}" = ?`).join(", ");return{sql:`UPDATE "${e}" SET ${o} WHERE "${t}" = ?`,params:[...s.map(([,l])=>ce(l)),ce(n)]}}function ht(e,t,n,r,s){let o=Object.entries(t);if(o.length===0)v("NO_COLUMNS_TO_UPDATE","foxdb: no columns to update",{table:e});let i=o.map(([u])=>`"${u}" = ?`).join(", "),{sql:l,params:m}=ie(n,r,s);return{sql:`UPDATE "${e}" SET ${i} ${l}`.trim(),params:[...o.map(([,u])=>ce(u)),...m]}}function Ae(e,t){switch(e.type){case"condition":return De(e.field,e.filter,t);case"raw":return{sql:e.sql,params:e.params};case"and":{let n=e.children.map((s)=>Ae(s,t)),r=n.map((s)=>s.sql).filter(Boolean).join(" AND ");if(!r)return{sql:"",params:[]};return{sql:`(${r})`,params:n.flatMap((s)=>s.params)}}case"or":{let n=e.children.map((s)=>Ae(s,t)),r=n.map((s)=>s.sql).filter(Boolean).join(" OR ");if(!r)return{sql:"",params:[]};return{sql:`(${r})`,params:n.flatMap((s)=>s.params)}}case"not":{let n=Ae(e.child,t);if(!n.sql)return{sql:"",params:[]};return{sql:`NOT (${n.sql})`,params:n.params}}case"nested":{let n=t?.subTables.find((i)=>i.fieldName===e.field);if(!n||!t?.primaryKey)throw Error(`nested() filter on "${e.field}": field is not an object-array sub-table`);let r=e.children.map((i)=>Ae(i,t)).filter((i)=>i.sql);if(r.length===0)return{sql:"",params:[]};let s=r.map((i)=>i.sql).join(" AND "),o=r.flatMap((i)=>i.params);return{sql:`EXISTS (SELECT 1 FROM "${n.tableName}" WHERE "_owner_id" = "${t.tableName}"."${t.primaryKey}" AND ${s})`,params:o}}}}function Z(e,t,n){let r=[];if(t)r.push({sql:`"${t}" IS NULL`,params:[]});for(let s of e){let o=Ae(s,n);if(o.sql)r.push(o)}if(r.length===0)return{sql:"",params:[]};return{sql:`WHERE ${r.map((s)=>s.sql).join(" AND ")}`,params:r.flatMap((s)=>s.params)}}class J{_executor;_asyncExecutor;_nodes=[];_orderByFields=[];_limitValue;_offsetValue;_selectFields;_includeFields;_includeDeletedValue=!1;_distinctValue=!1;_distinctOnFields;constructor(e,t){this._executor=e;this._asyncExecutor=t}_assertExecutor(){if(!this._executor)throw Error("FilterBuilder has no executor - cannot exec() on a logical-group-only builder");return this._executor}_collectState(){return{nodes:this._nodes,orderBy:this._orderByFields,limit:this._limitValue,offset:this._offsetValue,select:this._selectFields,include:this._includeFields,includeDeleted:this._includeDeletedValue,distinct:this._distinctValue,distinctOn:this._distinctOnFields}}equals(e,t){return this._nodes.push({type:"condition",field:e,filter:{eq:t}}),this}notEquals(e,t){return this._nodes.push({type:"condition",field:e,filter:{ne:t}}),this}greaterThan(e,t){return this._nodes.push({type:"condition",field:e,filter:{gt:t}}),this}greaterThanOrEqual(e,t){return this._nodes.push({type:"condition",field:e,filter:{gte:t}}),this}lessThan(e,t){return this._nodes.push({type:"condition",field:e,filter:{lt:t}}),this}lessThanOrEqual(e,t){return this._nodes.push({type:"condition",field:e,filter:{lte:t}}),this}between(e,t,n){return this._nodes.push({type:"condition",field:e,filter:{between:[t,n]}}),this}like(e,t){return this._nodes.push({type:"condition",field:e,filter:{like:t}}),this}contains(e,t){return this._nodes.push({type:"condition",field:e,filter:{like:`%${t}%`}}),this}startsWith(e,t){return this._nodes.push({type:"condition",field:e,filter:{like:`${t}%`}}),this}endsWith(e,t){return this._nodes.push({type:"condition",field:e,filter:{like:`%${t}`}}),this}in(e,t){return this._nodes.push({type:"condition",field:e,filter:{in:t}}),this}notIn(e,t){return this._nodes.push({type:"condition",field:e,filter:{notIn:t}}),this}isNull(e){return this._nodes.push({type:"condition",field:e,filter:{isNull:!0}}),this}isNotNull(e){return this._nodes.push({type:"condition",field:e,filter:{isNotNull:!0}}),this}arraySome(e,t){return this._nodes.push({type:"condition",field:e,filter:{arraySome:t}}),this}arrayNone(e,t){return this._nodes.push({type:"condition",field:e,filter:{arrayNot:t}}),this}isEmpty(e){return this._nodes.push({type:"condition",field:e,filter:{isEmpty:!0}}),this}isNotEmpty(e){return this._nodes.push({type:"condition",field:e,filter:{isEmpty:!1}}),this}arrayEvery(e,t){throw Error("arrayEvery is not yet implemented. Use arrayNone with negation or filter in application code.")}arrayContainsAll(e,t){throw Error("arrayContainsAll is not yet implemented. Use multiple arraySome calls with AND.")}arrayLength(e,t,n){throw Error("arrayLength is not yet implemented.")}nested(e,t){let n=new J;if(t(n),n._nodes.length>0)this._nodes.push({type:"nested",field:e,children:n._nodes});return this}and(e){let t=new J;if(e(t),t._nodes.length>0)this._nodes.push({type:"and",children:t._nodes});return this}or(e){let t=new J;if(e(t),t._nodes.length>0)this._nodes.push({type:"or",children:t._nodes});return this}not(e){let t=new J;if(e(t),t._nodes.length>0)if(t._nodes.length===1){let n=t._nodes[0];if(n)this._nodes.push({type:"not",child:n})}else this._nodes.push({type:"not",child:{type:"and",children:t._nodes}});return this}raw(e,t=[]){return this._nodes.push({type:"raw",sql:e,params:t}),this}orderBy(e,t="ASC"){return this._orderByFields=[{column:e,direction:t}],this}thenBy(e,t="ASC"){return this._orderByFields.push({column:e,direction:t}),this}limit(e){return this._limitValue=e,this}offset(e){return this._offsetValue=e,this}select(...e){return this._selectFields=e,this}include(...e){return this._includeFields=e,this}distinct(){return this._distinctValue=!0,this}distinctOn(...e){return this._distinctOnFields=e,this._distinctValue=!0,this}includeDeleted(){return this._includeDeletedValue=!0,this}exec(){return this._assertExecutor()(this._collectState())}execAsync(){let e=this._collectState();if(this._asyncExecutor)return this._asyncExecutor(e);let t=this._assertExecutor();return Promise.resolve().then(()=>t(e))}execThrowable(){let t=this._assertExecutor()(this._collectState());if(t==null)throw Error("No result found");if(Array.isArray(t)&&t.length===0)throw Error("No results found");return t}}class Me{_executor;_asyncExecutor;_aggregations={};_groupByFields;_havingNodes=[];_whereNodes=[];_includeDeletedValue=!1;constructor(e,t){this._executor=e;this._asyncExecutor=t}sum(e,t){return this._aggregations[t]={op:"sum",field:e},this}count(e,t){return this._aggregations[t]={op:"count",field:e},this}avg(e,t){return this._aggregations[t]={op:"avg",field:e},this}min(e,t){return this._aggregations[t]={op:"min",field:e},this}max(e,t){return this._aggregations[t]={op:"max",field:e},this}groupBy(...e){return this._groupByFields=e,this}having(e){let t=new J;return e(t),this._havingNodes=t._nodes,this}includeDeleted(){return this._includeDeletedValue=!0,this}exec(){return this._executor({aggregations:this._aggregations,groupBy:this._groupByFields,having:this._havingNodes,includeDeleted:this._includeDeletedValue})}execAsync(){let e={aggregations:this._aggregations,groupBy:this._groupByFields,having:this._havingNodes,includeDeleted:this._includeDeletedValue};if(this._asyncExecutor)return this._asyncExecutor(e);return Promise.resolve().then(()=>this._executor(e))}}function ae(e){return`_foxdb_fts_${e}`}function yt(e,t){if(t===!0||typeof t==="object"&&!t.columns){let r=e.columns.filter((s)=>!s.generated&&s.sqlType==="TEXT"&&(s.decode??0)===0).map((s)=>s.name);if(r.length===0)v("FTS_NO_TEXT_COLUMNS",`foxdb: table "${e.tableName}" has fts enabled but no TEXT columns to index`,{table:e.tableName});return r}let n=t.columns.map((r)=>r.name);for(let r of n)if(!e.columnByName.has(r))v("FTS_INVALID_COLUMN",`foxdb: fts column "${r}" not found in table "${e.tableName}"`,{table:e.tableName,column:r});return n}function Vt(e,t,n){let r=ae(e),o=[t.map((i)=>`"${i}"`).join(", "),`content='${e}'`,"content_rowid='rowid'"];if(n.tokenizer)o.push(`tokenize='${n.tokenizer.replace(/'/g,"''")}'`);if(n.prefix&&n.prefix.length>0)o.push(`prefix='${n.prefix.join(" ")}'`);return`CREATE VIRTUAL TABLE IF NOT EXISTS "${r}" USING fts5(${o.join(", ")})`}function gt(e,t,n,r,s="pk"){let o=ae(e),i=["rowid",...n].map((a)=>`"${a}"`).join(", "),l=s==="rowid"?'"rowid"':`"${t}"`,m=Array(r).fill("?").join(", ");return{sql:`INSERT INTO "${o}"(${i}) SELECT ${i} FROM "${e}" WHERE ${l} IN (${m})`,placeholders:r}}function bt(e,t,n,r,s="pk"){let o=ae(e),i=[`"${o}"`,'"rowid"',...n.map((u)=>`"${u}"`)].join(", "),l=["'delete'",'"rowid"',...n.map((u)=>`"${u}"`)].join(", "),m=s==="rowid"?'"rowid"':`"${t}"`,a=Array(r).fill("?").join(", ");return{sql:`INSERT INTO "${o}"(${i}) SELECT ${l} FROM "${e}" WHERE ${m} IN (${a})`,placeholders:r}}function Ht(e){let t=ae(e);return`INSERT INTO "${t}"("${t}") VALUES('delete-all')`}function Jt(e){let t=ae(e);return`INSERT INTO "${t}"("${t}") VALUES('rebuild')`}function Xt(e,t){let n=ae(e),r=["rowid",...t].map((o)=>`"${o}"`).join(", "),s=t.map(()=>"?").join(", ");return`INSERT INTO "${n}"(${r}) VALUES (?, ${s})`}function Yt(e,t){let n=ae(e),r=[`"${n}"`,'"rowid"',...t.map((o)=>`"${o}"`)].join(", "),s=t.map(()=>"?").join(", ");return`INSERT INTO "${n}"(${r}) VALUES ('delete', ?, ${s})`}function Ge(e,t,n,r,s){let o=ae(e),i=new Map(t.map((g,S)=>[g,S])),l=`bm25("${o}")`;if(n.weights&&n.weights.length>0){let g=n.weights.map((S)=>{if(typeof S!=="number"||!Number.isFinite(S))throw Error("fts weight must be a finite number");return String(S)});l=`bm25("${o}", ${g.join(", ")})`}let m=['rowid AS "_rid"',`${l} AS "_score"`],a=[],u=[],c=[];for(let g of n.snippets){let S=i.get(g.field);if(S===void 0)throw Error(`fts snippet: "${g.field}" is not an indexed column`);let E=`_snip_${g.field}`;m.push(`snippet("${o}", ${S}, ?, ?, ?, ?) AS "${E}"`),a.push(g.open,g.close,g.ellipsis,g.tokens),u.push({field:g.field,alias:E})}for(let g of n.highlights){let S=i.get(g.field);if(S===void 0)throw Error(`fts highlight: "${g.field}" is not an indexed column`);let E=`_hl_${g.field}`;m.push(`highlight("${o}", ${S}, ?, ?) AS "${E}"`),a.push(g.open,g.close),c.push({field:g.field,alias:E})}let d=Z(n.nodes,n.includeDeleted?void 0:r,s),f=d.sql?` ${d.sql}`:"",p=[`"${e}".*`,'m."_score"',...u.map((g)=>`m."${g.alias}"`),...c.map((g)=>`m."${g.alias}"`)].join(", "),h=[],y=[];if(n.limit!==void 0)h.push("LIMIT ?"),y.push(n.limit);if(n.offset!==void 0)h.push("OFFSET ?"),y.push(n.offset);return{sql:[`SELECT ${p}`,`FROM (SELECT ${m.join(", ")} FROM "${o}" WHERE "${o}" MATCH ?) m`,`JOIN "${e}" ON "${e}".rowid = m."_rid"`,f,'ORDER BY m."_score"',h.join(" ")].filter(Boolean).join(" "),params:[...a,n.query,...d.params,...y],snippetAliases:u,highlightAliases:c}}class je{_exec;_execAsync;_state;constructor(e,t,n){this._exec=t;this._execAsync=n;this._state={query:e,snippets:[],highlights:[],includeDeleted:!1,nodes:[]}}limit(e){return this._state.limit=e,this}offset(e){return this._state.offset=e,this}includeDeleted(){return this._state.includeDeleted=!0,this}weight(e,t){return(this._state.weightMap??={})[e]=t,this}weights(e){for(let[t,n]of Object.entries(e))if(typeof n==="number")this.weight(t,n);return this}snippet(e,t){return this._state.snippets.push({field:e,open:t?.open??"<b>",close:t?.close??"</b>",ellipsis:t?.ellipsis??"\u2026",tokens:t?.tokens??15}),this}highlight(e,t){return this._state.highlights.push({field:e,open:t?.open??"[",close:t?.close??"]"}),this}where(e){let t=new J;e(t);for(let n of t._nodes)this._state.nodes.push(n);return this}exec(){return this._exec(this._state)}execAsync(){if(this._execAsync)return this._execAsync(this._state);return Promise.resolve().then(()=>this._exec(this._state))}}function Ln(e){return e.replace(/'/g,"''")}function Se(e,t,n){if(!t)return`"${e}"`;if(n&&e.startsWith(n+".")){let o=e.slice(n.length+1),i=t.columnByPath.get(o);if(i)return`"${i.name}"`;return`"${o}"`}let r=t.columnByPath.get(e);if(r)return`"${r.name}"`;let s=e.split(".");for(let o=s.length-1;o>=1;o--){let i=s.slice(0,o).join("."),l=s.slice(o).join("."),m=t.columnByPath.get(i);if(m&&m.sqlType==="TEXT")return`JSON_EXTRACT("${m.name.replace(/"/g,'""')}", '$.${Ln(l)}')`}return`"${e}"`}function Pn(e,t){let n=e.subTables.find((r)=>r.fieldName===t);if(!n)return;return{tableName:n.tableName,columnByPath:n.columnByPath}}function Tt(e,t,n,r){let s=t.subTable&&r?Pn(r,t.subTable):void 0,o=s?.tableName??e,i=s?{...r,columnByPath:s.columnByPath}:r,{sql:l,params:m}=ie(t.where,t.subTable?void 0:t.includeDeleted?void 0:n,i),a=[];if(t.groupBy)for(let h of t.groupBy){let y=Se(h,i,s?.tableName);a.push(`${y} as "${h.replace(/"/g,'""')}"`)}for(let[h,y]of Object.entries(t.aggregations))if("sum"in y&&y.sum)a.push(`SUM(${Se(y.sum,i,s?.tableName)}) as "${h}"`);else if("count"in y&&y.count)a.push(`COUNT(${y.count==="*"?"*":Se(y.count,i,s?.tableName)}) as "${h}"`);else if("avg"in y&&y.avg)a.push(`AVG(${Se(y.avg,i,s?.tableName)}) as "${h}"`);else if("min"in y&&y.min)a.push(`MIN(${Se(y.min,i,s?.tableName)}) as "${h}"`);else if("max"in y&&y.max)a.push(`MAX(${Se(y.max,i,s?.tableName)}) as "${h}"`);let u=t.groupBy?`GROUP BY ${t.groupBy.map((h)=>Se(h,i,s?.tableName)).join(", ")}`:"",c=[],d=[];if(t.having){for(let[h,y]of Object.entries(t.having))if(y&&typeof y==="object"&&!Array.isArray(y)){let _=De(h,y,i);c.push(_.sql),d.push(..._.params)}}let f=c.length>0?`HAVING ${c.join(" AND ")}`:"";return{sql:`SELECT ${a.join(", ")} FROM "${o}" ${l} ${u} ${f}`.trim(),params:[...m,...d]}}function vn(e,t,n,r){if("rowNumber"in t)return`ROW_NUMBER() OVER (${n}) as "${e}"`;if("rank"in t)return`RANK() OVER (${n}) as "${e}"`;if("denseRank"in t)return`DENSE_RANK() OVER (${n}) as "${e}"`;if("lead"in t){let s=H(t.lead,r),o=t.offset??1;return`LEAD(${s}, ${o}) OVER (${n}) as "${e}"`}if("lag"in t){let s=H(t.lag,r),o=t.offset??1;return`LAG(${s}, ${o}) OVER (${n}) as "${e}"`}return`"${e}"`}function St(e,t,n,r){let{sql:s,params:o}=ie(t.where,n,r),i=t.partitionBy&&t.partitionBy.length>0?`PARTITION BY ${t.partitionBy.map((p)=>H(p,r)).join(", ")}`:"",l=t.orderBy?(Array.isArray(t.orderBy)?t.orderBy:[t.orderBy]).map((p)=>`${H(p.column,r)} ${p.direction??"ASC"}`):[],m=l.length>0?`ORDER BY ${l.join(", ")}`:"",a=[i,m].filter(Boolean).join(" "),u=a?a:"ORDER BY (SELECT NULL)",c=[];for(let[p,h]of Object.entries(t.select))c.push(vn(p,h,u,r));let d=t.limit!==void 0?`LIMIT ${t.limit}`:"";return{sql:[`SELECT ${c.join(", ")} FROM "${e}"`,s,d].filter(Boolean).join(" "),params:o}}class Ke{buffer=[];maxBuffer;tableName;db;prepare;onFlush;timer;constructor(e,t,n={},r){if(this.tableName=e,this.db=t,this.maxBuffer=n.maxBuffer??1000,this.prepare=r.prepare,this.onFlush=r.onFlush,n.flushIntervalMs)this.timer=setInterval(()=>this.flush(),n.flushIntervalMs)}insert(e){let t=this.prepare(e);if(this.buffer.push(t),this.buffer.length>=this.maxBuffer)this.flush()}flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0,this.buffer.length);this.db.transaction(()=>{let t=de(this.tableName,e);for(let{sql:n,params:r}of t)this.db.prepare(n).run(...r)}),this.onFlush?.(e)}close(){if(this.timer)clearInterval(this.timer);this.flush()}}var xe={createdAt:"createdAt",updatedAt:"updatedAt"};function _t(e,t){if(e===!1||!e)return{createdAt:null,updatedAt:null};let n=typeof e==="object"&&e.createdAt!==void 0?e.createdAt:xe.createdAt,r=typeof e==="object"&&e.updatedAt!==void 0?e.updatedAt:xe.updatedAt,s=new Set(t.columns.map((o)=>o.name));return{createdAt:s.has(n)?n:null,updatedAt:s.has(r)?r:null}}function pe(e,t){let n=e[t];if(n===null||n===void 0)return null;if(typeof n==="string"||typeof n==="number"||typeof n==="boolean"||typeof n==="bigint")return n;return null}class We{tableName;meta;getSubTableName(e){return this.meta.subTables.find((t)=>t.fieldName===e)?.tableName}validator;db;descriptor;_entityProto=null;_timestampNames;_hasTimestamps;_hasEviction;_materialize;_materializeMany;_events;_executor;_codecs;_insertColsSql;_insertPlaceholders;_readScheduler;_allColumnNames;_onDeleteBehavior;_ftsEnabled;_ftsTableName;_ftsColumns;_ftsColumnSet;_ftsInsertDirectSql;_ftsDeleteDirectSql;setEventBus(e){this._events=e}setMetricsHook(e){this._executor=new Ce({db:this.db,tableName:this.tableName,metricsHook:e})}constructor(e,t,n,r,s="native"){if(this.tableName=e,this.descriptor=t,this._onDeleteBehavior=s,this.db=n,this._readScheduler=r,this._executor=new Ce({db:n,tableName:this.tableName}),this.meta=ke(e,t.schema,Be(t.generated),t.primaryKey.name),t.timestamps){let i=typeof t.timestamps==="object"?t.timestamps:{},l=i.createdAt??xe.createdAt,m=i.updatedAt??xe.updatedAt;for(let a of[l,m])if(!this.meta.columnByName.has(a)){let u={name:a,sqlType:"INTEGER",nullable:!1,optional:!1};this.meta.columns.push(u),this.meta.columnByName.set(a,u),this.meta.insertColumns.push(u),this.meta.insertColumnNames.push(a)}this.meta._hydrateFast=at(this.meta)}this._timestampNames=_t(t.timestamps,this.meta),this._hasTimestamps=!!(this._timestampNames.createdAt||this._timestampNames.updatedAt),this._hasEviction=!!t.eviction,this.validator=qn(t.schema);let o=new Map;if(t.compression?.algorithm==="gzip")for(let i of t.compression.columns)o.set(i.name,Ut);this._codecs=o;for(let i of this.meta.columns)if(this._codecs.has(i.name))i.sqlType="BLOB";if(this._allColumnNames=this.meta.columns.map((i)=>i.name),this._insertColsSql=this.meta.insertColumnNames.map((i)=>`"${i}"`).join(", "),this._insertPlaceholders=this.meta.insertColumnNames.map(()=>"?").join(", "),t.fts)this._ftsEnabled=!0,this._ftsTableName=ae(e),this._ftsColumns=yt(this.meta,t.fts),this._ftsColumnSet=new Set(this._ftsColumns),this._ftsInsertDirectSql=Xt(e,this._ftsColumns),this._ftsDeleteDirectSql=Yt(e,this._ftsColumns);else this._ftsEnabled=!1,this._ftsTableName="",this._ftsColumns=[],this._ftsColumnSet=new Set,this._ftsInsertDirectSql="",this._ftsDeleteDirectSql="";if(this._migrate(),t.eviction){if(n.scheduler.schedule(`evict:${e}`,30000,()=>this._runEviction()),t.eviction.maxRows&&!t.eviction.lruColumn)console.warn(`[foxdb] table "${e}" has eviction.maxRows without lruColumn. Eviction will use PK order, which is not true LRU.`)}}_ensureSelectPk(e){let t=this.descriptor.primaryKey.name;if(e.select&&e.include&&!e.select.includes(t))return{...e,select:[...e.select,t]};return e}_fetchRows(e,t){Q("repo.fetchRows");let n=this.descriptor.primaryKey.name,r=this.descriptor.softDelete?.column;if(!(!e.select&&e.where&&Object.keys(e.where).length>0)){Q("repo.fetchRows.singlePhase");let{sql:p,params:h}=fe(this.tableName,e,r,this.meta),y=this._executor.all(p,h,t);return D(),D({phase:"single",rows:y.length}),y}Q("repo.fetchRows.phase1");let o={...e,select:[n],include:void 0},{sql:i,params:l}=fe(this.tableName,o,r,this.meta),a=this._executor.all(i,l,t).map((p)=>p[n]).filter((p)=>typeof p==="string"||typeof p==="number");if(D({matched:a.length}),a.length===0)return D({phase:"twoPhase",matched:0}),[];if(a.length>500){Q("repo.fetchRows.phase2Batched");let p=[];for(let y=0;y<a.length;y+=500){let _=a.slice(y,y+500),g=_.map(()=>"?").join(", "),S=this._executor.all(`SELECT * FROM "${this.tableName}" WHERE "${n}" IN (${g})`,_,t);for(let E of S)p.push(E)}let h=new Map(a.map((y,_)=>[y,_]));return p.sort((y,_)=>{let g=y[n],S=_[n],E=h.get(g)??0,C=h.get(S)??0;return E-C}),D({rows:p.length}),D({phase:"twoPhase_batched",rows:p.length}),p}Q("repo.fetchRows.phase2");let u=a.map(()=>"?").join(", "),c=`SELECT * FROM "${this.tableName}" WHERE "${n}" IN (${u})`,d=this._executor.all(c,a,t),f=new Map(a.map((p,h)=>[p,h]));return d.sort((p,h)=>{let y=p[n],_=h[n],g=f.get(y)??0,S=f.get(_)??0;return g-S}),D({rows:d.length}),D({phase:"twoPhase",rows:d.length}),d}setMaterializer(e,t){this._materialize=e,this._materializeMany=t;let n=Object.create(null);Object.defineProperty(n,"materialize",{value:function(){return e(this)},writable:!1,enumerable:!1,configurable:!1}),this._entityProto=n}_wrap(e){if(!this._entityProto)return e;let t=Object.create(this._entityProto);return Object.assign(t,e),t}_wrapNoSubs(e){if(!this._entityProto)return e;let t=Object.create(this._entityProto);return Object.assign(t,e),t}_record(e){return e}_assertPk(e){if(e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="bigint")return e;v("INSERT_INVALID_PK",`Primary key must be a scalar, got ${typeof e}`,{table:this.tableName})}_emit(e,t){if(!this._events)return;let n=Date.now(),s={...{table:this.tableName,operation:e,timestamp:n},...t},o=`${this.tableName}.${e}`;if(this._events.has(o))this._events.emit(o,s);let i;if(e.startsWith("find")||e==="count")i="read";else if(e==="delete"||e==="deleteWhere"||e==="flush")i="delete";else i="write";let l=`${this.tableName}.${i}`;if(this._events.has(l))this._events.emit(l,{...s,operation:i})}_migrate(){let e=this.descriptor.primaryKey.name,t=this.descriptor.indexes??[];At(`DDL: ${this.tableName}`),j(`ddl.migrate starting for table ${this.tableName}`,{primaryKey:e,totalDDLStatements:"(computed by buildCreateTableSQL)",userIndexes:t.length,userIndexDetails:t.map((r)=>({columns:r.columns.map((s)=>s.name),unique:r.unique??!1,name:r.name,where:r.where})),subTables:this.meta.subTables.map((r)=>({fieldName:r.fieldName,tableName:r.tableName}))});let n=lt(this.meta,e,this.descriptor.autoIndex??!1,this._onDeleteBehavior);j("ddl.migrate DDL statements count",{count:n.length+t.length}),this.db.transaction(()=>{for(let r of n)Qe(r),this.db.exec(r);for(let r of t){let s=qt(this.tableName,r.columns.map((o)=>o.name),r.unique??!1,r.name,r.where,r.include?.map((o)=>o.name));Qe(s),j(`ddl.userIndex for ${this.tableName}`,{sql:s,columns:r.columns.map((o)=>o.name),unique:r.unique??!1,where:r.where,reason:"user-configured index in table() descriptor"}),this.db.exec(s)}if(this._ftsEnabled){let r=this.descriptor.fts,s=typeof r==="object"?r:{},o=Vt(this.tableName,this._ftsColumns,{tokenizer:s.tokenizer,prefix:s.prefix});if(Qe(o),this.db.exec(o),this.db.prepare(`SELECT count(*) AS c FROM "${this.tableName}"`).get().c>0){if(this.db.prepare(`SELECT count(*) AS c FROM "${this._ftsTableName}"`).get().c===0)this.db.exec(Jt(this.tableName))}}})}_runEviction(){let e=this.descriptor.eviction;if(!e)return;let t=Date.now();if(e.ttlColumn&&e.ttlMs){let n=t-e.ttlMs;this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${e.ttlColumn}" < ?`,[n],"evict")}if(e.maxRows){let n=e.lruColumn??this.descriptor.primaryKey.name,s=this.db.prepare(`SELECT COUNT(*) as c FROM "${this.tableName}"`).get().c;if(s<=e.maxRows)return;let o=s-e.maxRows;this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${this.descriptor.primaryKey.name}" IN (
9
9
  SELECT "${this.descriptor.primaryKey.name}" FROM "${this.tableName}"
10
10
  ORDER BY "${n}" ASC
11
11
  LIMIT ?
12
- )`,[a],"evict")}}parse(e){return this.validator.Parse(e)}check(e){return this.validator.Check(e)}insert(e){return C("repository.insert",{table:this.tableName},()=>{let t=this.parse(e),n=this._record(t),r=Date.now();if(this._timestampNames.createdAt)n[this._timestampNames.createdAt]=r;if(this._timestampNames.updatedAt)n[this._timestampNames.updatedAt]=r;if(this.db.transaction(()=>{let s=U(n,this.meta,this._codecs),{sql:a,params:o}=H(this.tableName,s);this._executor.exec(a,o,"insert");let i=n[this.descriptor.primaryKey.name];for(let l of this.meta.subTables){let u=n[l.fieldName];if(!globalThis.Array.isArray(u)||u.length===0)continue;let m=X(this._assertPk(i),u,l,this._codecs);for(let c of m){let{sql:d,params:p}=H(l.tableName,c);this._executor.exec(d,p,"insert")}}}),this.descriptor.eviction)this._runEviction();return this._emit("insert",{data:n}),this._wrap(n)})}insertMany(e){return C("repository.insertMany",{table:this.tableName},()=>{let n=e.map((s)=>this.parse(s)).map((s)=>{let a=this._record(s),o=Date.now();if(this._timestampNames.createdAt)a[this._timestampNames.createdAt]=o;if(this._timestampNames.updatedAt)a[this._timestampNames.updatedAt]=o;return a}),r=n.map((s)=>U(s,this.meta,this._codecs));if(this.db.transaction(()=>{let s=pe(this.tableName,r);for(let{sql:a,params:o}of s)this._executor.exec(a,o,"insertMany");for(let a of n){let o=a[this.descriptor.primaryKey.name];for(let i of this.meta.subTables){let l=a[i.fieldName];if(!globalThis.Array.isArray(l)||l.length===0)continue;let u=X(this._assertPk(o),l,i,this._codecs);for(let m of u){let{sql:c,params:d}=H(i.tableName,m);this._executor.exec(c,d,"insertMany")}}}}),this.descriptor.eviction)this._runEviction();return this._emit("insertMany",{data:n}),n.map((s)=>this._wrap(s))})}createBatchWriter(e){let t=this;return new fe(this.tableName,this.db,e,{prepare(n){let r=t.parse(n),s=t._record(r),a=Date.now();if(t._timestampNames.createdAt)s[t._timestampNames.createdAt]=a;if(t._timestampNames.updatedAt)s[t._timestampNames.updatedAt]=a;return U(s,t.meta,t._codecs)},onFlush(n){if(t._emit("insertMany",{data:n}),t.descriptor.eviction&&Math.random()<0.2)t._runEviction()}})}upsert(e){return C("repository.upsert",{table:this.tableName},()=>{let t=this.parse(e.data),n=this._record(t),r=Date.now();if(this._timestampNames.createdAt)n[this._timestampNames.createdAt]=r;if(this._timestampNames.updatedAt)n[this._timestampNames.updatedAt]=r;let s=U(n,this.meta,this._codecs),a=globalThis.Array.isArray(e.conflictTarget)?e.conflictTarget:[e.conflictTarget],o=Object.keys(s),i=e.update??o.filter((l)=>!a.includes(l));if(this.descriptor.softDelete&&!i.includes(this.descriptor.softDelete.column))i.push(this.descriptor.softDelete.column),s[this.descriptor.softDelete.column]=null;if(this.db.transaction(()=>{let{sql:l,params:u}=rt(this.tableName,s,a,i);this._executor.exec(l,u,"upsert");let m=n[this.descriptor.primaryKey.name];for(let c of this.meta.subTables){this._executor.exec(`DELETE FROM "${c.tableName}" WHERE "_owner_id" = ?`,[m],"delete");let d=n[c.fieldName];if(!globalThis.Array.isArray(d)||d.length===0)continue;let p=X(this._assertPk(m),d,c,this._codecs);for(let h of p){let{sql:T,params:k}=H(c.tableName,h);this._executor.exec(T,k,"insert")}}}),this.descriptor.eviction)this._runEviction();return this._emit("upsert",{data:t}),this._wrap(this._record(t))})}upsertMany(e){return C("repository.upsertMany",{table:this.tableName},()=>{let n=e.data.map((l)=>this.parse(l)).map((l)=>{let u=this._record(l),m=Date.now();if(this._timestampNames.createdAt)u[this._timestampNames.createdAt]=m;if(this._timestampNames.updatedAt)u[this._timestampNames.updatedAt]=m;return u}),r=n.map((l)=>U(l,this.meta,this._codecs)),s=globalThis.Array.isArray(e.conflictTarget)?e.conflictTarget:[e.conflictTarget],a=Object.keys(r[0]??{}),o=e.update??a.filter((l)=>!s.includes(l));if(this.descriptor.softDelete&&!o.includes(this.descriptor.softDelete.column)){o.push(this.descriptor.softDelete.column);for(let l of r)l[this.descriptor.softDelete.column]=null}let i=0;if(this.db.transaction(()=>{let l=st(this.tableName,r,s,o);for(let{sql:u,params:m}of l){let c=this._executor.exec(u,m,"upsertMany");i+=c.changes}for(let u of n){let m=u[this.descriptor.primaryKey.name];for(let c of this.meta.subTables){this._executor.exec(`DELETE FROM "${c.tableName}" WHERE "_owner_id" = ?`,[m],"delete");let d=u[c.fieldName];if(!globalThis.Array.isArray(d)||d.length===0)continue;let p=X(this._assertPk(m),d,c,this._codecs);for(let h of p){let{sql:T,params:k}=H(c.tableName,h);this._executor.exec(T,k,"insert")}}}}),this.descriptor.eviction)this._runEviction();return this._emit("upsertMany",{data:n,result:i}),i})}findById(e){return C("repository.findById",{table:this.tableName},()=>{let t=this._findByIdRaw(e);return this._emit("findById",{id:e,result:t}),t})}_findByIdRaw(e){let t=this.descriptor.primaryKey.name,n=this.descriptor.softDelete?`SELECT * FROM "${this.tableName}" WHERE "${t}" = ? AND "${this.descriptor.softDelete.column}" IS NULL LIMIT 1`:`SELECT * FROM "${this.tableName}" WHERE "${t}" = ? LIMIT 1`,r=this._executor.get(n,[e],"findById");if(!r)return null;if(this.descriptor.eviction?.lruColumn&&Math.random()<0.1){let s=this.descriptor.eviction.lruColumn,a=this.descriptor.primaryKey.name;Promise.resolve().then(()=>{try{this._executor.exec(`UPDATE "${this.tableName}" SET "${s}" = ? WHERE "${a}" = ?`,[Date.now(),e])}catch{}})}return this._wrap(this._hydrateOne(r))}findMany(e={}){return C("repository.findMany",{table:this.tableName},()=>{let t=e.select&&e.include?this._ensureSelectPk({...e,select:e.select}):e,n=this._fetchRows(t,"findMany");if(this.descriptor.eviction?.lruColumn){let i=this.descriptor.eviction.lruColumn,l=this.descriptor.primaryKey.name,u=[];for(let m of n)if(Math.random()<0.1){let c=m[l];if(typeof c==="string"||typeof c==="number")u.push(c)}if(u.length>0){let m=Date.now(),c=u.map(()=>"?").join(", ");Promise.resolve().then(()=>{try{this._executor.exec(`UPDATE "${this.tableName}" SET "${i}" = ? WHERE "${l}" IN (${c})`,[m,...u])}catch{}})}}let r=this.descriptor.primaryKey.name,s=n.map((i)=>i[r]).filter((i)=>typeof i==="string"||typeof i==="number"),a=new Map;for(let i of this.meta.subTables){if(!(!e.include||e.include.some((d)=>d===i.fieldName)))continue;if(s.length===0)continue;let u=s.map(()=>"?").join(", "),m=this._executor.all(`SELECT * FROM "${i.tableName}" WHERE "_owner_id" IN (${u}) ORDER BY "_index" ASC`,s,"findMany"),c=new Map;for(let d of m){let p=d._owner_id;if(typeof p!=="string"&&typeof p!=="number")continue;if(!c.has(p))c.set(p,[]);c.get(p).push(d)}a.set(i.tableName,c)}let o=n.map((i)=>{let l=new Map;for(let u of this.meta.subTables){if(!(!e.include||e.include.some((h)=>h===u.fieldName)))continue;let c=a.get(u.tableName),d=i[r],p=typeof d==="string"||typeof d==="number"?d:void 0;l.set(u.tableName,p!==void 0?c?.get(p)??[]:[])}return this._wrap(this._hydrateOne(i,e.include,e.select,l))});return this._emit("findMany",{options:e,result:o}),o})}findPage(e={}){return C("repository.findPage",{table:this.tableName},()=>{let t=e.select&&e.include?this._ensureSelectPk(e):e,{countSql:n,countParams:r}=se(this.tableName,t,this.descriptor.softDelete?.column,this.meta),s=this._fetchRows(t,"findPage").map((i)=>this._wrap(this._hydrateOne(i,e.include,e.select))),a=this._executor.get(n,r,"count"),o={data:s,total:(a??{_count:0})._count,limit:e.limit??s.length,offset:e.offset??0};return this._emit("findPage",{options:e,result:o}),o})}findCursorPage(e){return C("repository.findCursorPage",{table:this.tableName},()=>{let t=e.orderBy.direction??"ASC",n=Q(e.orderBy.column,this.meta),r=e.limit??25,{sql:s,params:a}=P(e.where,this.descriptor.softDelete?.column,this.meta),o=`SELECT * FROM "${this.tableName}"`,i=[...a];if(e.cursor){let h=Q(e.cursor.column,this.meta),T=e.cursor.direction==="next"?t==="ASC"?">":"<":t==="ASC"?"<":">",k=`${h} ${T} ?`;if(i.push(e.cursor.value),s)o+=` ${s} AND ${k}`;else o+=` WHERE ${k}`}else if(s)o+=` ${s}`;let l=e.cursor?.direction==="prev"?t==="ASC"?"DESC":"ASC":t;o+=` ORDER BY ${n} ${l} LIMIT ${r}`;let m=this._executor.all(o,i,"findCursorPage").map((h)=>this._wrap(this._hydrateOne(h)));if(e.cursor?.direction==="prev")m.reverse();let c=m.length===r?{column:e.orderBy.column,value:m[m.length-1][e.orderBy.column]}:null,d=m.length>0?{column:e.orderBy.column,value:m[0][e.orderBy.column]}:null,p={data:m,nextCursor:c,prevCursor:d};return this._emit("findCursorPage",{options:e,result:p}),p})}findOne(e={}){return C("repository.findOne",{table:this.tableName},()=>{let t=e.select&&e.include?this._ensureSelectPk(e):e,n=this._fetchRows({...t,limit:1},"findOne"),r=n.length>0?n[0]:null,s=r?this._wrap(this._hydrateOne(r,e.include,e.select)):null;return this._emit("findOne",{options:e,result:s}),s})}*iterate(e={}){Ee("repository.iterate",{table:this.tableName});try{let t=e.select&&e.include?this._ensureSelectPk(e):e.select?this._ensureSelectPk(e):e,{sql:n,params:r}=Be(this.tableName,t,this.descriptor.softDelete?.column,this.meta),s=this._executor.iterate(n,r,"iterate");if(!e.include||e.include.length===0){for(let l of s)yield this._wrap(this._hydrateOne(l,void 0,e.select));return}let a=this.descriptor.primaryKey.name,o=100,i=[];for(let l of s)if(i.push(l),i.length>=o)yield*this._hydrateWindow(i,e.include,e.select),i=[];if(i.length>0)yield*this._hydrateWindow(i,e.include,e.select)}finally{Oe()}}*_hydrateWindow(e,t,n){let r=this.descriptor.primaryKey.name,s=e.map((o)=>o[r]).filter((o)=>typeof o==="string"||typeof o==="number"),a=new Map;for(let o of this.meta.subTables){if(!t.some((c)=>c===o.fieldName))continue;if(s.length===0)continue;let l=s.map(()=>"?").join(", "),u=this._executor.all(`SELECT * FROM "${o.tableName}" WHERE "_owner_id" IN (${l}) ORDER BY "_index" ASC`,s,"iterate"),m=new Map;for(let c of u){let d=c._owner_id;if(typeof d!=="string"&&typeof d!=="number")continue;if(!m.has(d))m.set(d,[]);m.get(d).push(c)}a.set(o.tableName,m)}for(let o of e){let i=new Map;for(let l of this.meta.subTables){if(!t.some((p)=>p===l.fieldName))continue;let m=a.get(l.tableName),c=o[r],d=typeof c==="string"||typeof c==="number"?c:void 0;i.set(l.tableName,d!==void 0?m?.get(d)??[]:[])}yield this._wrap(this._hydrateOne(o,t,n,i))}}findManyMaterialized(e={}){let t=this.findMany(e);if(!this._materializeMany)return t;let n=this._materializeMany(t);if(this._entityProto){for(let r of n)if(Object.getPrototypeOf(r)!==this._entityProto)Object.setPrototypeOf(r,this._entityProto)}return n}count(e){return C("repository.count",{table:this.tableName},()=>{let{sql:t,params:n}=P(e,this.descriptor.softDelete?.column,this.meta),r=`SELECT COUNT(*) as "_count" FROM "${this.tableName}" ${t}`.trim(),a=(this._executor.get(r,n,"count")??{_count:0})._count;return this._emit("count",{where:e,result:a}),a})}aggregate(e){return C("repository.aggregate",{table:this.tableName},()=>{let{sql:t,params:n}=at(this.tableName,e,this.descriptor.softDelete?.column,this.meta),r=this._executor.all(t,n,"aggregate");return this._emit("aggregate",{options:e,result:r}),r})}windowQuery(e){return C("repository.windowQuery",{table:this.tableName},()=>{let{sql:t,params:n}=lt(this.tableName,e,this.descriptor.softDelete?.column,this.meta),r=this._executor.all(t,n,"windowQuery");return this._emit("windowQuery",{options:e,result:r}),r})}update(e){return C("repository.update",{table:this.tableName},()=>{let t=this._record(e),n=this.descriptor.primaryKey.name,r=t[n];if(r===void 0||r===null)O("UPDATE_MISSING_PK",`foxdb: update() requires primary key "${n}"`,{table:this.tableName,column:n});let s=this._findByIdRaw(this._assertPk(r));if(!s)return null;let a=this.parse({...s,...e}),o=this._record(a);if(this._timestampNames.updatedAt)o[this._timestampNames.updatedAt]=Date.now();let i=U(o,this.meta,this._codecs),l=Object.fromEntries(Object.entries(i).filter(([m])=>m!==n));this.db.transaction(()=>{let{sql:m,params:c}=ot(this.tableName,n,this._assertPk(r),l);this._executor.exec(m,c,"update");for(let d of this.meta.subTables){this._executor.exec(`DELETE FROM "${d.tableName}" WHERE "_owner_id" = ?`,[this._assertPk(r)],"delete");let p=o[d.fieldName];if(!globalThis.Array.isArray(p)||p.length===0)continue;let h=X(this._assertPk(r),p,d,this._codecs);for(let T of h){let{sql:k,params:D}=H(d.tableName,T);this._executor.exec(k,D,"insert")}}});let u=this._wrap(o);return this._emit("update",{id:r,data:{...e}}),u})}updateWhere(e){return C("repository.updateWhere",{table:this.tableName},()=>{let t=this._record(e.data),n=tt(t,this.meta,this._codecs);if(this._timestampNames.updatedAt&&this._timestampNames.updatedAt in n===!1)n[this._timestampNames.updatedAt]=Date.now();let r=e.includeDeleted?void 0:this.descriptor.softDelete?.column,{sql:s,params:a}=it(this.tableName,n,e.where,r,this.meta),o=this._executor.exec(s,a,"updateWhere");return this._emit("updateWhere",{where:e.where,result:o.changes}),o.changes})}deleteById(e){return C("repository.deleteById",{table:this.tableName},()=>{let t=this.descriptor.primaryKey.name;if(this.descriptor.softDelete){let r=this.descriptor.softDelete.column;return this._executor.exec(`UPDATE "${this.tableName}" SET "${r}" = ? WHERE "${t}" = ?`,[Date.now(),e],"delete"),this._emit("delete",{id:e}),!0}let n=this.db.transaction(()=>{for(let s of this.meta.subTables)this._executor.exec(`DELETE FROM "${s.tableName}" WHERE "_owner_id" = ?`,[e],"delete");return this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${t}" = ?`,[e],"delete").changes>0});return this._emit("delete",{id:e}),n})}deleteWhere(e){return C("repository.deleteWhere",{table:this.tableName},()=>{let t=this.descriptor.primaryKey.name;if(this.descriptor.softDelete){let a=this.descriptor.softDelete.column,{sql:o,params:i}=P(e,a,this.meta),l=`UPDATE "${this.tableName}" SET "${a}" = ? ${o}`.trim(),u=this._executor.exec(l,[Date.now(),...i],"deleteWhere").changes;return this._emit("deleteWhere",{where:e,result:u}),u}let{sql:n,params:r}=P(e,void 0,this.meta),s=this.db.transaction(()=>{for(let i of this.meta.subTables){let l=`DELETE FROM "${i.tableName}" WHERE "_owner_id" IN (SELECT "${t}" FROM "${this.tableName}" ${n})`.trim();this._executor.exec(l,r,"delete")}let a=`DELETE FROM "${this.tableName}" ${n}`.trim();return this._executor.exec(a,r,"delete").changes});return this._emit("deleteWhere",{where:e,result:s}),s})}flush(){C("repository.flush",{table:this.tableName},()=>{this.db.exec(`DELETE FROM "${this.tableName}"`);for(let e of this.meta.subTables)this.db.exec(`DELETE FROM "${e.tableName}"`);this._emit("flush",{})})}drop(){for(let e of this.meta.subTables)this.db.exec(`DROP TABLE IF EXISTS "${e.tableName}"`);this.db.exec(`DROP TABLE IF EXISTS "${this.tableName}"`)}_hydrateOne(e,t,n,r){let s=this.descriptor.primaryKey.name,a=e[s],o=new Map;for(let i of this.meta.subTables){if(t&&!t.includes(i.fieldName)){o.set(i.tableName,[]);continue}let l={tableName:i.tableName,columns:i.columns,subTables:[],columnByName:i.columnByName,columnByPath:i.columnByPath};if(r&&r.has(i.tableName)){let d=r.get(i.tableName).map((p)=>{let h={};for(let T of Object.keys(p))if(T!=="_id"&&T!=="_owner_id"&&T!=="_index")h[T]=p[T];return de(h,l,new Map,this._codecs)});o.set(i.tableName,d);continue}let m=this._executor.all(`SELECT * FROM "${i.tableName}" WHERE "_owner_id" = ? ORDER BY "_index" ASC`,[a],"read").map((c)=>{let d={};for(let p of Object.keys(c))if(p!=="_id"&&p!=="_owner_id"&&p!=="_index")d[p]=c[p];return de(d,l,new Map,this._codecs)});o.set(i.tableName,m)}return de(e,this.meta,o,this._codecs,n,t)}raw(e,...t){return this._executor.all(e,t,"raw")}}class ct{tables;relations=[];constructor(e){this.tables=e}from(e){let t=e;return{scalar:(n)=>({to:(r,s,a)=>{let o={ownerTable:t,ownerField:n,targetTable:r,targetField:s,kind:"scalar",as:a?.as};return this.relations.push(o),o}}),subTable:(n,r)=>({to:(s,a,o)=>{let i={ownerTable:t,ownerField:`${n}.${r}`,targetTable:s,targetField:a,kind:"subTable",as:o?.as};return this.relations.push(i),i}})}}build(){return this.relations}}function Qe(e){return new ct(e)}import{Type as _}from"typebox";import{Compile as z}from"typebox/schema";var Vt=_.Object({key:_.String(),value:_.String(),encoding:_.String(),updatedAt:_.Integer()}),ut=z(Vt),Gt=_.String(),yt=_.Record(_.String(),_.Unknown()),Jt=_.Array(_.String()),Xt=_.Array(_.Object({ownerTable:_.String(),ownerField:_.String(),targetTable:_.String(),targetField:_.String(),kind:_.Union([_.Literal("scalar"),_.Literal("subTable")]),as:_.Optional(_.String())})),Yt=_.String(),br=z(Gt),dt=z(yt),mt=z(Jt),pt=z(Xt),Tr=z(Yt),je="plain",ft="json",ht="deflate-base64";class ${db;static KEY_SCHEMA_HASH="schemaHash";static KEY_SCHEMA_JSON="schemaJSON";static KEY_TABLES="tables";static KEY_RELATIONS="relations";static KEY_VERSION="version";constructor(e){this.db=e,this.db.exec(`
12
+ )`,[o],"evict")}}parse(e){return this.validator.Parse(e)}check(e){return this.validator.Check(e)}insert(e){return V("repository.insert",{table:this.tableName},()=>{Q("repo.insert.parse");let t=this.parse(e),n=this._record(t);D();let r=Date.now();if(this._hasTimestamps){if(this._timestampNames.createdAt)n[this._timestampNames.createdAt]=r;if(this._timestampNames.updatedAt)n[this._timestampNames.updatedAt]=r}let s=()=>{this._insertRow(n)};if(this.db._txDepth>0)s();else this.db.transaction(s);if(this._hasEviction)this._runEviction();return this._emit("insert",{data:n}),this._wrapNoSubs(n)})}_insertRow(e){Q("repo.insert.flatten");let t=Ee(e,this.meta,this._codecs);D(),Q("repo.insert.execMain");let n=this.meta.insertColumns.length,r=Array(n);for(let m=0;m<n;m++)r[m]=t[this.meta.insertColumns[m].name];let s=this._executor.exec(`INSERT INTO "${this.tableName}" (${this._insertColsSql}) VALUES (${this._insertPlaceholders})`,r,"insert");if(D(),this._ftsEnabled)this._executor.exec(this._ftsInsertDirectSql,this._ftsBindInsert(Number(s.lastInsertRowid),t),"insert");let o=e[this.descriptor.primaryKey.name];Q("repo.insert.subTables");let i=this.meta.subTables,l=i.length;for(let m=0;m<l;m++){let a=i[m],u=e[a.fieldName];if(!globalThis.Array.isArray(u)||u.length===0)continue;let c=Re(this._assertPk(o),u,a,this._codecs);if(c.length>0){let d=de(a.tableName,c,999,a.insertColsSql,a.insertValueGroup,a.insertColumnNames);for(let{sql:f,params:p}of d)this._executor.exec(f,p,"insert")}}D()}insertMany(e){return V("repository.insertMany",{table:this.tableName},()=>{Q("repo.insertMany.parse");let n=e.map((s)=>this.parse(s)).map((s)=>{let o=this._record(s),i=Date.now();if(this._timestampNames.createdAt)o[this._timestampNames.createdAt]=i;if(this._timestampNames.updatedAt)o[this._timestampNames.updatedAt]=i;return o});D(),Q("repo.insertMany.flatten");let r=n.map((s)=>Ee(s,this.meta,this._codecs));if(D(),this.db.transaction(()=>{Q("repo.insertMany.buildInsertMany");let s=de(this.tableName,r);D(),Q("repo.insertMany.execBatches");for(let{sql:o,params:i}of s)this._executor.exec(o,i,"insertMany");D(),Q("repo.insertMany.subTables");for(let o of this.meta.subTables){let i=[];for(let l of n){let m=l[this.descriptor.primaryKey.name],a=l[o.fieldName];if(!globalThis.Array.isArray(a)||a.length===0)continue;let u=Re(this._assertPk(m),a,o,this._codecs);for(let c of u)i.push(c)}if(i.length>0){let l=de(o.tableName,i,999,o.insertColsSql,o.insertValueGroup,o.insertColumnNames);for(let{sql:m,params:a}of l)this._executor.exec(m,a,"insertMany")}}if(D(),this._ftsEnabled){let o=this.descriptor.primaryKey.name;this._ftsIndexByPk(n.map((i)=>this._assertPk(i[o])))}}),this._hasEviction)this._runEviction();return this._emit("insertMany",{data:n}),n.map((s)=>this._wrapNoSubs(s))})}createBatchWriter(e){let t=this;return new Ke(this.tableName,this.db,e,{prepare(n){let r=t.parse(n),s=t._record(r),o=Date.now();if(t._hasTimestamps){if(t._timestampNames.createdAt)s[t._timestampNames.createdAt]=o;if(t._timestampNames.updatedAt)s[t._timestampNames.updatedAt]=o}return Ee(s,t.meta,t._codecs)},onFlush(n){if(t._emit("insertMany",{data:n}),t._hasEviction&&Math.random()<0.2)t._runEviction()}})}upsert(e){return V("repository.upsert",{table:this.tableName},()=>{let t=this.parse(e.data),n=this._record(t),r=Date.now();if(this._hasTimestamps){if(this._timestampNames.createdAt)n[this._timestampNames.createdAt]=r;if(this._timestampNames.updatedAt)n[this._timestampNames.updatedAt]=r}let s=Ee(n,this.meta,this._codecs),o=globalThis.Array.isArray(e.conflictTarget)?e.conflictTarget:[e.conflictTarget],i=Object.keys(s),l=e.update??i.filter((m)=>!o.includes(m));if(this.descriptor.softDelete&&!l.includes(this.descriptor.softDelete.column))l.push(this.descriptor.softDelete.column),s[this.descriptor.softDelete.column]=null;if(this.db.transaction(()=>{if(this._ftsEnabled)this._ftsDeleteByPk([this._assertPk(n[this.descriptor.primaryKey.name])]);let{sql:m,params:a}=Gt(this.tableName,s,o,l);this._executor.exec(m,a,"upsert");let u=n[this.descriptor.primaryKey.name];for(let c of this.meta.subTables){this._executor.exec(`DELETE FROM "${c.tableName}" WHERE "_owner_id" = ?`,[u],"delete");let d=n[c.fieldName];if(!globalThis.Array.isArray(d)||d.length===0)continue;let f=Re(this._assertPk(u),d,c,this._codecs);if(f.length>0){let p=de(c.tableName,f,999,c.insertColsSql,c.insertValueGroup,c.insertColumnNames);for(let{sql:h,params:y}of p)this._executor.exec(h,y,"insert")}}if(this._ftsEnabled)this._ftsIndexByPk([this._assertPk(n[this.descriptor.primaryKey.name])])}),this._hasEviction)this._runEviction();return this._emit("upsert",{data:t}),this._wrapNoSubs(this._record(t))})}upsertMany(e){return V("repository.upsertMany",{table:this.tableName},()=>{let n=e.data.map((a)=>this.parse(a)).map((a)=>{let u=this._record(a),c=Date.now();if(this._timestampNames.createdAt)u[this._timestampNames.createdAt]=c;if(this._timestampNames.updatedAt)u[this._timestampNames.updatedAt]=c;return u}),r=n.map((a)=>Ee(a,this.meta,this._codecs)),s=globalThis.Array.isArray(e.conflictTarget)?e.conflictTarget:[e.conflictTarget],o=Object.keys(r[0]??{}),i=e.update??o.filter((a)=>!s.includes(a));if(this.descriptor.softDelete&&!i.includes(this.descriptor.softDelete.column)){i.push(this.descriptor.softDelete.column);for(let a of r)a[this.descriptor.softDelete.column]=null}let l=0,m=n.map((a)=>this._assertPk(a[this.descriptor.primaryKey.name]));if(this.db.transaction(()=>{if(this._ftsEnabled)this._ftsDeleteByPk(m);let a=jt(this.tableName,r,s,i);for(let{sql:u,params:c}of a){let d=this._executor.exec(u,c,"upsertMany");l+=d.changes}for(let u of this.meta.subTables){let c=[];for(let d of n){let f=this._assertPk(d[this.descriptor.primaryKey.name]);this._executor.exec(`DELETE FROM "${u.tableName}" WHERE "_owner_id" = ?`,[f],"delete");let p=d[u.fieldName];if(!globalThis.Array.isArray(p)||p.length===0)continue;let h=Re(f,p,u,this._codecs);for(let y of h)c.push(y)}if(c.length>0){let d=de(u.tableName,c,999,u.insertColsSql,u.insertValueGroup,u.insertColumnNames);for(let{sql:f,params:p}of d)this._executor.exec(f,p,"upsertMany")}}if(this._ftsEnabled)this._ftsIndexByPk(m)}),this._hasEviction)this._runEviction();return this._emit("upsertMany",{data:n,result:l}),l})}findById(e){return V("repository.findById",{table:this.tableName},()=>{let t=this._findByIdRaw(e);return this._emit("findById",{id:e,result:t}),t})}_findByIdRaw(e){Q("repo.findByIdRaw.query");let t=this.descriptor.primaryKey.name,n=this.descriptor.softDelete?`SELECT * FROM "${this.tableName}" WHERE "${t}" = ? AND "${this.descriptor.softDelete.column}" IS NULL LIMIT 1`:`SELECT * FROM "${this.tableName}" WHERE "${t}" = ? LIMIT 1`,r=this._executor.get(n,[e],"findById");if(D({found:!!r}),!r)return null;return this._wrap(this._hydrateOne(r))}_findFlatRow(e){let t=this.descriptor.primaryKey.name,n=this._ftsEnabled?'*, "rowid" AS "_fts_rowid"':"*",r=this.descriptor.softDelete?`SELECT ${n} FROM "${this.tableName}" WHERE "${t}" = ? AND "${this.descriptor.softDelete.column}" IS NULL LIMIT 1`:`SELECT ${n} FROM "${this.tableName}" WHERE "${t}" = ? LIMIT 1`;return this._executor.get(r,[e],"findById")}O_findMany(e={}){return V("repository.findMany",{table:this.tableName},()=>{Q("repo.findMany.fetchRows");let t={...e.include?this._ensureSelectPk(e):e,limit:e.limit??1000},n=this._fetchRows(t,"findMany");if(D({rows:n.length}),this._hasEviction&&this.descriptor.eviction.lruColumn){let l=this.descriptor.eviction.lruColumn,m=this.descriptor.primaryKey.name,a=[];for(let u of n)if(Math.random()<0.1){let c=u[m];if(typeof c==="string"||typeof c==="number")a.push(c)}if(a.length>0){let u=Date.now(),c=a.map(()=>"?").join(", ");Promise.resolve().then(()=>{try{this._executor.exec(`UPDATE "${this.tableName}" SET "${l}" = ? WHERE "${m}" IN (${c})`,[u,...a])}catch{}})}}Q("repo.findMany.prefetchSubs");let r=this.descriptor.primaryKey.name,s=n.map((l)=>l[r]).filter((l)=>typeof l==="string"||typeof l==="number"),o=new Map;if(e.include&&e.include.length>0)for(let l of this.meta.subTables){if(!e.include.some((d)=>d===l.fieldName))continue;if(s.length===0)continue;Q(`repo.findMany.prefetch.${l.fieldName}`);let a=s.map(()=>"?").join(", "),u=this._executor.all(`SELECT * FROM "${l.tableName}" WHERE "_owner_id" IN (${a}) ORDER BY "_index" ASC`,s,"findMany"),c=new Map;for(let d of u){let f=d._owner_id;if(typeof f!=="string"&&typeof f!=="number")continue;if(!c.has(f))c.set(f,[]);c.get(f).push(d)}o.set(l.tableName,c),D({subRows:u.length})}if(D(),Q("repo.findMany.hydrate"),e.include&&e.include.length>0){let l=n.map((m)=>{let a=new Map;for(let u of this.meta.subTables){if(!e.include.some((h)=>h===u.fieldName))continue;let d=o.get(u.tableName),f=m[r],p=typeof f==="string"||typeof f==="number"?f:void 0;a.set(u.tableName,p!==void 0?d?.get(p)??[]:[])}return this._wrapNoSubs(this._hydrateOne(m,e.include,e.select,a))});return D(),this._emit("findMany",{options:e,result:l}),l}let i=n.map((l)=>this._wrapNoSubs(re(l,this.meta,se,this._codecs,e.select,e.include)));return D(),this._emit("findMany",{options:e,result:i}),i})}O_findPage(e={}){return V("repository.findPage",{table:this.tableName},()=>{let t=e.include?this._ensureSelectPk(e):e,{countSql:n,countParams:r}=fe(this.tableName,t,this.descriptor.softDelete?.column,this.meta),s=this._fetchRows(t,"findPage"),o=t.include,i=this.descriptor.primaryKey.name;if(o&&o.length>0){let u=s.map((h)=>h[i]).filter((h)=>typeof h==="string"||typeof h==="number"),c=new Map;for(let h of this.meta.subTables){if(!o.some((E)=>E===h.fieldName)||u.length===0)continue;let _=u.map(()=>"?").join(", "),g=this._executor.all(`SELECT * FROM "${h.tableName}" WHERE "_owner_id" IN (${_}) ORDER BY "_index" ASC`,u,"findPage"),S=new Map;for(let E of g){let C=E._owner_id;if(typeof C!=="string"&&typeof C!=="number")continue;if(!S.has(C))S.set(C,[]);S.get(C).push(E)}c.set(h.tableName,S)}let d=s.map((h)=>{let y=new Map;for(let _ of this.meta.subTables){if(!o.some((x)=>x===_.fieldName))continue;let S=c.get(_.tableName),E=h[i],C=typeof E==="string"||typeof E==="number"?E:void 0;y.set(_.tableName,C!==void 0?S?.get(C)??[]:[])}return this._wrapNoSubs(this._hydrateOne(h,o,t.select,y))}),f=this._executor.get(n,r,"count"),p={data:d,total:(f??{_count:0})._count,limit:t.limit??d.length,offset:t.offset??0};return this._emit("findPage",{options:e,result:p}),p}let l=s.map((u)=>this._wrapNoSubs(re(u,this.meta,se,this._codecs,t.select))),m=this._executor.get(n,r,"count"),a={data:l,total:(m??{_count:0})._count,limit:t.limit??l.length,offset:t.offset??0};return this._emit("findPage",{options:e,result:a}),a})}O_findCursorPage(e){return V("repository.findCursorPage",{table:this.tableName},()=>{let t=e.orderBy.direction??"ASC",n=H(e.orderBy.column,this.meta),r=e.limit??25,{sql:s,params:o}=ie(e.where,this.descriptor.softDelete?.column,this.meta),i=`SELECT * FROM "${this.tableName}"`,l=[...o];if(e.cursor){let p=H(e.cursor.column,this.meta),h=e.cursor.direction==="next"?t==="ASC"?">":"<":t==="ASC"?"<":">",y=`${p} ${h} ?`;if(l.push(e.cursor.value),s)i+=` ${s} AND ${y}`;else i+=` WHERE ${y}`}else if(s)i+=` ${s}`;let m=e.cursor?.direction==="prev"?t==="ASC"?"DESC":"ASC":t;i+=` ORDER BY ${n} ${m} LIMIT ${r}`;let u=this._executor.all(i,l,"findCursorPage").map((p)=>this._wrapNoSubs(this._hydrateOne(p)));if(e.cursor?.direction==="prev")u.reverse();let c=u.length===r?{column:e.orderBy.column,value:pe(u[u.length-1],e.orderBy.column)}:null,d=u.length>0?{column:e.orderBy.column,value:pe(u[0],e.orderBy.column)}:null,f={data:u,nextCursor:c,prevCursor:d};return this._emit("findCursorPage",{options:e,result:f}),f})}O_findOne(e={}){return V("repository.findOne",{table:this.tableName},()=>{Q("repo.findOne.fetchRow");let t=e.include?this._ensureSelectPk(e):e,n=this._fetchRows({...t,limit:1},"findOne"),r=n.length>0?n[0]:null;if(D({found:!!r}),!r)return this._emit("findOne",{options:e,result:null}),null;if(e.include&&e.include.length>0){let o=this._wrapNoSubs(this._hydrateOne(r,e.include,e.select));return this._emit("findOne",{options:e,result:o}),o}let s=this._wrapNoSubs(re(r,this.meta,se,this._codecs,e.select,e.include));return this._emit("findOne",{options:e,result:s}),s})}*O_iterate(e={}){return yield*V("repository.iterate",{table:this.tableName},()=>this._iterateImpl(e))}*_iterateImpl(e){let t=e.include?this._ensureSelectPk(e):e,{sql:n,params:r}=pt(this.tableName,t,this.descriptor.softDelete?.column,this.meta),s=this._executor.iterate(n,r,"iterate");if(!e.include||e.include.length===0){for(let m of s)yield this._wrapNoSubs(this._hydrateOne(m,void 0,e.select));return}let o=this.descriptor.primaryKey.name,i=100,l=[];for(let m of s)if(l.push(m),l.length>=i)yield*this._hydrateWindow(l,e.include,e.select),l=[];if(l.length>0)yield*this._hydrateWindow(l,e.include,e.select)}*_hydrateWindow(e,t,n){let r=this.descriptor.primaryKey.name,s=e.map((i)=>i[r]).filter((i)=>typeof i==="string"||typeof i==="number"),o=new Map;for(let i of this.meta.subTables){if(!t.some((c)=>c===i.fieldName))continue;if(s.length===0)continue;let m=s.map(()=>"?").join(", "),a=this._executor.all(`SELECT * FROM "${i.tableName}" WHERE "_owner_id" IN (${m}) ORDER BY "_index" ASC`,s,"iterate"),u=new Map;for(let c of a){let d=c._owner_id;if(typeof d!=="string"&&typeof d!=="number")continue;if(!u.has(d))u.set(d,[]);u.get(d).push(c)}o.set(i.tableName,u)}for(let i of e){let l=new Map;for(let m of this.meta.subTables){if(!t.some((f)=>f===m.fieldName))continue;let u=o.get(m.tableName),c=i[r],d=typeof c==="string"||typeof c==="number"?c:void 0;l.set(m.tableName,d!==void 0?u?.get(d)??[]:[])}yield this._wrapNoSubs(this._hydrateOne(i,t,n,l))}}findManyMaterialized(e={}){let t=this.meta.subTables.map((a)=>a.fieldName),n={...e,include:t,limit:e.limit??1000},r=this._fetchRows(n,"findMany"),s=this.descriptor.primaryKey.name,o=r.map((a)=>a[s]).filter((a)=>typeof a==="string"||typeof a==="number"),i=new Map;for(let a of this.meta.subTables){if(o.length===0)continue;let u=o.map(()=>"?").join(", "),c=this._executor.all(`SELECT * FROM "${a.tableName}" WHERE "_owner_id" IN (${u}) ORDER BY "_index" ASC`,o,"findMany"),d=new Map;for(let f of c){let p=f._owner_id;if(typeof p!=="string"&&typeof p!=="number")continue;if(!d.has(p))d.set(p,[]);d.get(p).push(f)}i.set(a.tableName,d)}let l=r.map((a)=>{let u=new Map;for(let c of this.meta.subTables){let d=i.get(c.tableName),f=a[s],p=typeof f==="string"||typeof f==="number"?f:void 0;u.set(c.tableName,p!==void 0?d?.get(p)??[]:[])}return this._wrap(this._hydrateOne(a,t,e.select,u))});if(!this._materializeMany)return l;let m=this._materializeMany(l);if(this._entityProto){for(let a of m)if(Object.getPrototypeOf(a)!==this._entityProto)Object.setPrototypeOf(a,this._entityProto)}return m}O_count(e){return V("repository.count",{table:this.tableName},()=>{Q("repo.count.buildWhere");let{sql:t,params:n}=ie(e,this.descriptor.softDelete?.column,this.meta);D(),Q("repo.count.exec");let r=`SELECT COUNT(*) as "_count" FROM "${this.tableName}" ${t}`.trim(),s=this._executor.get(r,n,"count");D();let o=(s??{_count:0})._count;return this._emit("count",{where:e,result:o}),o})}O_aggregate(e){return V("repository.aggregate",{table:this.tableName},()=>{let{sql:t,params:n}=Tt(this.tableName,e,this.descriptor.softDelete?.column,this.meta),r=this._executor.all(t,n,"aggregate");return this._emit("aggregate",{options:e,result:r}),r})}O_windowQuery(e){return V("repository.windowQuery",{table:this.tableName},()=>{let{sql:t,params:n}=St(this.tableName,e,this.descriptor.softDelete?.column,this.meta),r=this._executor.all(t,n,"windowQuery");return this._emit("windowQuery",{options:e,result:r}),r})}async O_findManyAsync(e={}){if(!this._readScheduler)return Promise.resolve().then(()=>this.O_findMany(e));let t={...e.include?this._ensureSelectPk(e):e,limit:e.limit??1000},{sql:n,params:r}=fe(this.tableName,t,this.descriptor.softDelete?.column,this.meta),s=await this._readScheduler.execWithCols(n,r,this._allColumnNames),o=this.descriptor.primaryKey.name,i=s.map((a)=>a[o]).filter((a)=>typeof a==="string"||typeof a==="number"),l=new Map;if(e.include&&e.include.length>0)for(let a of this.meta.subTables){if(!e.include.some((p)=>p===a.fieldName))continue;if(i.length===0)continue;let c=i.map(()=>"?").join(", "),d=await this._readScheduler.exec(`SELECT * FROM "${a.tableName}" WHERE "_owner_id" IN (${c}) ORDER BY "_index" ASC`,i),f=new Map;for(let p of d){let h=p._owner_id;if(typeof h!=="string"&&typeof h!=="number")continue;if(!f.has(h))f.set(h,[]);f.get(h).push(p)}l.set(a.tableName,f)}let m;if(e.include&&e.include.length>0)m=s.map((a)=>{let u=new Map;for(let c of this.meta.subTables){if(!e.include.some((y)=>y===c.fieldName))continue;let f=l.get(c.tableName),p=a[o],h=typeof p==="string"||typeof p==="number"?p:void 0;u.set(c.tableName,h!==void 0?f?.get(h)??[]:[])}return this._wrapNoSubs(this._hydrateOne(a,e.include,e.select,u))});else m=s.map((a)=>this._wrapNoSubs(re(a,this.meta,se,this._codecs,e.select,e.include)));return this._emit("findMany",{options:e,result:m}),m}async O_findOneAsync(e={}){if(!this._readScheduler)return Promise.resolve().then(()=>this.O_findOne(e));let t=e.select&&e.include?this._ensureSelectPk(e):e,{sql:n,params:r}=fe(this.tableName,{...t,limit:1},this.descriptor.softDelete?.column,this.meta),o=(await this._readScheduler.execWithCols(n,r,this._allColumnNames))[0]??null,i=o?this._wrapNoSubs(this._hydrateOne(o,e.include,e.select)):null;return this._emit("findOne",{options:e,result:i}),i}async O_findPageAsync(e={}){if(!this._readScheduler)return Promise.resolve().then(()=>this.O_findPage(e));let t=e.include?this._ensureSelectPk(e):e,{sql:n,params:r,countSql:s,countParams:o}=fe(this.tableName,t,this.descriptor.softDelete?.column,this.meta),[i,l]=await Promise.all([this._readScheduler.execWithCols(n,r,this._allColumnNames),this._readScheduler.exec(s,o)]),m=t.include,a=this.descriptor.primaryKey.name;if(m&&m.length>0){let f=i.map((g)=>g[a]).filter((g)=>typeof g==="string"||typeof g==="number"),p=new Map;for(let g of this.meta.subTables){if(!m.some((M)=>M===g.fieldName)||f.length===0)continue;let E=f.map(()=>"?").join(", "),C=await this._readScheduler.exec(`SELECT * FROM "${g.tableName}" WHERE "_owner_id" IN (${E}) ORDER BY "_index" ASC`,f),x=new Map;for(let M of C){let q=M._owner_id;if(typeof q!=="string"&&typeof q!=="number")continue;if(!x.has(q))x.set(q,[]);x.get(q).push(M)}p.set(g.tableName,x)}let h=i.map((g)=>{let S=new Map;for(let E of this.meta.subTables){if(!m.some((F)=>F===E.fieldName))continue;let x=p.get(E.tableName),M=g[a],q=typeof M==="string"||typeof M==="number"?M:void 0;S.set(E.tableName,q!==void 0?x?.get(q)??[]:[])}return this._wrapNoSubs(this._hydrateOne(g,m,t.select,S))}),y=(l[0]??{_count:0})._count,_={data:h,total:y,limit:e.limit??h.length,offset:e.offset??0};return this._emit("findPage",{options:e,result:_}),_}let u=i.map((f)=>this._wrapNoSubs(re(f,this.meta,se,this._codecs,t.select))),c=(l[0]??{_count:0})._count,d={data:u,total:c,limit:e.limit??u.length,offset:e.offset??0};return this._emit("findPage",{options:e,result:d}),d}async O_findCursorPageAsync(e){if(!this._readScheduler)return Promise.resolve().then(()=>this.O_findCursorPage(e));let t=e.orderBy.direction??"ASC",n=H(e.orderBy.column,this.meta),r=e.limit??25,{sql:s,params:o}=ie(e.where,this.descriptor.softDelete?.column,this.meta),i=`SELECT * FROM "${this.tableName}"`,l=[...o];if(e.cursor){let p=H(e.cursor.column,this.meta),h=e.cursor.direction==="next"?t==="ASC"?">":"<":t==="ASC"?"<":">",y=`${p} ${h} ?`;if(l.push(e.cursor.value),s)i+=` ${s} AND ${y}`;else i+=` WHERE ${y}`}else if(s)i+=` ${s}`;let m=e.cursor?.direction==="prev"?t==="ASC"?"DESC":"ASC":t;i+=` ORDER BY ${n} ${m} LIMIT ${r}`;let u=(await this._readScheduler.execWithCols(i,l,this._allColumnNames)).map((p)=>this._wrapNoSubs(this._hydrateOne(p)));if(e.cursor?.direction==="prev")u.reverse();let c=u.length===r?{column:e.orderBy.column,value:pe(u[u.length-1],e.orderBy.column)}:null,d=u.length>0?{column:e.orderBy.column,value:pe(u[0],e.orderBy.column)}:null,f={data:u,nextCursor:c,prevCursor:d};return this._emit("findCursorPage",{options:e,result:f}),f}async O_countAsync(e){if(!this._readScheduler)return Promise.resolve().then(()=>this.O_count(e));let{sql:t,params:n}=ie(e,this.descriptor.softDelete?.column,this.meta),r=`SELECT COUNT(*) as "_count" FROM "${this.tableName}" ${t}`.trim(),o=((await this._readScheduler.exec(r,n))[0]??{_count:0})._count;return this._emit("count",{where:e,result:o}),o}async O_aggregateAsync(e){if(!this._readScheduler)return Promise.resolve().then(()=>this.O_aggregate(e));let{sql:t,params:n}=Tt(this.tableName,e,this.descriptor.softDelete?.column,this.meta),r=await this._readScheduler.exec(t,n);return this._emit("aggregate",{options:e,result:r}),r}async O_windowQueryAsync(e){if(!this._readScheduler)return Promise.resolve().then(()=>this.O_windowQuery(e));let{sql:t,params:n}=St(this.tableName,e,this.descriptor.softDelete?.column,this.meta),r=await this._readScheduler.exec(t,n);return this._emit("windowQuery",{options:e,result:r}),r}async findByIdAsync(e){if(!this._readScheduler)return Promise.resolve().then(()=>this.findById(e));let t=this.descriptor.primaryKey.name,n=this.descriptor.softDelete?`SELECT * FROM "${this.tableName}" WHERE "${t}" = ? AND "${this.descriptor.softDelete.column}" IS NULL LIMIT 1`:`SELECT * FROM "${this.tableName}" WHERE "${t}" = ? LIMIT 1`,s=(await this._readScheduler.execWithCols(n,[e],this._allColumnNames))[0]??null,o=s?this._wrap(this._hydrateOne(s)):null;return this._emit("findById",{id:e,result:o}),o}async findManyMaterializedAsync(e={}){if(!this._readScheduler)return Promise.resolve().then(()=>this.findManyMaterialized(e));let t=this.meta.subTables.map((c)=>c.fieldName),n={...e,include:t,limit:e.limit??1000},{sql:r,params:s}=fe(this.tableName,n,this.descriptor.softDelete?.column,this.meta),o=await this._readScheduler.exec(r,s),i=this.descriptor.primaryKey.name,l=o.map((c)=>c[i]).filter((c)=>typeof c==="string"||typeof c==="number"),m=new Map;for(let c of this.meta.subTables){if(l.length===0)continue;let d=l.map(()=>"?").join(", "),f=await this._readScheduler.exec(`SELECT * FROM "${c.tableName}" WHERE "_owner_id" IN (${d}) ORDER BY "_index" ASC`,l),p=new Map;for(let h of f){let y=h._owner_id;if(typeof y!=="string"&&typeof y!=="number")continue;if(!p.has(y))p.set(y,[]);p.get(y).push(h)}m.set(c.tableName,p)}let a=o.map((c)=>{let d=new Map;for(let f of this.meta.subTables){let p=m.get(f.tableName),h=c[i],y=typeof h==="string"||typeof h==="number"?h:void 0;d.set(f.tableName,y!==void 0?p?.get(y)??[]:[])}return this._wrap(this._hydrateOne(c,t,e.select,d))});if(!this._materializeMany)return a;let u=this._materializeMany(a);if(this._entityProto){for(let c of u)if(Object.getPrototypeOf(c)!==this._entityProto)Object.setPrototypeOf(c,this._entityProto)}return u}async rawAsync(e,...t){if(!this._readScheduler)return Promise.resolve().then(()=>this.raw(e,...t));return await this._readScheduler.exec(e,t.map(ce))??[]}findMany(){let e=this.tableName,t=this.meta,n=this._executor,r=this._readScheduler,s=this.descriptor.softDelete?.column,o=this.descriptor.primaryKey.name,i=this.meta.subTables,l=this._wrapNoSubs.bind(this),m=this._hydrateOne.bind(this),a=this._emit.bind(this),u=(d)=>{let{sql:f,params:p}=Z(d.nodes,d.includeDeleted?void 0:s,t),h="*";if(d.include&&d.include.length>0&&d.select&&!d.select.includes(o))d.select=[...d.select,o];if(d.select&&d.select.length>0)h=d.select.map((L)=>`"${L}"`).join(", ");let y=d.distinct?"DISTINCT ":"",_=d.orderBy.length>0?"ORDER BY "+d.orderBy.map((L)=>`${H(L.column,t)} ${L.direction}`).join(", "):"",g=[],S=[],E=d.limit??1000;if(g.push("LIMIT ?"),S.push(E),d.offset!==void 0)g.push("OFFSET ?"),S.push(d.offset);let C=[`SELECT ${y}${h} FROM "${e}"`,f,_,g.join(" ")].filter(Boolean).join(" "),x=n.all(C,[...p,...S],"findMany"),M=x.map((L)=>L[o]).filter((L)=>typeof L==="string"||typeof L==="number"),q=new Map;if(d.include&&d.include.length>0)for(let L of i){if(!d.include.some((T)=>T===L.fieldName))continue;if(M.length===0)continue;let b=M.map(()=>"?").join(", "),w=n.all(`SELECT * FROM "${L.tableName}" WHERE "_owner_id" IN (${b}) ORDER BY "_index" ASC`,M,"findMany"),I=new Map;for(let T of w){let O=T._owner_id;if(typeof O!=="string"&&typeof O!=="number")continue;if(!I.has(O))I.set(O,[]);I.get(O).push(T)}q.set(L.tableName,I)}let F=d.include&&d.include.length>0?x.map((L)=>{let B=new Map;for(let b of i){if(!d.include.some((k)=>k===b.fieldName))continue;let I=q.get(b.tableName),T=L[o],O=typeof T==="string"||typeof T==="number"?T:void 0;B.set(b.tableName,O!==void 0?I?.get(O)??[]:[])}return l(m(L,d.include,d.select,B))}):x.map((L)=>l(re(L,t,se,this._codecs,d.select,d.include)));return a("findMany",{options:{},result:F}),F},c=new J(u);if(r)return new J(u,async(f)=>{let{sql:p,params:h}=Z(f.nodes,f.includeDeleted?void 0:s,t),y="*";if(f.include&&f.include.length>0&&f.select&&!f.select.includes(o))f.select=[...f.select,o];if(f.select&&f.select.length>0)y=f.select.map((B)=>`"${B}"`).join(", ");let _=f.distinct?"DISTINCT ":"",g=f.orderBy.length>0?"ORDER BY "+f.orderBy.map((B)=>`${H(B.column,t)} ${B.direction}`).join(", "):"",S=[],E=[],C=f.limit??1000;if(S.push("LIMIT ?"),E.push(C),f.offset!==void 0)S.push("OFFSET ?"),E.push(f.offset);let x=[`SELECT ${_}${y} FROM "${e}"`,p,g,S.join(" ")].filter(Boolean).join(" "),M=y==="*"?await r.execWithCols(x,[...h,...E],this._allColumnNames):await r.exec(x,[...h,...E]),q=M.map((B)=>B[o]).filter((B)=>typeof B==="string"||typeof B==="number"),F=new Map;if(f.include&&f.include.length>0)for(let B of i){if(!f.include.some((O)=>O===B.fieldName))continue;if(q.length===0)continue;let w=q.map(()=>"?").join(", "),I=await r.exec(`SELECT * FROM "${B.tableName}" WHERE "_owner_id" IN (${w}) ORDER BY "_index" ASC`,q),T=new Map;for(let O of I){let k=O._owner_id;if(typeof k!=="string"&&typeof k!=="number")continue;if(!T.has(k))T.set(k,[]);T.get(k).push(O)}F.set(B.tableName,T)}let L=f.include&&f.include.length>0?M.map((B)=>{let b=new Map;for(let w of i){if(!f.include.some((N)=>N===w.fieldName))continue;let T=F.get(w.tableName),O=B[o],k=typeof O==="string"||typeof O==="number"?O:void 0;b.set(w.tableName,k!==void 0?T?.get(k)??[]:[])}return l(m(B,f.include,f.select,b))}):M.map((B)=>l(re(B,t,se,this._codecs,f.select,f.include)));return a("findMany",{options:{},result:L}),L});return c}findOne(){let e=this.tableName,t=this.meta,n=this._executor,r=this._readScheduler,s=this.descriptor.softDelete?.column,o=this.descriptor.primaryKey.name,i=this._wrapNoSubs.bind(this),l=this._hydrateOne.bind(this),m=this._emit.bind(this),a=(c)=>{let{sql:d,params:f}=Z(c.nodes,c.includeDeleted?void 0:s,t),p="*";if(c.include&&c.include.length>0&&c.select&&!c.select.includes(o))c.select=[...c.select,o];if(c.select&&c.select.length>0)p=c.select.map((S)=>`"${S}"`).join(", ");let h=c.orderBy.length>0?"ORDER BY "+c.orderBy.map((S)=>`${H(S.column,t)} ${S.direction}`).join(", "):"",y=[`SELECT ${p} FROM "${e}"`,d,h,"LIMIT 1"].filter(Boolean).join(" "),_=n.get(y,f,"findOne");if(!_)return m("findOne",{options:{},result:null}),null;let g=i(l(_,c.include,c.select));return m("findOne",{options:{},result:g}),g},u=new J(a);if(r)return new J(a,async(d)=>{let{sql:f,params:p}=Z(d.nodes,d.includeDeleted?void 0:s,t),h="*";if(d.include&&d.include.length>0&&d.select&&!d.select.includes(o))d.select=[...d.select,o];if(d.select&&d.select.length>0)h=d.select.map((C)=>`"${C}"`).join(", ");let y=d.orderBy.length>0?"ORDER BY "+d.orderBy.map((C)=>`${H(C.column,t)} ${C.direction}`).join(", "):"",_=[`SELECT ${h} FROM "${e}"`,f,y,"LIMIT 1"].filter(Boolean).join(" "),S=(h==="*"?await r.execWithCols(_,p,this._allColumnNames):await r.exec(_,p))[0]??null;if(!S)return m("findOne",{options:{},result:null}),null;let E=d.include&&d.include.length>0?i(l(S,d.include,d.select)):i(re(S,t,se,this._codecs,d.select,d.include));return m("findOne",{options:{},result:E}),E});return u}count(){let e=this.tableName,t=this.meta,n=this._executor,r=this._readScheduler,s=this.descriptor.softDelete?.column,o=(l)=>{let{sql:m,params:a}=Z(l.nodes,l.includeDeleted?void 0:s,t),u=`SELECT COUNT(*) as "_count" FROM "${e}" ${m}`.trim();return(n.get(u,a,"count")??{_count:0})._count},i=new J(o);if(r)return new J(o,async(m)=>{let{sql:a,params:u}=Z(m.nodes,m.includeDeleted?void 0:s,t),c=`SELECT COUNT(*) as "_count" FROM "${e}" ${a}`.trim();return((await r.exec(c,u))[0]??null??{_count:0})._count});return i}findPage(){let e=this.tableName,t=this.meta,n=this._executor,r=this._readScheduler,s=this.descriptor.softDelete?.column,o=this.descriptor.primaryKey.name,i=this._wrapNoSubs.bind(this),l=this._hydrateOne.bind(this),m=(u)=>{let{sql:c,params:d}=Z(u.nodes,u.includeDeleted?void 0:s,t),f="*";if(u.include&&u.include.length>0&&u.select&&!u.select.includes(o))u.select=[...u.select,o];if(u.select&&u.select.length>0)f=u.select.map((M)=>`"${M}"`).join(", ");let p=u.orderBy.length>0?"ORDER BY "+u.orderBy.map((M)=>`${H(M.column,t)} ${M.direction}`).join(", "):"",h=[],y=[],_=u.limit??1000;if(h.push("LIMIT ?"),y.push(_),u.offset!==void 0)h.push("OFFSET ?"),y.push(u.offset);let g=[`SELECT ${f} FROM "${e}"`,c,p,h.join(" ")].filter(Boolean).join(" "),S=`SELECT COUNT(*) as "_count" FROM "${e}" ${c}`.trim(),E=n.all(g,[...d,...y],"findPage"),C=n.get(S,d,"count"),x;if(u.include&&u.include.length>0){let M=E.map((F)=>F[o]).filter((F)=>typeof F==="string"||typeof F==="number"),q=new Map;for(let F of this.meta.subTables){if(!u.include.some((I)=>I===F.fieldName)||M.length===0)continue;let B=M.map(()=>"?").join(", "),b=n.all(`SELECT * FROM "${F.tableName}" WHERE "_owner_id" IN (${B}) ORDER BY "_index" ASC`,M,"findPage"),w=new Map;for(let I of b){let T=I._owner_id;if(typeof T!=="string"&&typeof T!=="number")continue;if(!w.has(T))w.set(T,[]);w.get(T).push(I)}q.set(F.tableName,w)}x=E.map((F)=>{let L=new Map;for(let B of this.meta.subTables){if(!u.include.some((O)=>O===B.fieldName))continue;let w=q.get(B.tableName),I=F[o],T=typeof I==="string"||typeof I==="number"?I:void 0;L.set(B.tableName,T!==void 0?w?.get(T)??[]:[])}return i(l(F,u.include,u.select,L))})}else x=E.map((M)=>this._wrapNoSubs(re(M,this.meta,se,this._codecs,u.select,u.include)));return{data:x,total:(C??{_count:0})._count,limit:u.limit??E.length,offset:u.offset??0}},a=new J(m);if(r)return new J(m,async(c)=>{let{sql:d,params:f}=Z(c.nodes,c.includeDeleted?void 0:s,t),p="*";if(c.include&&c.include.length>0&&c.select&&!c.select.includes(o))c.select=[...c.select,o];if(c.select&&c.select.length>0)p=c.select.map((F)=>`"${F}"`).join(", ");let h=c.orderBy.length>0?"ORDER BY "+c.orderBy.map((F)=>`${H(F.column,t)} ${F.direction}`).join(", "):"",y=[],_=[],g=c.limit??1000;if(y.push("LIMIT ?"),_.push(g),c.offset!==void 0)y.push("OFFSET ?"),_.push(c.offset);let S=[`SELECT ${p} FROM "${e}"`,d,h,y.join(" ")].filter(Boolean).join(" "),E=`SELECT COUNT(*) as "_count" FROM "${e}" ${d}`.trim(),[C,x]=await Promise.all([p==="*"?r.execWithCols(S,[...f,..._],this._allColumnNames):r.exec(S,[...f,..._]),r.exec(E,f)]),M=x[0]??null,q;if(c.include&&c.include.length>0){let F=C.map((B)=>B[o]).filter((B)=>typeof B==="string"||typeof B==="number"),L=new Map;for(let B of this.meta.subTables){if(!c.include.some((O)=>O===B.fieldName)||F.length===0)continue;let w=F.map(()=>"?").join(", "),I=await r.exec(`SELECT * FROM "${B.tableName}" WHERE "_owner_id" IN (${w}) ORDER BY "_index" ASC`,F),T=new Map;for(let O of I){let k=O._owner_id;if(typeof k!=="string"&&typeof k!=="number")continue;if(!T.has(k))T.set(k,[]);T.get(k).push(O)}L.set(B.tableName,T)}q=C.map((B)=>{let b=new Map;for(let w of this.meta.subTables){if(!c.include.some((N)=>N===w.fieldName))continue;let T=L.get(w.tableName),O=B[o],k=typeof O==="string"||typeof O==="number"?O:void 0;b.set(w.tableName,k!==void 0?T?.get(k)??[]:[])}return i(l(B,c.include,c.select,b))})}else q=C.map((F)=>this._wrapNoSubs(re(F,this.meta,se,this._codecs,c.select,c.include)));return{data:q,total:(M??{_count:0})._count,limit:c.limit??C.length,offset:c.offset??0}});return a}findCursorPage(){let e=this.tableName,t=this.meta,n=this._executor,r=this._readScheduler,s=this.descriptor.softDelete?.column,o=this._wrapNoSubs.bind(this),i=this._hydrateOne.bind(this),l=(a)=>{let{sql:u,params:c}=Z(a.nodes,a.includeDeleted?void 0:s,t),d=a.limit??25,f=a.orderBy[0]?.direction??"ASC",p=a.orderBy.length>0?H(a.orderBy[0].column,t):`"${this.descriptor.primaryKey.name}"`,h=`SELECT * FROM "${e}"`,y=[...c];if(u)h+=` ${u}`;h+=` ORDER BY ${p} ${f} LIMIT ${d}`;let g=n.all(h,y,"findCursorPage").map((x)=>o(i(x))),S=a.orderBy[0]?.column??this.descriptor.primaryKey.name,E=g.length===d?{column:S,value:pe(g[g.length-1],S)}:null,C=g.length>0?{column:S,value:pe(g[0],S)}:null;return{data:g,nextCursor:E,prevCursor:C}},m=new J(l);if(r)return new J(l,async(u)=>{let{sql:c,params:d}=Z(u.nodes,u.includeDeleted?void 0:s,t),f=u.limit??25,p=u.orderBy[0]?.direction??"ASC",h=u.orderBy.length>0?H(u.orderBy[0].column,t):`"${this.descriptor.primaryKey.name}"`,y=`SELECT * FROM "${e}"`,_=[...d];if(c)y+=` ${c}`;y+=` ORDER BY ${h} ${p} LIMIT ${f}`;let S=(await r.execWithCols(y,_,this._allColumnNames)).map((M)=>o(i(M))),E=u.orderBy[0]?.column??this.descriptor.primaryKey.name,C=S.length===f?{column:E,value:pe(S[S.length-1],E)}:null,x=S.length>0?{column:E,value:pe(S[0],E)}:null;return{data:S,nextCursor:C,prevCursor:x}});return m}aggregate(){let e=this.tableName,t=this.meta,n=this._executor,r=this._readScheduler,s=this.descriptor.softDelete?.column,o=(l)=>{let m=[];for(let[c,{op:d,field:f}]of Object.entries(l.aggregations)){let h=`"${t?t.columnByPath.get(f)?.name??f:f}"`;if(d==="count"&&f==="*")m.push(`COUNT(*) as "${c}"`);else m.push(`${d.toUpperCase()}(${h}) as "${c}"`)}let a=Z([],l.includeDeleted?void 0:s,t),u=`SELECT ${m.join(", ")} FROM "${e}"`;if(a.sql)u+=` ${a.sql}`;if(l.groupBy&&l.groupBy.length>0){let c=l.groupBy.map((d)=>`"${t?t.columnByPath.get(d)?.name??d:d}"`).join(", ");u+=` GROUP BY ${c}`}return n.all(u,a.params,"aggregate")},i=new Me(o);if(r)return new Me(o,async(m)=>{let a=[];for(let[d,{op:f,field:p}]of Object.entries(m.aggregations)){let y=`"${t?t.columnByPath.get(p)?.name??p:p}"`;if(f==="count"&&p==="*")a.push(`COUNT(*) as "${d}"`);else a.push(`${f.toUpperCase()}(${y}) as "${d}"`)}let u=Z([],m.includeDeleted?void 0:s,t),c=`SELECT ${a.join(", ")} FROM "${e}"`;if(u.sql)c+=` ${u.sql}`;if(m.groupBy&&m.groupBy.length>0){let d=m.groupBy.map((f)=>`"${t?t.columnByPath.get(f)?.name??f:f}"`).join(", ");c+=` GROUP BY ${d}`}return r.exec(c,u.params)});return i}search(e){let t=this.meta,n=this.tableName,r=this._ftsColumns,s=this.descriptor.softDelete?.column,o=this._executor,i=this._readScheduler,l=this._codecs,m=this._wrapNoSubs.bind(this),a=this._emit.bind(this),u=(p)=>{if(!p.weightMap)return;p.weights=r.map((h)=>(h in p.weightMap)?p.weightMap[h]:1)},c=(p,h,y)=>p.map((_)=>{let g=m(re(_,t,se,l)),S=_._score;g._score=typeof S==="number"?S:Number(S);let E={};for(let x of h)E[x.field]=String(_[x.alias]??"");let C={};for(let x of y)C[x.field]=String(_[x.alias]??"");return g._snippet=E,g._highlight=C,g});return new je(e,(p)=>{u(p);let{sql:h,params:y,snippetAliases:_,highlightAliases:g}=Ge(n,r,p,s,t),S=o.all(h,y,"search"),E=c(S,_,g);return a("findMany",{options:{fts:p.query},result:E}),E},i?async(p)=>{u(p);let{sql:h,params:y,snippetAliases:_,highlightAliases:g}=Ge(n,r,p,s,t),S=await i.exec(h,y);return c(S,_,g)}:void 0)}searchAsync(e){return this.search(e).execAsync()}update(e){return V("repository.update",{table:this.tableName},()=>{Q("repo.update.extractPk");let t=this._record(e),n=this.descriptor.primaryKey.name,r=t[n];if(r===void 0||r===null)v("UPDATE_MISSING_PK",`foxdb: update() requires primary key "${n}"`,{table:this.tableName,column:n});D(),Q("repo.update.fetchExisting");let s=this._findFlatRow(this._assertPk(r));if(D({found:!!s}),!s)return null;Q("repo.update.mergeAndFlatten");let o=this._hydrateOne(s),i=this.parse({...o,...e}),l=this._record(i);if(this._hasTimestamps&&this._timestampNames.updatedAt)l[this._timestampNames.updatedAt]=Date.now();let m=this._record(e),a=mt(m,this.meta,this._codecs);if(delete a[n],this._hasTimestamps&&this._timestampNames.updatedAt)a[this._timestampNames.updatedAt]=l[this._timestampNames.updatedAt];D();let u=()=>{let d=this._patchTouchesFts(a),f=d?Number(s._fts_rowid):0;if(d)this._executor.exec(this._ftsDeleteDirectSql,this._ftsBindDelete(f,s),"update");Q("repo.update.execMain");let{sql:p,params:h}=Kt(this.tableName,n,this._assertPk(r),a);this._executor.exec(p,h,"update"),D(),Q("repo.update.syncSubs");let y=e;for(let _ of this.meta.subTables){if(!(_.fieldName in y))continue;this._executor.exec(`DELETE FROM "${_.tableName}" WHERE "_owner_id" = ?`,[this._assertPk(r)],"delete");let g=l[_.fieldName];if(!globalThis.Array.isArray(g)||g.length===0)continue;let S=Re(this._assertPk(r),g,_,this._codecs);if(S.length>0){let E=de(_.tableName,S,999,_.insertColsSql,_.insertValueGroup,_.insertColumnNames);for(let{sql:C,params:x}of E)this._executor.exec(C,x,"insert")}}if(D(),d){let _=[f];for(let g of this._ftsColumns)_.push(g in a?a[g]:s[g]);this._executor.exec(this._ftsInsertDirectSql,_,"update")}};if(this.db._txDepth>0)u();else this.db.transaction(u);let c=this._wrapNoSubs(l);return this._emit("update",{id:r,data:{...e}}),c})}updateWhere(e){return V("repository.updateWhere",{table:this.tableName},()=>{let t=this._record(e.data),n=mt(t,this.meta,this._codecs);if(this._hasTimestamps&&this._timestampNames.updatedAt&&this._timestampNames.updatedAt in n===!1)n[this._timestampNames.updatedAt]=Date.now();let r=e.includeDeleted?void 0:this.descriptor.softDelete?.column;if(this._ftsEnabled&&this._patchTouchesFts(n)){let{sql:l,params:m}=ie(e.where,r,this.meta),a=this._executor.all(`SELECT rowid FROM "${this.tableName}" ${l}`.trim(),m,"read").map((u)=>u.rowid);return this.db.transaction(()=>{if(a.length>0)this._ftsDeleteByRowid(a);let{sql:u,params:c}=ht(this.tableName,n,e.where,r,this.meta),d=this._executor.exec(u,c,"updateWhere");if(a.length>0)this._ftsIndexByRowid(a);return this._emit("updateWhere",{where:e.where,result:d.changes}),d.changes})}let{sql:s,params:o}=ht(this.tableName,n,e.where,r,this.meta),i=this._executor.exec(s,o,"updateWhere");return this._emit("updateWhere",{where:e.where,result:i.changes}),i.changes})}deleteById(e){return V("repository.deleteById",{table:this.tableName},()=>{let t=this.descriptor.primaryKey.name;if(this.descriptor.softDelete){let r=this.descriptor.softDelete.column;return this._executor.exec(`UPDATE "${this.tableName}" SET "${r}" = ? WHERE "${t}" = ?`,[Date.now(),e],"delete"),this._emit("delete",{id:e}),!0}if(this._onDeleteBehavior==="foxdb")for(let r of this.meta.subTables)this._executor.exec(`DELETE FROM "${r.tableName}" WHERE "_owner_id" = ?`,[e],"delete");let n=this.db.transaction(()=>{if(this._ftsEnabled)this._ftsDeleteByPk([e]);return this._executor.exec(`DELETE FROM "${this.tableName}" WHERE "${t}" = ?`,[e],"delete").changes>0});return this._emit("delete",{id:e}),n})}deleteWhere(e){return V("repository.deleteWhere",{table:this.tableName},()=>{let t=this.descriptor.primaryKey.name;if(this.descriptor.softDelete){let o=this.descriptor.softDelete.column,{sql:i,params:l}=ie(e,o,this.meta),m=`UPDATE "${this.tableName}" SET "${o}" = ? ${i}`.trim(),a=this._executor.exec(m,[Date.now(),...l],"deleteWhere").changes;return this._emit("deleteWhere",{where:e,result:a}),a}let{sql:n,params:r}=ie(e,void 0,this.meta);if(this._onDeleteBehavior==="foxdb"&&this.meta.subTables.length>0){let o=`SELECT "${t}" FROM "${this.tableName}" ${n}`.trim(),i=this._executor.all(o,r,"read");if(i.length>0){let l=[];for(let m of i){let a=m[t];if(typeof a==="string"||typeof a==="number")l.push(a)}if(l.length>0)for(let m of this.meta.subTables)this._executor.exec(`DELETE FROM "${m.tableName}" WHERE "_owner_id" IN (${l.map(()=>"?").join(", ")})`,l,"delete")}}let s=this.db.transaction(()=>{if(this._ftsEnabled){let m=this._executor.all(`SELECT "${t}" FROM "${this.tableName}" ${n}`.trim(),r,"read").map((a)=>a[t]).filter((a)=>typeof a==="string"||typeof a==="number");this._ftsDeleteByPk(m)}let o=`DELETE FROM "${this.tableName}" ${n}`.trim();return this._executor.exec(o,r,"delete").changes});return this._emit("deleteWhere",{where:e,result:s}),s})}flush(){V("repository.flush",{table:this.tableName},()=>{this.db.exec(`DELETE FROM "${this.tableName}"`);for(let e of this.meta.subTables)this.db.exec(`DELETE FROM "${e.tableName}"`);if(this._ftsEnabled)this.db.exec(Ht(this.tableName));this._emit("flush",{})})}drop(){for(let e of this.meta.subTables)this.db.exec(`DROP TABLE IF EXISTS "${e.tableName}"`);if(this._ftsEnabled)this.db.exec(`DROP TABLE IF EXISTS "${this._ftsTableName}"`);this.db.exec(`DROP TABLE IF EXISTS "${this.tableName}"`)}_ftsIndexByPk(e){if(!this._ftsEnabled||e.length===0)return;let t=this.descriptor.primaryKey.name;for(let n=0;n<e.length;n+=500){let r=e.slice(n,n+500),{sql:s}=gt(this.tableName,t,this._ftsColumns,r.length,"pk");this._executor.exec(s,r,"insert")}}_ftsDeleteByPk(e){if(!this._ftsEnabled||e.length===0)return;let t=this.descriptor.primaryKey.name;for(let n=0;n<e.length;n+=500){let r=e.slice(n,n+500),{sql:s}=bt(this.tableName,t,this._ftsColumns,r.length,"pk");this._executor.exec(s,r,"delete")}}_ftsIndexByRowid(e){if(!this._ftsEnabled||e.length===0)return;for(let t=0;t<e.length;t+=500){let n=e.slice(t,t+500),{sql:r}=gt(this.tableName,"rowid",this._ftsColumns,n.length,"rowid");this._executor.exec(r,n,"insert")}}_ftsDeleteByRowid(e){if(!this._ftsEnabled||e.length===0)return;for(let t=0;t<e.length;t+=500){let n=e.slice(t,t+500),{sql:r}=bt(this.tableName,"rowid",this._ftsColumns,n.length,"rowid");this._executor.exec(r,n,"delete")}}_patchTouchesFts(e){if(!this._ftsEnabled)return!1;for(let t of Object.keys(e))if(this._ftsColumnSet.has(t))return!0;return!1}_ftsBindInsert(e,t){let n=[e];for(let r of this._ftsColumns)n.push(t[r]);return n}_ftsBindDelete(e,t){let n=[e];for(let r of this._ftsColumns)n.push(t[r]);return n}_hydrateOne(e,t,n,r){Q("repo.hydrateOne");let s=this.descriptor.primaryKey.name,o=e[s],i=new Map;for(let m of this.meta.subTables){if(t&&!t.includes(m.fieldName)){i.set(m.tableName,[]);continue}let a={tableName:m.tableName,columns:m.columns,subTables:[],columnByName:m.columnByName,columnByPath:m.columnByPath,insertColumns:m.columns,insertColumnNames:m.columns.map((d)=>d.name)};if(r&&r.has(m.tableName)){let d=r.get(m.tableName);Q("repo.hydrateOne.cleanPrefetched");let f=d.map((p)=>re(p,a,se,this._codecs));D({sub:m.fieldName,rows:d.length}),i.set(m.tableName,f);continue}Q("repo.hydrateOne.fetchSub");let u=this._executor.all(`SELECT * FROM "${m.tableName}" WHERE "_owner_id" = ? ORDER BY "_index" ASC`,[o],"read");D({sub:m.fieldName,rows:u.length});let c=u.map((d)=>re(d,a,se,this._codecs));i.set(m.tableName,c)}let l=re(e,this.meta,i,this._codecs,n,t);return D(),l}raw(e,...t){return this._executor.all(e,t.map(ce),"raw")}}class zt{tables;relations=[];constructor(e){this.tables=e}from(e){let t=e;return{scalar:(n)=>({to:(r,s,o)=>{let i={ownerTable:t,ownerField:n,targetTable:r,targetField:s,kind:"scalar",as:o?.as};return this.relations.push(i),i}}),subTable:(n,r)=>({to:(s,o,i)=>{let l={ownerTable:t,ownerField:`${n}.${r}`,targetTable:s,targetField:o,kind:"subTable",as:i?.as};return this.relations.push(l),l}})}}build(){return this.relations}}function wt(e){return new zt(e)}import{Type as W}from"typebox";import{Compile as Oe}from"typebox/schema";var Un=W.Object({key:W.String(),value:W.String(),encoding:W.String(),updatedAt:W.Integer()}),Zt=Oe(Un),Gn=W.String(),on=W.Record(W.String(),W.Unknown()),jn=W.Array(W.String()),Kn=W.Array(W.Object({ownerTable:W.String(),ownerField:W.String(),targetTable:W.String(),targetField:W.String(),kind:W.Union([W.Literal("scalar"),W.Literal("subTable")]),as:W.Optional(W.String())})),Wn=W.String(),js=Oe(Gn),en=Oe(on),tn=Oe(jn),nn=Oe(Kn),Ks=Oe(Wn),Et="plain",rn="json",sn="deflate-base64";class z{db;static KEY_SCHEMA_HASH="schemaHash";static KEY_SCHEMA_JSON="schemaJSON";static KEY_TABLES="tables";static KEY_RELATIONS="relations";static KEY_VERSION="version";constructor(e){this.db=e,this.db.exec(`
13
13
  CREATE TABLE IF NOT EXISTS _foxdb_meta (
14
14
  key TEXT PRIMARY KEY,
15
15
  value TEXT NOT NULL,
16
16
  encoding TEXT NOT NULL,
17
17
  updatedAt INTEGER NOT NULL
18
18
  )
19
- `)}getRow(e){let n=this.db.prepare("SELECT key, value, encoding, updatedAt FROM _foxdb_meta WHERE key = ?").get(e);if(n==null)return null;try{return ut.Parse(n)}catch{let[,r]=ut.Errors(n);throw Error(`MetaStore: row validation failed for key "${e}". Errors: ${JSON.stringify(r)}`)}}setRow(e,t,n){this.db.prepare(`
19
+ `)}getRow(e){let n=this.db.prepare("SELECT key, value, encoding, updatedAt FROM _foxdb_meta WHERE key = ?").get(e);if(n==null)return null;try{return Zt.Parse(n)}catch{let[,r]=Zt.Errors(n);throw Error(`MetaStore: row validation failed for key "${e}". Errors: ${JSON.stringify(r)}`)}}setRow(e,t,n){this.db.prepare(`
20
20
  INSERT INTO _foxdb_meta (key, value, encoding, updatedAt)
21
21
  VALUES (?, ?, ?, ?)
22
22
  ON CONFLICT (key) DO UPDATE SET
23
23
  value = excluded.value,
24
24
  encoding = excluded.encoding,
25
25
  updatedAt = excluded.updatedAt
26
- `).run(e,t,n,Date.now())}getValidatedJSON(e,t,n){let r=JSON.parse(n);if(!t.Check(r)){let[,s]=t.Errors(r);throw Error(`MetaStore: JSON validation failed for key "${e}". Errors: ${JSON.stringify(s)}`)}return r}validateAndSetJSON(e,t,n){if(!t.Check(n)){let[,r]=t.Errors(n);throw Error(`MetaStore: JSON validation failed for key "${e}" before write. Errors: ${JSON.stringify(r)}`)}this.setRow(e,JSON.stringify(n),ft)}getString(e){let t=this.getRow(e);if(t==null)return null;return t.value}setString(e,t){this.setRow(e,t,je)}getJSON(e){let t=this.getRow(e);if(t==null)return null;try{return JSON.parse(t.value)}catch{return null}}setJSON(e,t){this.setRow(e,JSON.stringify(t),ft)}getCompressed(e){let t=this.getRow(e);if(t==null)return null;if(t.encoding!==ht)return null;let n=Uint8Array.fromBase64(t.value);return Bun.inflateSync(n)}setCompressed(e,t){let n=new Uint8Array(t),s=Bun.deflateSync(n).toBase64();this.setRow(e,s,ht)}delete(e){this.db.prepare("DELETE FROM _foxdb_meta WHERE key = ?").run(e)}getSchemaHash(){let e=this.getRow($.KEY_SCHEMA_HASH);if(e==null)return null;return e.value}setSchemaHash(e){this.setRow($.KEY_SCHEMA_HASH,e,je)}getSchemaJSON(){let e=this.getRow($.KEY_SCHEMA_JSON);if(e==null)return null;return this.getValidatedJSON($.KEY_SCHEMA_JSON,dt,e.value)}setSchemaJSON(e){this.validateAndSetJSON($.KEY_SCHEMA_JSON,dt,e)}getTables(){let e=this.getRow($.KEY_TABLES);if(e==null)return null;return this.getValidatedJSON($.KEY_TABLES,mt,e.value)}setTables(e){this.validateAndSetJSON($.KEY_TABLES,mt,e)}getRelations(){let e=this.getRow($.KEY_RELATIONS);if(e==null)return null;return this.getValidatedJSON($.KEY_RELATIONS,pt,e.value)}setRelations(e){this.validateAndSetJSON($.KEY_RELATIONS,pt,e)}getVersion(){let e=this.getRow($.KEY_VERSION);if(e==null)return null;return e.value}setVersion(e){this.setRow($.KEY_VERSION,e,je)}}function zt(e){return e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_foxdb_%' ORDER BY name").all().map((r)=>r.name)}function Zt(e,t){return e.prepare(`SELECT name, "unique" AS "unique" FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'sqlite_autoindex_%'`).all(t)}function en(e,t){return e.prepare(`PRAGMA index_info("${t}")`).all().map((s)=>s.name).filter((s)=>s!=null)}function gt(e,t){let r=e.prepare(`PRAGMA table_info("${t}")`).all(),s=[];for(let a of Zt(e,t)){let o=en(e,a.name);s.push({name:a.name,unique:a.unique,columns:o})}return{name:t,columns:r,indexes:s}}function qe(e){return zt(e).map((n)=>gt(e,n))}function tn(e){return e.toUpperCase().trim()}function bt(e){let t=tn(e);if(t.includes("INT"))return"INTEGER";if(t.includes("CHAR")||t.includes("CLOB")||t.includes("TEXT"))return"TEXT";if(t.includes("BLOB"))return"BLOB";if(t.includes("REAL")||t.includes("FLOA")||t.includes("DOUB"))return"REAL";return"NUMERIC"}function nn(e){return e==="_id"||e==="_owner_id"||e==="_index"}function rn(e,t){return e.columns.find((n)=>n.name===t)}function sn(e,t,n){let r=[...t].sort().join(",");return e.indexes.find((s)=>{if(Boolean(s.unique)!==n)return!1;return[...s.columns].sort().join(",")===r})}function on(e){return e.columns.filter((t)=>t.pk>0).sort((t,n)=>t.pk-n.pk).map((t)=>t.name)}function Fe(e,t){let n=[],r=[],s=new Map(t.map((o)=>[o.name,o]));for(let o of e){let i=s.get(o.name);if(!i){if(o.name.includes("__"))n.push({kind:"add-subtable",table:o.name.split("__")[0],subTable:{fieldName:o.name.split("__")[1],tableName:o.name,columns:o.columns.map((c)=>({name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional}))}});else n.push({kind:"add-table",table:o.name});continue}for(let c of o.columns){let d=rn(i,c.name);if(!d){if(c.nullable)n.push({kind:"add-column",table:o.name,column:{name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional},hasDefault:!1});else r.push({kind:"add-column",table:o.name,column:{name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional},hasDefault:!1});continue}if(bt(c.sqlType)!==bt(d.type))r.push({kind:"change-type",table:o.name,column:c.name,from:d.type,to:c.sqlType});let p=!c.nullable,h=d.notnull===1;if(p!==h)if(h&&!p)n.push({kind:"change-nullable",table:o.name,column:c.name,to:!0});else r.push({kind:"change-nullable",table:o.name,column:c.name,to:!1})}for(let c of i.columns){if(nn(c.name))continue;if(!o.columns.find((d)=>d.name===c.name))r.push({kind:"drop-column",table:o.name,column:c.name})}let l=on(i),u=o.primaryKey.split(",").map((c)=>c.trim());if(l.length!==u.length||!l.every((c,d)=>c===u[d]))r.push({kind:"change-pk",table:o.name});let m=i.indexes.filter((c)=>!c.name.startsWith("sqlite_")&&!c.name.startsWith("idx_sqlite_"));for(let c of o.indexes)if(!sn(i,c.columns,c.unique??!1))n.push({kind:"add-index",table:o.name,index:{name:c.name??`idx_${o.name}__${c.columns.join("_")}`,unique:c.unique?1:0,columns:c.columns}});for(let c of m)if(!o.indexes.some((p)=>{let h=[...p.columns].sort().join(","),T=[...c.columns].sort().join(",");return h===T&&Boolean(p.unique)===Boolean(c.unique)}))r.push({kind:"drop-index",table:o.name,index:{name:c.name,unique:c.unique,columns:c.columns}})}let a=new Set(e.map((o)=>o.name));for(let o of t)if(!a.has(o.name))r.push({kind:"drop-table",table:o.name});return{safe:n,unsafe:r}}function We(e,t){return e.find((n)=>n.name===t)}function an(e){let t=e.columns.map((n)=>{let r=!n.nullable?" NOT NULL":"",s=n.name===e.primaryKey?" PRIMARY KEY":"";return` "${n.name}" ${n.sqlType}${s}${r}`});return`CREATE TABLE IF NOT EXISTS "${e.name}" (
26
+ `).run(e,t,n,Date.now())}getValidatedJSON(e,t,n){let r=JSON.parse(n);if(!t.Check(r)){let[,s]=t.Errors(r);throw Error(`MetaStore: JSON validation failed for key "${e}". Errors: ${JSON.stringify(s)}`)}return r}validateAndSetJSON(e,t,n){if(!t.Check(n)){let[,r]=t.Errors(n);throw Error(`MetaStore: JSON validation failed for key "${e}" before write. Errors: ${JSON.stringify(r)}`)}this.setRow(e,JSON.stringify(n),rn)}getString(e){let t=this.getRow(e);if(t==null)return null;return t.value}setString(e,t){this.setRow(e,t,Et)}getJSON(e){let t=this.getRow(e);if(t==null)return null;try{return JSON.parse(t.value)}catch{return null}}setJSON(e,t){this.setRow(e,JSON.stringify(t),rn)}getCompressed(e){let t=this.getRow(e);if(t==null)return null;if(t.encoding!==sn)return null;let n=Uint8Array.fromBase64(t.value);return Bun.inflateSync(n)}setCompressed(e,t){let n=new Uint8Array(t),s=Bun.deflateSync(n).toBase64();this.setRow(e,s,sn)}delete(e){this.db.prepare("DELETE FROM _foxdb_meta WHERE key = ?").run(e)}getSchemaHash(){let e=this.getRow(z.KEY_SCHEMA_HASH);if(e==null)return null;return e.value}setSchemaHash(e){this.setRow(z.KEY_SCHEMA_HASH,e,Et)}getSchemaJSON(){let e=this.getRow(z.KEY_SCHEMA_JSON);if(e==null)return null;return this.getValidatedJSON(z.KEY_SCHEMA_JSON,en,e.value)}setSchemaJSON(e){this.validateAndSetJSON(z.KEY_SCHEMA_JSON,en,e)}getTables(){let e=this.getRow(z.KEY_TABLES);if(e==null)return null;return this.getValidatedJSON(z.KEY_TABLES,tn,e.value)}setTables(e){this.validateAndSetJSON(z.KEY_TABLES,tn,e)}getRelations(){let e=this.getRow(z.KEY_RELATIONS);if(e==null)return null;return this.getValidatedJSON(z.KEY_RELATIONS,nn,e.value)}setRelations(e){this.validateAndSetJSON(z.KEY_RELATIONS,nn,e)}getVersion(){let e=this.getRow(z.KEY_VERSION);if(e==null)return null;return e.value}setVersion(e){this.setRow(z.KEY_VERSION,e,Et)}}function Vn(e){return e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_foxdb_%' ORDER BY name").all().map((r)=>r.name)}function Hn(e,t){return e.prepare(`SELECT name, "unique" AS "unique" FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'sqlite_autoindex_%'`).all(t)}function Jn(e,t){return e.prepare(`PRAGMA index_info("${t}")`).all().map((s)=>s.name).filter((s)=>s!=null)}function an(e,t){let r=e.prepare(`PRAGMA table_info("${t}")`).all(),s=[];for(let o of Hn(e,t)){let i=Jn(e,o.name);s.push({name:o.name,unique:o.unique,columns:i})}return{name:t,columns:r,indexes:s}}function Rt(e){return Vn(e).map((n)=>an(e,n))}function Xn(e){return e.toUpperCase().trim()}function ln(e){let t=Xn(e);if(t.includes("INT"))return"INTEGER";if(t.includes("CHAR")||t.includes("CLOB")||t.includes("TEXT"))return"TEXT";if(t.includes("BLOB"))return"BLOB";if(t.includes("REAL")||t.includes("FLOA")||t.includes("DOUB"))return"REAL";return"NUMERIC"}function Yn(e){return e==="_id"||e==="_owner_id"||e==="_index"}function zn(e,t){return e.columns.find((n)=>n.name===t)}function Zn(e,t,n){let r=[...t].sort().join(",");return e.indexes.find((s)=>{if(Boolean(s.unique)!==n)return!1;return[...s.columns].sort().join(",")===r})}function er(e){return e.columns.filter((t)=>t.pk>0).sort((t,n)=>t.pk-n.pk).map((t)=>t.name)}function Nt(e,t){let n=[],r=[],s=new Map(t.map((i)=>[i.name,i]));for(let i of e){let l=s.get(i.name);if(!l){if(i.name.includes("__"))n.push({kind:"add-subtable",table:i.name.split("__")[0],subTable:{fieldName:i.name.split("__")[1],tableName:i.name,columns:i.columns.map((c)=>({name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional}))}});else n.push({kind:"add-table",table:i.name});continue}for(let c of i.columns){let d=zn(l,c.name);if(!d){if(c.nullable)n.push({kind:"add-column",table:i.name,column:{name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional},hasDefault:!1});else r.push({kind:"add-column",table:i.name,column:{name:c.name,sqlType:c.sqlType,nullable:c.nullable,optional:c.optional},hasDefault:!1});continue}if(ln(c.sqlType)!==ln(d.type))r.push({kind:"change-type",table:i.name,column:c.name,from:d.type,to:c.sqlType});let f=!c.nullable,p=d.notnull===1;if(f!==p)if(p&&!f)n.push({kind:"change-nullable",table:i.name,column:c.name,to:!0});else r.push({kind:"change-nullable",table:i.name,column:c.name,to:!1})}for(let c of l.columns){if(Yn(c.name))continue;if(!i.columns.find((d)=>d.name===c.name))r.push({kind:"drop-column",table:i.name,column:c.name})}let m=er(l),a=i.primaryKey.split(",").map((c)=>c.trim());if(m.length!==a.length||!m.every((c,d)=>c===a[d]))r.push({kind:"change-pk",table:i.name});let u=l.indexes.filter((c)=>!c.name.startsWith("sqlite_")&&!c.name.startsWith("idx_sqlite_"));for(let c of i.indexes)if(!Zn(l,c.columns,c.unique??!1))n.push({kind:"add-index",table:i.name,index:{name:c.name??`idx_${i.name}__${c.columns.join("_")}`,unique:c.unique?1:0,columns:c.columns}});for(let c of u)if(!i.indexes.some((f)=>{let p=[...f.columns].sort().join(","),h=[...c.columns].sort().join(",");return p===h&&Boolean(f.unique)===Boolean(c.unique)}))r.push({kind:"drop-index",table:i.name,index:{name:c.name,unique:c.unique,columns:c.columns}})}let o=new Set(e.map((i)=>i.name));for(let i of t)if(!o.has(i.name))r.push({kind:"drop-table",table:i.name});return{safe:n,unsafe:r}}function Ot(e,t){return e.find((n)=>n.name===t)}function tr(e){let t=e.columns.map((n)=>{let r=!n.nullable?" NOT NULL":"",s=n.name===e.primaryKey?" PRIMARY KEY":"";return` "${n.name}" ${n.sqlType}${s}${r}`});return`CREATE TABLE IF NOT EXISTS "${e.name}" (
27
27
  ${t.join(`,
28
28
  `)}
29
- )`}function ln(e,t){let n=!t.nullable?" NOT NULL":"";return`ALTER TABLE "${e}" ADD COLUMN "${t.name}" ${t.sqlType}${n}`}function cn(e,t){let n=t.unique?"UNIQUE ":"",r=t.columns.map((s)=>`"${s}"`).join(", ");return`CREATE ${n}INDEX IF NOT EXISTS "${t.name}" ON "${e}" (${r})`}function un(e,t){let n=`${t.name}_foxdb_temp`,r=t.columns.map((s)=>{let a=!s.nullable?" NOT NULL":"",o=s.name===t.primaryKey?" PRIMARY KEY":"";return` "${s.name}" ${s.sqlType}${o}${a}`});e.transaction(()=>{e.exec(`CREATE TABLE "${n}" (
29
+ )`}function nr(e,t){let n=!t.nullable?" NOT NULL":"";return`ALTER TABLE "${e}" ADD COLUMN "${t.name}" ${t.sqlType}${n}`}function rr(e,t){let n=t.unique?"UNIQUE ":"",r=t.columns.map((s)=>`"${s}"`).join(", ");return`CREATE ${n}INDEX IF NOT EXISTS "${t.name}" ON "${e}" (${r})`}function sr(e,t){let n=`${t.name}_foxdb_temp`,r=t.columns.map((s)=>{let o=!s.nullable?" NOT NULL":"",i=s.name===t.primaryKey?" PRIMARY KEY":"";return` "${s.name}" ${s.sqlType}${i}${o}`});e.transaction(()=>{e.exec(`CREATE TABLE "${n}" (
30
30
  ${r.join(`,
31
31
  `)}
32
- )`);let s=t.columns.map((a)=>`"${a.name}"`).join(", ");e.exec(`INSERT INTO "${n}" (${s}) SELECT ${s} FROM "${t.name}"`),e.exec(`DROP TABLE "${t.name}"`),e.exec(`ALTER TABLE "${n}" RENAME TO "${t.name}"`)})}function dn(e,t,n){let{table:r,subTable:s}=n,a=We(t,r);if(!a)throw Error(`foxdb sync: cannot find owner table "${r}" for sub-table "${s.tableName}"`);let l=[' "_id" INTEGER PRIMARY KEY AUTOINCREMENT',` "_owner_id" ${a.columns.find((u)=>u.name===a.primaryKey)?.sqlType??"TEXT"} NOT NULL`,' "_index" INTEGER NOT NULL',...s.columns.map((u)=>{let m=!u.nullable?" NOT NULL":"";return` "${u.name}" ${u.sqlType}${m}`})];e.transaction(()=>{e.exec(`CREATE TABLE IF NOT EXISTS "${s.tableName}" (
33
- ${l.join(`,
32
+ )`);let s=t.columns.map((o)=>`"${o.name}"`).join(", ");e.exec(`INSERT INTO "${n}" (${s}) SELECT ${s} FROM "${t.name}"`),e.exec(`DROP TABLE "${t.name}"`),e.exec(`ALTER TABLE "${n}" RENAME TO "${t.name}"`)})}function ir(e,t,n){let{table:r,subTable:s}=n,o=Ot(t,r);if(!o)throw Error(`foxdb sync: cannot find owner table "${r}" for sub-table "${s.tableName}"`);let m=[' "_id" INTEGER PRIMARY KEY AUTOINCREMENT',` "_owner_id" ${o.columns.find((a)=>a.name===o.primaryKey)?.sqlType??"TEXT"} NOT NULL`,' "_index" INTEGER NOT NULL',...s.columns.map((a)=>{let u=!a.nullable?" NOT NULL":"";return` "${a.name}" ${a.sqlType}${u}`})];e.transaction(()=>{e.exec(`CREATE TABLE IF NOT EXISTS "${s.tableName}" (
33
+ ${m.join(`,
34
34
  `)}
35
- )`),e.exec(`CREATE INDEX IF NOT EXISTS "idx_${s.tableName}__owner" ON "${s.tableName}" ("_owner_id")`)})}function Ke(e,t,n){for(let r of e.safe)switch(r.kind){case"add-table":{let s=We(n,r.table);if(!s)throw Error(`foxdb sync: missing desired schema for table "${r.table}"`);t.exec(an(s));break}case"add-subtable":{dn(t,n,r);break}case"add-column":{if(!r.column.nullable)throw Error(`foxdb sync: cannot auto-apply required column "${r.column.name}" without default. Use a migration.`);t.exec(ln(r.table,r.column));break}case"add-index":{t.exec(cn(r.table,r.index));break}case"change-nullable":{if(!r.to)throw Error(`foxdb sync: cannot auto-apply nullable \u2192 NOT NULL change on "${r.table}.${r.column}". Use a migration.`);let s=We(n,r.table);if(!s)throw Error(`foxdb sync: missing desired schema for table "${r.table}"`);un(t,s);break}case"drop-index":{t.exec(`DROP INDEX IF EXISTS "${r.index.name}"`);break}}}function mn(e,t,n){if(e.unsafe.length===0&&e.safe.length===0)return!0;if(n==="ignore")return!0;if(n==="warn"){if(e.unsafe.length>0){console.warn(`[foxdb] ${e.unsafe.length} unsafe schema change(s) detected:`);for(let r of e.unsafe)console.warn(` - ${r.kind}: ${JSON.stringify(r)}`)}return!0}if(n==="error"){if(e.unsafe.length>0||e.safe.length>0)throw Error(`foxdb sync: schema drift detected. Safe=${e.safe.length}, Unsafe=${e.unsafe.length}`);return!0}if(n==="auto")return!0;if(typeof n==="function")return n(e,t)!==!1;return!0}function Ue(e,t,n,r){if(e.safe.length===0&&e.unsafe.length===0)return;if(!mn(e,t,n))return;if(n==="auto"){if(Ke(e,t,r),e.unsafe.length>0)throw Error(`foxdb sync: ${e.unsafe.length} unsafe change(s) cannot be auto-applied. Use migrations.
36
- `+e.unsafe.map((a)=>` - ${a.kind}: ${JSON.stringify(a)}`).join(`
37
- `));return}if(n==="ignore")return;if(n==="warn"||n==="error"){if(e.unsafe.length===0)Ke(e,t,r);return}if(typeof n==="function"){if(e.unsafe.length===0)Ke(e,t,r);return}}import{readdirSync as pn,existsSync as fn}from"fs";import{join as hn,resolve as yn}from"path";function gn(e){e.exec(`
35
+ )`),e.exec(`CREATE INDEX IF NOT EXISTS "idx_${s.tableName}__owner" ON "${s.tableName}" ("_owner_id")`)})}function xt(e,t,n){for(let r of e.safe)switch(r.kind){case"add-table":{let s=Ot(n,r.table);if(!s)throw Error(`foxdb sync: missing desired schema for table "${r.table}"`);t.exec(tr(s));break}case"add-subtable":{ir(t,n,r);break}case"add-column":{if(!r.column.nullable)throw Error(`foxdb sync: cannot auto-apply required column "${r.column.name}" without default. Use a migration.`);t.exec(nr(r.table,r.column));break}case"add-index":{t.exec(rr(r.table,r.index));break}case"change-nullable":{if(!r.to)throw Error(`foxdb sync: cannot auto-apply nullable \u2192 NOT NULL change on "${r.table}.${r.column}". Use a migration.`);let s=Ot(n,r.table);if(!s)throw Error(`foxdb sync: missing desired schema for table "${r.table}"`);sr(t,s);break}case"drop-index":{t.exec(`DROP INDEX IF EXISTS "${r.index.name}"`);break}}}function or(e,t,n){if(e.unsafe.length===0&&e.safe.length===0)return!0;if(n==="ignore")return!0;if(n==="warn"){if(e.unsafe.length>0){console.warn(`[foxdb] ${e.unsafe.length} unsafe schema change(s) detected:`);for(let r of e.unsafe)console.warn(` - ${r.kind}: ${JSON.stringify(r)}`)}return!0}if(n==="error"){if(e.unsafe.length>0||e.safe.length>0)throw Error(`foxdb sync: schema drift detected. Safe=${e.safe.length}, Unsafe=${e.unsafe.length}`);return!0}if(n==="auto")return!0;if(typeof n==="function")return n(e,t)!==!1;return!0}function Ct(e,t,n,r){if(e.safe.length===0&&e.unsafe.length===0)return;if(!or(e,t,n))return;if(n==="auto"){if(xt(e,t,r),e.unsafe.length>0)throw Error(`foxdb sync: ${e.unsafe.length} unsafe change(s) cannot be auto-applied. Use migrations.
36
+ `+e.unsafe.map((o)=>` - ${o.kind}: ${JSON.stringify(o)}`).join(`
37
+ `));return}if(n==="ignore")return;if(n==="warn"||n==="error"){if(e.unsafe.length===0)xt(e,t,r);return}if(typeof n==="function"){if(e.unsafe.length===0)xt(e,t,r);return}}import{readdirSync as ar,existsSync as lr}from"fs";import{join as cr,resolve as ur}from"path";function dr(e){e.exec(`
38
38
  CREATE TABLE IF NOT EXISTS "_foxdb_migrations" (
39
39
  "name" TEXT PRIMARY KEY,
40
40
  "appliedAt" INTEGER NOT NULL
41
41
  )
42
- `)}function bn(e){let n=e.prepare('SELECT "name" FROM "_foxdb_migrations"').all();return new Set(n.map((r)=>r.name))}function Tn(e,t){e.prepare('INSERT INTO "_foxdb_migrations" ("name", "appliedAt") VALUES (?, ?)').run(t,Date.now())}function Sn(e){if(!fn(e))return[];return pn(e,{withFileTypes:!0}).filter((r)=>r.isFile()&&r.name.endsWith(".ts")).map((r)=>({name:r.name.slice(0,-3),path:yn(hn(e,r.name))})).sort((r,s)=>r.name.localeCompare(s.name))}async function ye(e){let t=new K({path:e.path});try{gn(t);let n=bn(t),s=Sn(e.migrationsDir).filter((a)=>!n.has(a.name));if(s.length===0)return;for(let a of s){if(e.target&&a.name>e.target)break;let i=(await import(a.path)).default;if(!i)throw Error(`foxdb migrate: file "${a.path}" does not export a default Migration`);if(typeof i.up!=="function")throw Error(`foxdb migrate: migration "${i.name}" is missing an up() function`);t.transaction(()=>{i.up(t),Tn(t,a.name)})}}finally{t.close()}}class ge{listeners=new Map;tableActive=new Set;has(e){let t=this.listeners.get(e);return t!==void 0&&t.size>0}hasAny(e){return this.tableActive.has(e)}on(e,t){if(!this.listeners.has(e))this.listeners.set(e,new Set);this.listeners.get(e).add(t);let n=e.split(".")[0];if(n&&n!=="*")this.tableActive.add(n);return()=>{let r=this.listeners.get(e);if(r){if(r.delete(t),r.size===0)this.listeners.delete(e)}}}emit(e,t){let n=this.listeners.get(e);if(n)for(let s of n)try{s(t)}catch(a){console.error(`[foxdb] event listener error for "${e}":`,a)}let r=e.indexOf(".");if(r>0){let a=`${e.slice(0,r)}.*`,o=this.listeners.get(a);if(o)for(let i of o)try{i(t)}catch(l){console.error(`[foxdb] event listener error for "${a}":`,l)}}}emitIf(e,t){let n=e.indexOf("."),r=n>0&&this.has(`${e.slice(0,n)}.*`);if(this.has(e)||r)this.emit(e,t)}}function Rn(e){return typeof e==="object"&&e!==null&&"then"in e&&typeof e.then==="function"}function be(e,t,n){for(let r of e)try{let s=r(t);if(s&&Rn(s))s.catch((a)=>{console.error(`[foxdb] async ${n} hook error:`,a)})}catch(s){console.error(`[foxdb] ${n} hook error:`,s)}}class Te{startHooks=[];readyHooks=[];shutdownHooks=[];exitHooks=[];_ready=!1;_shutdown=!1;get isReady(){return this._ready}get isShutdown(){return this._shutdown}onStart(e){this.startHooks.push(e)}onReady(e){this.readyHooks.push(e)}onShutdown(e){this.shutdownHooks.push(e)}onExit(e){this.exitHooks.push(e)}runStart(e){be(this.startHooks,e,"onStart")}runReady(e){be(this.readyHooks,e,"onReady"),this._ready=!0}runShutdown(e){if(this._shutdown)return;this._shutdown=!0,be(this.shutdownHooks,e,"onShutdown")}runExit(e){be(this.exitHooks,e,"onExit")}}function wn(e){let t=e.path??":memory:";if(e.rebuildOnLaunch&&t!==":memory:"&&t.length>0)ae(t);let n=new K(e);if(e.autoVacuum==="incremental"&&e.vacuumIntervalMs)n.scheduler.schedule("auto-vacuum",e.vacuumIntervalMs,()=>{try{n.exec("PRAGMA incremental_vacuum(1000);")}catch{}});let r,s=new ge;try{let ie=function(f,b){let w=u.filter((g)=>g.ownerTable===f);if(w.length===0)return b;let y={};for(let[g,S]of Object.entries(b))y[g]=S;let N=w.filter((g)=>g.kind==="scalar");if(N.length>0){let g=new Proxy({},{get(S,R){let x=N.find((E)=>E.as===R||E.ownerField===R);if(!x)return;let M=o.get(x.targetTable);if(!M)return null;let A=b[x.ownerField];if(A==null)return null;return M.raw(`SELECT * FROM "${x.targetTable}" WHERE "${x.targetField}" = ? LIMIT 1`,A)[0]??null}});Object.defineProperty(y,"related",{value:g,writable:!1,enumerable:!1,configurable:!1});for(let S of N)if(S.as)Object.defineProperty(y,S.as,{get(){return y.related[S.as]},enumerable:!1,configurable:!1})}let v=w.filter((g)=>g.kind==="subTable");for(let g of v){let[S,R]=g.ownerField.split("."),x=y[S];if(!globalThis.Array.isArray(x))continue;let M=o.get(g.targetTable);if(!M)continue;let A=x.map((E)=>E[R]).filter((E)=>E!=null),q=new Map;if(A.length>0){let E=A.map(()=>"?").join(", "),I=M.raw(`SELECT * FROM "${g.targetTable}" WHERE "${g.targetField}" IN (${E})`,...A);q=new Map(I.map((L)=>[L[g.targetField],L]))}y[S]=x.map((E)=>{let I=q.get(E[R])??null,L=Object.create(null);Object.assign(L,E);let j=new Proxy({},{get(Re,F){if(F===g.as||F===g.ownerField)return I;return}});if(Object.defineProperty(L,"related",{value:j,writable:!1,enumerable:!1,configurable:!1}),g.as)Object.defineProperty(L,g.as,{value:I,writable:!1,enumerable:!1,configurable:!1});return L})}return y},Ve=function(f,b){if(b.length===0)return[];let w=u.filter((g)=>g.ownerTable===f);if(w.length===0)return b;let y=b.map((g)=>{let S=Object.getPrototypeOf(g),R=S?Object.create(S):{};return Object.assign(R,g),R}),N=w.filter((g)=>g.kind==="scalar"),v=w.filter((g)=>g.kind==="subTable");for(let g of N){let S=o.get(g.targetTable);if(!S)continue;let R=g.ownerField,x=[...new Set(y.map((E)=>E[R]).filter((E)=>E!==null&&E!==void 0))];if(x.length===0)continue;let M=x.map(()=>"?").join(", "),A=S.raw(`SELECT * FROM "${g.targetTable}" WHERE "${g.targetField}" IN (${M})`,...x),q=new Map(A.map((E)=>[E[g.targetField],E]));for(let E of y){let I=q.get(E[R]);if(I)Object.defineProperty(E,`_${R}_resolved`,{value:I,writable:!1,enumerable:!1,configurable:!1})}}for(let g of v){let S=o.get(g.targetTable);if(!S)continue;let[R,x]=g.ownerField.split("."),M=[...new Set(y.flatMap((I)=>{let L=I[R];if(!globalThis.Array.isArray(L))return[];return L.map((j)=>j[x]).filter((j)=>j!==null&&j!==void 0)}))];if(M.length===0)continue;let A=M.map(()=>"?").join(", "),q=S.raw(`SELECT * FROM "${g.targetTable}" WHERE "${g.targetField}" IN (${A})`,...M),E=new Map(q.map((I)=>[I[g.targetField],I]));for(let I of y){let L=I[R];if(!globalThis.Array.isArray(L))continue;I[R]=L.map((j)=>{let Re=E.get(j[x])??null,F=Object.create(null);Object.assign(F,j);let _t=new Proxy({},{get(Dn,Ge){if(Ge===g.as||Ge===g.ownerField)return Re;return}});if(Object.defineProperty(F,"related",{value:_t,writable:!1,enumerable:!1,configurable:!1}),g.as)Object.defineProperty(F,g.as,{value:Re,writable:!1,enumerable:!1,configurable:!1});return F})}}if(N.length>0)for(let g of y){let S=new Proxy({},{get(R,x){let M=N.find((A)=>A.as===x||A.ownerField===x);if(!M)return;return g[`_${M.ownerField}_resolved`]??null}});Object.defineProperty(g,"related",{value:S,writable:!1,enumerable:!1,configurable:!1});for(let R of N)if(R.as)Object.defineProperty(g,R.as,{get(){return g[`_${R.ownerField}_resolved`]??null},enumerable:!1,configurable:!1})}return y},Rt=function(f){for(let b of o.values())b.flush();if(f?.includeMeta)for(let b of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])c.delete(b)},Ot=function(){if(i.runShutdown(l),e.flushOnExit)for(let b of e.flushOnExit)o.get(b)?.flush();if(e.dropOnExit)for(let b of e.dropOnExit)o.get(b)?.drop();if(e.flushMetaOnExit)for(let b of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])c.delete(b);n.close(),i.runExit(l),s.emit("exit",{phase:"exit",timestamp:Date.now()});let f=e.unlinkDbFilesOnExit;if(f===!0||f==="onlyGraceful")ae(t)},a=Object.entries(e.tables);if(a.length===0)O("NO_TABLES","foxdb: at least one table must be defined in `tables`");let o=new Map;for(let[f,b]of a){let w=J(f,b.schema,ne(b.generated)),y=new Set(w.columns.map((g)=>g.name)),N=b.primaryKey.name;if(!y.has(N))O("INVALID_PK",`foxdb: primary key "${N}" is not a scalar column in table "${f}"`,{table:f,column:N});for(let g of b.indexes??[])for(let S of g.columns)if(!y.has(S.name))O("INVALID_INDEX",`foxdb: index column "${S.name}" not found in table "${f}"`,{table:f,column:S.name});let v=new he(f,b,n);o.set(f,v)}for(let[f,b]of o)b.setEventBus(s);if(e.hooks?.onQuery)for(let f of o.values())f.setMetricsHook(e.hooks.onQuery);let i=new Te;if(e.onStart)i.onStart(e.onStart);if(e.onReady)i.onReady(e.onReady);if(e.onShutdown)i.onShutdown(e.onShutdown);if(e.onExit)i.onExit(e.onExit);let l,u=[];if(typeof e.relations==="function"){let f=Qe(e.tables),b=e.relations(f);for(let w of b)u.push(w)}else for(let[f,b]of Object.entries(e.relations??{})){if(!b)continue;let w=o.get(f);if(!w)O("INVALID_RELATION",`foxdb: relation owner table "${f}" not found in tables`,{table:f});for(let y of b){let N=o.get(y.targetTableName);if(!N)O("INVALID_RELATION",`foxdb: relation target table "${y.targetTableName}" not found in tables`,{table:y.targetTableName});let v=y.ownerField.split(".");if(v.length===1){let[S=""]=v;if(!new Set(w.meta.columns.map((x)=>x.name)).has(S))O("INVALID_RELATION",`foxdb: relation ownerField "${y.ownerField}" is not a scalar column in table "${f}"`,{table:f,field:y.ownerField})}else if(v.length===2){let[S="",R=""]=v,x=w.meta.subTables.find((A)=>A.fieldName===S);if(!x)O("INVALID_RELATION",`foxdb: relation ownerField "${y.ownerField}" references unknown sub-table "${S}" in table "${f}"`,{table:f,field:y.ownerField});if(!new Set(x.columns.map((A)=>A.name)).has(R))O("INVALID_RELATION",`foxdb: relation ownerField "${y.ownerField}" references unknown column "${R}" in sub-table "${S}" of table "${f}"`,{table:f,field:y.ownerField})}else O("INVALID_RELATION",`foxdb: relation ownerField "${y.ownerField}" has too many dot segments (max 2 allowed)`,{table:f,field:y.ownerField});if(!new Set(N.meta.columns.map((S)=>S.name)).has(y.targetField))O("INVALID_RELATION",`foxdb: relation targetField "${y.targetField}" is not a scalar column in table "${y.targetTableName}"`,{table:y.targetTableName,field:y.targetField});u.push({ownerTable:f,ownerField:y.ownerField,targetTable:y.targetTableName,targetField:y.targetField,kind:v.length===1?"scalar":"subTable",as:void 0})}}let m=[];for(let[f,b]of a){let w=J(f,b.schema,ne(b.generated));m.push({name:f,columns:w.columns,indexes:(b.indexes??[]).map((y)=>({name:y.name,columns:y.columns.map((N)=>N.name),unique:y.unique})),primaryKey:b.primaryKey.name});for(let y of w.subTables)m.push({name:y.tableName,columns:y.columns,indexes:(b.subTables?.[y.fieldName]?.indexes??[]).map((N)=>({name:N.name,columns:N.columns.map((v)=>v.name),unique:N.unique})),primaryKey:"_id"})}let c=new $(n),d=Object.fromEntries(a.map(([f,b])=>[f,b.schema])),p=JSON.stringify(d),h=Bun.hash(p),T=new TextEncoder().encode(p),k=c.getString("_schema_hash"),D=String(h);if(k!==D&&e.sync&&e.sync!=="ignore"){let f=qe(n),b=Fe(m,f);Ue(b,n,e.sync,m)}c.setString("_schema_hash",D),c.setCompressed("_schema_compressed",T),c.setJSON("_tables",Object.keys(e.tables)),c.setJSON("_relations",u),c.setString("_foxdb_version","0.0.2");let wt={get schemaHash(){return c.getString("_schema_hash")},get schemaJSON(){let f=c.getCompressed("_schema_compressed");return f?new TextDecoder().decode(f):null},get tables(){return c.getJSON("_tables")},get relations(){return c.getJSON("_relations")},get version(){return c.getString("_foxdb_version")}};for(let[f,b]of o){if(u.filter((y)=>y.ownerTable===f).length===0)continue;b.setMaterializer((y)=>ie(f,y),(y)=>Ve(f,y))}r=Object.create(null);for(let f of Object.keys(e.tables))Object.defineProperty(r,f,{get(){return o.get(f)},enumerable:!0,configurable:!0});let xt=async()=>{if(!e.migrations)O("MIGRATIONS_NOT_CONFIGURED","foxdb: migrations dir not configured. Pass `migrations: { dir: ... }` to createORM().");await ye({path:t,migrationsDir:e.migrations.dir})},Et={on(f,b,w){if(typeof b==="string"&&typeof w==="function"){let y=`${f}.${b}`;return s.on(y,w)}if(typeof b==="function")return s.on(f,b);O("INVALID_EVENT_LISTENER","foxdb: invalid event listener arguments")}};if(e.bulkLoadMode)n.setSynchronous("OFF");if(l={orm:r,db:n,meta:c,tables:Object.keys(e.tables),repos:o,logger:{log:(...f)=>{console.log("[foxdb]",...f)},error:(...f)=>{console.error("[foxdb]",...f)}}},e.unlinkDbFilesOnExit==="any"){let f=()=>{try{ae(t)}catch{}},b=()=>{i.runExit(l),f(),process.exit(1)};process.on("exit",f),process.on("SIGINT",b),process.on("SIGTERM",b),process.on("uncaughtException",(w)=>{s.emit("fail",{phase:"fail",error:w,timestamp:Date.now()}),b()})}if(Object.assign(r,{_transaction:n.transaction.bind(n),_close:Ot,_setBulkLoadMode(f){n.setSynchronous(f?"OFF":"NORMAL")},_meta:wt,_materialize:ie,_materializeMany:Ve,_flush:Rt,_migrate:xt,_events:Et}),i.runStart(l),e.flushOnStart)for(let f of e.flushOnStart)o.get(f)?.flush();if(e.dropOnStart)for(let f of e.dropOnStart)o.get(f)?.drop();if(e.flushMetaOnStart)for(let f of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])c.delete(f);if(e.autoMigrate&&e.migrations)ye({path:t,migrationsDir:e.migrations.dir}).catch((f)=>{console.error("[foxdb] autoMigrate failed:",f)});if(e.seed)e.seed(r);i.runReady(l),s.emit("ready",{phase:"ready",timestamp:Date.now()})}catch(a){if(a instanceof G)s.emit("fail",{phase:"fail",error:a,timestamp:Date.now()});else{let o=new G(String(a),{code:"UNEXPECTED",trace:_e()});s.emit("fail",{phase:"fail",error:o,timestamp:Date.now()})}throw a}return r}import{IsString as xn,IsNumber as En,IsInteger as On,IsBoolean as _n,IsLiteral as Nn,IsObject as Tt,IsOptional as kn}from"typebox";function He(e){return xn(e)||En(e)||On(e)||_n(e)||Nn(e)}function Se(e){if(kn(e)){let t=e,n={};for(let r of Object.keys(t)){if(r==="~optional")continue;n[r]=t[r]}return n}return e}function St(e){let t={};for(let n of Object.keys(e.properties)){let r=e.properties[n];if(r&&He(r))t[n]={_tag:"ColumnRef",name:n,schema:r};if(r){let s=Se(r);if(s&&Tt(s)){let o=s.properties;for(let i of Object.keys(o)){let l=o[i];if(l){let u=Se(l);if(He(u)){let c=`${n}__${i}`;t[c]={_tag:"ColumnRef",name:c,schema:u}}let m=Se(l);if(m&&Tt(m)){let d=m.properties;for(let p of Object.keys(d)){let h=d[p];if(h){let T=Se(h);if(He(T)){let k=`${n}__${i}__${p}`;t[k]={_tag:"ColumnRef",name:k,schema:T}}}}}}}}}}return t}function Cn(e,t){let n=St(e),r=t(n);return{schema:e,...r}}import{existsSync as An,mkdirSync as $n,writeFileSync as Mn}from"fs";import{join as In,resolve as vn}from"path";function Ln(e,t){return`import type { Migration } from "@xwxfox/foxdb";
42
+ `)}function mr(e){let n=e.prepare('SELECT "name" FROM "_foxdb_migrations"').all();return new Set(n.map((r)=>r.name))}function fr(e,t){e.prepare('INSERT INTO "_foxdb_migrations" ("name", "appliedAt") VALUES (?, ?)').run(t,Date.now())}function pr(e){if(!lr(e))return[];return ar(e,{withFileTypes:!0}).filter((r)=>r.isFile()&&r.name.endsWith(".ts")).map((r)=>({name:r.name.slice(0,-3),path:ur(cr(e,r.name))})).sort((r,s)=>r.name.localeCompare(s.name))}async function Ve(e){let t=new ge({path:e.path});try{dr(t);let n=mr(t),s=pr(e.migrationsDir).filter((o)=>!n.has(o.name));if(s.length===0)return;for(let o of s){if(e.target&&o.name>e.target)break;let l=(await import(o.path)).default;if(!l)throw Error(`foxdb migrate: file "${o.path}" does not export a default Migration`);if(typeof l.up!=="function")throw Error(`foxdb migrate: migration "${l.name}" is missing an up() function`);t.transaction(()=>{l.up(t),fr(t,o.name)})}}finally{t.close()}}class He{listeners=new Map;tableActive=new Set;has(e){let t=this.listeners.get(e);return t!==void 0&&t.size>0}hasAny(e){return this.tableActive.has(e)}on(e,t){if(!this.listeners.has(e))this.listeners.set(e,new Set);this.listeners.get(e).add(t);let n=e.split(".")[0];if(n&&n!=="*")this.tableActive.add(n);return()=>{let r=this.listeners.get(e);if(r){if(r.delete(t),r.size===0)this.listeners.delete(e)}}}emit(e,t){let n=this.listeners.get(e);if(n)for(let s of n)try{s(t)}catch(o){console.error(`[foxdb] event listener error for "${e}":`,o)}let r=e.indexOf(".");if(r>0){let o=`${e.slice(0,r)}.*`,i=this.listeners.get(o);if(i)for(let l of i)try{l(t)}catch(m){console.error(`[foxdb] event listener error for "${o}":`,m)}}}emitIf(e,t){let n=e.indexOf("."),r=n>0&&this.has(`${e.slice(0,n)}.*`);if(this.has(e)||r)this.emit(e,t)}}function hr(e){return typeof e==="object"&&e!==null&&"then"in e&&typeof e.then==="function"}function Je(e,t,n){for(let r of e)try{let s=r(t);if(s&&hr(s))s.catch((o)=>{console.error(`[foxdb] async ${n} hook error:`,o)})}catch(s){console.error(`[foxdb] ${n} hook error:`,s)}}class Xe{startHooks=[];readyHooks=[];shutdownHooks=[];exitHooks=[];_ready=!1;_shutdown=!1;get isReady(){return this._ready}get isShutdown(){return this._shutdown}onStart(e){this.startHooks.push(e)}onReady(e){this.readyHooks.push(e)}onShutdown(e){this.shutdownHooks.push(e)}onExit(e){this.exitHooks.push(e)}runStart(e){Je(this.startHooks,e,"onStart")}runReady(e){Je(this.readyHooks,e,"onReady"),this._ready=!0}runShutdown(e){if(this._shutdown)return;this._shutdown=!0,Je(this.shutdownHooks,e,"onShutdown")}runExit(e){Je(this.exitHooks,e,"onExit")}}class It{workers=[];workerStatus=[];taskCounter=0;MAX_PENDING_TASKS=65536;pendingTasks;overflowQueue=[];overflowHead=0;nextWorkerHint=0;columnCache=new Map;constructor(e={},t){let n=t??navigator.hardwareConcurrency??4;this.pendingTasks=Array(this.MAX_PENDING_TASKS).fill(null),this.initWorkers(n,e)}initWorkers(e,t){let n=new URL("./worker.ts",import.meta.url).href;for(let r=0;r<e;r++){let s=new Worker(n);s.postMessage({type:"INIT",opts:t});let o=r;s.onmessage=(i)=>{let l=i.data,m=this.pendingTasks[l.taskId];if(!m)return;if(this.pendingTasks[l.taskId]=null,!l.success){m.reject(Error(l.error)),this.dequeueOrIdle(o);return}let a=this.columnCache.get(m.sql);if(a){let u=l.result,c=Array(u.length);for(let d=0;d<u.length;d++){let f=u[d],p={};for(let h=0;h<a.length;h++)p[a[h]]=f[h];c[d]=p}m.resolve(c)}else m.resolve(l.result);this.dequeueOrIdle(o)},this.workers.push(s),this.workerStatus.push(!0)}}dispatch(e,t,n,r,s,o){this.workerStatus[e]=!1;let i=this.taskCounter;if(this.taskCounter=(this.taskCounter+1)%this.MAX_PENDING_TASKS,this.pendingTasks[i]={resolve:s,reject:o,sql:t},this.workers[e])this.workers[e].postMessage({type:"EXEC",taskId:i,sql:t,params:n,zeroCopy:r});else throw Error("tried dispatching message to non-existent worker thread")}dequeueOrIdle(e){if(this.overflowHead<this.overflowQueue.length){let t=this.overflowQueue[this.overflowHead];this.overflowQueue[this.overflowHead]=void 0,this.overflowHead++,this.dispatch(e,t.sql,t.params,t.zeroCopy,t.resolve,t.reject)}else this.overflowQueue.length=0,this.overflowHead=0,this.workerStatus[e]=!0}exec(e,t=[]){return this.enqueue(e,t,!1)}execWithCols(e,t,n){return this.columnCache.set(e,n),this.enqueue(e,t,!0)}enqueue(e,t,n){return new Promise((r,s)=>{let o=this.workerStatus.length;for(let i=0;i<o;i++){let l=(this.nextWorkerHint+i)%o;if(this.workerStatus[l]){this.nextWorkerHint=(l+1)%o,this.dispatch(l,e,t,n,r,s);return}}this.overflowQueue.push({sql:e,params:t,zeroCopy:n,resolve:r,reject:s})})}terminate(){for(let e=0;e<this.workers.length;e++)try{this.workers[e].terminate()}catch{}this.workers=[],this.overflowQueue.length=0,this.overflowHead=0}}function yr(e){let t=e.path??":memory:";if(e.rebuildOnLaunch&&t!==":memory:"&&t.length>0)Fe(t);let n=new ge(e);if(e.autoVacuum==="incremental"&&e.vacuumIntervalMs)n.scheduler.schedule("auto-vacuum",e.vacuumIntervalMs,()=>{try{n.exec("PRAGMA incremental_vacuum(1000);")}catch{}});let r,s=new He,o;try{let E=function(b,w){let I=u.filter((N)=>N.ownerTable===b);if(I.length===0)return w;let T={};for(let[N,A]of Object.entries(w))T[N]=A;let O=I.filter((N)=>N.kind==="scalar");if(O.length>0){let N=new Proxy({},{get(A,P){let U=O.find((G)=>G.as===P||G.ownerField===P);if(!U)return;let ee=l.get(U.targetTable);if(!ee)return null;let Y=w[U.ownerField];if(Y==null)return null;return ee.raw(`SELECT * FROM "${U.targetTable}" WHERE "${U.targetField}" = ? LIMIT 1`,Y)[0]??null}});Object.defineProperty(T,"related",{value:N,writable:!1,enumerable:!1,configurable:!1});for(let A of O)if(A.as)Object.defineProperty(T,A.as,{get(){return T.related[A.as]},enumerable:!1,configurable:!1})}let k=I.filter((N)=>N.kind==="subTable");for(let N of k){let[A,P]=N.ownerField.split("."),U=T[A];if(!globalThis.Array.isArray(U))continue;let ee=l.get(N.targetTable);if(!ee)continue;let Y=U.map((G)=>G[P]).filter((G)=>G!=null),he=new Map;if(Y.length>0){let G=Y.map(()=>"?").join(", "),te=ee.raw(`SELECT * FROM "${N.targetTable}" WHERE "${N.targetField}" IN (${G})`,...Y);he=new Map(te.map((oe)=>[oe[N.targetField],oe]))}T[A]=U.map((G)=>{let te=he.get(G[P])??null,oe=Object.create(null);Object.assign(oe,G);let ue=new Proxy({},{get(ze,ye){if(ye===N.as||ye===N.ownerField)return te;return}});if(Object.defineProperty(oe,"related",{value:ue,writable:!1,enumerable:!1,configurable:!1}),N.as)Object.defineProperty(oe,N.as,{value:te,writable:!1,enumerable:!1,configurable:!1});return oe})}return T},C=function(b,w){if(w.length===0)return[];let I=u.filter((N)=>N.ownerTable===b);if(I.length===0)return w;let T=w.map((N)=>{let A=Object.getPrototypeOf(N),P=A?Object.create(A):{};return Object.assign(P,N),P}),O=I.filter((N)=>N.kind==="scalar"),k=I.filter((N)=>N.kind==="subTable");for(let N of O){let A=l.get(N.targetTable);if(!A)continue;let P=N.ownerField,U=[...new Set(T.map((G)=>G[P]).filter((G)=>G!==null&&G!==void 0))];if(U.length===0)continue;let ee=U.map(()=>"?").join(", "),Y=A.raw(`SELECT * FROM "${N.targetTable}" WHERE "${N.targetField}" IN (${ee})`,...U),he=new Map(Y.map((G)=>[G[N.targetField],G]));for(let G of T){let te=he.get(G[P]);if(te)Object.defineProperty(G,`_${P}_resolved`,{value:te,writable:!1,enumerable:!1,configurable:!1})}}for(let N of k){let A=l.get(N.targetTable);if(!A)continue;let[P,U]=N.ownerField.split("."),ee=[...new Set(T.flatMap((te)=>{let oe=te[P];if(!globalThis.Array.isArray(oe))return[];return oe.map((ue)=>ue[U]).filter((ue)=>ue!==null&&ue!==void 0)}))];if(ee.length===0)continue;let Y=ee.map(()=>"?").join(", "),he=A.raw(`SELECT * FROM "${N.targetTable}" WHERE "${N.targetField}" IN (${Y})`,...ee),G=new Map(he.map((te)=>[te[N.targetField],te]));for(let te of T){let oe=te[P];if(!globalThis.Array.isArray(oe))continue;te[P]=oe.map((ue)=>{let ze=G.get(ue[U])??null,ye=Object.create(null);Object.assign(ye,ue);let dn=new Proxy({},{get($r,kt){if(kt===N.as||kt===N.ownerField)return ze;return}});if(Object.defineProperty(ye,"related",{value:dn,writable:!1,enumerable:!1,configurable:!1}),N.as)Object.defineProperty(ye,N.as,{value:ze,writable:!1,enumerable:!1,configurable:!1});return ye})}}if(O.length>0)for(let N of T){let A=new Proxy({},{get(P,U){let ee=O.find((Y)=>Y.as===U||Y.ownerField===U);if(!ee)return;return N[`_${ee.ownerField}_resolved`]??null}});Object.defineProperty(N,"related",{value:A,writable:!1,enumerable:!1,configurable:!1});for(let P of O)if(P.as)Object.defineProperty(N,P.as,{get(){return N[`_${P.ownerField}_resolved`]??null},enumerable:!1,configurable:!1})}return T},x=function(b){for(let w of l.values())w.flush();if(b?.includeMeta)for(let w of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])d.delete(w)},L=function(){if(m.runShutdown(a),e.flushOnExit)for(let w of e.flushOnExit)l.get(w)?.flush();if(e.dropOnExit)for(let w of e.dropOnExit)l.get(w)?.drop();if(e.flushMetaOnExit)for(let w of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])d.delete(w);Mt(),o?.terminate(),n.close(),m.runExit(a),s.emit("exit",{phase:"exit",timestamp:Date.now()});let b=e.unlinkDbFilesOnExit;if(b===!0||b==="onlyGraceful")Fe(t)};if(e.asyncReaderPool&&e.asyncReaderPool>=1){if(t!==":memory:"&&t.length>0)o=new It({path:t,cacheSize:e.cacheSize,busyTimeout:e.busyTimeout,synchronous:e.synchronous,mmapSize:e.mmapSize},e.asyncReaderPool)}let i=Object.entries(e.tables);if(i.length===0)v("NO_TABLES","foxdb: at least one table must be defined in `tables`");let l=new Map;for(let[b,w]of i){let I=Ie(w.schema.properties,[],0,!0),T=new Set(I.map((A)=>A.name)),O=Be(w.generated);if(O)for(let A of O)T.add(A.name);let k=w.primaryKey.name;if(!T.has(k))v("INVALID_PK",`foxdb: primary key "${k}" is not a scalar column in table "${b}"`,{table:b,column:k});for(let A of w.indexes??[])for(let P of A.columns)if(!T.has(P.name))v("INVALID_INDEX",`foxdb: index column "${P.name}" not found in table "${b}"`,{table:b,column:P.name});let N=new We(b,w,n,o,e.onDeleteBehavior);l.set(b,N)}for(let[b,w]of l)w.setEventBus(s);if(e.hooks?.onQuery)for(let b of l.values())b.setMetricsHook(e.hooks.onQuery);let m=new Xe;if(e.onStart)m.onStart(e.onStart);if(e.onReady)m.onReady(e.onReady);if(e.onShutdown)m.onShutdown(e.onShutdown);if(e.onExit)m.onExit(e.onExit);let a,u=[];if(typeof e.relations==="function"){let b=wt(e.tables),w=e.relations(b);for(let I of w)u.push(I)}else for(let[b,w]of Object.entries(e.relations??{})){if(!w)continue;let I=l.get(b);if(!I)v("INVALID_RELATION",`foxdb: relation owner table "${b}" not found in tables`,{table:b});for(let T of w){let O=l.get(T.targetTableName);if(!O)v("INVALID_RELATION",`foxdb: relation target table "${T.targetTableName}" not found in tables`,{table:T.targetTableName});let k=T.ownerField.split(".");if(k.length===1){let[A=""]=k;if(!new Set(I.meta.columns.map((U)=>U.name)).has(A))v("INVALID_RELATION",`foxdb: relation ownerField "${T.ownerField}" is not a scalar column in table "${b}"`,{table:b,field:T.ownerField})}else if(k.length===2){let[A="",P=""]=k,U=I.meta.subTables.find((Y)=>Y.fieldName===A);if(!U)v("INVALID_RELATION",`foxdb: relation ownerField "${T.ownerField}" references unknown sub-table "${A}" in table "${b}"`,{table:b,field:T.ownerField});if(!new Set(U.columns.map((Y)=>Y.name)).has(P))v("INVALID_RELATION",`foxdb: relation ownerField "${T.ownerField}" references unknown column "${P}" in sub-table "${A}" of table "${b}"`,{table:b,field:T.ownerField})}else v("INVALID_RELATION",`foxdb: relation ownerField "${T.ownerField}" has too many dot segments (max 2 allowed)`,{table:b,field:T.ownerField});if(!new Set(O.meta.columns.map((A)=>A.name)).has(T.targetField))v("INVALID_RELATION",`foxdb: relation targetField "${T.targetField}" is not a scalar column in table "${T.targetTableName}"`,{table:T.targetTableName,field:T.targetField});u.push({ownerTable:b,ownerField:T.ownerField,targetTable:T.targetTableName,targetField:T.targetField,kind:k.length===1?"scalar":"subTable",as:void 0})}}let c=[];for(let[b,w]of i){let I=ke(b,w.schema,Be(w.generated));c.push({name:b,columns:I.columns,indexes:(w.indexes??[]).map((T)=>({name:T.name,columns:T.columns.map((O)=>O.name),unique:T.unique})),primaryKey:w.primaryKey.name});for(let T of I.subTables)c.push({name:T.tableName,columns:T.columns,indexes:(w.subTables?.[T.fieldName]?.indexes??[]).map((O)=>({name:O.name,columns:O.columns.map((k)=>k.name),unique:O.unique})),primaryKey:"_id"})}let d=new z(n),f=Object.fromEntries(i.map(([b,w])=>[b,w.schema])),p=JSON.stringify(f),h=Bun.hash(p),y=new TextEncoder().encode(p),_=d.getString("_schema_hash"),g=String(h);if(_!==g&&e.sync&&e.sync!=="ignore"){let b=Rt(n),w=Nt(c,b);Ct(w,n,e.sync,c)}d.setString("_schema_hash",g),d.setCompressed("_schema_compressed",y),d.setJSON("_tables",Object.keys(e.tables)),d.setJSON("_relations",u),d.setString("_foxdb_version","0.0.2");let M={get schemaHash(){return d.getString("_schema_hash")},get schemaJSON(){let b=d.getCompressed("_schema_compressed");return b?new TextDecoder().decode(b):null},get tables(){return d.getJSON("_tables")},get relations(){return d.getJSON("_relations")},get version(){return d.getString("_foxdb_version")}};for(let[b,w]of l){if(u.filter((T)=>T.ownerTable===b).length===0)continue;w.setMaterializer((T)=>E(b,T),(T)=>C(b,T))}r=Object.create(null);for(let b of Object.keys(e.tables))Object.defineProperty(r,b,{get(){return l.get(b)},enumerable:!0,configurable:!0});let q=async()=>{if(!e.migrations)v("MIGRATIONS_NOT_CONFIGURED","foxdb: migrations dir not configured. Pass `migrations: { dir: ... }` to createORM().");await Ve({path:t,migrationsDir:e.migrations.dir})},F={on(b,w,I){if(typeof w==="string"&&typeof I==="function"){let T=`${b}.${w}`;return s.on(T,I)}if(typeof w==="function")return s.on(b,w);v("INVALID_EVENT_LISTENER","foxdb: invalid event listener arguments")}};if(e.bulkLoadMode)n.setSynchronous("OFF");if(a={orm:r,db:n,meta:d,tables:Object.keys(e.tables),repos:l,logger:{log:(...b)=>{console.log("[foxdb]",...b)},error:(...b)=>{console.error("[foxdb]",...b)}}},e.unlinkDbFilesOnExit==="any"){let b=()=>{try{Fe(t)}catch{}},w=()=>{m.runExit(a),b(),process.exit(1)};process.on("exit",b),process.on("SIGINT",w),process.on("SIGTERM",w),process.on("uncaughtException",(I)=>{s.emit("fail",{phase:"fail",error:I,timestamp:Date.now()}),w()})}let B=n.transaction.bind(n);if(Object.assign(r,{_transaction:(b)=>{n._txDepth++;try{return B(b)}finally{n._txDepth--}},_close:L,_setBulkLoadMode(b){n.setSynchronous(b?"OFF":"NORMAL")},_meta:M,_materialize:E,_materializeMany:C,_flush:x,_migrate:q,_events:F}),m.runStart(a),e.flushOnStart)for(let b of e.flushOnStart)l.get(b)?.flush();if(e.dropOnStart)for(let b of e.dropOnStart)l.get(b)?.drop();if(e.flushMetaOnStart)for(let b of["_schema_hash","_schema_compressed","_tables","_relations","_foxdb_version"])d.delete(b);if(e.autoMigrate&&e.migrations)Ve({path:t,migrationsDir:e.migrations.dir}).catch((b)=>{console.error("[foxdb] autoMigrate failed:",b)});if(e.seed)e.seed(r);m.runReady(a),s.emit("ready",{phase:"ready",timestamp:Date.now()})}catch(i){if(i instanceof we)s.emit("fail",{phase:"fail",error:i,timestamp:Date.now()});else{let l=new we(String(i),{code:"UNEXPECTED",trace:nt()});s.emit("fail",{phase:"fail",error:l,timestamp:Date.now()})}throw i}return r}import{IsString as gr,IsNumber as br,IsInteger as Tr,IsBoolean as Sr,IsLiteral as _r,IsObject as wr,IsOptional as Er}from"typebox";function Bt(e){return gr(e)||br(e)||Tr(e)||Sr(e)||_r(e)}function cn(e){return wr(e)}function Ye(e){let t=e;if(Er(e)){let n={};for(let r of Object.keys(t)){if(r==="~optional")continue;n[r]=t[r]}return n}return e}function un(e){let t={};for(let n of Object.keys(e.properties)){let r=e.properties[n];if(r&&Bt(r))t[n]={_tag:"ColumnRef",name:n,schema:r};if(r){let s=Ye(r);if(s&&cn(s)){let o=s.properties;for(let i of Object.keys(o)){let l=o[i];if(l){let m=Ye(l);if(Bt(m)){let u=`${n}__${i}`;t[u]={_tag:"ColumnRef",name:u,schema:m}}let a=Ye(l);if(a&&cn(a)){let u=a.properties;for(let c of Object.keys(u)){let d=u[c];if(d){let f=Ye(d);if(Bt(f)){let p=`${n}__${i}__${c}`;t[p]={_tag:"ColumnRef",name:p,schema:f}}}}}}}}}}return t}function Rr(e,t){let n=un(e),r=t(n);return{schema:e,...r}}import{existsSync as Nr,mkdirSync as xr,writeFileSync as Or}from"fs";import{join as Cr,resolve as Ir}from"path";function Br(e,t){return`import type { Migration } from "@xwxfox/foxdb";
43
43
 
44
44
  export default {
45
45
  name: "${e}",
@@ -49,4 +49,4 @@ export default {
49
49
  // Your migration logic here
50
50
  },
51
51
  } satisfies Migration;
52
- `}function Bn(e,t){if(!An(t))$n(t,{recursive:!0});let n=new Date,r=n.getFullYear(),s=String(n.getMonth()+1).padStart(2,"0"),a=String(n.getDate()).padStart(2,"0"),o=String(n.getHours()).padStart(2,"0"),i=String(n.getMinutes()).padStart(2,"0"),l=String(n.getSeconds()).padStart(2,"0"),m=`${`${r}${s}${a}_${o}${i}${l}`}_${e}.ts`,c=vn(In(t,m)),d=n.toISOString(),p=Ln(e,d);return Mn(c,p,"utf-8"),c}export{C as withTrace,Cn as table,Pe as resolveTimestampNames,O as raise,ye as migrate,J as introspectTable,gt as inspectSchema,qe as inspectAllTables,Qe as createRelationBuilder,wn as createORM,Bn as createMigration,Fe as computeDiff,Ie as buildCreateTableSQL,Ue as applySync,yt as SchemaJSONSchema,he as Repository,G as ORMError,$ as MetaStore,Te as LifecycleManager,ge as EventBus,De as DEFAULT_TIMESTAMP_NAMES,K as BunDatabase,fe as BatchWriter};
52
+ `}function kr(e,t){if(!Nr(t))xr(t,{recursive:!0});let n=new Date,r=n.getFullYear(),s=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0"),i=String(n.getHours()).padStart(2,"0"),l=String(n.getMinutes()).padStart(2,"0"),m=String(n.getSeconds()).padStart(2,"0"),u=`${`${r}${s}${o}_${i}${l}${m}`}_${e}.ts`,c=Ir(Cr(t,u)),d=n.toISOString(),f=Br(e,d);return Or(c,f,"utf-8"),c}export{Me as AggregateBuilder,Ke as BatchWriter,ge as BunDatabase,xe as DEFAULT_TIMESTAMP_NAMES,He as EventBus,J as FilterBuilder,je as FtsSearchBuilder,Xe as LifecycleManager,z as MetaStore,we as ORMError,We as Repository,on as SchemaJSONSchema,Ct as applySync,lt as buildCreateTableSQL,Ge as buildFtsSearchSql,Z as buildWhereFromNodes,Nt as computeDiff,kr as createMigration,yr as createORM,wt as createRelationBuilder,ae as ftsTableName,Rt as inspectAllTables,an as inspectSchema,ke as introspectTable,Ve as migrate,v as raise,yt as resolveFtsColumns,_t as resolveTimestampNames,Rr as table,V as withTrace};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xwxfox/foxdb",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "itty bitty e2e typed orm for bun :3",
5
5
  "main": "dist/index.mjs",
6
6
  "publishConfig": {
@@ -11,6 +11,7 @@
11
11
  "build": "bunup",
12
12
  "docs": "bun run docs.ts",
13
13
  "bench": "bun run ./benchmarks/real-world-schema-bench.ts",
14
+ "bench:fts": "bun run ./benchmarks/fts-bench.ts",
14
15
  "release": "bun run publish.ts"
15
16
  },
16
17
  "keywords": [
@@ -65,4 +66,4 @@
65
66
  "dependencies": {
66
67
  "typebox": "^1.1.34"
67
68
  }
68
- }
69
+ }