@lunora/shard-engine 1.0.0-alpha.40 → 1.0.0-alpha.41

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 (67) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +25 -8
  3. package/dist/index.d.ts +25 -8
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-DcSYybsq.mjs → ADMIN_FUNCTIONS-DKos6M_I.mjs} +1 -1
  6. package/dist/packem_shared/{AGG_COUNT-B6_CmAZD.mjs → AGG_COUNT-DLoWGwBC.mjs} +1 -1
  7. package/dist/packem_shared/{AUDIT_LOG_TABLE-uNVU9O1W.mjs → AUDIT_LOG_TABLE-ONxmEAIz.mjs} +1 -1
  8. package/dist/packem_shared/CDC_LOG_TABLE-BknLCi4r.mjs +15 -0
  9. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs → CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs} +1 -1
  10. package/dist/packem_shared/{COMMIT_SEQ_FIELD-CSe_oNZu.mjs → COMMIT_SEQ_FIELD-BUdOMG5y.mjs} +1 -1
  11. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs → DATA_MIGRATION_STATE_TABLE-CKRGRMxV.mjs} +1 -1
  12. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs → DEFAULT_MAX_RELATION_KEYS-Bbyb7_rO.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BPv7jVgK.mjs → DEFAULT_MAX_RELAYS-4Lslx8Qu.mjs} +1 -1
  14. package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs → DEFAULT_PROMOTION_THRESHOLDS-BDnVpbQ9.mjs} +1 -1
  15. package/dist/packem_shared/{DurableStreamRunner-DDBi1UXj.mjs → DurableStreamRunner-cq7kMv9M.mjs} +1 -1
  16. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs} +1 -1
  17. package/dist/packem_shared/{IDEMPOTENCY_TABLE-DKVe2Ohf.mjs → IDEMPOTENCY_TABLE-DOpm_oMF.mjs} +1 -1
  18. package/dist/packem_shared/{MAIL_RETENTION-Cig9Dmc8.mjs → MAIL_RETENTION-DGAQTHHs.mjs} +1 -1
  19. package/dist/packem_shared/NotUniqueError-D5URxcDG.mjs +1 -0
  20. package/dist/packem_shared/{QUEUE_TABLE-zj9Tt6tk.mjs → QUEUE_TABLE-s7QJZvBz.mjs} +1 -1
  21. package/dist/packem_shared/{RANK_TIEBREAK-ci3MaM65.mjs → RANK_TIEBREAK-DBzb8aDX.mjs} +1 -1
  22. package/dist/packem_shared/{REACTOR_STATE_TABLE-Cr9Orfp8.mjs → REACTOR_STATE_TABLE-QPRFyxMS.mjs} +1 -1
  23. package/dist/packem_shared/{ReactiveCache-DlJ38txF.mjs → ReactiveCache-gcV_jBm2.mjs} +1 -1
  24. package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs → SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs} +1 -1
  25. package/dist/packem_shared/{SEARCH_STATE_TABLE-Dju8ebbU.mjs → SEARCH_STATE_TABLE-BCqn5ksa.mjs} +1 -1
  26. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs +8 -0
  27. package/dist/packem_shared/{ShapeDiffCache-mE7ZzdPr.mjs → ShapeDiffCache-DLBPMAaA.mjs} +1 -1
  28. package/dist/packem_shared/{aggregateTableName-Cy5e03oz.mjs → aggregateTableName-XtEbp1DE.mjs} +1 -1
  29. package/dist/packem_shared/{appendStreamChunk-CH4e4nJn.mjs → appendStreamChunk-8eH4HB1Q.mjs} +1 -1
  30. package/dist/packem_shared/{applyOnDelete-BlcwKjuO.mjs → applyOnDelete-VGMOvm-o.mjs} +1 -1
  31. package/dist/packem_shared/applySelect-gwCG8hQF.mjs +1 -0
  32. package/dist/packem_shared/awaitWsDrain-BpfFOTSS.mjs +1 -0
  33. package/dist/packem_shared/{backfillAggregateIndexes-C9wGiPH4.mjs → backfillAggregateIndexes-wsjTZz7k.mjs} +1 -1
  34. package/dist/packem_shared/{buildPokeFrames-BhYUbqzO.mjs → buildPokeFrames-BvgtmTHk.mjs} +1 -1
  35. package/dist/packem_shared/{buildReprojectionMigration-D0f-sshM.mjs → buildReprojectionMigration-DcEoW2QQ.mjs} +1 -1
  36. package/dist/packem_shared/{buildShapeDiff-C3sZW3bZ.mjs → buildShapeDiff-DEPp9Rbv.mjs} +1 -1
  37. package/dist/packem_shared/{clearMemoryTables-CXULwypv.mjs → clearMemoryTables-BGbmag2i.mjs} +1 -1
  38. package/dist/packem_shared/compileWhereSql-DMH7Qtzd.mjs +1 -0
  39. package/dist/packem_shared/{computeRankPage-Bby1Npkd.mjs → computeRankPage-CfDhzXMF.mjs} +1 -1
  40. package/dist/packem_shared/createCompanionSync-29Gp1xI_.mjs +1 -0
  41. package/dist/packem_shared/{createReplicaLink-Bv7250Ef.mjs → createReplicaLink-GrknD9FY.mjs} +1 -1
  42. package/dist/packem_shared/{ctx-db-companions-BQRTS_WY.mjs → ctx-db-companions-B4gOYjdz.mjs} +1 -1
  43. package/dist/packem_shared/{ctx-db-relay-shapes-Jf5xpD1r.mjs → ctx-db-relay-shapes-C93UQ7LV.mjs} +1 -1
  44. package/dist/packem_shared/{defineEngineContractSuite-CjxJNwwG.mjs → defineEngineContractSuite-Dvd03W9-.mjs} +1 -1
  45. package/dist/packem_shared/do-sql-DqQTxsj_.mjs +1 -0
  46. package/dist/packem_shared/{isSoftDeleted-D0iaSrDV.mjs → isSoftDeleted-DvUFsJE9.mjs} +1 -1
  47. package/dist/packem_shared/{materializeExternalRows-CX55UoV7.mjs → materializeExternalRows-DmSW2ujk.mjs} +1 -1
  48. package/dist/packem_shared/{param-Ib8WHnrF.mjs → param-DlozcSQu.mjs} +1 -1
  49. package/dist/packem_shared/{runDrizzle-it6rL9bR.mjs → runDrizzle-2ULFQR_k.mjs} +1 -1
  50. package/dist/packem_shared/runShardMigrations-C4bvso2W.mjs +5 -0
  51. package/dist/packem_shared/{selectExpiredIds-w4fPtlwT.mjs → selectExpiredIds-rvmKjueQ.mjs} +1 -1
  52. package/dist/packem_shared/selectShapeMembers-Ce5Jr6UH.mjs +1 -0
  53. package/dist/packem_shared/{stableWireKey-DSCJB6E7.mjs → stableWireKey-BC6DtQic.mjs} +1 -1
  54. package/dist/packem_shared/where-sql-DxCbgqDJ.mjs +1 -0
  55. package/dist/packem_shared/wire-codec-CDds5uQW.mjs +1 -0
  56. package/package.json +1 -1
  57. package/dist/packem_shared/CDC_LOG_TABLE-CW0wHEgW.mjs +0 -15
  58. package/dist/packem_shared/NotUniqueError-Dnik6z41.mjs +0 -1
  59. package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs +0 -7
  60. package/dist/packem_shared/applySelect-BQbHyo-W.mjs +0 -1
  61. package/dist/packem_shared/awaitWsDrain-CeaR5jj8.mjs +0 -1
  62. package/dist/packem_shared/compileWhereSql-JBpSfQm9.mjs +0 -1
  63. package/dist/packem_shared/createCompanionSync-Cfju9Ng2.mjs +0 -1
  64. package/dist/packem_shared/do-sql-DbEszTyj.mjs +0 -1
  65. package/dist/packem_shared/runShardMigrations-DFc_LoP-.mjs +0 -5
  66. package/dist/packem_shared/selectShapeMembers-C0vtU60D.mjs +0 -1
  67. package/dist/packem_shared/wire-codec-BU9T2xJ7.mjs +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.40",
3
+ "version": "1.0.0-alpha.41",
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",
@@ -1,15 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";import{k as m,l as A}from"./do-sql-DbEszTyj.mjs";import{ConflictError as p}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",q="__cdc_log_table_seq",_=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
2
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
- ts REAL NOT NULL,
4
- ${t.identifier("table")} TEXT NOT NULL,
5
- id TEXT NOT NULL,
6
- op TEXT NOT NULL,
7
- doc TEXT
8
- )`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(q)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}},w=(e,o,r,i,s,d)=>{const E=d===void 0?null:m(d);n(e,t`INSERT INTO ${t.identifier(c)} (ts, ${t.identifier("table")}, id, op, doc) VALUES (${o}, ${r}, ${i}, ${s}, ${E})`)},C=90,S=e=>!e||e.size===0?t``:t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,F=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),s=S(o.tables),E=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(c)} WHERE seq > ${r}${s} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const f={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?f:{...f,doc:A(a.doc)}});return{changes:E,cursor:E.at(-1)?.seq??r}},b=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let s=0;s<i.length;s+=C){const d=new Set(i.slice(s,s+C));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${S(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,R=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),y=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=R(e),i=!0,l.set(e,r));for(const s of o)if(!r.has(s)&&(i||(r=R(e),i=!0,l.set(e,r),!r.has(s))))return!1;return!0},g=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq FROM ${t.identifier(c)}
9
- WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
10
- GROUP BY id
11
- ORDER BY maxSeq ASC`).toArray().map(d=>({id:d.id,op:d.op,seq:d.maxSeq})),U=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(c)} WHERE seq IN (
12
- SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
13
- )`)},X=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
14
- SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
15
- )`)},B=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},H=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},v=(e,o)=>e!==void 0&&e>o+1,x=(e,o,r)=>new u("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),$=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,W=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=$(e);return r===void 0?i:Math.max(r+1,i??0)},T="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(T)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},Y=e=>{L(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(T)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${i})`),i},G=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(T)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},I=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof p))throw i;const s={...r};delete s._id,await e.replace(o.id,s,void 0,{allowExplicitId:!0})}},K=async(e,o)=>{for(const r of o)await I(e,r)};export{c as CDC_LOG_TABLE,q as CDC_LOG_TABLE_SEQ_INDEX,T as CDC_META_TABLE,w as appendCdcChange,K as applyCdcChanges,G as bumpCdcEpoch,y as cdcCanVouchFor,B as cdcSeqLeavingRows,b as cdcTouchesTables,x as cdcTrimmedError,X as compactCdcDocs,v as cursorBelowRetainedFloor,_ as migrateCdcLog,L as migrateCdcMeta,W as minCdcReplayableSeq,$ as minCdcSeq,g as readCdcChangeKeys,F as readCdcChanges,H as readCdcCursor,Y as readCdcEpoch,U as trimCdcChanges};
@@ -1 +0,0 @@
1
- import{LunoraError as y}from"@lunora/errors";import{c as Ht,q as Je,S as Nt,l as Ae,a as jt}from"./ctx-db-companions-BQRTS_WY.mjs";import{sql as r}from"drizzle-orm";import{d as Kt}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as Ot,aggregateSqlFunction as ve,normalizeCountArgument as Qt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as qe,encodeAggregateKey as Be,readAggregateValue as Ue}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as zt,selectIndexForCount as Jt,selectIndexForAggregate as Vt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Yt}from"./backfillAggregateIndexes-C9wGiPH4.mjs";import{backfillAggregateIndexes as jr,backfillRankIndexes as Kr,backfillSearchIndexes as Or}from"./backfillAggregateIndexes-C9wGiPH4.mjs";import{appendCdcChange as Xt}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{CDC_LOG_TABLE as zr,applyCdcChanges as Jr,bumpCdcEpoch as Vr,cdcCanVouchFor as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as eo,compactCdcDocs as to,cursorBelowRetainedFloor as no,minCdcReplayableSeq as ro,minCdcSeq as oo,readCdcChangeKeys as io,readCdcChanges as so,readCdcCursor as co,readCdcEpoch as ao,trimCdcChanges as lo}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{allocateCommitSeq as Zt,COMMIT_SEQ_FIELD as en}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{isMemoryTable as tn}from"./clearMemoryTables-CXULwypv.mjs";import{computeRankPage as dt}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as B}from"./runDrizzle-it6rL9bR.mjs";import{D as K,k as se,r as de,b as Ie,A as Ge,a as Ce,e as V,t as It,f as lt,i as nn,h as Ct,g as rn}from"./do-sql-DbEszTyj.mjs";import{WORKERD_SQLITE_LIMITS as xt,unionAll as Ke,sqliteInList as on}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as sn,boundingBoxGeohashes as cn,haversineMeters as an,pointInBoundingBox as dn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as ln}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as un,buildSeekWhere as Mt,decodeCursor as Oe,applySelect as ut,encodeCursor as Qe,buildSeekBeforeWhere as fn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as ft,sortColumnName as ht,resolveRankPartition as hn,encodePartitionKey as wn,RANK_TIEBREAK as pn}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as gn,buildIndexRange as $n}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as wt}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Ne,resolveWith as pt,relationHooks as gt,applyOnDelete as yn,fanOutScalarCounts as En}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as mn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as Sn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Rn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Tn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as fo,advanceClientWatermark as ho,migrateClientWatermark as wo,readClientWatermark as po}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as $o,deleteGlobalShapeSnapshot as yo,deleteGlobalShapeSnapshotsForConnection as Eo,migrateGlobalShapeSnapshot as mo,readGlobalShapeSnapshot as So,writeGlobalShapeSnapshot as Ro}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as _o,readIdempotent as Ao,trimIdempotent as vo,writeIdempotent as Io}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as xo}from"./runShardMigrations-DFc_LoP-.mjs";import{SEARCH_STATE_TABLE as bo}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMembers as ko,selectShapeRows as Lo}from"./selectShapeMembers-C0vtU60D.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as _n}from"./quoteIdentifier-CObIFRhb.mjs";const An=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},vn=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},In=()=>new y("BAD_REQUEST","invalid cursor"),$t=16,yt=8,X=1024,Ve=(o,i)=>i.query(o),Cn=(o,i)=>{if(o.length===0)return 0;let t=0;for(const[a,f]of i.entries()){const g=a===i.length-1;let E=0;for(const T of o)(g?T.startsWith(f):T===f)&&(E+=1);if(E===0)return 0;t+=E}return t},xn=(o,i)=>{if(!i)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 f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},Mn=(o,i,t)=>{const a={eq:(f,g)=>{if(!o.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=yt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(yt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:g}),a},search:(f,g)=>{const E=o;if(f!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${f}"`);const T=Ve(g,t).length;if(T>$t)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String($t)} search terms are supported (got ${String(T)})`);return E.field=f,E.query=g,E.hasQuery=!0,a}};return a},bn=o=>{if(o.length>X)throw new y("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Dn=o=>Math.min(o.offset+o.numItems+1,X),kn=o=>An(`search:${String(o)}`),Ln=o=>{let i;try{i=vn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Fn=o=>{if(typeof o.endCursor=="string")throw new y("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 y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Ln(o.cursor):0;if(t===void 0)throw In();if(t+i>=X)throw new y("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:t}},Wn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?kn(t):null,isDone:!a,page:o.slice(i.offset,t)}},qn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new y("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Bn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Un=o=>{if(!Bn.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Et=50,bt=500,xe=Math.floor(xt.boundParams/3),we=xt.boundParams,Pn=128,ce=(o,i,t)=>{const a=i??bt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Gn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Hn=o=>Math.max(o,X),Dt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${oe(a.value)}`);return i&&t.push(i),t},Nn=(o,i,t,a,f)=>{const g=Ve(t.query,Je(t.definition.language));if(g.length===0)return[];const E=Nt(i,t.indexName),T=`${E}__vocab`,S=g.length-1,$=g.map((W,M)=>{const N=xn(W,M===S),j=N.exact?r`${r.identifier("term")} = ${N.lower}`:r`${r.identifier("term")} >= ${N.lower} AND ${r.identifier("term")} < ${N.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(T)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),L=g.map((W,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(L,r` + `)} AS ${r.identifier("__score__")} FROM (${Ke($)}) u JOIN ${r.identifier(E)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(L.map(W=>r`${W} > 0`),r` AND `)}`,v=Dt(t,f);let R=r`SELECT m.id, m._creationTime, m.${r.identifier(K)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;v.length>0&&(R=r`${R} WHERE ${r.join(v,r` AND `)}`),R=r`${R} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const F=[];for(const W of B(o,R)){const M=Ct(W);if(M){const N=W.__score__;F.push({document:M,score:typeof N=="number"?N:Number(N??0)})}}return F},jn=(o,i,t,a,f)=>{const g=Je(t.definition.language),E=Ve(t.query,g);if(E.length===0)return[];const T=Dt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;T.length>0&&(S=r`${S} WHERE ${r.join(T,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Hn(a)))}`;const $=B(o,S).toArray(),L=[];for(const _ of $){const v=Ct(_);if(!v)continue;const R=Cn(jt(v,t.definition),E);R>0&&L.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:R})}return L.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),L.slice(0,a).map(_=>({document:_.doc,score:_.score}))},je=(o,i,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 y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Kn=(o,i)=>{const t=o,a={near:(f,g)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f,".near() point",i,t.indexName),!Number.isFinite(g)||g<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(g)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:g},a},within:f=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f.sw,".within() sw corner",i,t.indexName),je(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .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:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},On=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},Qn=(o,i)=>{const t=On(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=an(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return dn(t,i.within)?{creationTime:a,distance:0}:void 0},zn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?sn(t.near.point,t.near.radiusMeters):cn(t.within),g=rn(i,t.indexName),E=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),T=[r`(${r.join(E,r` OR `)})`];a&&T.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(K)} FROM ${r.identifier(g)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(T,r` AND `)}`,$=B(o,S).toArray(),L=[];for(const _ of $){const v=de(_),R=v?Qn(v,t):void 0;v&&R&&L.push({creationTime:R.creationTime,distance:R.distance,doc:v})}return L.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),L},kt=(o,i,t,a)=>{const f=[];for(const g of o)if(i.every(E=>E(a(g)))&&(f.push(g),typeof t=="number"&&f.length>=t))break;return f},Jn=(o,i,t,a,f,g=()=>{})=>{const E=t.within!==void 0,T=zn(o,i,t,f).map(S=>({distanceMeters:E?null:S.distance,document:S.doc}));return g(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},Lt=(o,i,t,a,f,g=()=>{})=>{const{geo:E}=t;if(!E)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const T=t.inMemoryFilters.length>0,S=Jn(o,i,E,T?void 0:f,a,g);return T?kt(S,t.inMemoryFilters,f,$=>$.document):S},Vn=(o,i,t,a,f,g=()=>{})=>Lt(o,i,t,a,f,g).map(E=>E.document),Yn=(o,i,t,a,f,g,E=()=>{})=>{const T=[];for(const _ of t.sqlConditions)T.push(r`${V(_.field)} ${r.raw(_.comparator)} ${oe(_.value)}`);a&&T.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;T.length>0&&(S=r`${S} WHERE ${r.join(T,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof g=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(g))))}`);const $=B(o,S).toArray();E($.length);const L=[];for(const _ of $){const v=de(_);if(v&&t.inMemoryFilters.every(R=>R(v))&&(L.push(v),typeof g=="number"&&L.length>=g))break}return L},re={fieldRef:V,serialize:oe},Ft=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&Sn(t)},mt=(o,i)=>i.some(t=>Ft(o,t)),St=(o,i,t)=>{if(Ft(o,i))throw new y("BAD_REQUEST",`${t}: "${i}" 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`)},Xn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:g,negated:E,parentTable:T,relation:S}=f,$=`__rel_${String(i)}`,L=t.at(-1)??T;i+=1,o(S.table,H);const _=S.kind==="one"?S.field:S.references,v=S.kind==="one"?S.references:S.field,R=r`${lt($,v)} = ${lt(L,_)}`;t.push($);const F=te(g,a);t.pop();const W=F?r`${R} AND ${F}`:R,M=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${W})`;return E?r`NOT ${M}`:M},serialize:oe};return a},Wt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},Zn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},er=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},tr=(o,i,t,a)=>{const f=o.sqlConditions.map(g=>({[g.field]:{[Zn[g.comparator]??"eq"]:g.value}}));if(t&&f.push(Mt(i,Oe(t))),a&&f.push(fn(i,Oe(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},nr=(o,i,t)=>{const a=[];for(const f of o){const g=de(f);if(g&&i.every(E=>E(g))&&(a.push(g),t!==void 0&&a.length>t))break}return a},rr=(o,i,t,a,f,g=()=>{})=>{const E=Math.max(0,Math.floor(a.numItems)),T=er(t),S=typeof a.endCursor=="string",$=te(tr(t,T,a.cursor,a.endCursor),re),L=f&&$?r`${$} AND ${f}`:f??$;let _=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;L&&(_=r`${_} WHERE ${L}`),_=r`${_} ORDER BY ${Wt(T)}`;const v=t.inMemoryFilters.length>0;!v&&!S&&(_=r`${_} LIMIT ${r.raw(String(E+1))}`);const R=B(o,_).toArray();g(R.length);const F=nr(R,t.inMemoryFilters,v||S?void 0:E);if(S){const j=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:j?Qe(j,T):null}}const W=F.length>E,M=W?F.slice(0,E):F,N=M.at(-1);return{continueCursor:W&&N?Qe(N,T):null,isDone:!W,page:M}};class or extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ir=/\s/u,sr=String.fromCodePoint(0),Rt=(o,i,t)=>{if(!o.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||ir.test(t)||t.includes(sr)?null:t},cr=(o,i,t,a=()=>{},f=()=>{},g=()=>{})=>{const E=i.tables[t];if(!E)throw new y("INTERNAL",`unknown table: ${t}`);const T=ae(E.softDeleteMode,void 0),S=T?te(T,re):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let L=0;const _=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Yt(o,t,E);const k=$.inMemoryFilters.length>0,C=qn(k?void 0:m),O=nn(o)?Nn(o,t,b,C,S):jn(o,t,b,C,S);return k?(L=O.length,kt(O,$.inMemoryFilters,m,be=>be.document)):(m===void 0&&bn(O),O)},v=m=>_(m).map(b=>b.document),R=m=>{const b=Fn(m);return Wn(v(Dn(b)),b)},F=()=>{const m=$.indexFields.length>0?$.indexFields:["_creationTime"],b=$.order==="desc"?"DESC":"ASC";return r.join(m.map(k=>r`${V(k)} ${r.raw(b)}`),r`, `)},W=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f($n(t,$.indexName,$.indexFields,$.sqlConditions,oe))},M=m=>{W();let b=0;const k=(()=>{if($.search){const C=v(m);return b=L,C}return $.geo?Vn(o,t,$,S,m,C=>{b=C}):Yn(o,t,$,S,F(),m,C=>{b=C})})();return g(Math.max(b,k.length)),k},N=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const b=(()=>{if($.search){const k=_(void 0);return m=L,k}return Lt(o,t,$,S,void 0,k=>{m=k})})();return g(Math.max(m,b.length)),b},j={async*[Symbol.asyncIterator](){const m=[...$.inMemoryFilters];let b;$.inMemoryFilters=[];try{for(;;){const k=await j.paginate({cursor:b??null,numItems:Pn});for(const C of k.page)m.every(O=>O(C))&&(yield C);if(k.isDone||k.continueCursor===null)return;b=k.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return M(void 0)},async collectWithScores(){return N()},filter(m){return $.inMemoryFilters.push(m),j},async first(){return M($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",j},async paginate(m){let b=0;if(W(),$.search){const C=R(m);return g(C.page.length),C}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=rr(o,t,$,m,S,C=>{b=C});return g(Math.max(b,k.page.length)),k},async take(m){return M(m)},async unique(){const m=M($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new or(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const k=(E.geoIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const C={definition:k,indexName:m};if($.geo=C,b(Kn(C,t)),!C.near&&!C.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,b){const k=E.indexes.find(C=>C.name===m);if(!k)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=k.fields,b&&b(Gn($)),j},withSearchIndex(m,b){const k=(E.searchIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const C={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=C,b(Mn(C,t,Je(k.language))),!C.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return j}};return j},Tt=(o,i,t)=>{const a={...i};for(const[f,g]of It(o)){if(g.serverDefault){a[f]=g.serverDefault({auth:t});continue}a[f]===void 0&&(g.defaultFn?a[f]=g.defaultFn():"defaultValue"in g&&(a[f]=g.defaultValue))}return a},_t=(o,i,t,a)=>{const f=t;for(const[g,E]of It(o)){if(E.serverDefault){g in i&&(f[g]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(g in i)&&(f[g]=E.onUpdateFn())}},At=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ar=/unique constraint failed/i,dr=o=>o instanceof Error&&ar.test(o.message),ze=(o,i,t)=>{try{B(o,t)}catch(a){throw dr(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},Me=(o,i,t)=>{if(ze(o,i,t),B(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},vt=(o,i,t,a,f,g,E)=>{const T=[];for(let _=0;_<t.length+1;_+=1){const v=[];for(let M=0;M<_;M+=1)v.push(r`${r.identifier(t[M])} IS ${g[M]}`);const R=t[_],F=a[_];if(R!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";v.push(r`${r.identifier(R)} ${r.raw(M)} ${g[_]}`)}else v.push(r`${r.identifier(pn)} < ${E}`);const[W]=v;T.push(v.length===1&&W!==void 0?W:r`(${r.join(v,r` AND `)})`)}const S=r.join(T,r` OR `),$=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),L=B(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:L.c}},Gr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{});let f;const g=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((f===void 0||!g())&&(f=Zt(i)),{[en]:f}),T=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...gn(s,h,oe));return u.length>0?u:void 0},{headroom:S}=o;let $=!1;const L=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},_=o.onRead??(()=>{}),v=o.onReadRange??(e=>{_(e.table,H)}),R=(e,n)=>{n!==void 0&&n!==H&&!$&&S?.recordRead(1),_(e,n)},F=o.onIndexUse??(()=>{}),W=o.onWrite??(()=>{}),M=e=>{$||S?.recordWrite(e)},N=async e=>{M(e.doc),await W(e)},{cache:j}=o,m=o.clock??(()=>Date.now()),b=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??Ot,{globalDb:C}=o,O=o.auth??{identity:null,userId:null},be=o.cdc??!1,De=k,qt=Rn({scheduler:typeof De.list=="function"&&typeof De.get=="function"?De:void 0,storage:o.storage}),le=(e,n,s,u)=>{be&&!tn(t.tables[e])&&Xt(i,m(),e,n,s,u)},ie=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return U},ke=e=>Ye(e,"cascade"),z=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},Xe=async(e,n,s,u,h)=>{h&&M(s);const l=await e.insert(n,s,u);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},Le=(e,n)=>Ye(e,"relation load").findMany(e,n),Ze=(e,n)=>(ie(e)&&R(e,H),Le(e,n)),Bt=e=>!ie(e.table),et=o.relationExistsPushDown??"auto",tt=et!=="never",{maxRelationKeys:nt}=o,ge=(e,n,s)=>wt(e,{fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:s,schema:t,tableName:n}),rt=async(e,n,s,u)=>{const h=z(e,"relation grouped count");if(h)return R(e,H),En((q,I)=>h.count(q,I),e,n,s,u);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=J(J(d,u),c),A=await ge(w,e,void 0),p=te(A,re),x=V(n);let D=r`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;p&&(D=r`${D} WHERE ${p}`),D=r`${D} GROUP BY ${x}`;const P=B(i,D).toArray();return new Map(P.map(q=>[q.__fk__,q.count]))};let $e=0;const ot=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ot.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ot.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>Et)throw $e-=1,new pe(`trigger recursion exceeded ${String(Et)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Tn({ctx:Pt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Fe,ensureRankBackfilled:We,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:it,syncGeo:Ee,syncRanks:he,syncSearch:me}=Ht({broadcast:a,indexKeysFor:(e,n)=>T(e,n),invalidateCache:(e,n,s)=>j?.invalidate(e,n,T(e,s)),recordCdc:le,schema:t,sql:i}),st=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.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})},ct=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ne=(e,n)=>{const s=ct(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(p=>r`SELECT ${r.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(p)} WHERE id = ${e}`),[l]=B(i,r`${Ke(h)} LIMIT 1`).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[K];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Ut=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ct(n);for(let l=0;l<h.length;l+=we){const c=h.slice(l,l+we),d=Math.floor(we/c.length),w=on(r`${r.identifier("id")}`,s,!1,d),A=c.map(p=>r`SELECT ${r.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(p)} WHERE ${w}`);for(const p of B(i,Ke(A))){const{id:x,__t__:D}=p;typeof D=="string"&&typeof x=="string"&&u.set(x,D)}}return u},at={assertRankPartitionLocal:st,ensureRankBackfilled:We,onRead:R,rowToDocument:de,schema:t,sql:i},U={system:qt,async aggregate(e,n){const s=z(e,"aggregate");if(s)return R(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,H);const h=ae(u.softDeleteMode,void 0),l=J(J(n.baseWhere,n.where),h),c=await ge(l,e,n.relationBaseWhere),d=c!==l;if(u.aggregateIndexes&&!n.baseWhere&&!d&&(!h||mt(u,[n.field]))){const q=Vt(u.aggregateIndexes,n.op,n.field,n.where);if(q){Fe(e,q.index);const I=Be(q.index.by??[],q.key),Q=qe(e,q.index.name),Y=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(Q)} WHERE ${Ce} = ${I}`).toArray()[0];return Ue(n.op,Y)}}St(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,re),A=ve(n.op),p=V(n.field);let x=r`SELECT ${r.raw(A)}(${p}) AS value FROM ${r.identifier(e)}`;w&&(x=r`${x} WHERE ${w}`);const P=B(i,x).toArray()[0]?.value;return P??null},asId(e,n){const s=Rt(t,e,n);if(s===null)throw new y("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,H),s.count(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=Qt(n);if(h.restrictsCounts)throw new Pe(e);R(e,H);const l=ae(u.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),l),d=await ge(c,e,h.relationBaseWhere),w=d!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!l){const D=Jt(u.aggregateIndexes,h.where);if(D){Fe(e,D.index);const P=Be(D.index.by??[],D.key),q=qe(e,D.index.name),I=B(i,r`SELECT ${Ie} AS value FROM ${r.identifier(q)} WHERE ${Ce} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(d,re);let p=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return A&&(p=r`${p} WHERE ${A}`),B(i,p).one().count},async delete(e,n,s){const u=ne(e,n);if(!u){const p=n===void 0?C:void 0;p&&(M(void 0),await p.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c],w=s?.hard===!0,A=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await yn({deletedId:e,deletedReference:p=>l[p],findHolders:async(p,x,D)=>(await ke(p).findMany(p,{includeDeleted:w,where:{[x]:D}})).page,onCascade:(p,x)=>ke(p).delete(x,void 0,s),onRestrict:p=>{throw new pe(p,"restrict")},onSetNull:(p,x,D)=>ke(p).patch(x,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),A){const p={...l,...E(c),[A]:m(),_id:e};Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,p,l),Ee(c,e,void 0),ye(c,l,p),he(c,e,l,void 0),j?.invalidate(c,e,T(c,l,p)),le(c,e,"update",p),a({indexKeys:T(c,l,p),key:e,op:"update",row:p,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c});return}Me(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,l,void 0),he(c,e,l,void 0),j?.invalidate(c,e,T(c,l)),le(c,e,"delete"),a({indexKeys:T(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??bt),u=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const d=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await U.delete(w,h,u),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(z(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new ln(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return R(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,H):R(e);const l=un(n.orderBy),c=n.cursor?Mt(l,Oe(n.cursor)):void 0;let d=J(n.baseWhere,n.where);d=J(d,ae(u.softDeleteMode,n.includeDeleted)),d=await wt(d,{canPushExists:tt?Bt:void 0,existsPushMode:et==="always"?"always":"auto",fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=tt?Xn(R):re,A=te(d,w);let p=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(e)}`;A&&(p=r`${p} WHERE ${A}`),p=r`${p} ORDER BY ${Wt(l)}`;const x=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;x!==void 0&&(p=r`${p} LIMIT ${r.raw(String(x+1))}`);const D=B(i,p).toArray();h&&!$&&S?.recordRead(D.length);const P=[];for(const Y of D){const G=de(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&R(e,G._id))}if(x===void 0)return n.with&&await pt({groupedCounter:rt,fetcher:Le,parents:P,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:ut(P,n.select,n.with)};const q=P.length>x,I=q?P.slice(0,x):P,Q=I.at(-1);return n.with&&await pt({fetcher:Le,groupedCounter:rt,parents:I,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:q&&Q?Qe(Q,l):null,isDone:!q,page:ut(I,n.select,n.with)}},async get(e,n){const s=ne(e,n);if(!s){const u=n===void 0?C:void 0;return u?u.get(e):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=ne(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,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(u.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),l),d=await ge(c,e,n.relationBaseWhere),w=d!==c,A=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!l||mt(u,A))){const I=zt(u.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,Y=I?.index.by?.length??0;if(I&&(Q===0||Q===Y)){Fe(e,I.index);const G=qe(e,I.index.name),Se=Object.keys(I.partial),Re=[];if(Se.length===(I.index.by??[]).length&&Se.length>0){const Te=Be(I.index.by??[],I.partial),_e=B(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Te}`).toArray();return _e.length>0&&Re.push({key:{...I.partial},value:Ue(h.op,_e[0])}),Re}const Gt=B(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)}`).toArray();for(const Te of Gt){const _e=Kt(JSON.parse(Te.key));Re.push({key:_e,value:Ue(h.op,Te)})}return Re}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;St(u,I,Q)}const p=te(d,re),x=n.by.map(I=>r`${V(I)} AS ${r.identifier(I)}`);if(h.op==="count")x.push(r`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);x.push(r`${r.raw(ve(h.op))}(${V(I)}) AS value`)}let D=r`SELECT ${r.join(x,r`, `)} FROM ${r.identifier(e)}`;p&&(D=r`${D} WHERE ${p}`),D=r`${D} GROUP BY ${r.join(n.by.map(I=>V(I)),r`, `)}`;const P=B(i,D).toArray(),q=[];for(const I of P){const Q={};for(const G of n.by)Q[G]=I[G]??null;const{value:Y}=I;q.push({key:Q,value:Y==null?null:Number(Y)})}return q},async insert(e,n,s){const u=z(e,"insert");if(u)return Xe(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=Tt(h,n,O);Ne(h,l);let c;s?.clientId!==void 0?(Un(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=b();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:m(),w={...l,...E(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES (${c}, ${d}, ${se(w)})`),it(e,c,w),Z(e,"after","insert")&&await ee("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(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=z(e,"insert");if(u){const d=[];for(const w of n)M(w);for(const w of n){const A=await u.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:A,op:"insert",row:{...w,_id:A},table:e}),d.push(A)}return d}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=[];for(let d=0;d<n.length;d+=xe)l.push(E(e));const c=n.map((d,w)=>{const A=Tt(h,d,O),p=s?.allowExplicitId===!0&&typeof A._id=="string"?A._id:b(),x=s?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:m(),D={...A,...l[Math.floor(w/xe)],_creationTime:x,_id:p};return{creationTime:x,document:D,id:p}});for(const d of c)M(d.document);for(let d=0;d<c.length;d+=xe){const w=r.join(c.slice(d,d+xe).map(A=>r`(${A.id}, ${A.creationTime}, ${se(A.document)})`),r`, `);ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES ${w}`)}for(const{document:d,id:w}of c)it(e,w,d),await W({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],l=z(e,"insert");if(l)for(const d of n)M(d);const c=async d=>l?Xe(l,e,d,void 0,!1):U.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Rt(t,e,n)},async patch(e,n,s){const u=ne(e,s);if(!u){const A=s===void 0?C:void 0;if(A){M(n),await A.patch(e,n);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c];if(!d)throw new y("INTERNAL",`unknown table: ${c}`);R(c,e),At("patch",n);const w={...l,...n,...E(c),_id:e};_t(d,n,w,O),Ne(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),ue(c),fe(c),Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(w)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,w,l),Ee(c,e,w),ye(c,l,w),he(c,e,l,w),j?.invalidate(c,e,T(c,l,w)),le(c,e,"update",w),a({indexKeys:T(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(z(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},query(e){const n=z(e,"query");return n?(R(e,H),n.query(e)):cr(i,t,e,F,s=>{s?v(s):R(e,H)},s=>{$||S?.recordRead(s)})},async rank(e,n,s){const u=z(e,"rank");if(u)return R(e,H),u.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(st(e,h,l),s.restrictsCounts)throw new Pe(e);R(e,H),We(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=ft(e,l.name),w=l.sortBy.map((G,Se)=>ht(Se)),A=w.map(G=>_n(G)).join(", "),p=B(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(A)} FROM ${r.identifier(d)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[x]=p;if(x===void 0)return null;let D=x.__partition__;const P=J(s.baseWhere,s.where);He(P,t,e,"rank");const q=hn(l,P);if(q){const G=wn(l.partitionBy??[],q);if(G!==D)return null;D=G}const I=w.map(G=>x[G]),{before:Q,total:Y}=vt(i,d,w,l.sortBy,D,I,c);return{position:Q+1,total:Y}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Pe(e);R(e,H),We(e,h);const l=ft(e,h.name),c=h.sortBy.map((w,A)=>ht(A)),d=h.sortBy.map((w,A)=>oe(s.sortValues[A]??null));return vt(i,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage");const u=z(e,"rankPage");if(u)return R(e,H),u.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=dt(at,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:u,hasMore:h,rows:l}=dt(at,e,n,s);return{directions:u,hasMore:h,rows:l}},async restore(e,n){const s=ne(e,n);if(!s){const l=n===void 0?C:void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=ne(e,s);if(!h){const x=s===void 0?C:void 0;if(x){M(n),await x.replace(e,n,void 0,u);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new y("INTERNAL",`unknown table: ${d}`);At("replace",n);const A=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:m(),p={...n,...E(d),_creationTime:A,_id:e};_t(w,n,p,O),Ne(w,p),Z(d,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:c,table:d}),ue(d),fe(d),Me(i,d,r`UPDATE ${r.identifier(d)} SET _creationTime = ${A}, ${r.identifier(K)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(K)} = ${l}`),me(d,e,p,c),Ee(d,e,p),ye(d,c,p),he(d,e,c,p),j?.invalidate(d,e,T(d,c,p)),le(d,e,"update",p),a({indexKeys:T(d,c,p),key:e,op:"update",row:p,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:c,table:d}),await N({doc:p,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new y("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of u){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},Pt={db:U,scheduler:k};return o.enforceRls===!0?mn(U,t,(e,n)=>ne(e,n)?.tableName,(e,n)=>Ut(e,n)):U};export{zr as CDC_LOG_TABLE,fo as CLIENT_WATERMARK_TABLE,$o as GLOBAL_SHAPE_SNAPSHOT_TABLE,_o as IDEMPOTENCY_TABLE,or as NotUniqueError,bo as SEARCH_STATE_TABLE,ho as advanceClientWatermark,Jr as applyCdcChanges,Un as assertValidClientId,jr as backfillAggregateIndexes,Kr as backfillRankIndexes,Or as backfillSearchIndexes,Vr as bumpCdcEpoch,Yr as cdcCanVouchFor,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,eo as cdcTrimmedError,to as compactCdcDocs,Gr as createShardCtxDb,no as cursorBelowRetainedFloor,yo as deleteGlobalShapeSnapshot,Eo as deleteGlobalShapeSnapshotsForConnection,wo as migrateClientWatermark,mo as migrateGlobalShapeSnapshot,ro as minCdcReplayableSeq,oo as minCdcSeq,Rt as normalizeIdStructurally,io as readCdcChangeKeys,so as readCdcChanges,co as readCdcCursor,ao as readCdcEpoch,po as readClientWatermark,So as readGlobalShapeSnapshot,Ao as readIdempotent,xo as runShardMigrations,ko as selectShapeMembers,Lo as selectShapeRows,lo as trimCdcChanges,vo as trimIdempotent,Ro as writeGlobalShapeSnapshot,Io as writeIdempotent};
@@ -1,7 +0,0 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-it6rL9bR.mjs";const n="__shape_poke_cursor",u=r=>{i(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(n)} (
2
- connection_id TEXT NOT NULL,
3
- sub_id TEXT NOT NULL,
4
- cursor INTEGER NOT NULL,
5
- PRIMARY KEY (connection_id, sub_id)
6
- )`)},d=(r,e,s)=>i(r,o`SELECT cursor FROM ${o.identifier(n)} WHERE connection_id = ${e} AND sub_id = ${s} LIMIT 1`).toArray()[0]?.cursor,T=(r,e,s,c)=>{i(r,o`INSERT INTO ${o.identifier(n)} (connection_id, sub_id, cursor) VALUES (${e}, ${s}, ${c})
7
- ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},_=r=>i(r,o`SELECT MIN(cursor) AS cursor FROM ${o.identifier(n)}`).toArray()[0]?.cursor??void 0,S=(r,e,s)=>{i(r,o`DELETE FROM ${o.identifier(n)} WHERE connection_id = ${e} AND sub_id = ${s}`)},L=(r,e)=>{i(r,o`DELETE FROM ${o.identifier(n)} WHERE connection_id = ${e}`)};export{n as SHAPE_POKE_CURSOR_TABLE,S as deleteShapePokeCursor,L as deleteShapePokeCursorsForConnection,u as migrateShapePokeCursor,_ as minShapePokeCursor,d as readShapePokeCursor,T as writeShapePokeCursor};
@@ -1 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{d as m,e as h}from"./wire-codec-BU9T2xJ7.mjs";const y="id",b=new Set(["_id","id"]),A=o=>{const e=[];for(const t of o??[])for(const[r,s]of Object.entries(t))e.push({direction:s,field:r});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},E=o=>{const e=new TextEncoder().encode(o);let t="";for(const r of e)t+=String.fromCodePoint(r);return btoa(t)},v=o=>{const e=atob(o),t=Uint8Array.from(e,r=>r.codePointAt(0)??0);return new TextDecoder().decode(t)},D=(o,e)=>{const t=e.map(r=>o[r.field]);return t.push(o._id),E(JSON.stringify(h(t)))},f=()=>new S("BAD_REQUEST","invalid cursor"),O=o=>{let e;try{e=m(JSON.parse(v(o)))}catch{throw f()}if(!Array.isArray(e))throw f();return e},l=(o,e,t)=>{const r=o.some(n=>b.has(n.field))?o:[...o,{direction:"asc",field:y}],s=[];for(const[n,i]of r.entries()){const c=[];for(const[a,p]of r.slice(0,n).entries())c.push({[p.field]:{eq:e[a]}});const u=t(i.direction,n===r.length-1);c.push({[i.field]:{[u]:e[n]}});const[d]=c;s.push(c.length===1&&d!==void 0?d:{AND:c})}return{OR:s}},k=(o,e)=>l(o,e,t=>t==="desc"?"lt":"gt"),_=(o,e)=>o==="desc"?e?"gte":"gt":e?"lte":"lt",w=(o,e)=>l(o,e,_),C=["_id","_creationTime"],B=(o,e,t)=>{if(!e)return o;const r=new Set([...e,...C,...t?Object.keys(t):[]]);return o.map(s=>{const n={};for(const i of r)i in s&&(n[i]=s[i]);return n})},L=(o,e)=>o&&e!==!0?{[o.field]:{isNull:!0}}:void 0,x=(o,e)=>e===void 0||o[e]===null||o[e]===void 0;export{B as applySelect,w as buildSeekBeforeWhere,k as buildSeekWhere,O as decodeCursor,D as encodeCursor,v as fromBase64,f as invalidCursor,x as isLiveForCompanion,A as normalizeOrderKeys,L as softDeleteScope,E as toBase64};
@@ -1 +0,0 @@
1
- import{stableStringify as m}from"./stableStringify-G9OF5wcs.mjs";import{i as A,e as w}from"./wire-codec-BU9T2xJ7.mjs";const D="_id",p="_creationTime",y="page",J=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},_=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=J(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},F="__lunora__",L=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=L(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},E=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},R=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),a=e.byId.get(r),d=JSON.stringify(w(i)),c=a===void 0?void 0:JSON.stringify(a);if(c===d)continue;const f=c===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},P=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!A(e)||!A(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(m(n(e))===m(w(n(t))))return{next:o,previous:s}},T=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(_(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=P(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const a=s===""?F:s,d=JSON.stringify(a),c=[...E(r,i,a,d),...R(r,i,a,d)];return T(r,i,c)?c:void 0},B=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},C=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:a,table:d}=e,c=JSON.stringify(a),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${c},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${c},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},W=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{W as awaitWsDrain,K as subscriptionFrames,B as subscriptionListDeltas,C as trySendFrame};
@@ -1 +0,0 @@
1
- import{LunoraError as L}from"@lunora/errors";import{sql as s}from"drizzle-orm";import{sqliteInList as a,WORKERD_SQLITE_LIMITS as I}from"./param-Ib8WHnrF.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const m=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],T=new Set(m),E={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},O=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const o=Object.keys(t);return o.length>0&&o.every(n=>T.has(n))},$=(t,o,n)=>{const i=s`${n.serialize(o)}`;return n.containsExpr?n.containsExpr(t,i):s`instr(lower(${t}), lower(${i})) > 0`},A=(t,o,n,i,r)=>i===null?o==="ne"?s`${t} IS NOT NULL`:s`${t} IS NULL`:s`${t} ${s.raw(n)} ${r.serialize(i)}`,S=(t,o,n,i)=>{const r=Array.isArray(n)?n:[];if(r.length===0)return o==="IN"?s`0 = 1`:s`1 = 1`;const e=r.map(l=>i.serialize(l)),c=o==="NOT IN";return(i.inList??a)(t,e,c)},M=(t,o,n)=>{const i=s.join(o.map(r=>s`${r}`),s`, `);return n?s`${t} NOT IN (${i})`:s`${t} IN (${i})`},h=(t,o,n)=>{const i=o,r=[];for(const e of m){if(!(e in i))continue;const c=i[e],l=E[e];l?r.push(A(t,e,l,c,n)):e==="isNull"?r.push(c?s`${t} IS NULL`:s`${t} IS NOT NULL`):e==="contains"?r.push($(t,c,n)):r.push(S(t,e==="in"?"IN":"NOT IN",c,n))}return r},R=(t,o,n)=>{const i=n.fieldRef(t);return O(o)?h(i,o,n):o===null?[s`${i} IS NULL`]:[s`${i} = ${n.serialize(o)}`]},p=(t,o)=>{if(t.length<=1)return t[0];const n=Math.floor(t.length/2);return s`(${p(t.slice(0,n),o)}) ${s.raw(o)} (${p(t.slice(n),o)})`},d=(t,o,n)=>{const i=Array.isArray(t)?t:[],r=[];for(const e of i){const c=f(e??{},n);c&&r.push(c)}return r.length===0?o==="OR"?s`0 = 1`:void 0:p(r,o)},_=new Set(["AND","NOT","OR",N]),b=(t,o,n)=>{if(t===N){if(!n.relationExists)throw new L("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return n.relationExists(o)}if(t==="NOT"){const i=f(o??{},n);return i?s`NOT (${i})`:void 0}return d(o,t,n)},f=(t,o)=>{const n=[];for(const[i,r]of Object.entries(t))if(_.has(i)){const e=b(i,r,o);e&&n.push(e)}else n.push(...R(i,r,o));return p(n,"AND")},j=I.boundParams/2,u=t=>{if(Array.isArray(t))return t.reduce((n,i)=>n+u(i),0);if(t===null||typeof t!="object")return 0;let o=0;for(const[n,i]of Object.entries(t))n==="in"||n==="notIn"?o+=1:(n==="AND"||n==="NOT"||n==="OR"||O(i))&&(o+=u(i));return o},q=(t,o)=>{if(!t||Object.keys(t).length===0)return;const n=o.inList??a,i=u(t);if(i===0)return f(t,o);const r=Math.max(1,Math.floor(j/i));return f(t,{...o,inList:(e,c,l)=>n(e,c,l,r)})};export{q as compileWhereSql,M as literalInList};
@@ -1 +0,0 @@
1
- import{c as l,i as C,r as R}from"./ctx-db-companions-BQRTS_WY.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-Cy5e03oz.mjs";import"./runDrizzle-it6rL9bR.mjs";import"./do-sql-DbEszTyj.mjs";import"./param-Ib8WHnrF.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./applySelect-BQbHyo-W.mjs";import"./RANK_TIEBREAK-ci3MaM65.mjs";import"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";import{sql as n}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as E,e as T}from"./wire-codec-BU9T2xJ7.mjs";import{runDrizzle as _}from"./runDrizzle-it6rL9bR.mjs";import{s as $}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const p=/^[A-Za-z_$][\w$]*$/u,S=e=>p.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,u="__doc__",i="__originals__",v=e=>{if(Object.hasOwn(e,i))throw new c("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[o,s]of Object.entries(e)){const a=$(s);a!==void 0&&(t??={...e},r??=Object.create(null),t[o]=a,r[o]=s)}t&&r&&(t[i]=r);try{return JSON.stringify(T(t??e))}catch(o){throw new c("BAD_REQUEST",`this document cannot be stored: ${o instanceof Error?o.message:String(o)}`)}},O=e=>{const t=E(JSON.parse(e)),{[i]:r,...o}=t;return r===null||typeof r!="object"||Array.isArray(r)?t:{...o,...r}},P=(e,t)=>`${e}__geo_${t}`,m=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${u}, '$.${S(t).replaceAll("'","''")}')`,b=e=>m("",e),R=e=>n.raw(b(e)),h=(e,t)=>m(`${A(e)}.`,t),G=(e,t)=>n.raw(h(e,t)),q=(e,t,r,o)=>n`CREATE ${o?n`UNIQUE `:n``}INDEX IF NOT EXISTS ${n.identifier(e)} ON ${n.identifier(t)} (${r})`,l=n.identifier("__key__"),g=n.identifier("__value__"),N=n.identifier("__count__"),B=(e,t,r,o,s)=>n`INSERT INTO ${n.identifier(e)} (${l}, ${g}, ${N}) VALUES (${t}, ${r}, ${o}) ON CONFLICT(${l}) DO UPDATE SET ${s}`,f=new WeakMap,J=e=>{const t=f.get(e);if(t!==void 0)return t;const r=[];for(const[o,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([o,a]))}return Object.freeze(r),f.set(e,r),r},y=e=>{if(!e)return;const t=e[u];let r;typeof t=="string"?r=O(t):t&&typeof t=="object"?r=t:r={};const{id:o}=e;typeof o=="string"&&(r._id=o);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},z=e=>{try{return y(e)}catch{return}},d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;let r;try{_(e,n`CREATE VIRTUAL TABLE IF NOT EXISTS ${n.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{_(e,n`DROP TABLE IF EXISTS ${n.identifier("__lunora_fts_probe")}`)}catch{}}return d.set(e,r),r};export{N as A,u as D,l as a,g as b,B as c,q as d,R as e,G as f,P as g,z as h,F as i,b as j,v as k,O as l,S as m,i as n,h as q,y as r,J as t};
@@ -1,5 +0,0 @@
1
- import{S,y as L,l as N}from"./ctx-db-companions-BQRTS_WY.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-Cy5e03oz.mjs";import{backfillSearchIndexesForTable as u}from"./backfillAggregateIndexes-C9wGiPH4.mjs";import{migrateCdcLog as h,migrateCdcMeta as R}from"./CDC_LOG_TABLE-CW0wHEgW.mjs";import{migrateClientWatermark as x}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{migrateCommitSeq as C}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{migrateGlobalShapeSnapshot as O}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{m as U}from"./ctx-db-relay-shapes-Jf5xpD1r.mjs";import{migrateSearchState as l}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{migrateShapePokeCursor as $}from"./SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as X,e as T,d,t as G,i as D,g as B,a as M,b as k,A as E}from"./do-sql-DbEszTyj.mjs";import{migrateDurableStreams as F}from"./appendStreamChunk-CH4e4nJn.mjs";import{rankTableName as Y,sortColumnName as P}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{migrateReactorState as j}from"./REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{recordSchemaVersion as y}from"./SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";const v=(r,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,m=e.join(i.fields.map(s=>T(s)),e`, `);a(r,d(t,n,m,i.unique??!1))}for(const[i,t]of G(o)){if(!t.unique)continue;const m=`${n}_unique_${i}`;a(r,d(m,n,T(i),!0))}},K=(r,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!D(r))){for(const i of o.searchIndexes){const t=S(n,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(L)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}u(r,n,o)}},V=(r,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=B(n,i.name);a(r,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 m=`${n}__geo_${i.name}__btree`;a(r,d(m,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},w=(r,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=p(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${M} TEXT PRIMARY KEY, ${k} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},z=(r,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=Y(n,i.name),m=i.sortBy.map((f,_)=>P(_)),s=m.map(f=>e`${e.identifier(f)} BLOB`),g=s.length>0?e`, ${e.join(s,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${g})`);const c=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of m.entries()){const I=i.sortBy[f]?.direction;c.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}c.push(e`${e.identifier("__id__")} ASC`);const A=`${n}__rank_${i.name}__btree`;a(r,d(A,t,e.join(c,e`, `),!1))}},_e=(r,n,o={})=>{o.schemaSnapshot!==void 0&&y(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),l(r);for(const[i,t]of Object.entries(n.tables))t.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${e.identifier(X)} TEXT NOT NULL
5
- )`),v(r,i,t),K(r,i,t),V(r,i,t),w(r,i,t),z(r,i,t));o.cdc&&(h(r),R(r),x(r),$(r),U(r)),Object.values(n.tables).some(i=>i.commitOrderedMode===!0)&&C(r),j(r),b(r),O(r),F(r)};export{_e as runShardMigrations};
@@ -1 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as p,r as d,e as h}from"./do-sql-DbEszTyj.mjs";import{sqliteInList as w}from"./param-Ib8WHnrF.mjs";import{compileWhereSql as S}from"./compileWhereSql-JBpSfQm9.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-DbI1VQYM.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),n=a(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of n){const s=d(l),{id:c}=l;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},z=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,g(t)),l=a(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of l){const c=d(s),{id:m}=s;c!==void 0&&typeof m=="string"&&n.set(m,c)}return n};export{z as selectShapeMembers,v as selectShapeRows};
@@ -1 +0,0 @@
1
- import{t as w,f as O}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",m=64,A=1024,d="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},j=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},a=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const y=typeof e;if(y==="bigint")return[o,"bigint",e.toString()];if(y==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(y!=="object")return e;if(e instanceof Date)return[o,"date",a(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r))r[c]!==void 0&&(n[c]=a(r[c],t+1));const i=[o,"error",r.name,r.message,n];return r.cause!==void 0&&i.push(a(r.cause,t+1)),i}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,n])=>[a(r,t+1),a(n,t+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>a(r,t+1))];if(e instanceof ArrayBuffer)return[o,"bytes",w(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[o,"bytes",w(i)]:[o,"bytes",w(i),n]}if(Array.isArray(e)){const r=e.map(n=>a(n,t+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!j(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const u=e,s={};for(const r of Object.keys(u)){const n=u[r];if(n===void 0)continue;const i=a(n,t+1);r===d?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):s[r]=i}return s},f=(e,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>A||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(r)}case"date":return new Date(f(e[2],t+1));case"map":return new Map(e[2].map(([r,n])=>[f(r,t+1),f(n,t+1)]));case"set":return new Set(e[2].map(r=>f(r,t+1)));case"url":return new URL(e[2]);case"error":{const r=e[2],n=e[3],i=(Object.hasOwn(E,r)?E[r]:void 0)??Error,c=new i(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const g=f(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(c,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):c[b]=g[b];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:f(e[5],t+1),writable:!0}),c}case"bytes":{const r=O(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const i=Object.hasOwn(p,n)?p[n]:void 0;return i?new i(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,t+1))}return e.map(s=>f(s,t+1))}const y=e,u={};for(const s of Object.keys(y)){const r=f(y[s],t+1);s===d?Object.defineProperty(u,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):u[s]=r}return u};export{f as d,a as e,j as i};