@lunora/shard-engine 1.0.0-alpha.52 → 1.0.0-alpha.53

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.
Files changed (46) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +4 -3
  3. package/dist/index.d.ts +4 -3
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-1OWiZgrN.mjs → ADMIN_FUNCTIONS-Jsbz35Pz.mjs} +1 -1
  6. package/dist/packem_shared/{AGG_COUNT-gkJ8xtVW.mjs → AGG_COUNT-FqmOn0fB.mjs} +1 -1
  7. package/dist/packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs +1 -0
  8. package/dist/packem_shared/{CDC_LOG_TABLE-Cva29kfS.mjs → CDC_LOG_TABLE-DVUFJikx.mjs} +1 -1
  9. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BVaTptvb.mjs → DEFAULT_MAX_RELAYS-BAJHxoe-.mjs} +1 -1
  10. package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-D_gjjTFo.mjs → DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs} +1 -1
  11. package/dist/packem_shared/MAX_SQL_ROWS-DOEw2HBt.mjs +4 -0
  12. package/dist/packem_shared/MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs +1 -0
  13. package/dist/packem_shared/NotUniqueError-BdMwMt_A.mjs +1 -0
  14. package/dist/packem_shared/{RANK_TIEBREAK-BXD4YaG3.mjs → RANK_TIEBREAK-DGlhcKKv.mjs} +1 -1
  15. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs +1 -0
  16. package/dist/packem_shared/{ReactiveCache-CwSgH_wK.mjs → ReactiveCache-C8Y0FuN8.mjs} +1 -1
  17. package/dist/packem_shared/SEARCH_STATE_TABLE-D5mnK5kX.mjs +1 -0
  18. package/dist/packem_shared/backfillAggregateIndexes-vSnbgww7.mjs +1 -0
  19. package/dist/packem_shared/{buildReprojectionMigration-D-9DU7D2.mjs → buildReprojectionMigration-CD97i4QW.mjs} +1 -1
  20. package/dist/packem_shared/{buildShapeDiff-C-jrV9kY.mjs → buildShapeDiff-BcSSPYR8.mjs} +1 -1
  21. package/dist/packem_shared/{computeRankPage-CuWuhRZN.mjs → computeRankPage-BjcLdI-1.mjs} +1 -1
  22. package/dist/packem_shared/{createCompanionSync-DlYfWB_e.mjs → createCompanionSync-BtNrMh1X.mjs} +1 -1
  23. package/dist/packem_shared/{createReplicaLink-COCkDNMK.mjs → createReplicaLink-BtUkvhFo.mjs} +1 -1
  24. package/dist/packem_shared/ctx-db-companions-QC15-pzG.mjs +1 -0
  25. package/dist/packem_shared/ctx-db-search-state-ruTuCsxa.mjs +1 -0
  26. package/dist/packem_shared/{defineEngineContractSuite-BQBhgHJM.mjs → defineEngineContractSuite-1aM30yIJ.mjs} +1 -1
  27. package/dist/packem_shared/{do-sql-qxXsaO03.mjs → do-sql-A80W5VLt.mjs} +1 -1
  28. package/dist/packem_shared/{estimate-bytes-D6KN5_7y.mjs → estimate-bytes-DKqVDdZQ.mjs} +1 -1
  29. package/dist/packem_shared/exportShardRows-D_upYHRQ.mjs +1 -0
  30. package/dist/packem_shared/{isSoftDeleted-cRWEfyMb.mjs → isSoftDeleted-DVEZ9xVv.mjs} +1 -1
  31. package/dist/packem_shared/{materializeExternalRows-DDXDqsGW.mjs → materializeExternalRows-a5CvNwTW.mjs} +1 -1
  32. package/dist/packem_shared/runShardMigrations-DtD-pA0_.mjs +5 -0
  33. package/dist/packem_shared/{selectExpiredIds-DHm7CSED.mjs → selectExpiredIds-Dbwd__6n.mjs} +1 -1
  34. package/dist/packem_shared/{selectShapeMembers-CPdl1Ht1.mjs → selectShapeMembers-9Jz7ec_-.mjs} +1 -1
  35. package/dist/packem_shared/serializeSqlValue-B_-zaEWZ.mjs +1 -0
  36. package/package.json +3 -3
  37. package/dist/packem_shared/BIGINT_KEY_DIGITS-Djq7G5Xx.mjs +0 -1
  38. package/dist/packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs +0 -5
  39. package/dist/packem_shared/NotUniqueError-C7gJLEay.mjs +0 -1
  40. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CepZvBVl.mjs +0 -1
  41. package/dist/packem_shared/SEARCH_STATE_TABLE-xmYM_nOd.mjs +0 -1
  42. package/dist/packem_shared/backfillAggregateIndexes-BCmY3OYO.mjs +0 -1
  43. package/dist/packem_shared/ctx-db-companions-CTabzjgb.mjs +0 -1
  44. package/dist/packem_shared/exportShardRows-4Xezo8F6.mjs +0 -1
  45. package/dist/packem_shared/runShardMigrations-DiCqfU82.mjs +0 -5
  46. package/dist/packem_shared/serializeSqlValue-BBtrWwiu.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{LunoraError as f}from"@lunora/errors";const w=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends f{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const M=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),S=(o,n,u)=>{const l=n?.tables,a=new Set(n?.exclude);for(const c of o)(l===void 0||l.includes(c))&&!a.has(c)&&u(c)},m={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(m).filter(([,o])=>o==="loop-gated").map(([o])=>o),v=(o,n,u,l)=>{if(n.rlsMode!=="required")return o;const a=o,c=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},d=e=>{if(c(e))throw new R(e)},i=async(e,t)=>{if(t!==void 0){d(t);return}const r=await u(e);r!==void 0&&d(r)},p=async(e,t)=>{if(t!==void 0){d(t);return}if(!l){for(const s of e)await i(s,t);return}const r=await l([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&d(h)}},g={...o,[w]:o,delete:async(e,t,r)=>(await i(e,t),a.delete(e,t,r)),deleteMany:async(e,t,r)=>(await p(e,r),a.deleteMany(e,t,r)),deleteWhere:a.deleteWhere?async(e,t,r)=>(d(e),await a.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await i(e,t),a.get(e,t)),lookupById:async(e,t)=>(await i(e,t),a.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await i(e,r),a.patch(e,t,r)),patchMany:async(e,t,r)=>(await p(e.map(s=>s.id),r),a.patchMany(e,t,r)),patchWhere:a.patchWhere?async(e,t,r)=>(d(e),await a.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await i(e,r),a.replace(e,t,r,s)),restore:async(e,t)=>(await i(e,t),a.restore?.(e,t))},y=a;for(const e of W){const t=y[e];typeof t=="function"&&(g[e]=(r,...s)=>(d(r),t.call(a,r,...s)))}if(a.wipeShard){const{wipeShard:e}=a;g.wipeShard=t=>(S(M(n),t,d),e.call(a,t))}return g};export{W as LOOP_GATED_METHODS,w as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,m as WRITER_METHOD_GATING,v as guardWriter};
@@ -1 +1 @@
1
- import{stableWireKey as y}from"./stableWireKey-CSJKu_ID.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-D6KN5_7y.mjs";import{keysTouchRanges as x}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
1
+ import{stableWireKey as y}from"./stableWireKey-CSJKu_ID.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-DKqVDdZQ.mjs";import{keysTouchRanges as x}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
@@ -0,0 +1 @@
1
+ import{S as t,m as S,r as c,a as i,w as s}from"./ctx-db-search-state-ruTuCsxa.mjs";import"./runDrizzle-2ULFQR_k.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
@@ -0,0 +1 @@
1
+ import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-QC15-pzG.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as F}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as D,foldAggregateTally as v}from"./aggregateTableName-CCCIulmn.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as w,r as p,a as B,b as G,A as U,D as I,h as H}from"./do-sql-A80W5VLt.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-B1i1J8Zi.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-DGlhcKKv.mjs";const k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,Y=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,A=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),j=(e,o,n,r)=>{const i=N(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=A(e,o);for(const d of s){const f=p(d);if(!f||!P(f,r)||n.where&&!F(f,n.where))continue;const g=D(c,f);v(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${B}, ${G}, ${U}) VALUES (${d}, ${f.value}, ${f.count})`)},te=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)j(e,n,i,r.softDeleteMode?.field)},K=(e,o,n)=>{const r=W(o,n.name);if(k(e,r))return;const i=M(n),c=A(e,o);for(const a of c){const s=p(a);!s||n.where&&!V(s,n.where)||x(e,r,n,i,s._id,s)}},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)K(e,n,i)},u=500,$=(e,o,n)=>{const r=R(o,n.name),i=T(n),c=b(E(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(u))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(u))}`).toArray();let d=a;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;d=m,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${m}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(_)}, ${t.identifier(h)}) VALUES (${y(S,n)}, ${m})`)}const f=s.length<u;return L(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=R(o,n.name),i=T(n);return b(E(e,r),i).finished?!0:C(e,r)},se=(e,o,n)=>{if(w(e))for(const r of n.searchIndexes??[])r.staged&&Y(e,o)||$(e,o,r)},z=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=$(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},ce=(e,o,n={})=>{if(!w(e))return{done:!0,pages:0};O(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=z(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{te as backfillAggregateIndexes,ie as backfillRankIndexes,ce as backfillSearchIndexes,se as backfillSearchIndexesForTable,ae as searchIndexCoversTable};
@@ -1 +1 @@
1
- import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-UyQIjlyN.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as m,D as E}from"./do-sql-qxXsaO03.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
1
+ import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-UyQIjlyN.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as m,D as E}from"./do-sql-A80W5VLt.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-Cva29kfS.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-CPdl1Ht1.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-BmVH30dI.mjs";import{projectColumns as g}from"./buildPokeFrames-CySyxldi.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-DVUFJikx.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-9Jz7ec_-.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-BmVH30dI.mjs";import{projectColumns as g}from"./buildPokeFrames-CySyxldi.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as U,toBase64 as V}from"./CURSOR_PREFIX-B1i1J8Zi.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as P,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-BXD4YaG3.mjs";const X="__doc__",Y=n=>U+V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,Z=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},oo=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},no=o`${o.identifier("id")}`,to=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(X)} FROM ${o.identifier(r)} WHERE ${O(no,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},lo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new g("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new g("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=P(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${S}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${S}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=A(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=oo(y,to(n,r,K),l),N=C?Z(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{lo as computeRankPage,G as resolveRankSeekTuple};
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as U,toBase64 as V}from"./CURSOR_PREFIX-B1i1J8Zi.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as P,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-DGlhcKKv.mjs";const X="__doc__",Y=n=>U+V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,Z=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},oo=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},no=o`${o.identifier("id")}`,to=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(X)} FROM ${o.identifier(r)} WHERE ${O(no,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},lo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new g("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new g("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=P(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${S}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${S}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=A(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=oo(y,to(n,r,K),l),N=C?Z(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{lo as computeRankPage,G as resolveRankSeekTuple};
@@ -1 +1 @@
1
- import{c as l,i as C,r as R}from"./ctx-db-companions-CTabzjgb.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-CCCIulmn.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-qxXsaO03.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-B1i1J8Zi.mjs";import"./RANK_TIEBREAK-BXD4YaG3.mjs";import"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";import"./serializeSqlValue-BBtrWwiu.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
1
+ import{c as l,i as C,r as R}from"./ctx-db-companions-QC15-pzG.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-CCCIulmn.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-A80W5VLt.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-B1i1J8Zi.mjs";import"./RANK_TIEBREAK-DGlhcKKv.mjs";import"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import"./serializeSqlValue-B_-zaEWZ.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -1,4 +1,4 @@
1
- import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-Cva29kfS.mjs";import{envPositiveInt as h}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as _,R as f,s as S,a as v,b as y}from"./sibling-channel-Cxvk0Zca.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=s=>typeof s=="string"&&N.has(s),p="::replica::",R=s=>{const e=s.lastIndexOf(p);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+p.length);if(!(t.length===0||!T(r)))return{ownerKey:t,region:r}},L=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,g=1e3,b=10,I=5e4,m=s=>h(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",I),c="__replica_state",u=new WeakSet,E=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${c} (
1
+ import{cursorBelowRetainedFloor as w}from"./CDC_LOG_TABLE-DVUFJikx.mjs";import{envPositiveInt as h}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as _,R as f,s as S,a as v,b as y}from"./sibling-channel-Cxvk0Zca.mjs";const A=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],N=new Set(A),T=s=>typeof s=="string"&&N.has(s),p="::replica::",R=s=>{const e=s.lastIndexOf(p);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+p.length);if(!(t.length===0||!T(r)))return{ownerKey:t,region:r}},L=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},O=1e3,g=1e3,b=10,I=5e4,m=s=>h(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",I),c="__replica_state",u=new WeakSet,E=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${c} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -0,0 +1 @@
1
+ import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-CCCIulmn.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-A80W5VLt.mjs";import{param as le,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as de,GEO_DEFAULT_PRECISION as ue}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as N}from"./CURSOR_PREFIX-B1i1J8Zi.mjs";import{encodePartitionKey as Ee,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-DGlhcKKv.mjs";import{mayHoldProjectedValue as ye}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{serializeSqlValue as Z}from"./serializeSqlValue-B_-zaEWZ.mjs";const ge=(t,i)=>{if(!i.includes("."))return t[i];let f=t;for(const A of i.split(".")){if(f===null||typeof f!="object"||Array.isArray(f))return;f=f[A]}return f},pe=(t,i)=>`${t}__fts_${i}`,me="__text__",Q="__id__",he=1e3,Se=(t,i)=>i.document(t),W=(t,i)=>ge(t,i),Te=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",Re=(t,i,f)=>t!==void 0&&i!==void 0&&W(t,f.field)===W(i,f.field),Ae=(t,i)=>Se(Te(W(t,i.field)),ie(i.language)).slice(0,he),we=(t,i)=>Ae(t,i).join(" "),Fe=(t,i,f)=>[...t.partitionBy??[],...t.sortBy.map(S=>S.field),...t.where?Object.keys(t.where):[]].every(S=>i[S]===f[S]),x=t=>e.join(["__id__","__partition__",...t.sortBy.map((i,f)=>_e(f))].map(i=>e.identifier(i)),e`, `),ee=(t,i,f,A,S,y)=>{const c=Ee(f.partitionBy??[],y),C=f.sortBy.map(I=>Z(y[I.field]??null)),k=e.join([S,c,...C].map(I=>le(I)),e`, `);u(t,e`INSERT INTO ${e.identifier(i)} (${A}) VALUES (${k})`)},Oe=(t,i,f,A,S,y)=>{if(S&&y&&Fe(f,S,y))return;const c=X(i,f.name);S&&u(t,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${A}`),!(!y||f.where&&!Y(y,f.where))&&ee(t,c,f,x(f),A,y)},Be=t=>{const{broadcast:i,indexKeysFor:f,invalidateCache:A,recordCdc:S,schema:y,sql:c}=t,C=new Set,k=n=>y.tables[n]?.softDeleteMode?.field,I=new Set,j=(n,o)=>{const s=`${n}::${o.name}`;if(C.has(s))return;const l=z(n,o.name),$=o.by??[],d=k(n),_=new Map,m=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();for(const T of m){const E=q(T);if(!E||!N(E,d)||o.where&&!P(E,o.where))continue;const R=v($,E);J(_,R,o,E)}u(c,e`DELETE FROM ${e.identifier(l)}`);const w=Math.floor($e.boundParams/3),F=[..._];for(let T=0;T<F.length;T+=w){const E=F.slice(T,T+w),R=e.join(E.map(([r,a])=>e`(${r}, ${a.value}, ${a.count})`),e`, `);u(c,e`INSERT INTO ${e.identifier(l)} (${L}, ${h}, ${p}) VALUES ${R}`)}C.add(s)},oe=(n,o,s)=>{const l=o.by??[],$=o.field??"",d=[],_=(r,a)=>{const g=Z(a);g===null?d.push(e`${U(r)} IS NULL`):d.push(e`${U(r)} = ${g}`)};for(const r of l)_(r,s[r]??null);const m=k(n);m!==void 0&&_(m,null);for(const[r,a]of Object.entries(o.where??{}))_(r,a!==null&&typeof a=="object"&&!Array.isArray(a)?a.eq:a);const w=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,F=y.tables[n]?.shape[$];if(F&&ye(F)){const r=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}${w}`).toArray(),a=new Map;for(const g of r){const O=q(g);O&&J(a,"",o,O)}return{value:a.get("")?.value??null}}const T=ce(o.op),E=U($);return{value:u(c,e`SELECT ${e.raw(T)}(${E}) AS value FROM ${e.identifier(n)}${w}`).one().value??null}},ne=(n,o,s,l)=>{const $=z(n,o.name),{op:d}=o,_=o.field??"",m=r=>{u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r} AND ${p} <= 0`)},w=k(n),F=r=>!o.where||P(r,o.where),T=r=>N(r,w)&&F(r);l!==void 0&&d!=="count"&&F(l)&&b(l[_]);const E=s&&T(s)?s:void 0,R=l&&T(l)?l:void 0;if(!(!E&&!R)){if(d==="count"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=v(o.by??[],r);u(c,D($,g,a,a,e`${h} = ${h} + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(d==="sum"||d==="avg"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=b(r[_]);if(g===void 0)continue;const O=v(o.by??[],r);u(c,D($,O,a*g,a,e`${h} = COALESCE(${h}, 0) + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(E){const r=v(o.by??[],E),a=b(E[_]),g=u(c,e`SELECT ${h} AS value, ${p} AS count FROM ${e.identifier($)} WHERE ${L} = ${r}`).toArray()[0],O=(g?.count??0)-1;if(O<=0)u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r}`);else if(g&&a!==void 0&&g.value!==null&&a===g.value){const se=oe(n,o,E);u(c,e`UPDATE ${e.identifier($)} SET ${h} = ${se.value}, ${p} = ${O} WHERE ${L} = ${r}`)}else u(c,e`UPDATE ${e.identifier($)} SET ${p} = ${p} - 1 WHERE ${L} = ${r}`)}if(R){const r=v(o.by??[],R),a=b(R[_]);if(a===void 0)u(c,D($,r,null,1,e`${p} = ${p} + 1`));else{const g=d==="min"?"MIN":"MAX";u(c,D($,r,a,1,e`${h} = ${e.raw(g)}(COALESCE(${h}, excluded.${h}), excluded.${h}), ${p} = ${p} + 1`))}}}},te=n=>{for(const o of y.tables[n]?.aggregateIndexes??[])j(n,o)},H=(n,o,s)=>{for(const l of y.tables[n]?.aggregateIndexes??[])ne(n,l,o,s)},B=(n,o)=>{const s=`${n}::rank::${o.name}`;if(I.has(s))return;const l=X(n,o.name),$=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();u(c,e`DELETE FROM ${e.identifier(l)}`);const d=x(o);for(const _ of $){const m=q(_);!m||o.where&&!Y(m,o.where)||ee(c,l,o,d,m._id,m)}I.add(s)},re=n=>{for(const o of y.tables[n]?.rankIndexes??[])B(n,o)},K=(n,o,s,l)=>{for(const $ of y.tables[n]?.rankIndexes??[])Oe(c,n,$,o,s,l)},V=(n,o,s,l)=>{const $=y.tables[n]?.searchIndexes??[];if(!($.length===0||!fe(c)))for(const d of $){if(Re(l,s,d))continue;const _=pe(n,d.name);u(c,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier(Q)} = ${o}`),s&&u(c,e`INSERT INTO ${e.identifier(_)} (${e.identifier(me)}, ${e.identifier(Q)}) VALUES (${we(s,d)}, ${o})`)}},G=(n,o,s)=>{for(const l of y.tables[n]?.geoIndexes??[]){const $=ae(n,l.name);u(c,e`DELETE FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${o}`);const d=s?.[l.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:_,lng:m}=d,w=de({lat:_,lng:m},l.precision??ue);u(c,e`INSERT INTO ${e.identifier($)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${w}, ${_}, ${m})`)}}};return{ensureBackfilledForTable:te,ensureBackfilledIndex:j,ensureRankBackfilled:B,ensureRankBackfilledForTable:re,syncAggregates:H,syncCompanionsForInsert:(n,o,s)=>{V(n,o,s),G(n,o,s),H(n,void 0,s),K(n,o,void 0,s),A(n,o,s),S(n,o,"insert",s),i({indexKeys:f(n,s),key:o,op:"insert",row:s,table:n})},syncGeo:G,syncRanks:K,syncSearch:V}};export{pe as S,Ae as a,Be as c,we as d,ee as i,Q as l,x as r,me as y};
@@ -0,0 +1 @@
1
+ import{D as T}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as t}from"./runDrizzle-2ULFQR_k.mjs";const v=i=>`${T(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),n=r.lastIndexOf("/");return n===-1?r:r.slice(0,n)},S=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},a=(i,r)=>typeof i=="string"&&c(i)===c(r),o="__lunora_search_state",N=i=>{t(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{t(i,e`ALTER TABLE ${e.identifier(o)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{t(i,e`ALTER TABLE ${e.identifier(o)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}t(i,e`UPDATE ${e.identifier(o)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",R=(i,r)=>{const n=t(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(o)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(n[0]?.covered)},l=(i,r)=>{const d=t(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(o)} WHERE ${e.identifier("companion")} = ${r}`).toArray()[0];return d?{cursor:d.cursor??void 0,done:s(d.done),profile:d.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},O=(i,r,n,d,f)=>{const $=n??null,E=a(l(i,r).profile,f)?e`MAX(${e.identifier(o)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;t(i,e`INSERT INTO ${e.identifier(o)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${d?1:0}, ${f}, ${d?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${E}`)};export{o as S,R as a,v as c,S as l,N as m,l as r,O as w};
@@ -1 +1 @@
1
- import{createShardCtxDb as S}from"./NotUniqueError-C7gJLEay.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-BVaTptvb.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DiCqfU82.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-CrzPqmGP.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as S}from"./NotUniqueError-BdMwMt_A.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-BAJHxoe-.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DtD-pA0_.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-CrzPqmGP.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
@@ -1 +1 @@
1
- import{LunoraError as _}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as p}from"./wire-codec-UyQIjlyN.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{sqlComparableProjection as S}from"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";import"./serializeSqlValue-BBtrWwiu.mjs";const O=/^[A-Za-z_$][\w$]*$/u,b=e=>O.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",i="__originals__",R=e=>{if(Object.hasOwn(e,i))throw new _("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const c=S(a);c!==void 0&&(t??={...e},r??=Object.create(null),t[s]=c,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return $(n)?JSON.stringify(p(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},h=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},G=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${b(t).replaceAll("'","''")}')`,g=e=>E("",e),J=e=>o.raw(g(e)),N=(e,t)=>E(`${A(e)}.`,t),q=(e,t)=>o.raw(N(e,t)),B=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),y=o.identifier("__value__"),I=o.identifier("__count__"),z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${y}, ${I}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${f}) DO UPDATE SET ${s}`,d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),d.set(e,r),r},j=e=>{if(!e)return;const t=e[m];let r;typeof t=="string"?r=h(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},W=e=>{try{return j(e)}catch{return}},u=new WeakMap,k=e=>{const t=u.get(e);if(t!==void 0)return t;let r;try{l(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{l(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,r),r};export{I as A,m as D,f as a,y as b,z as c,B as d,J as e,q as f,G as g,W as h,k as i,g as j,R as k,h as l,b as m,i as n,N as q,j as r,F as t};
1
+ import{LunoraError as _}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as p}from"./wire-codec-UyQIjlyN.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{sqlComparableProjection as S}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import"./serializeSqlValue-B_-zaEWZ.mjs";const O=/^[A-Za-z_$][\w$]*$/u,b=e=>O.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",i="__originals__",R=e=>{if(Object.hasOwn(e,i))throw new _("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const c=S(a);c!==void 0&&(t??={...e},r??=Object.create(null),t[s]=c,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return $(n)?JSON.stringify(p(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},h=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},G=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${b(t).replaceAll("'","''")}')`,g=e=>E("",e),J=e=>o.raw(g(e)),N=(e,t)=>E(`${A(e)}.`,t),q=(e,t)=>o.raw(N(e,t)),B=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),y=o.identifier("__value__"),I=o.identifier("__count__"),z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${y}, ${I}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${f}) DO UPDATE SET ${s}`,d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),d.set(e,r),r},j=e=>{if(!e)return;const t=e[m];let r;typeof t=="string"?r=h(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},W=e=>{try{return j(e)}catch{return}},u=new WeakMap,k=e=>{const t=u.get(e);if(t!==void 0)return t;let r;try{l(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{l(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,r),r};export{I as A,m as D,f as a,y as b,z as c,B as d,J as e,q as f,G as g,W as h,k as i,g as j,R as k,h as l,b as m,i as n,N as q,j as r,F as t};
@@ -1 +1 @@
1
- import{BIGINT_KEY_DIGITS as c}from"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";const n=40,s=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=c+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{s as e};
1
+ import{BIGINT_KEY_DIGITS as c}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";const n=40,s=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=c+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{s as e};
@@ -0,0 +1 @@
1
+ import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";const f=200,p=(e,n)=>{const i=r=>{const o=e.tables[r];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(e.tables)).filter(r=>i(r))},u=async function*(e,n,i=f){let r=null,o=!1;for(;!o;){const t=await e.findMany(n,{cursor:r,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,o=t.isDone||r===null}},k=async function*(e,n,i){const r=p(n,i.tables),o=i.batchSize??f;for(const t of r)yield*u(e,t,o)},y=new Set(["_creationTime","_id"]),h=(e,n)=>{for(const[i,r]of Object.entries(e.shape)){const o=n[i];if(o===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(e,n,i)=>{const r=e.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(o))if(!Object.hasOwn(r.shape,t))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,o)},g=async(e,n)=>{try{return await e.get(n)!==null}catch{return!1}},w=e=>l in e?Object.fromEntries(Object.entries(e).filter(([n])=>n!==l)):e,A=async(e,n,i,r)=>{const{table:o}=i;let{doc:t}=i;if(typeof o!="string"||o.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:o},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:o},kind:"error"};t=w(t);const s=m(n,o,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:o},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0&&await g(e,c))return{kind:"conflict"};try{return await e.insert(o,t,{allowExplicitId:!0}),{kind:"inserted",table:o}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:o},kind:"error"}}},O=async(e,n,i)=>{const r=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await A(e,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:r,inserted:o}},v=e=>{const n=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:n}},R=e=>{const n=Array.isArray(e.rows)?e.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{rows:i,startLine:r}};export{k as exportShardRows,O as importShardRows,v as parseExportShardArgs,R as parseImportShardArgs,p as selectExportTables,m as validateImportRow};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-DDXDqsGW.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-a5CvNwTW.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -1 +1 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-Cva29kfS.mjs";import{selectShapeRows as m}from"./selectShapeMembers-CPdl1Ht1.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-DVUFJikx.mjs";import{selectShapeRows as m}from"./selectShapeMembers-9Jz7ec_-.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-QC15-pzG.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-CCCIulmn.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-vSnbgww7.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-DVUFJikx.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-B4bmET4W.mjs";import{m as X}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as G}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as M,d as E,e as g,t as F,i as B,g as y,a as Y,b as k,A as u}from"./do-sql-A80W5VLt.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as P}from"./appendStreamChunk-8eH4HB1Q.mjs";import{rankTableName as w,sortColumnName as j}from"./RANK_TIEBREAK-DGlhcKKv.mjs";import{migrateReactorState as K}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const A=e`_creationTime, id`,H=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(v("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(S=>e`${S} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},W=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${A}`;H(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of F(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},z=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!B(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},J=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Q=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},Z=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=w(o,r.name),s=r.sortBy.map((_,c)=>j(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Se=(i,o,n={})=>{n.schemaSnapshot!==void 0&&V(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),X(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${e.identifier(M)} TEXT NOT NULL
5
+ )`),a(i,E(`${r}__by_creation`,r,A,!1)),W(i,r,t),z(i,r,t),J(i,r,t),Q(i,r,t),Z(i,r,t));n.cdc&&(O(i),x(i),C(i),G(i),D(i)),Object.values(o.tables).some(r=>r.commitOrderedMode===!0)&&$(i),K(i),b(i),U(i),P(i)};export{Se as runShardMigrations};
@@ -1 +1 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-qxXsaO03.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-A80W5VLt.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
@@ -1 +1 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-qxXsaO03.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-B1l5NcUZ.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BBtrWwiu.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-A80W5VLt.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-B1l5NcUZ.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-B_-zaEWZ.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
@@ -0,0 +1 @@
1
+ import{sqlComparableProjection as o}from"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.52",
3
+ "version": "1.0.0-alpha.53",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -48,8 +48,8 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": "1.0.0-alpha.29",
52
- "@lunora/platform": "1.0.0-alpha.24",
51
+ "@lunora/errors": "1.0.0-alpha.30",
52
+ "@lunora/platform": "1.0.0-alpha.25",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
55
55
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";import{t as s}from"./base64-DfpzS4o_.mjs";const e=n=>{if(n.kind!=="optional")return n.kind;const t=n._meta?.inner;return t?e(t):n.kind},i=39,g="0",d="1",E=n=>{const t=n<0n,r=(t?-n:n).toString();if(r.length>i)throw new c("BAD_REQUEST",`bigint ${n.toString()} has ${String(r.length)} digits, over the ${String(i)}-digit limit for a queryable column`);const o=r.padStart(i,"0");return t?g+Array.from(o,f=>String(9-Number(f))).join(""):d+o},N=n=>typeof n=="bigint"?E(n):n instanceof ArrayBuffer?s(new Uint8Array(n)):ArrayBuffer.isView(n)?s(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)):void 0,m=n=>{const t=e(n);return t==="bigint"||t==="bytes"},b=n=>{const t=e(n);return m(n)||t==="any"||t==="union"||t==="from"};export{i as BIGINT_KEY_DIGITS,g as BIGINT_KEY_NEGATIVE,d as BIGINT_KEY_NON_NEGATIVE,E as bigintSqlKey,m as isProjectedKind,b as mayHoldProjectedValue,N as sqlComparableProjection};
@@ -1,5 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";const l="x",g={'"':'"',"'":"'","[":"]","`":"`"},h=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
2
- `;)e+=1;return e},m=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},E=n=>{const t=n.split("");let e=0;for(;e<n.length;){const s=n[e]??"",c=g[s];if(s==="-"&&n[e+1]==="-"){const o=h(n,e);t.fill(l,e,o),e=o}else if(s==="/"&&n[e+1]==="*"){const o=m(n,e);if(o===-1)return;t.fill(l,e,o),e=o}else if(c!==void 0){let o=e+1;for(;o<n.length;)if(n[o]!==c)o+=1;else if(c!=="]"&&n[o+1]===c)o+=2;else break;if(o>=n.length)return;t.fill(l,e,o+1),e=o+1}else e+=1}for(let s=0;s<n.length;s+=1)n[s]===`
3
- `&&(t[s]=`
4
- `);return t.join("")},L=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,S=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,p=/^\w+/u,A=/;\s*$/u,x=/\s/u,N=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
5
- `;)e+=1;return e},y=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},O=n=>{let t=0;for(;t<n.length;){const e=n[t];if(e!==void 0&&x.test(e))t+=1;else if(e==="-"&&n[t+1]==="-")t=N(n,t);else if(e==="/"&&n[t+1]==="*"){const s=y(n,t);if(s===-1)break;t=s}else break}return t},f=n=>{const t=O(n),e=n.slice(t).trimEnd();if(e==="")return{code:"SQL_EMPTY",message:"the query is empty"};const s=e.replace(A,""),c=(E(s)??s).indexOf(";");if(c!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+c};const o="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!L.test(s))return{code:"SQL_NOT_READONLY",length:p.exec(s)?.[0].length??1,message:o,offset:t};const r=S.exec(s);if(r!==null)return{code:"SQL_NOT_READONLY",length:r[0].length,message:`${o} (\`${r[0].toUpperCase()}\` is not allowed)`,offset:t+r.index}},d=1e3,T=n=>{const t=f(n);if(t!==void 0)throw new u(t.code,t.message,{status:400})},b=(n,t)=>{T(t);const e=n.exec(t).toArray(),s=e.length>d?e.slice(0,d):e;return{columns:s.length>0?Object.keys(s[0]):[],rowCount:e.length,rows:s,truncated:e.length>d}},_=/near "([^"]*)": syntax error/iu,R=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,w=(n,t)=>{if(t==="")return{};const e=n.indexOf(t);return e===-1?{}:{length:t.length,offset:e}},v=(n,t)=>{const e=f(t);if(e!==void 0)return{diagnostics:e.code==="SQL_EMPTY"?[]:[{length:e.length,message:e.message,offset:e.offset,severity:"error",source:"gate"}],plan:[]};let s;try{s=n.exec(`EXPLAIN QUERY PLAN ${t}`).toArray().map(r=>{const{detail:i}=r;return typeof i=="string"?i:""}).filter(r=>r!=="")}catch(r){const i=r instanceof Error?r.message:String(r),a=_.exec(i);return{diagnostics:[{...a?w(t,a[1]??""):{},message:i,severity:"error",source:"syntax"}],plan:[]}}const c=[],o=new Set;for(const r of s){const i=R.exec(r);if(i){const a=i[1]??"";o.has(a)||(o.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:s}};export{d as MAX_SQL_ROWS,T as assertReadonly,v as lintReadonlySql,b as runReadonlySql};
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{c as ln,q as it,S as un,l as Me,a as fn}from"./ctx-db-companions-CTabzjgb.mjs";import{sql as i}from"drizzle-orm";import{d as hn}from"./wire-codec-UyQIjlyN.mjs";import{throwingScheduler as wn,aggregateSqlFunction as De,normalizeCountArgument as pn}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Qe,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-CCCIulmn.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Ve,selectIndexForGroupBy as gn,selectIndexForCount as $n,selectIndexForAggregate as yn}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as En,searchIndexCoversTable as mn}from"./backfillAggregateIndexes-BCmY3OYO.mjs";import{backfillAggregateIndexes as yr,backfillRankIndexes as Er,backfillSearchIndexes as mr}from"./backfillAggregateIndexes-BCmY3OYO.mjs";import{appendCdcChange as Sn}from"./CDC_LOG_TABLE-Cva29kfS.mjs";import{CDC_LOG_TABLE as _r,applyCdcChanges as Rr,bumpCdcEpoch as Tr,cdcCanVouchFor as vr,cdcSeqLeavingRows as Ar,cdcTouchesTables as Ir,cdcTrimmedError as Cr,compactCdcDocs as xr,cursorBelowRetainedFloor as br,minCdcReplayableSeq as Mr,minCdcSeq as Dr,readCdcChangeKeys as kr,readCdcChanges as Lr,readCdcCursor as Fr,readCdcEpoch as qr,trimCdcChanges as Wr}from"./CDC_LOG_TABLE-Cva29kfS.mjs";import{allocateCommitSeq as _n,COMMIT_SEQ_FIELD as Rn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as St}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as _t}from"./computeRankPage-CuWuhRZN.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ce,r as le,b as ke,A as Ye,a as Le,e as X,t as Ot,j as We,q as Rt,i as Tn,h as jt,g as vn}from"./do-sql-qxXsaO03.mjs";import{renderSql as Kt,unionAll as st,WORKERD_SQLITE_LIMITS as Qt,sqliteInList as An}from"./param-DlozcSQu.mjs";import{coveringGeohashes as In,boundingBoxGeohashes as Cn,haversineMeters as xn,pointInBoundingBox as bn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Mn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as tt,buildSeekWhere as zt,decodeCursor as nt,applySelect as Tt,encodeCursor as ot,tiebreakDirectionFor as Jt,buildSeekBeforeWhere as Dn}from"./CURSOR_PREFIX-B1i1J8Zi.mjs";import{rankTableName as vt,sortColumnName as At,resolveRankPartition as kn,encodePartitionKey as Ln,RANK_TIEBREAK as Fn}from"./RANK_TIEBREAK-BXD4YaG3.mjs";import{UNVOUCHABLE_DEP as It}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as qn,buildIndexRange as Wn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Xe,resolveRelationPredicates as Ct}from"./DEFAULT_MAX_RELATION_KEYS-BbmpfQE4.mjs";import{runRowValidators as Ze,resolveWith as xt,relationHooks as bt,applyOnDelete as Bn,fanOutScalarCounts as Un}from"./applyOnDelete-CeHLU-Hh.mjs";import{guardWriter as Pn}from"./RLS_UNWRAP_SYMBOL-CepZvBVl.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{isProjectedKind as Gn}from"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";import{createSystemReader as Hn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Nn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ue,r as Be,j as Ee,i as Mt}from"./where-sql-B1l5NcUZ.mjs";import{CLIENT_WATERMARK_TABLE as Ur,advanceClientWatermark as Pr,migrateClientWatermark as Gr,readClientWatermark as Hr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Or,deleteGlobalShapeSnapshot as jr,deleteGlobalShapeSnapshotsForConnection as Kr,migrateGlobalShapeSnapshot as Qr,readGlobalShapeSnapshot as zr,writeGlobalShapeSnapshot as Jr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Yr,readIdempotent as Xr,trimIdempotent as Zr,writeIdempotent as ei}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as ni}from"./runShardMigrations-DiCqfU82.mjs";import{SEARCH_STATE_TABLE as ri}from"./SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{selectShapeMembers as si,selectShapeRows as ci}from"./selectShapeMembers-CPdl1Ht1.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-BBtrWwiu.mjs";const On=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},jn=()=>new $("BAD_REQUEST","invalid cursor"),Dt=16,kt=8,Y=1024,ct=(o,r)=>r.query(o),Kn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},Qn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},zn=(o,r,t)=>{const a={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),a},search:(d,p)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=ct(p,t).length;if(S>Dt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Dt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=p,E.hasQuery=!0,a}};return a},Jn=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Vn=o=>Math.min(o.offset+o.numItems+1,Y),Yn=o=>btoa(`search:${String(o)}`),Xn=o=>{let r;try{r=On(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Zn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Xn(o.cursor):0;if(t===void 0)throw jn();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},eo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?Yn(t):null,isDone:!a,page:o.slice(r.offset,t)}},to=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Pe=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Se(t));return r.set(t,d),d}},ue=Se(oe),no=Pe(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Lt=Pe(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),oo=Pe(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),ro=Pe(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),io="SELECT changes() AS changed",Ft=new Map,so="",co=o=>{const r=JSON.stringify(o),t=Ft.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(p)} WHERE id = ${so}`),{sql:d}=Kt("sqlite",i`${st(a)} LIMIT 1`);return Ft.set(r,d),d},ao=(o,r)=>r.map(()=>o),lo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,uo=o=>{if(!lo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},qt=50,Vt=500,Fe=Math.floor(Qt.boundParams/3),ge=Qt.boundParams,fo=128,ae=(o,r,t)=>{const a=r??Vt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},ho=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},wo=o=>Math.max(o,Y),Yt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},po=(o,r,t,a,d)=>{const p=ct(t.query,it(t.definition.language));if(p.length===0)return[];const E=un(r,t.indexName),S=`${E}__vocab`,_=p.length-1,D=p.map((R,k)=>{const W=Qn(R,k===_),K=W.exact?i`${i.identifier("term")} = ${W.lower}`:i`${i.identifier("term")} >= ${W.lower} AND ${i.identifier("term")} < ${W.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(k))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${K} GROUP BY ${i.identifier("doc")}`}),y=p.map((R,k)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(k))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${st(D)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(y.map(R=>i`${R} > 0`),i` AND `)}`,v=Yt(t,d);let F=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;v.length>0&&(F=i`${F} WHERE ${i.join(v,i` AND `)}`),F=i`${F} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const j=[];for(const R of O(o,F)){const k=jt(R);if(k){const W=R.__score__;j.push({document:k,score:typeof W=="number"?W:Number(W??0)})}}return j},go=(o,r,t,a,d)=>{const p=it(t.definition.language),E=ct(t.query,p);if(E.length===0)return[];const S=Yt(t,d);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(wo(a)))}`;const D=O(o,_).toArray(),y=[];for(const A of D){const v=jt(A);if(!v)continue;const F=Kn(fn(v,t.definition),E);F>0&&y.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:F})}return y.sort((A,v)=>v.score-A.score||v.creationTime-A.creationTime||A.id.localeCompare(v.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},et=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},$o=(o,r)=>{const t=o,a={near:(d,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(et(d,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(et(d.sw,".within() sw corner",r,t.indexName),et(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},yo=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},Eo=(o,r)=>{const t=yo(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=xn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return bn(t,r.within)?{creationTime:a,distance:0}:void 0},mo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?In(t.near.point,t.near.radiusMeters):Cn(t.within),p=vn(r,t.indexName),E=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,D=O(o,_).toArray(),y=[];for(const A of D){const v=le(A),F=v?Eo(v,t):void 0;v&&F&&y.push({creationTime:F.creationTime,distance:F.distance,doc:v})}return y.sort((A,v)=>A.distance-v.distance||v.creationTime-A.creationTime),y},Xt=(o,r,t,a)=>{const d=[];for(const p of o)if(r.every(E=>E(a(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},So=(o,r,t,a,d,p=()=>{})=>{const E=t.within!==void 0,S=mo(o,r,t,d).map(_=>({distanceMeters:E?null:_.distance,document:_.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Zt=(o,r,t,a,d,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,_=So(o,r,E,S?void 0:d,a,p);return S?Xt(_,t.inMemoryFilters,d,D=>D.document):_},en=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Se(oe)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Be(`${d} ${p}`):Ee(`${d} WHERE `,r,` ${p}`)},_o=(o,r,t,a,d,p=()=>{})=>Zt(o,r,t,a,d,p).map(E=>E.document),Ro=(o,r,t,a,d,p,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${X(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&S.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const D=O(o,_).toArray();E(D.length);const y=[];for(const A of D){const v=le(A);if(v&&t.inMemoryFilters.every(F=>F(v))&&(y.push(v),typeof p=="number"&&y.length>=p))break}return y},$e={fieldRef:X,serialize:re},tn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Gn(t)},Wt=(o,r)=>r.some(t=>tn(o,t)),Bt=(o,r,t)=>{if(tn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},at={fieldRef:o=>Be(We(o)),serialize:re},To=o=>{let r=0;const t=[],a={fieldRef:d=>Be(We(d)),relationExists:d=>{const{childWhere:p,negated:E,parentTable:S,relation:_}=d,D=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(_.table,G);const A=_.kind==="one"?_.field:_.references,v=_.kind==="one"?_.references:_.field,F=Be(`${Rt(D,v)} = ${Rt(y,A)}`);t.push(D);const j=ne(p,a,Ue);t.pop();const R=j===void 0?F:Ee(F," AND ",j),k=Ee("EXISTS (SELECT 1 FROM ",Mt(_.table)," AS ",Mt(D)," WHERE ",R,")");return E?Ee("NOT ",k):k},serialize:re};return a},nn=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${Jt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},vo=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Jt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Ao={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Io=o=>{const r=new Set(o.sqlConditions.filter(a=>a.comparator==="=").map(a=>a.field));let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},on=(o,r)=>{const t=o.order,a=Io(o);return a.length>0?tt(a.map(d=>({[d]:t})),r):tt([{_creationTime:t}],r)},Co=(o,r,t,a)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Ao[p.comparator]??"eq"]:p.value}}));if(t&&d.push(zt(r,nt(t))),a&&d.push(Dn(r,nt(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},xo=(o,r,t)=>{const a=[];for(const d of o){const p=le(d);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},bo=(o,r,t,a,d,p,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),_=on(a,t),D=typeof d.endCursor=="string",y=ne(Co(a,_,d.cursor,d.endCursor),at,Ue),A=p&&y?Ee(y," AND ",p):p??y,v=a.inMemoryFilters.length>0,F=en(r,A,nn(_),v||D?void 0:S+1),j=me(o,F.text,...F.params).toArray();E(j.length);const R=xo(j,a.inMemoryFilters,v||D?void 0:S);if(D){const N=R.length>=2?R[Math.floor(R.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:R,splitCursor:N?ot(N,_):null}}const k=R.length>S,W=k?R.slice(0,S):R,K=W.at(-1);return{continueCursor:k&&K?ot(K,_):null,isDone:!k,page:W}};class Mo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Do=/\s/u,ko=String.fromCodePoint(0),Ut=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Do.test(t)||t.includes(ko)?null:t},Lo=(o,r,t,a=()=>{},d=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),_=S?ne(S,$e):void 0,D=S?ne(S,at,Ue):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const v=m=>{const{search:C}=y;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");En(o,t,E);const M=y.inMemoryFilters.length>0,L=to(M?void 0:m),H=Tn(o);if(H&&!mn(o,t,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const Z=H?po(o,t,C,L,_):go(o,t,C,L,_);return M?(A=Z.length,Xt(Z,y.inMemoryFilters,m,Ge=>Ge.document)):(m===void 0&&Jn(Z),Z)},F=m=>v(m).map(C=>C.document),j=m=>{const C=Zn(m);return eo(F(Vn(C)),C)},R=()=>vo(on(y,E.shape)),k=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(Wn(t,y.indexName,y.indexFields,y.sqlConditions,re))},W=m=>{k();let C=0;const M=(()=>{if(y.search){const L=F(m);return C=A,L}return y.geo?_o(o,t,y,_,m,L=>{C=L}):Ro(o,t,y,_,R(),m,L=>{C=L})})();return p(Math.max(C,M.length)),M},K=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);k();let m=0;const C=(()=>{if(y.search){const M=v(void 0);return m=A,M}return Zt(o,t,y,_,void 0,M=>{m=M})})();return p(Math.max(m,C.length)),C},N={async*[Symbol.asyncIterator](){if(y.search){yield*W(void 0);return}const m=[...y.inMemoryFilters];let C;y.inMemoryFilters=[];try{for(;;){const M=await N.paginate({cursor:C??null,numItems:fo});for(const L of M.page)m.every(H=>H(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;C=M.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return W(void 0)},async collectWithScores(){return K()},filter(m){return y.inMemoryFilters.push(m),N},async first(){return W(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",N},async paginate(m){let C=0;if(k(),y.search){const L=j(m);return p(L.page.length),L}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=bo(o,t,E.shape,y,m,D,L=>{C=L});return p(Math.max(C,M.page.length)),M},async take(m){return W(m)},async unique(){const m=W(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Mo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const M=(E.geoIndexes??[]).find(H=>H.name===m);if(!M)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const L={definition:M,indexName:m};if(y.geo=L,C($o(L,t)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(m,C){const M=E.indexes.find(L=>L.name===m);if(!M)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=M.fields,C&&C(ho(y)),N},withSearchIndex(m,C){const M=(E.searchIndexes??[]).find(H=>H.name===m);if(!M)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=L,C(zn(L,t,it(M.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return N}};return N},Pt=(o,r,t)=>{const a={...r};for(const[d,p]of Ot(o)){if(p.serverDefault){a[d]=p.serverDefault({auth:t});continue}a[d]===void 0&&(p.defaultFn?a[d]=p.defaultFn():"defaultValue"in p&&(a[d]=p.defaultValue))}return a},Gt=(o,r,t,a)=>{const d=t;for(const[p,E]of Ot(o)){if(E.serverDefault){p in r&&(d[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(d[p]=E.onUpdateFn())}},Ht=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Fo=/unique constraint failed/i,qo=o=>o instanceof Error&&Fo.test(o.message),rt=(o,r,t,a)=>{try{me(o,t,...a)}catch(d){throw qo(d)?new ye(`unique constraint violation on "${r}"`,"unique"):d}},qe=(o,r,t,a)=>{if(rt(o,r,t,a),me(o,io).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,p,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const v=[];for(let k=0;k<A;k+=1)v.push(i`${i.identifier(t[k])} IS ${p[k]}`);const F=t[A],j=a[A];if(F!==void 0&&j!==void 0){const k=j.direction==="desc"?">":"<";v.push(i`${i.identifier(F)} ${i.raw(k)} ${p[A]}`)}else v.push(i`${i.identifier(Fn)} < ${E}`);const[R]=v;S.push(v.length===1&&R!==void 0?R:i`(${i.join(v,i` AND `)})`)}const _=i.join(S,i` OR `),D=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${_})`).one(),y=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:D.c,total:y.c}},pr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!p())&&(d=_n(r)),{[Rn]:d}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...qn(s,h,re));return f.length>0?f:void 0},{headroom:_}=o;let D=!1;const y=async e=>{const n=D;D=!0;try{return await e()}finally{D=n}},A=o.onRead??(()=>{}),v=e=>{St(t.tables[e])&&A(It,It)},F=o.onReadRange??(e=>{A(e.table,G)}),j=e=>{v(e.table),F(e)},R=(e,n)=>{n!==void 0&&n!==G&&!D&&_?.recordRead(1),v(e),A(e,n)},k=o.onIndexUse??(()=>{}),W=o.onWrite??(()=>{}),K=e=>{D||_?.recordWrite(e)},N=async e=>{K(e.doc),await W(e)},{cache:m}=o,C=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??wn,{globalDb:H}=o,Z=o.auth??{identity:null,userId:null},Ge=o.cdc??!1,He=L,rn=Hn({scheduler:typeof He.list=="function"&&typeof He.get=="function"?He:void 0,storage:o.storage}),fe=(e,n,s,f)=>{Ge&&!St(t.tables[e])&&Sn(r,C(),e,n,s,f)},se=e=>t.tables[e]?.shardMode?.kind==="global",dt=(e,n)=>{if(se(e)){if(!H)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return H}return B},Ne=e=>dt(e,"cascade"),z=(e,n)=>{if(se(e)){if(!H)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return H}},lt=async(e,n,s,f,h)=>{h&&K(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},Oe=(e,n)=>dt(e,"relation load").findMany(e,n),ut=(e,n)=>(se(e)&&R(e,G),Oe(e,n)),sn=e=>!se(e.table),ft=o.relationExistsPushDown??"auto",ht=ft!=="never",{maxRelationKeys:wt}=o,_e=(e,n,s)=>Ct(e,{fetcher:ut,maxRelationKeys:wt,relationBaseWhere:s,schema:t,tableName:n}),pt=async(e,n,s,f)=>{const h=z(e,"relation grouped count");if(h)return R(e,G),Un((q,I)=>h.count(q,I),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);R(e,G);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},w=J(J(l,f),c),T=await _e(w,e,void 0),g=ne(T,$e),b=X(n);let x=i`SELECT ${b} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${b}`;const U=O(r,x).toArray();return new Map(U.map(q=>[q.__fk__,q.count]))};let Re=0;const gt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))gt.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>gt.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(Re+=1,Re>qt)throw Re-=1,new ye(`trigger recursion exceeded ${String(qt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Nn({ctx:an,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Re-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:je,ensureRankBackfilled:Ke,ensureRankBackfilledForTable:we,syncAggregates:Te,syncCompanionsForInsert:$t,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=ln({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>m?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),yt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Et=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ie=(e,n)=>{const s=Et(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[u]=me(r,co(h),...ao(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const w=u[oe];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},cn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=Et(n);for(let u=0;u<h.length;u+=ge){const c=h.slice(u,u+ge),l=Math.floor(ge/c.length),w=An(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of O(r,st(T))){const{id:b,__t__:x}=g;typeof x=="string"&&typeof b=="string"&&f.set(b,x)}}return f},mt={assertRankPartitionLocal:yt,ensureRankBackfilled:Ke,onRead:R,rowToDocument:le,schema:t,sql:r},B={system:rn,async aggregate(e,n){const s=z(e,"aggregate");if(s)return R(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,G);const h=de(f.softDeleteMode,void 0),u=J(J(n.baseWhere,n.where),h),c=await _e(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const q=yn(f.aggregateIndexes,n.op,n.field,n.where);if(q){je(e,q.index);const I=ze(q.index.by??[],q.key),Q=Qe(e,q.index.name),V=O(r,i`SELECT ${ke} AS value, ${Ye} AS count FROM ${i.identifier(Q)} WHERE ${Le} = ${I}`).toArray()[0];return Je(n.op,V)}}Bt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=ne(c,$e),T=De(n.op),g=X(n.field);let b=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(b=i`${b} WHERE ${w}`);const U=O(r,b).toArray()[0]?.value;return U??null},asId(e,n){const s=Ut(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return R(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=pn(n);if(h.restrictsCounts)throw new Ve(e);R(e,G);const u=de(f.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),u),l=await _e(c,e,h.relationBaseWhere),w=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const x=$n(f.aggregateIndexes,h.where);if(x){je(e,x.index);const U=ze(x.index.by??[],x.key),q=Qe(e,x.index.name),I=O(r,i`SELECT ${ke} AS value FROM ${i.identifier(q)} WHERE ${Le} = ${U}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=ne(l,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),O(r,g).one().count},async delete(e,n,s){const f=ie(e,n);if(!f){const g=n===void 0?H:void 0;g&&(K(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],w=s?.hard===!0,T=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Bn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,b,x)=>(await Ne(g).findMany(g,{includeDeleted:w,where:{[b]:x}})).page,onCascade:(g,b)=>Ne(g).delete(b,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,b,x)=>Ne(g).patch(b,{[x]:null}),schema:t,tableName:c}),he(c),we(c),T){const g={...u,...E(c),[T]:C(),_id:e};qe(r,c,Lt(c),[ce(g),e,h]),Ae(c,e,g,u),ve(c,e,void 0),Te(c,u,g),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await N({id:e,op:"delete",table:c});return}qe(r,c,ro(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Te(c,u,void 0),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Vt),f=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await B.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await B.delete(w,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const f of e)await B.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(z(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),B.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(u,s)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await B.findFirst(e,n);if(s===null)throw new Mn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return R(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,G):R(e);const u=tt(n.orderBy,f.shape),c=n.cursor?zt(u,nt(n.cursor)):void 0;let l=J(n.baseWhere,n.where);l=J(l,de(f.softDeleteMode,n.includeDeleted)),l=await Ct(l,{canPushExists:ht?sn:void 0,existsPushMode:ft==="always"?"always":"auto",fetcher:ut,maxRelationKeys:wt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=ht?To(R):at,T=ne(l,w,Ue),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,b=en(e,T,nn(u),g===void 0?void 0:g+1),x=me(r,b.text,...b.params).toArray();h&&!D&&_?.recordRead(x.length);const U=[];for(const V of x){const P=le(V);P&&(U.push(P),!h&&typeof P._id=="string"&&R(e,P._id))}if(g===void 0)return n.with&&await xt({groupedCounter:pt,fetcher:Oe,parents:U,...bt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:Tt(U,n.select,n.with)};const q=U.length>g,I=q?U.slice(0,g):U,Q=I.at(-1);return n.with&&await xt({fetcher:Oe,groupedCounter:pt,parents:I,...bt(n),schema:t,tableName:e,with:n.with}),{continueCursor:q&&Q&&n.omitContinueCursor!==!0?ot(Q,u):null,isDone:!q,page:Tt(I,n.select,n.with)}},async get(e,n){const s=ie(e,n);if(!s){const f=n===void 0?H:void 0;return f?f.get(e):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=ie(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return R(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);R(e,G);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),u),l=await _e(c,e,n.relationBaseWhere),w=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||Wt(f,T))){const I=gn(f.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(Q===0||Q===V)){je(e,I.index);const P=Qe(e,I.index.name),Ie=Object.keys(I.partial),Ce=[];if(Ie.length===(I.index.by??[]).length&&Ie.length>0){const xe=ze(I.index.by??[],I.partial),be=O(r,i`SELECT ${ke} AS value, ${Ye} AS count FROM ${i.identifier(P)} WHERE ${Le} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...I.partial},value:Je(h.op,be[0])}),Ce}const dn=O(r,i`SELECT ${Le} AS key, ${ke} AS value, ${Ye} AS count FROM ${i.identifier(P)}`).toArray();for(const xe of dn){const be=hn(JSON.parse(xe.key));Ce.push({key:be,value:Je(h.op,xe)})}return Ce}}for(const I of T){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Bt(f,I,Q)}const g=ne(l,$e),b=n.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")b.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);b.push(i`${i.raw(De(h.op))}(${X(I)}) AS value`)}let x=i`SELECT ${i.join(b,i`, `)} FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${i.join(n.by.map(I=>X(I)),i`, `)}`;const U=O(r,x).toArray(),q=[];for(const I of U){const Q={};for(const P of n.by)Q[P]=I[P]??null;const{value:V}=I;q.push({key:Q,value:V==null?null:Number(V)})}return q},async insert(e,n,s){const f=z(e,"insert");if(f)return lt(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Pt(h,n,Z);Ze(h,u);let c;s?.clientId!==void 0?(uo(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=M();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:C(),w={...u,...E(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),rt(r,e,no(e),[c,l,ce(w)]),$t(e,c,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:c,op:"insert",table:e}),await N({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=z(e,"insert");if(f){const l=[];for(const w of n)K(w);for(const w of n){const T=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...w,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=Fe)u.push(E(e));const c=n.map((l,w)=>{const T=Pt(h,l,Z),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:M(),b=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:C(),x={...T,...u[Math.floor(w/Fe)],_creationTime:b,_id:g};return{creationTime:b,document:x,id:g}});for(const l of c)K(l.document);for(let l=0;l<c.length;l+=Fe){const w=i.join(c.slice(l,l+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),T=Kt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${w}`);rt(r,e,T.sql,T.params)}for(const{document:l,id:w}of c)$t(e,w,l),await W({doc:l,id:w,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=z(e,"insert");if(u)for(const l of n)K(l);const c=async l=>u?lt(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Ut(t,e,n)},async patch(e,n,s){const f=ie(e,s);if(!f){const T=s===void 0?H:void 0;if(T){K(n),await T.patch(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);R(c,e),Ht("patch",n);const w={...u,...n,...E(c),_id:e};Gt(l,n,w,Z),Ze(l,w,!0),ee(c,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),qe(r,c,Lt(c),[ce(w),e,h]),Ae(c,e,w,u),ve(c,e,w),Te(c,u,w),pe(c,e,u,w),m?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),ee(c,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await B.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(z(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),B.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(u,s),{patched:u.length}},query(e){const n=z(e,"query");return n?(R(e,G),n.query(e)):Lo(r,t,e,k,s=>{s?j(s):R(e,G)},s=>{D||_?.recordRead(s)})},async rank(e,n,s){const f=z(e,"rank");if(f)return R(e,G),f.rank(e,n,s);k(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(P=>P.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(yt(e,h,u),s.restrictsCounts)throw new Ve(e);R(e,G),Ke(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=vt(e,u.name),w=u.sortBy.map((P,Ie)=>At(Ie)),T=w.map(P=>Se(P)).join(", "),g=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[b]=g;if(b===void 0)return null;let x=b.__partition__;const U=J(s.baseWhere,s.where);Xe(U,t,e,"rank");const q=kn(u,U);if(q){const P=Ln(u.partitionBy??[],q);if(P!==x)return null;x=P}const I=w.map(P=>b[P]),{before:Q,total:V}=Nt(r,l,w,u.sortBy,x,I,c);return{position:Q+1,total:V}},async rankBefore(e,n,s){if(se(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ve(e);R(e,G),Ke(e,h);const u=vt(e,h.name),c=h.sortBy.map((w,T)=>At(T)),l=h.sortBy.map((w,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Xe(J(s.baseWhere,s.where),t,e,"rankPage");const f=z(e,"rankPage");if(f)return R(e,G),f.rankPage(e,n,s);k(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=_t(mt,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Xe(J(s.baseWhere,s.where),t,e,"rankPage"),k(e,n,"rank");const{directions:f,hasMore:h,rows:u}=_t(mt,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=ie(e,n);if(!s){const u=n===void 0?H:void 0;if(u?.restore){await u.restore(e);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await B.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=ie(e,s);if(!h){const b=s===void 0?H:void 0;if(b){K(n),await b.replace(e,n,void 0,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Ht("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:C(),g={...n,...E(l),_creationTime:T,_id:e};Gt(w,n,g,Z),Ze(w,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),qe(r,l,oo(l),[T,ce(g),e,u]),Ae(l,e,g,c),ve(l,e,g),Te(l,c,g),pe(l,e,c,g),m?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await N({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=B;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},an={db:B,scheduler:L};return o.enforceRls===!0?Pn(B,t,(e,n)=>ie(e,n)?.tableName,(e,n)=>cn(e,n)):B};export{_r as CDC_LOG_TABLE,Ur as CLIENT_WATERMARK_TABLE,Or as GLOBAL_SHAPE_SNAPSHOT_TABLE,Yr as IDEMPOTENCY_TABLE,Mo as NotUniqueError,ri as SEARCH_STATE_TABLE,Pr as advanceClientWatermark,Rr as applyCdcChanges,Ht as assertNoExplicitUndefined,uo as assertValidClientId,yr as backfillAggregateIndexes,Er as backfillRankIndexes,mr as backfillSearchIndexes,Tr as bumpCdcEpoch,vr as cdcCanVouchFor,Ar as cdcSeqLeavingRows,Ir as cdcTouchesTables,Cr as cdcTrimmedError,xr as compactCdcDocs,pr as createShardCtxDb,br as cursorBelowRetainedFloor,jr as deleteGlobalShapeSnapshot,Kr as deleteGlobalShapeSnapshotsForConnection,Gr as migrateClientWatermark,Qr as migrateGlobalShapeSnapshot,Mr as minCdcReplayableSeq,Dr as minCdcSeq,Ut as normalizeIdStructurally,kr as readCdcChangeKeys,Lr as readCdcChanges,Fr as readCdcCursor,qr as readCdcEpoch,Hr as readClientWatermark,zr as readGlobalShapeSnapshot,Xr as readIdempotent,ni as runShardMigrations,si as selectShapeMembers,ci as selectShapeRows,Wr as trimCdcChanges,Zr as trimIdempotent,Jr as writeGlobalShapeSnapshot,ei as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as w}from"@lunora/errors";const p=Symbol.for("lunora.ctxdb.rls-unwrap");class b extends w{table;constructor(s){super("RLS_REQUIRED",`ctx.db access to "${s}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=s}}const R=n=>Object.entries(n.tables).filter(([,s])=>s.shardMode?.kind!=="global").map(([s])=>s),S=(n,s,u)=>{const l=s?.tables,a=new Set(s?.exclude);for(const c of n)(l===void 0||l.includes(c))&&!a.has(c)&&u(c)},M={aggregate:"table-first",asId:"ungated",cdcChangedTables:"ungated",count:"table-first",delete:"id-gated",deleteAll:"table-first",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"table-first",findFirstOrThrow:"table-first",findMany:"table-first",get:"id-gated",groupBy:"table-first",insert:"table-first",insertMany:"table-first",insertManyUnsafe:"table-first",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"table-first",rank:"table-first",rankBefore:"table-first",rankPage:"table-first",rankPageRows:"table-first",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},m=Object.entries(M).filter(([,n])=>n==="table-first").map(([n])=>n),k=(n,s,u,l)=>{if(s.rlsMode!=="required")return n;const a=n,c=t=>{const e=s.tables[t];return e!==void 0&&e.isPublic!==!0},i=t=>{if(c(t))throw new b(t)},d=async(t,e)=>{if(e!==void 0){i(e);return}const r=await u(t);r!==void 0&&i(r)},g=async(t,e)=>{if(e!==void 0){i(e);return}if(!l){for(const o of t)await d(o,e);return}const r=await l([...new Set(t)],e);for(const o of t){const h=r.get(o);h!==void 0&&i(h)}},f={...n,[p]:n,delete:async(t,e,r)=>(await d(t,e),a.delete(t,e,r)),deleteMany:async(t,e,r)=>(await g(t,r),a.deleteMany(t,e,r)),deleteWhere:a.deleteWhere?async(t,e,r)=>(i(t),await a.deleteWhere?.(t,e,r)):void 0,get:async(t,e)=>(await d(t,e),a.get(t,e)),lookupById:async(t,e)=>(await d(t,e),a.lookupById?.(t,e)??null),patch:async(t,e,r)=>(await d(t,r),a.patch(t,e,r)),patchMany:async(t,e,r)=>(await g(t.map(o=>o.id),r),a.patchMany(t,e,r)),patchWhere:a.patchWhere?async(t,e,r)=>(i(t),await a.patchWhere?.(t,e,r)):void 0,replace:async(t,e,r,o)=>(await d(t,r),a.replace(t,e,r,o)),restore:async(t,e)=>(await d(t,e),a.restore?.(t,e))},y=a;for(const t of m){const e=y[t];typeof e=="function"&&(f[t]=(r,...o)=>(i(r),e.call(a,r,...o)))}if(a.wipeShard){const{wipeShard:t}=a;f.wipeShard=e=>(S(R(s),e,i),t.call(a,e))}return f};export{p as RLS_UNWRAP_SYMBOL,b as RlsRequiredError,m as TABLE_FIRST_METHODS,M as WRITER_METHOD_GATING,k as guardWriter};
@@ -1 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-2ULFQR_k.mjs";const r="__lunora_search_state",a=i=>{o(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);try{o(i,e`ALTER TABLE ${e.identifier(r)} ADD COLUMN ${e.identifier("profile")} TEXT`)}catch{}try{o(i,e`ALTER TABLE ${e.identifier(r)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`)}catch{}o(i,e`UPDATE ${e.identifier(r)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},f=i=>i===1||i===!0||i==="1",s=(i,d)=>{const t=o(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${d}`).toArray();return f(t[0]?.covered)},A=(i,d)=>{const n=o(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${d}`).toArray()[0];return n?{cursor:n.cursor??void 0,done:f(n.done),profile:n.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},L=(i,d,t,n,c)=>{const $=t??null;o(i,e`INSERT INTO ${e.identifier(r)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${d}, ${$}, ${n?1:0}, ${c}, ${n?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = MAX(${e.identifier(r)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`)};export{r as SEARCH_STATE_TABLE,a as migrateSearchState,A as readSearchBackfillState,s as readSearchIndexCoverage,L as writeSearchBackfillState};
@@ -1 +0,0 @@
1
- import{q as O,S as T,r as C,i as L,l as h,y as M,d as x}from"./ctx-db-companions-CTabzjgb.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as _}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as y,encodeAggregateKey as F,foldAggregateTally as N}from"./aggregateTableName-CCCIulmn.mjs";import{migrateSearchState as D,readSearchBackfillState as b,readSearchIndexCoverage as v,writeSearchBackfillState as B}from"./SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as p,r as E,a as G,b as U,A as H,D as I,h as P}from"./do-sql-qxXsaO03.mjs";import{isLiveForCompanion as W}from"./CURSOR_PREFIX-B1i1J8Zi.mjs";import{rankTableName as V,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-BXD4YaG3.mjs";const w=e=>`${O(e.language).profile}:${e.field}`,R=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,j=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,$=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),K=(e,o,n,r)=>{const i=y(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=$(e,o);for(const d of s){const f=E(d);if(!f||!W(f,r)||n.where&&!_(f,n.where))continue;const g=F(c,f);N(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${G}, ${U}, ${H}) VALUES (${d}, ${f.value}, ${f.count})`)},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)K(e,n,i,r.softDeleteMode?.field)},z=(e,o,n)=>{const r=V(o,n.name);if(k(e,r))return;const i=C(n),c=$(e,o);for(const a of c){const s=E(a);!s||n.where&&!Y(s,n.where)||L(e,r,n,i,s._id,s)}},ae=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)z(e,n,i)},m=500,A=(e,o,n)=>{const r=T(o,n.name),i=w(n),c=R(b(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(m))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(m))}`).toArray();let d=a;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;d=u,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${u}`);const S=P(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(M)}, ${t.identifier(h)}) VALUES (${x(S,n)}, ${u})`)}const f=s.length<m;return B(e,r,d,f,i),{done:f,rows:s.length}},se=(e,o,n)=>{const r=T(o,n.name),i=w(n);return R(b(e,r),i).finished?!0:v(e,r)},ce=(e,o,n)=>{if(p(e))for(const r of n.searchIndexes??[])r.staged&&j(e,o)||A(e,o,r)},J=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=A(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},fe=(e,o,n={})=>{if(!p(e))return{done:!0,pages:0};D(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=J(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{ie as backfillAggregateIndexes,ae as backfillRankIndexes,fe as backfillSearchIndexes,ce as backfillSearchIndexesForTable,se as searchIndexCoversTable};
@@ -1 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as I,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-CCCIulmn.mjs";import{runDrizzle as $}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-qxXsaO03.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-B1i1J8Zi.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-BXD4YaG3.mjs";import{mayHoldProjectedValue as ge}from"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-BBtrWwiu.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Fe="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,Oe=/[\u0080-\u{10FFFF}]/u,Le=/[\p{L}\p{N}]+/gu,oe=n=>Oe.test(n)?n.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase():n.toLowerCase(),k=n=>new Set(oe(n).split(" ")),Ie={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(Fe)},ke=2,qe=256,X=new Map,Ce=n=>{const s=n!==void 0&&_e(n)?n:"none",c=X.get(s);if(c)return c;const w=Ie[s],y=r=>{const A=(oe(r).match(Le)??[]).filter(T=>T.length<=qe);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${s}-v${String(ke)}`,query:r=>{const A=y(r);return A.filter((T,b)=>A.lastIndexOf(T)===b)}};return X.set(s,E),E},je=(n,s)=>{if(!s.includes("."))return n[s];let c=n;for(const w of s.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},De=(n,s)=>`${n}__fts_${s}`,Me="__text__",Y="__id__",ze=1e3,Ue=(n,s)=>s.document(n),U=(n,s)=>je(n,s),We=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",He=(n,s,c)=>n!==void 0&&s!==void 0&&U(n,c.field)===U(s,c.field),Be=(n,s)=>Ue(We(U(n,s.field)),Ce(s.language)).slice(0,ze),Ke=(n,s)=>Be(n,s).join(" "),Ve=(n,s,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>s[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((s,c)=>he(c))].map(s=>e.identifier(s)),e`, `),te=(n,s,c,w,y,E)=>{const r=pe(c.partitionBy??[],E),A=c.sortBy.map(b=>ee(E[b.field]??null)),T=e.join([y,r,...A].map(b=>de(b)),e`, `);$(n,e`INSERT INTO ${e.identifier(s)} (${w}) VALUES (${T})`)},Ge=(n,s,c,w,y,E)=>{if(y&&E&&Ve(c,y,E))return;const r=Z(s,c.name);y&&$(n,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,r,c,ne(c),w,E)},so=n=>{const{broadcast:s,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:r}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,b=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=I(u,m);J(p,R,o,m)}$(r,e`DELETE FROM ${e.identifier(f)}`);const F=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=F){const m=O.slice(v,v+F),R=e.join(m.map(([i,l])=>e`(${i}, ${l.value}, ${l.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(i,l)=>{const h=ee(l);h===null?d.push(e`${z(i)} IS NULL`):d.push(e`${z(i)} = ${h}`)};for(const i of f)p(i,a[i]??null);const _=T(t);_!==void 0&&p(_,null);for(const[i,l]of Object.entries(o.where??{}))p(i,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const F=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const i=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${F}`).toArray(),l=new Map;for(const h of i){const L=M(h);L&&J(l,"",o,L)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(r,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${F}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=i=>{$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i} AND ${g} <= 0`)},F=T(t),O=i=>!o.where||P(i,o.where),v=i=>Q(i,F)&&O(i);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=I(o.by??[],i);$(r,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=C(i[p]);if(h===void 0)continue;const L=I(o.by??[],i);$(r,j(u,L,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(m){const i=I(o.by??[],m),l=C(m[p]),h=$(r,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${i}`).toArray()[0],L=(h?.count??0)-1;if(L<=0)$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(r,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${L} WHERE ${q} = ${i}`)}else $(r,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${i}`)}if(R){const i=I(o.by??[],R),l=C(R[p]);if(l===void 0)$(r,j(u,i,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(r,j(u,i,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(b.has(a))return;const f=Z(t,o.name),u=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(r,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(r,f,o,d,_._id,_)}b.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Ge(r,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(r)))for(const d of u){if(He(f,a,d))continue;const p=De(t,d.name);$(r,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(r,e`INSERT INTO ${e.identifier(p)} (${e.identifier(Me)}, ${e.identifier(Y)}) VALUES (${Ke(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,F=me({lat:p,lng:_},f.precision??Ee);$(r,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${F}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),s({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{De as S,Be as a,so as c,Ke as d,te as i,Y as l,Ce as q,ne as r,Me as y};
@@ -1 +0,0 @@
1
- import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";const f=200,p=(e,n)=>{const i=r=>{const o=e.tables[r];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(e.tables)).filter(r=>i(r))},u=async function*(e,n,i=f){let r=null,o=!1;for(;!o;){const t=await e.findMany(n,{cursor:r,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,o=t.isDone||r===null}},k=async function*(e,n,i){const r=p(n,i.tables),o=i.batchSize??f;for(const t of r)yield*u(e,t,o)},y=new Set(["_creationTime","_id"]),h=(e,n)=>{for(const[i,r]of Object.entries(e.shape)){const o=n[i];if(o===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(e,n,i)=>{const r=e.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(o))if(!(t in r.shape))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,o)},g=async(e,n)=>{try{return await e.get(n)!==null}catch{return!1}},w=e=>l in e?Object.fromEntries(Object.entries(e).filter(([n])=>n!==l)):e,A=async(e,n,i,r)=>{const{table:o}=i;let{doc:t}=i;if(typeof o!="string"||o.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:o},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:o},kind:"error"};t=w(t);const s=m(n,o,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:o},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0&&await g(e,c))return{kind:"conflict"};try{return await e.insert(o,t,{allowExplicitId:!0}),{kind:"inserted",table:o}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:o},kind:"error"}}},O=async(e,n,i)=>{const r=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await A(e,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:r,inserted:o}},v=e=>{const n=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:n}},R=e=>{const n=Array.isArray(e.rows)?e.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{rows:i,startLine:r}};export{k as exportShardRows,O as importShardRows,v as parseExportShardArgs,R as parseImportShardArgs,p as selectExportTables,m as validateImportRow};
@@ -1,5 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{S as p,y as L,l as h}from"./ctx-db-companions-CTabzjgb.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as N}from"./aggregateTableName-CCCIulmn.mjs";import{backfillSearchIndexesForTable as l}from"./backfillAggregateIndexes-BCmY3OYO.mjs";import{migrateCdcLog as R,migrateCdcMeta as x}from"./CDC_LOG_TABLE-Cva29kfS.mjs";import{migrateClientWatermark as O}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as C}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as $}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as U}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as b}from"./ctx-db-relay-shapes-B4bmET4W.mjs";import{migrateSearchState as D}from"./SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as G,d as T,e as I,t as M,i as F,g as B,a as y,b as Y,A as g}from"./do-sql-qxXsaO03.mjs";import{renderSql as k}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as v}from"./appendStreamChunk-8eH4HB1Q.mjs";import{rankTableName as P,sortColumnName as w}from"./RANK_TIEBREAK-BXD4YaG3.mjs";import{migrateReactorState as j}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as K}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const u=e`_creationTime, id`,V=(i,o,n,r,t)=>{const d=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(d==null)return;const f=m=>{const _=m.indexOf("(");return _===-1?void 0:m.slice(_,m.lastIndexOf(")")+1)},c=f(k("sqlite",T(o,n,r,t)).sql),E=f(d);if(!(c===void 0||E===void 0||c===E)){if(t&&a(i,e`SELECT 1 FROM ${e.identifier(n)} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new S("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`);a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},z=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=e.join(r.fields.map(c=>I(c)),e`, `),f=s?d:e`${d}, ${u}`;V(i,t,o,f,s),a(i,T(t,o,f,s))}for(const[r,t]of M(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,T(s,o,I(r),!0))}},H=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!F(i))){for(const r of n.searchIndexes){const t=p(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(L)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}l(i,o,n)}},W=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=B(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,T(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},J=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=N(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${y} TEXT PRIMARY KEY, ${Y} REAL, ${g} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${g} INTEGER NOT NULL DEFAULT 0`)}},Q=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=P(o,r.name),s=r.sortBy.map((m,_)=>w(_)),d=s.map(m=>e`${e.identifier(m)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const c=[e`${e.identifier("__partition__")} ASC`];for(const[m,_]of s.entries()){const A=r.sortBy[m]?.direction;c.push(e`${e.identifier(_)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}c.push(e`${e.identifier("__id__")} ASC`);const E=`${o}__rank_${r.name}__btree`;a(i,T(E,t,e.join(c,e`, `),!1))}},Ae=(i,o,n={})=>{n.schemaSnapshot!==void 0&&K(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),D(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${e.identifier(G)} TEXT NOT NULL
5
- )`),a(i,T(`${r}__by_creation`,r,u,!1)),z(i,r,t),H(i,r,t),W(i,r,t),J(i,r,t),Q(i,r,t));n.cdc&&(R(i),x(i),O(i),X(i),b(i)),Object.values(o.tables).some(r=>r.commitOrderedMode===!0)&&C(i),j(i),U(i),$(i),v(i)};export{Ae as runShardMigrations};
@@ -1 +0,0 @@
1
- import{sqlComparableProjection as o}from"./BIGINT_KEY_DIGITS-Djq7G5Xx.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};