@lunora/shard-engine 1.0.0-alpha.129 → 1.0.0-alpha.130

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 (77) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +2 -3
  3. package/dist/index.d.ts +2 -3
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs +1 -0
  6. package/dist/packem_shared/{AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs → AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs} +1 -1
  7. package/dist/packem_shared/AGG_COUNT-CBe5drFS.mjs +1 -0
  8. package/dist/packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs +1 -0
  9. package/dist/packem_shared/{CDC_LOG_TABLE-CvInVdXu.mjs → CDC_LOG_TABLE-DsCz-DAV.mjs} +1 -1
  10. package/dist/packem_shared/CURSOR_PREFIX-6offuG6M.mjs +1 -0
  11. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CGF7qQsu.mjs → DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs} +1 -1
  12. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-COmk7y1x.mjs → DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-DSIYUnPB.mjs → DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs} +2 -2
  14. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs +1 -0
  15. package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs → DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs} +1 -1
  16. package/dist/packem_shared/DurableStreamRunner-Dzge_ywD.mjs +1 -0
  17. package/dist/packem_shared/NotUniqueError-CApXRyGS.mjs +1 -0
  18. package/dist/packem_shared/{RANK_TIEBREAK-BKugKf70.mjs → RANK_TIEBREAK-D3ye2GsL.mjs} +1 -1
  19. package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-Me5elP-K.mjs → RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs} +1 -1
  20. package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-BV39QRFd.mjs → RLS_UNWRAP_SYMBOL-DQt9luIF.mjs} +1 -1
  21. package/dist/packem_shared/ReactiveCache-DHhhLJtN.mjs +1 -0
  22. package/dist/packem_shared/ShapeDiffCache-iNO-hUiy.mjs +1 -0
  23. package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-CIi7v65O.mjs → VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs} +1 -1
  24. package/dist/packem_shared/aggregateTableName-B_CtIQCS.mjs +1 -0
  25. package/dist/packem_shared/{applyOnDelete-CGVYKtaW.mjs → applyOnDelete-BwxDC4lU.mjs} +1 -1
  26. package/dist/packem_shared/assertPatchAllowed-CA_H466g.mjs +1 -0
  27. package/dist/packem_shared/awaitWsDrain-N-oR29RI.mjs +1 -0
  28. package/dist/packem_shared/{backfillAggregateIndexes-DBrKU3Ya.mjs → backfillAggregateIndexes-Dw4Azd33.mjs} +1 -1
  29. package/dist/packem_shared/{buildIndexRange-6nIZDf4m.mjs → buildIndexRange-DQ3eWAGd.mjs} +1 -1
  30. package/dist/packem_shared/buildPokeFrames-WR-hp0mX.mjs +1 -0
  31. package/dist/packem_shared/buildReprojectionMigration-DQV0q3w9.mjs +1 -0
  32. package/dist/packem_shared/{buildShapeDiff-CdT2gjFd.mjs → buildShapeDiff-BHr3i1m6.mjs} +1 -1
  33. package/dist/packem_shared/{clearCompanionSignatures-Qf67j6dd.mjs → clearCompanionSignatures-8uVX84aT.mjs} +1 -1
  34. package/dist/packem_shared/compileWhereSql-CKoO19by.mjs +1 -0
  35. package/dist/packem_shared/{computeRankPage-D9mACvr3.mjs → computeRankPage-DLSi_oBt.mjs} +1 -1
  36. package/dist/packem_shared/{createCompanionSync-C2cZNaCR.mjs → createCompanionSync-DhYLePyV.mjs} +1 -1
  37. package/dist/packem_shared/{createReplicaLink-DjykIKTn.mjs → createReplicaLink-Bd7jCjDt.mjs} +1 -1
  38. package/dist/packem_shared/ctx-db-relay-shapes-CPwELrMf.mjs +17 -0
  39. package/dist/packem_shared/{defineEngineContractSuite-DCw8RIP6.mjs → defineEngineContractSuite-CMbAZiZB.mjs} +1 -1
  40. package/dist/packem_shared/diffExternalSource-B0FZlDoL.mjs +1 -0
  41. package/dist/packem_shared/do-sql-DqU-17Fs.mjs +1 -0
  42. package/dist/packem_shared/{estimate-bytes-CTuiPWMD.mjs → estimate-bytes-_k74s6LZ.mjs} +1 -1
  43. package/dist/packem_shared/{isSoftDeleted-CLY0FNLV.mjs → isSoftDeleted-D5MeQSk0.mjs} +1 -1
  44. package/dist/packem_shared/json-field-path-DeJW4U9z.mjs +1 -0
  45. package/dist/packem_shared/materializeExternalRows-D2zEvCAa.mjs +1 -0
  46. package/dist/packem_shared/{mergeChangedKeys-DH9RAARR.mjs → mergeChangedKeys-CF2mjYuy.mjs} +1 -1
  47. package/dist/packem_shared/{runShardMigrations-B6FUu4iW.mjs → runShardMigrations-BeqUbznb.mjs} +1 -1
  48. package/dist/packem_shared/{selectExpiredIds-CGR1ndMV.mjs → selectExpiredIds-B8PxwbIr.mjs} +1 -1
  49. package/dist/packem_shared/{selectShapeMembers-DS28-P_Z.mjs → selectShapeMembers-B1MIaRkE.mjs} +1 -1
  50. package/dist/packem_shared/serializeSqlValue-DeoBMpZ2.mjs +1 -0
  51. package/dist/packem_shared/{where-sql-CxnXsLbt.mjs → where-sql-DO1vOrhc.mjs} +1 -1
  52. package/package.json +2 -1
  53. package/dist/packem_shared/ADMIN_FUNCTIONS-DmacEYTh.mjs +0 -1
  54. package/dist/packem_shared/AGG_COUNT-DYFE3qB4.mjs +0 -1
  55. package/dist/packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs +0 -1
  56. package/dist/packem_shared/CURSOR_PREFIX-BztyXqNP.mjs +0 -1
  57. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs +0 -1
  58. package/dist/packem_shared/DurableStreamRunner-SCTUaMG0.mjs +0 -1
  59. package/dist/packem_shared/NotUniqueError-B69J01E7.mjs +0 -1
  60. package/dist/packem_shared/ReactiveCache-Bdzsahf3.mjs +0 -1
  61. package/dist/packem_shared/ShapeDiffCache-Br3kxusw.mjs +0 -1
  62. package/dist/packem_shared/aggregateTableName-DbAttCNH.mjs +0 -1
  63. package/dist/packem_shared/assertPatchAllowed-BJ_2LgkQ.mjs +0 -1
  64. package/dist/packem_shared/awaitWsDrain-D4E7Oiwo.mjs +0 -1
  65. package/dist/packem_shared/base64-DfpzS4o_.mjs +0 -1
  66. package/dist/packem_shared/buildPokeFrames-CDOP-XYp.mjs +0 -1
  67. package/dist/packem_shared/buildReprojectionMigration-D29YmeMF.mjs +0 -1
  68. package/dist/packem_shared/compileWhereSql-Dol9VRTW.mjs +0 -1
  69. package/dist/packem_shared/ctx-db-relay-shapes-OAI2tSoy.mjs +0 -17
  70. package/dist/packem_shared/diffExternalSource-DgDJhslq.mjs +0 -1
  71. package/dist/packem_shared/do-sql-CeuVvE0W.mjs +0 -1
  72. package/dist/packem_shared/json-field-path-B2fjnGc3.mjs +0 -1
  73. package/dist/packem_shared/materializeExternalRows-UxGuXjjF.mjs +0 -1
  74. package/dist/packem_shared/serializeSqlValue-BbZ5hKM7.mjs +0 -1
  75. package/dist/packem_shared/stableStringify-DibjylKD.mjs +0 -1
  76. package/dist/packem_shared/stableWireKey-Bdh5JSdg.mjs +0 -1
  77. package/dist/packem_shared/wire-codec-BYCSiazv.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{LunoraError as h}from"@lunora/errors";import{f as x,S as O}from"./fts-companion-DzfEHonU.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as A}from"./aggregateTableName-DbAttCNH.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-DBrKU3Ya.mjs";import{migrateCdcLog as C,migrateCdcMeta as N}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{migrateClientWatermark as b}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{migrateCommitSeq as D}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{migrateCompanionState as $}from"./clearCompanionSignatures-Qf67j6dd.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{migrateIdempotency as M}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{m as G}from"./ctx-db-relay-shapes-OAI2tSoy.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{m as y}from"./ctx-db-search-state-CrTLPmFN.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{runDrizzle as m,runAll as k}from"./runDrizzle-B2GG3IJa.mjs";import{D as P,d as E,e as u,t as Y,i as B,g as j,a as v,b as w,A as p}from"./do-sql-CeuVvE0W.mjs";import{renderSql as H}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{migrateDurableStreams as K}from"./appendStreamChunk-DF_Jrgpy.mjs";import{rankTableName as S,sortColumnName as W}from"./RANK_TIEBREAK-BKugKf70.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{recordSchemaVersion as z}from"./SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";const l=r`_creationTime, id`,L=(e,n,o,i,t,a)=>{const s=r.join(t.map(d=>r`${d} IS NOT NULL`),r` AND `);if(m(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${s} GROUP BY ${i} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new h("INTERNAL",`unique index "${n}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},J=(e,n,o,i,t,a)=>{const c=m(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o}`).toArray()[0]?.sql;if(c==null)return;const d=_=>{const g=_.indexOf("(");return g===-1?void 0:_.slice(g,_.lastIndexOf(")")+1)},T=d(H("sqlite",E(n,o,i,t)).sql),f=d(c);T===void 0||f===void 0||T===f||(t&&L(e,n,o,i,a,"cannot be re-created with its new column list"),m(e,r`DROP INDEX IF EXISTS ${r.identifier(n)}`))},Q=(e,n,o)=>m(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,n,o,i,t,a)=>{t&&!Q(e,n,o)&&L(e,n,o,i,a,"cannot be created"),m(e,E(n,o,i,t))},Z=(e,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,a=i.unique??!1,s=i.fields.map(T=>u(T)),c=r.join(s,r`, `),d=a?c:r`${c}, ${l}`;J(e,t,n,d,a,s),I(e,t,n,d,a,s)}for(const[i,t]of Y(o)){if(!t.unique)continue;const a=u(i);I(e,`${n}_unique_${i}`,n,a,!0,[a])}},q=(e,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!B(e))){for(const i of o.searchIndexes)k(e,x(O(n,i.name)));R(e,n,o)}},ee=(e,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=j(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${n}__geo_${i.name}__btree`;m(e,E(a,t,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},re=(e,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=A(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${v} TEXT PRIMARY KEY, ${w} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),m(e,r`PRAGMA table_info(${r.identifier(t)})`).toArray().some(s=>s.name==="__count__")||m(e,r`ALTER TABLE ${r.identifier(t)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},te=(e,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=S(n,i.name),a=i.sortBy.map((f,_)=>W(_)),s=a.map(f=>r`${r.identifier(f)} BLOB`),c=s.length>0?r`, ${r.join(s,r`, `)}`:r``;m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${c})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const g=i.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(g==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${n}__rank_${i.name}__btree`;m(e,E(T,t,r.join(d,r`, `),!1))}},Oe=(e,n,o={})=>{o.schemaSnapshot!==void 0&&z(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),y(e);const i=[];for(const[t,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"&&(m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
1
+ import{LunoraError as h}from"@lunora/errors";import{f as x,S as O}from"./fts-companion-DzfEHonU.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as A}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{migrateCdcLog as C,migrateCdcMeta as N}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{migrateClientWatermark as b}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{migrateCommitSeq as D}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{migrateCompanionState as $}from"./clearCompanionSignatures-8uVX84aT.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{migrateIdempotency as M}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{m as G}from"./ctx-db-relay-shapes-CPwELrMf.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{m as y}from"./ctx-db-search-state-CrTLPmFN.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{runDrizzle as m,runAll as k}from"./runDrizzle-B2GG3IJa.mjs";import{D as P,d as E,e as u,t as Y,i as B,g as j,a as v,b as w,A as p}from"./do-sql-DqU-17Fs.mjs";import{renderSql as H}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{migrateDurableStreams as K}from"./appendStreamChunk-DF_Jrgpy.mjs";import{rankTableName as S,sortColumnName as W}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{recordSchemaVersion as z}from"./SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";const l=r`_creationTime, id`,L=(e,n,o,i,t,a)=>{const s=r.join(t.map(d=>r`${d} IS NOT NULL`),r` AND `);if(m(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${s} GROUP BY ${i} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new h("INTERNAL",`unique index "${n}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},J=(e,n,o,i,t,a)=>{const c=m(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o}`).toArray()[0]?.sql;if(c==null)return;const d=_=>{const g=_.indexOf("(");return g===-1?void 0:_.slice(g,_.lastIndexOf(")")+1)},T=d(H("sqlite",E(n,o,i,t)).sql),f=d(c);T===void 0||f===void 0||T===f||(t&&L(e,n,o,i,a,"cannot be re-created with its new column list"),m(e,r`DROP INDEX IF EXISTS ${r.identifier(n)}`))},Q=(e,n,o)=>m(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,n,o,i,t,a)=>{t&&!Q(e,n,o)&&L(e,n,o,i,a,"cannot be created"),m(e,E(n,o,i,t))},Z=(e,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,a=i.unique??!1,s=i.fields.map(T=>u(T)),c=r.join(s,r`, `),d=a?c:r`${c}, ${l}`;J(e,t,n,d,a,s),I(e,t,n,d,a,s)}for(const[i,t]of Y(o)){if(!t.unique)continue;const a=u(i);I(e,`${n}_unique_${i}`,n,a,!0,[a])}},q=(e,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!B(e))){for(const i of o.searchIndexes)k(e,x(O(n,i.name)));R(e,n,o)}},ee=(e,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=j(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${n}__geo_${i.name}__btree`;m(e,E(a,t,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},re=(e,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=A(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${v} TEXT PRIMARY KEY, ${w} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),m(e,r`PRAGMA table_info(${r.identifier(t)})`).toArray().some(s=>s.name==="__count__")||m(e,r`ALTER TABLE ${r.identifier(t)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},te=(e,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=S(n,i.name),a=i.sortBy.map((f,_)=>W(_)),s=a.map(f=>r`${r.identifier(f)} BLOB`),c=s.length>0?r`, ${r.join(s,r`, `)}`:r``;m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${c})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const g=i.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(g==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${n}__rank_${i.name}__btree`;m(e,E(T,t,r.join(d,r`, `),!1))}},Oe=(e,n,o={})=>{o.schemaSnapshot!==void 0&&z(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),y(e);const i=[];for(const[t,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"&&(m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  _creationTime REAL NOT NULL,
4
4
  ${r.identifier(P)} TEXT NOT NULL
@@ -1 +1 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-B2GG3IJa.mjs";import{e}from"./do-sql-CeuVvE0W.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-B2GG3IJa.mjs";import{e}from"./do-sql-DqU-17Fs.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 l}from"./runDrizzle-B2GG3IJa.mjs";import{D as p,r as a,m as h}from"./do-sql-CeuVvE0W.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{c as $}from"./where-sql-CxnXsLbt.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-B2GG3IJa.mjs";import{D as p,r as a,m as h}from"./do-sql-DqU-17Fs.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{c as $}from"./where-sql-DO1vOrhc.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
@@ -0,0 +1 @@
1
+ import{sqlComparableProjection as o}from"./BIGINT_KEY_DIGITS-DE6yshOt.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};
@@ -1 +1 @@
1
- import{LunoraError as S}from"@lunora/errors";import{sql as c}from"drizzle-orm";import{i as T,a as y}from"./json-field-path-B2fjnGc3.mjs";import{sqliteInList as x,isJsonSafe as O,bytesAsHexJson as C,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{quoteIdentifier as w}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as b,SEEK_RANGE as j}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const U={binary:(t,n,s)=>c`${t} ${c.raw(n)} ${s}`,constant:t=>t?c`1 = 1`:c`0 = 1`,connect:(t,n,s)=>c`(${t}) ${c.raw(s)} (${n})`,contains:(t,n)=>c`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>x(t,n,s,o),negate:t=>c`NOT (${t})`,nullCheck:(t,n)=>n?c`${t} IS NOT NULL`:c`${t} IS NULL`,value:t=>c`${t}`},h=(...t)=>{let n="";const s=[];for(const o of t)typeof o=="string"?n+=o:(n+=o.text,s.push(...o.params));return{params:s,text:n}},E=t=>({params:[t],text:"?"}),A=t=>({params:[],text:t}),nt=t=>A(w(t)),st={binary:(t,n,s)=>h(t," ".concat(n," "),E(s)),constant:t=>A(t?"1 = 1":"0 = 1"),connect:(t,n,s)=>h("(",t,") ".concat(s," ("),n,")"),contains:(t,n)=>h("instr(lower(",t,"), lower(",n,")) > 0"),inList:(t,n,s,o)=>{const i=s?" NOT IN ":" IN ",e=n.every(l=>O(l)),r=n.length>o&&!e?C(n):void 0;if(r!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',E(r),"))");if(n.length>o&&!e)throw new S("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);if(n.length<=o){const l=[t,i,"("];for(const[a,u]of n.entries())a>0&&l.push(", "),l.push(E(u));return l.push(")"),h(...l)}return h(t,i,'(SELECT "value" FROM json_each(',E(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:E},v=L.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],M=new Set(I),R=new Set(["gt","gte","lt","lte"]),D={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>M.has(s))},P=(t,n,s,o,i)=>{const e=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,e):i.contains(n,e)},g=(t,n,s,o,i)=>{const e=y(s);return e===void 0?i.constant(!1):i.connect(n,o.rangeTypeGuard(t,e),"AND")},k=(t,n,s,o,i,e,r,l)=>{if(i===null)return s==="eq"||s==="ne"?r.nullCheck(n,s==="ne"):r.constant(!1);const a=r.binary(n,o,e.serialize(i,t));return!l&&R.has(s)&&T(t)?g(t,a,i,e,r):a},F=(t,n,s,o,i,e)=>{if(!Array.isArray(o))throw new S("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const r=o;if(r.length===0)return e.constant(s==="NOT IN");const l=r.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,l,a):e.inList(n,l,a,v)},$=L.boundParams/2,G=6e4,B=(t,n)=>{const s={bytes:[],hasNull:!1,numbers:[],strings:[]};for(const o of t)if(o===null)s.hasNull=!0;else if(o instanceof Uint8Array)s.bytes.push(Array.from(o,i=>i.toString(16).padStart(2,"0")).join(""));else if(typeof o=="number"&&O(o))s.numbers.push(o);else if(typeof o=="string"&&O(o))s.strings.push(o);else throw new S("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value that cannot be bound as one parameter (a non-finite number, or malformed text). Narrow the list to ${String(n)} values or fewer.`);return s},q=(t,n,s)=>{const o=[],i=c.identifier("v"),e=c.identifier("__in__"),r=a=>c`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,l=(a,u)=>c`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${c.raw(u)} PATH '$')) ${e}`;return s.strings.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT ${r(s.strings)})`:c`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${l(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT CAST(${r(s.numbers)} AS double precision))`:c`${n} IN (SELECT ${i} FROM ${l(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT decode(${r(s.bytes)}, 'hex'))`:c`${n} IN (SELECT UNHEX(${i}) FROM ${l(s.bytes,"LONGTEXT")})`),o},ot=t=>(n,s,o,i=$)=>{const e=Math.floor(G*i/$);if(s.length<=e){const u=c.join(s.map(p=>c`${p}`),c`, `);return o?c`${n} NOT IN (${u})`:c`${n} IN (${u})`}const r=B(s,e);if(o&&r.hasNull)return c`1 = 0`;const l=q(t,n,r);if(l.length===0)return c`1 = 0`;const a=l.length===1?l[0]:c`(${c.join(l,c` OR `)})`;return o?c`NOT (${a})`:a},K=(t,n,s,o,i)=>{const e=s,r=[];for(const l of I){if(!(l in e))continue;const a=e[l],u=D[l];u?r.push(k(t,n,l,u,a,o,i,s[j]===!0)):l==="isNull"?r.push(i.nullCheck(n,!a)):l==="contains"?r.push(P(t,n,a,o,i)):r.push(F(t,n,l==="in"?"IN":"NOT IN",a,o,i))}return r},z=(t,n,s,o)=>{const i=s.fieldRef(t);return d(n)?K(t,i,n,s,o):n===null?[o.nullCheck(i,!1)]:[o.binary(i,"=",s.serialize(n,t))]},N=(t,n,s)=>{if(t.length<=1)return t[0];const o=Math.floor(t.length/2);return s.connect(N(t.slice(0,o),n,s),N(t.slice(o),n,s),n)},J=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],e=[];for(const r of i){const l=f(r??{},s,o);if(l!==void 0)e.push(l);else if(n==="OR")return}return e.length===0?n==="OR"?o.constant(!1):void 0:N(e,n,o)},Y=new Set(["AND","NOT","OR",b]),Q=(t,n,s,o)=>{if(t===b){if(!s.relationExists)throw new S("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=f(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return J(n,t,s,o)},f=(t,n,s)=>{const o=[];for(const[i,e]of Object.entries(t))if(Y.has(i)){const r=Q(i,e,n,s);r!==void 0&&o.push(r)}else o.push(...z(i,e,n,s));return N(o,"AND",s)},m=t=>{let n=0,s=0;const o=i=>{const e=m(i);n+=e.lists,s+=e.scalars};if(Array.isArray(t)){for(const i of t)o(i);return{lists:n,scalars:s}}if(t===null||typeof t!="object")return{lists:n,scalars:s};for(const[i,e]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||d(e)?(o(e),T(i)&&(s+=1+Object.keys(e).filter(r=>R.has(r)).length)):s+=T(i)?2:1;return{lists:n,scalars:s}},it=(t,n,s=U,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:e}=m(t);if(i===0)return f(t,n,s);const r=Math.max(1,Math.floor(Math.min($,L.boundParams-e-o)/i)),l=n.inList??((a,u,p,_)=>s.inList(a,u,p,_??r));return f(t,{...n,inList:(a,u,p)=>l(a,u,p,r)},s)};export{it as c,nt as i,h as j,A as r,ot as s,st as t};
1
+ import{LunoraError as S}from"@lunora/errors";import{sql as c}from"drizzle-orm";import{i as T,b as y}from"./json-field-path-DeJW4U9z.mjs";import{sqliteInList as x,isJsonSafe as O,bytesAsHexJson as C,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{quoteIdentifier as w}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as b,SEEK_RANGE as j}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const U={binary:(t,n,s)=>c`${t} ${c.raw(n)} ${s}`,constant:t=>t?c`1 = 1`:c`0 = 1`,connect:(t,n,s)=>c`(${t}) ${c.raw(s)} (${n})`,contains:(t,n)=>c`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>x(t,n,s,o),negate:t=>c`NOT (${t})`,nullCheck:(t,n)=>n?c`${t} IS NOT NULL`:c`${t} IS NULL`,value:t=>c`${t}`},h=(...t)=>{let n="";const s=[];for(const o of t)typeof o=="string"?n+=o:(n+=o.text,s.push(...o.params));return{params:s,text:n}},E=t=>({params:[t],text:"?"}),A=t=>({params:[],text:t}),nt=t=>A(w(t)),st={binary:(t,n,s)=>h(t," ".concat(n," "),E(s)),constant:t=>A(t?"1 = 1":"0 = 1"),connect:(t,n,s)=>h("(",t,") ".concat(s," ("),n,")"),contains:(t,n)=>h("instr(lower(",t,"), lower(",n,")) > 0"),inList:(t,n,s,o)=>{const i=s?" NOT IN ":" IN ",e=n.every(l=>O(l)),r=n.length>o&&!e?C(n):void 0;if(r!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',E(r),"))");if(n.length>o&&!e)throw new S("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);if(n.length<=o){const l=[t,i,"("];for(const[a,u]of n.entries())a>0&&l.push(", "),l.push(E(u));return l.push(")"),h(...l)}return h(t,i,'(SELECT "value" FROM json_each(',E(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:E},v=L.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],M=new Set(I),R=new Set(["gt","gte","lt","lte"]),D={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>M.has(s))},P=(t,n,s,o,i)=>{const e=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,e):i.contains(n,e)},g=(t,n,s,o,i)=>{const e=y(s);return e===void 0?i.constant(!1):i.connect(n,o.rangeTypeGuard(t,e),"AND")},k=(t,n,s,o,i,e,r,l)=>{if(i===null)return s==="eq"||s==="ne"?r.nullCheck(n,s==="ne"):r.constant(!1);const a=r.binary(n,o,e.serialize(i,t));return!l&&R.has(s)&&T(t)?g(t,a,i,e,r):a},F=(t,n,s,o,i,e)=>{if(!Array.isArray(o))throw new S("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const r=o;if(r.length===0)return e.constant(s==="NOT IN");const l=r.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,l,a):e.inList(n,l,a,v)},$=L.boundParams/2,G=6e4,B=(t,n)=>{const s={bytes:[],hasNull:!1,numbers:[],strings:[]};for(const o of t)if(o===null)s.hasNull=!0;else if(o instanceof Uint8Array)s.bytes.push(Array.from(o,i=>i.toString(16).padStart(2,"0")).join(""));else if(typeof o=="number"&&O(o))s.numbers.push(o);else if(typeof o=="string"&&O(o))s.strings.push(o);else throw new S("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value that cannot be bound as one parameter (a non-finite number, or malformed text). Narrow the list to ${String(n)} values or fewer.`);return s},q=(t,n,s)=>{const o=[],i=c.identifier("v"),e=c.identifier("__in__"),r=a=>c`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,l=(a,u)=>c`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${c.raw(u)} PATH '$')) ${e}`;return s.strings.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT ${r(s.strings)})`:c`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${l(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT CAST(${r(s.numbers)} AS double precision))`:c`${n} IN (SELECT ${i} FROM ${l(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?c`${n} IN (SELECT decode(${r(s.bytes)}, 'hex'))`:c`${n} IN (SELECT UNHEX(${i}) FROM ${l(s.bytes,"LONGTEXT")})`),o},ot=t=>(n,s,o,i=$)=>{const e=Math.floor(G*i/$);if(s.length<=e){const u=c.join(s.map(p=>c`${p}`),c`, `);return o?c`${n} NOT IN (${u})`:c`${n} IN (${u})`}const r=B(s,e);if(o&&r.hasNull)return c`1 = 0`;const l=q(t,n,r);if(l.length===0)return c`1 = 0`;const a=l.length===1?l[0]:c`(${c.join(l,c` OR `)})`;return o?c`NOT (${a})`:a},K=(t,n,s,o,i)=>{const e=s,r=[];for(const l of I){if(!(l in e))continue;const a=e[l],u=D[l];u?r.push(k(t,n,l,u,a,o,i,s[j]===!0)):l==="isNull"?r.push(i.nullCheck(n,!a)):l==="contains"?r.push(P(t,n,a,o,i)):r.push(F(t,n,l==="in"?"IN":"NOT IN",a,o,i))}return r},z=(t,n,s,o)=>{const i=s.fieldRef(t);return d(n)?K(t,i,n,s,o):n===null?[o.nullCheck(i,!1)]:[o.binary(i,"=",s.serialize(n,t))]},N=(t,n,s)=>{if(t.length<=1)return t[0];const o=Math.floor(t.length/2);return s.connect(N(t.slice(0,o),n,s),N(t.slice(o),n,s),n)},J=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],e=[];for(const r of i){const l=f(r??{},s,o);if(l!==void 0)e.push(l);else if(n==="OR")return}return e.length===0?n==="OR"?o.constant(!1):void 0:N(e,n,o)},Y=new Set(["AND","NOT","OR",b]),Q=(t,n,s,o)=>{if(t===b){if(!s.relationExists)throw new S("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=f(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return J(n,t,s,o)},f=(t,n,s)=>{const o=[];for(const[i,e]of Object.entries(t))if(Y.has(i)){const r=Q(i,e,n,s);r!==void 0&&o.push(r)}else o.push(...z(i,e,n,s));return N(o,"AND",s)},m=t=>{let n=0,s=0;const o=i=>{const e=m(i);n+=e.lists,s+=e.scalars};if(Array.isArray(t)){for(const i of t)o(i);return{lists:n,scalars:s}}if(t===null||typeof t!="object")return{lists:n,scalars:s};for(const[i,e]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||d(e)?(o(e),T(i)&&(s+=1+Object.keys(e).filter(r=>R.has(r)).length)):s+=T(i)?2:1;return{lists:n,scalars:s}},it=(t,n,s=U,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:e}=m(t);if(i===0)return f(t,n,s);const r=Math.max(1,Math.floor(Math.min($,L.boundParams-e-o)/i)),l=n.inList??((a,u,p,_)=>s.inList(a,u,p,_??r));return f(t,{...n,inList:(a,u,p)=>l(a,u,p,r)},s)};export{it as c,nt as i,h as j,A as r,ot as s,st as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.129",
3
+ "version": "1.0.0-alpha.130",
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",
@@ -50,6 +50,7 @@
50
50
  "dependencies": {
51
51
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
52
52
  "@lunora/platform": "1.0.0-alpha.64",
53
+ "@lunora/wire": "1.0.0-alpha.1",
53
54
  "drizzle-orm": "^0.45.3"
54
55
  },
55
56
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{sql as x}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{n as A,o as j}from"./do-sql-CeuVvE0W.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{d as U}from"./wire-codec-BYCSiazv.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-BbZ5hKM7.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...U(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[d],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(o=>o!==d),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${j(e)}`]}},z=/^-?\d+$/u,Z=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,Z(e,o)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},y=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>_===d?oe(u(_)):I(u(_)));i.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const a=_e(t);if(a!==void 0){for(const c of e)o.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),i.push(a.from,a.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(o.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),i.push(JSON.stringify(_),a.from,a.to))}s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=te(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),i=u(n),o=R(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(o,a,t.filters,t.columnKinds),l=ce(t.orderBy,o),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${i}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(o,P),sqlColumns:o,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),i=R(e,s),o=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,i)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const a=y(i,o,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(o=>o!==d));if(!n.includes(d))return s;for(const o of Object.keys(r??{}))s.add(o);const i=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:o}of i){const a=typeof o=="string"?$(o):void 0;if(a!==void 0)for(const _ of Object.keys(a))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),i=R(e,s);if(!le(e,s,i,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=E(n,i);if(o===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(i,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...f,...o.params,a+1).toArray(),p=g.length>a,h=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,a).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const i of s)r[i]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[i,o]of Object.entries(t)){if(M(i)||!F(e,i))continue;const a=u(i),_=R(e,a);for(const c of o){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(x.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${a} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:i})}}return{references:r,storageColumns:t}},Ne=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Pe=(e,t=ue)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
@@ -1 +0,0 @@
1
- import"./effective-kind-BmG_zCAy.mjs";import"./json-field-path-B2fjnGc3.mjs";import{A as i,a as n,b as d,D as m,n as p,c as u,d as q,l as G,s as c,m as S,k as f,g as A,i as D,j as h,e as T,p as _,u as g,q as j,f as y,r as C,t as O,h as b}from"./do-sql-CeuVvE0W.mjs";import{quoteIdentifier as I}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-BYCSiazv.mjs";import"./runDrizzle-B2GG3IJa.mjs";import{serializeSqlValue as N}from"./serializeSqlValue-BbZ5hKM7.mjs";import"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";export{i as AGG_COUNT,n as AGG_KEY,d as AGG_VALUE,m as DOC_COLUMN,p as DOC_ORIGINALS_KEY,u as aggUpsertSql,q as createIndexSql,G as decodeDocJson,c as decodeGroupKeyValue,S as doWhereSqlStrategy,f as encodeDocJson,A as geoTableName,D as isFtsAvailable,h as jsonPath,T as jsonPathSql,_ as jsonTypeGuard,g as jsonTypeGuardSql,j as qualifiedJsonPath,y as qualifiedJsonPathSql,I as quoteIdentifier,C as rowToDocument,N as serializeSqlValue,O as tableColumns,b as tryRowToDocument};
@@ -1 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{t as o}from"./base64-DfpzS4o_.mjs";import{e as s}from"./effective-kind-BmG_zCAy.mjs";const i=39,f="0",c="1",a=t=>Array.from(t,e=>String(9-Number(e))).join(""),d=t=>{const e=t<0n,n=(e?-t:t).toString();if(n.length>i)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(n.length)} digits, over the ${String(i)}-digit limit for a queryable column`);const r=n.padStart(i,"0");return e?f+a(r):c+r},l=/^\d+$/u,b=t=>{if(t.length!==i+1)return;const e=t.slice(0,1),n=t.slice(1);if(l.test(n))return e===c?BigInt(n):e===f?-BigInt(a(n)):void 0},m=/^[\da-f]{16}$/u,p=t=>{const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t===0?0:t,!1);let n=e.getUint32(0,!1),r=e.getUint32(4,!1);return(n&2147483648)===0?n=(n^2147483648)>>>0:(n=~n>>>0,r=~r>>>0),n.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")},E=t=>{if(!m.test(t))return;let e=Number.parseInt(t.slice(0,8),16),n=Number.parseInt(t.slice(8),16);(e&2147483648)===0?(e=~e>>>0,n=~n>>>0):e=(e^2147483648)>>>0;const r=new DataView(new ArrayBuffer(8));return r.setUint32(0,e,!1),r.setUint32(4,n,!1),r.getFloat64(0,!1)},h=t=>typeof t=="bigint"?d(t):t instanceof ArrayBuffer?o(new Uint8Array(t)):ArrayBuffer.isView(t)?o(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):void 0,u=t=>{const e=s(t);return e==="bigint"||e==="bytes"},w=t=>{const e=s(t);return u(t)||e==="any"||e==="union"||e==="from"};export{i as BIGINT_KEY_DIGITS,d as bigintSqlKey,b as decodeBigintSqlKey,E as decodeFloat64SqlKey,p as float64SqlKey,u as isProjectedKind,w as mayHoldProjectedValue,h as sqlComparableProjection};
@@ -1 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{v as p}from"./accepts-null-D1zmJbyR.mjs";import{r as O}from"./json-field-path-B2fjnGc3.mjs";import{d as _,e as E}from"./wire-codec-BYCSiazv.mjs";import{SEEK_RANGE as A}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const R="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",b=new Set(["_id","id"]),F=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(F.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1||p(n)},T=new Set(["AND","NOT","OR"]),U=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,r]of Object.entries(e)){if(T.has(n))continue;if(r===null||typeof r!="object"||Array.isArray(r)){t.add(n);continue}const o=Object.keys(r);o.length===1&&o[0]==="eq"&&t.add(n)}return t},x=(e,t)=>{const n=[];for(const r of e??[])r.unique===!0&&n.push(r.fields);for(const[r,o]of Object.entries(t??{}))o._meta?.column?.unique===!0&&n.push([r]);return n},I=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(r=>e.has(r))),y=e=>e.nulls===void 0?e.direction!=="desc":e.nulls==="first",K=e=>e?" NULLS FIRST":" NULLS LAST",D=e=>{if(typeof e!="object"||e===null)return!1;const{nulls:t,sort:n}=e;return(n==="asc"||n==="desc")&&(t==="first"||t==="last")},L=(e,t,n)=>{if(t!=="asc"&&t!=="desc"&&!D(t))throw new S("VALIDATION_ERROR",`orderBy "${e}": expected "asc", "desc" or { sort: "asc" | "desc", nulls: "first" | "last" }`);const r=typeof t=="string"?t:t.sort,o=g(e,n);return typeof t=="string"||!o||y({direction:r})===(t.nulls==="first")?{direction:r,field:e,nullable:o}:{direction:r,field:e,nullable:o,nulls:t.nulls}},J=(e,t,n)=>{const r=[],o=new Set(n?.pinned);let l="asc";for(const i of e??[])for(const[c,s]of Object.entries(i)){const u=L(c,s,t),{direction:a}=u;l=a,o.add(c),!n?.pinned?.has(c)&&r.push(u)}return r.length===0?[{direction:l,field:"_creationTime",nullable:!1}]:(r.some(i=>b.has(i.field)||i.field==="_creationTime")||I(o,n?.uniqueBy)||r.push({direction:h(r),field:"_creationTime",nullable:!1}),r)},w=/[\u0080-\u{10FFFF}]/u,v=e=>{if(!w.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},C=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},f="~4",z=(e,t)=>{const n=t.map(r=>O(e,r.field)??null);return n.push(e._id),f+v(JSON.stringify(E(n)))},d=()=>new S("BAD_REQUEST","invalid cursor"),G=e=>{if(!e.startsWith(f))throw d();let t;try{t=_(JSON.parse(C(e.slice(f.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,l=e.direction!=="desc"===n,i=y(e)===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let c=l?"gt":"lt";r&&(c=l?"gte":"lte");const s={[o]:{[c]:t,[A]:!0}};return i||!e.nullable?s:{OR:[s,{[o]:{isNull:!0}}]}},N=(e,t,n,r)=>{const o=e.some(s=>b.has(s.field))?e:[...e,{direction:h(e),field:R,nullable:!1}];if(t.length<o.length)throw d();const l=s=>{const u=o[s];if(u===void 0)throw d();const a=m(u,t[s],n,r&&s===o.length-1);return s===o.length-1?a:{OR:[a,{AND:[{[u.field]:{eq:t[s]}},l(s+1)]}]}},i=l(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?i:{AND:[m(c,t[0],n,!0),i]}},H=(e,t)=>N(e,t,!0,!1),M=(e,t)=>N(e,t,!1,!0),j=["_id","_creationTime"],Q=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...j,...n?Object.keys(n):[]]);return e.map(o=>{const l={};for(const i of r)i in o&&(l[i]=o[i]);return l})},X=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,Y=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{f as CURSOR_PREFIX,Q as applySelect,M as buildSeekBeforeWhere,H as buildSeekWhere,G as decodeCursor,z as encodeCursor,U as equalityPinnedFields,C as fromBase64,Y as isLiveForCompanion,J as normalizeOrderKeys,y as nullsFirstOf,K as nullsOrderSuffix,X as softDeleteScope,h as tiebreakDirectionFor,v as toBase64,x as uniqueIndexFields};
@@ -1 +0,0 @@
1
- import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-Bdh5JSdg.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
@@ -1 +0,0 @@
1
- import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-BYCSiazv.mjs";import{readStreamRun as w,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-DF_Jrgpy.mjs";const S=5e4,p=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=w(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&T(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>S||u>p)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(S)} chunks / ${String(p)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r,new Set(this.runs.keys()))}catch{}}}}export{I as DurableStreamRunner,p as MAX_DURABLE_STREAM_BYTES,S as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
@@ -1 +0,0 @@
1
- import{LunoraError as y}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Rn,l as qe,h as Tn}from"./fts-companion-DzfEHonU.mjs";import{sql as a}from"drizzle-orm";import{d as vn}from"./wire-codec-BYCSiazv.mjs";import{stableWireKey as xt}from"./stableWireKey-Bdh5JSdg.mjs";import{throwingScheduler as An,aggregateSqlFunction as We,normalizeCountArgument as In}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as Ze,encodeAggregateKey as et,readAggregateValue as tt}from"./aggregateTableName-DbAttCNH.mjs";import{mergeWhere as N,CountRlsUnsupportedError as nt,selectIndexForGroupBy as Cn,selectIndexForCount as xn,selectIndexForAggregate as bn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Mn,searchIndexCoversTable as Dn}from"./backfillAggregateIndexes-DBrKU3Ya.mjs";import{backfillAggregateIndexes as ii,backfillRankIndexes as si,backfillSearchIndexes as ci}from"./backfillAggregateIndexes-DBrKU3Ya.mjs";import{appendCdcChange as kn,readCdcDocAtOrBefore as Ln}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{CDC_LOG_TABLE as di,applyCdcChanges as li,bumpCdcEpoch as ui,cdcCanVouchFor as fi,cdcForkedError as hi,cdcSeqLeavingRows as wi,cdcTouchesTables as pi,cdcTrimmedError as gi,compactCdcDocs as yi,cursorBelowRetainedFloor as $i,minCdcReplayableSeq as Ei,minCdcSeq as mi,readCdcChangeKeys as Si,readCdcChanges as _i,readCdcCursor as Ri,readCdcEpoch as Ti,trimCdcChanges as vi}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{allocateCommitSeq as Fn,COMMIT_SEQ_FIELD as qn}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{createCompanionSync as Wn}from"./createCompanionSync-C2cZNaCR.mjs";import{isMemoryTable as bt}from"./clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Mt}from"./computeRankPage-D9mACvr3.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as G}from"./runDrizzle-B2GG3IJa.mjs";import{p as Bn,j as at,D as re,r as ve,k as de,b as Be,A as rt,a as Pe,m as ue,e as fe,s as Pn,t as rn,i as Un,q as Dt,h as on,g as On}from"./do-sql-CeuVvE0W.mjs";import{renderSql as sn,unionAll as ft,WORKERD_SQLITE_LIMITS as cn,sqliteInList as Hn}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{coveringGeohashes as Gn,boundingBoxGeohashes as jn,haversineMeters as Kn,pointInBoundingBox as Nn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Qn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Vn,assertPatchAllowed as Jn,operatorFields as zn,readPatchField as kt}from"./assertPatchAllowed-BJ_2LgkQ.mjs";import{tiebreakDirectionFor as Yn,encodeCursor as Ge,nullsOrderSuffix as Xn,normalizeOrderKeys as Lt,uniqueIndexFields as Zn,buildSeekWhere as er,decodeCursor as Ft,buildSeekBeforeWhere as tr,softDeleteScope as Te,applySelect as qt}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as Wt,sortColumnName as Bt,resolveRankPartition as nr,encodePartitionKey as rr,RANK_TIEBREAK as or,rankPivotConditionSql as ir}from"./RANK_TIEBREAK-BKugKf70.mjs";import{UNVOUCHABLE_DEP as Pt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as sr,buildIndexRange as cr}from"./buildIndexRange-6nIZDf4m.mjs";import{r as je,j as Ae,c as Y,t as Ke,i as Ut}from"./where-sql-CxnXsLbt.mjs";import{serializeSqlValue as Ie}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as ar,isPushableWhere as dr}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as lr,findRelated as ur}from"./RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as fr,composeReadPredicate as hr}from"./DEFAULT_MAX_RELATION_KEYS-COmk7y1x.mjs";import{describeRelationWrites as wr}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as it,resolveWith as Ot,relationHooks as Ht,applyOnDelete as pr,fanOutScalarCounts as gr}from"./applyOnDelete-CGVYKtaW.mjs";import{guardWriter as yr}from"./RLS_UNWRAP_SYMBOL-BV39QRFd.mjs";import{mayHoldProjectedValue as $r}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as Er}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ce}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Gt,runTriggers as mr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ii,migrateClientWatermark as Ci,readClientWatermark as xi}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{IDEMPOTENCY_TABLE as Mi,readIdempotent as Di,trimIdempotent as ki,writeIdempotent as Li}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{runShardMigrations as qi}from"./runShardMigrations-B6FUu4iW.mjs";import{selectShapeMembers as Bi,selectShapeRows as Pi}from"./selectShapeMembers-DS28-P_Z.mjs";const Sr=n=>{const s=atob(n),r=Uint8Array.from(s,c=>c.codePointAt(0)??0);return new TextDecoder().decode(r)},_r=()=>new y("BAD_REQUEST","invalid cursor"),jt=16,Kt=8,J=1024,ht=(n,s)=>s.query(n),Rr=(n,s)=>{if(n.length===0)return 0;let r=0;for(const[c,i]of s.entries()){const w=c===s.length-1;let _=0;for(const S of n)(w?S.startsWith(i):S===i)&&(_+=1);if(_===0)return 0;r+=_}return r},Tr=(n,s)=>{if(!s)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",c=(r.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(c)}},vr=(n,s,r)=>{const c={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new y("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${s}"`);if(n.filters.length>=Kt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${s}": at most ${String(Kt)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),c},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new y("INTERNAL",`search index "${_.indexName}" on table "${s}" indexes "${_.definition.field}", not "${i}"`);const S=ht(w,r).length;if(S>jt)throw new y("BAD_REQUEST",`search index "${_.indexName}" on table "${s}": at most ${String(jt)} search terms are supported (got ${String(S)})`);return _.field=i,_.query=w,_.hasQuery=!0,c}};return c},Ar=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Ir=n=>Math.min(n.offset+n.numItems+1,J),Cr=n=>btoa(`search:${String(n)}`),xr=n=>{let s;try{s=Sr(n)}catch{return}if(!s.startsWith("search:"))return;const r=Number(s.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},br=n=>{if(typeof n.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(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const s=Math.max(0,Math.floor(n.numItems)),r=n.cursor?xr(n.cursor):0;if(r===void 0)throw _r();if(r+s>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-document limit (offset ${String(r)} + ${String(s)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,J-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:s,offset:r}},Mr=(n,s)=>{const r=s.offset+s.numItems,c=s.numItems>0&&n.length>r;return{continueCursor:c?Cr(r):null,isDone:!c,page:n.slice(s.offset,r)}},Dr=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const s=Math.max(0,Math.floor(n));if(s>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(s)}) — narrow the query or paginate instead`);return s},kr=32,Lr=1024,an=(n,s,r,c)=>{const i=`SELECT id, _creationTime, ${Ce(re)} FROM ${Ce(n)}`,w=`ORDER BY ${r}${c===void 0?"":` LIMIT ${String(c)}`}`;return s===void 0?je(`${i} ${w}`):Ae(`${i} WHERE `,s,` ${w}`)},Ne={fieldRef:n=>je(at(n)),rangeTypeGuard:(n,s)=>je(Bn(n,s)),serialize:Ie},Fr=n=>n===void 0?"":Xn(n==="first"),dn=n=>{const s=n.map(r=>`${at(r.field)} ${r.direction==="desc"?"DESC":"ASC"}${Fr(r.nulls)}`);return n.some(r=>r.field==="_id"||r.field==="id")||s.push(`${at("id")} ${Yn(n)==="desc"?"DESC":"ASC"}`),s.join(", ")},qr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},ln=n=>new Set(n.sqlConditions.filter(s=>s.comparator==="=").map(s=>s.field)),Wr=n=>{const s=ln(n);let r=0;for(;r<n.indexFields.length&&s.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},Br=(n,s)=>{const r=n.order,c=Wr(n),{shape:i}=s;return c.length>0?Lt(c.map(w=>({[w]:r})),i,{pinned:ln(n),uniqueBy:Zn(s.indexes,i)}):Lt([{_creationTime:r}],i)},Pr=(n,s,r,c)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[qr[w.comparator]??"eq"]:w.value}}));if(r&&i.push(er(s,Ft(r))),c&&i.push(tr(s,Ft(c))),i.length!==0)return i.length===1?i[0]:{AND:i}},Ur=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,kr):n.want},dt=(n,s,r,c,i,w,_)=>{const S=Br(c,r),C=dn(S),g=[],{filters:q,want:I}=w;let R=w.cursor??void 0,M=Ur(w);if(I===0)return{documents:g,orderKeys:S};for(;;){const F=Y(Pr(c,S,R,w.endCursor),Ne,Ke),B=an(s,i&&F?Ae(F," AND ",i):i??F,C,M),L=he(n,B.text,...B.params).toArray();let W={};_(L.length);for(const j of L)if(W=ve(j),q.every(pe=>pe(W))&&g.push(W)===I)return{documents:g,orderKeys:S};if(M===void 0||L.length<M)return{documents:g,orderKeys:S};R=Ge(W,S),M=Math.max(M,Math.min(M*2,Lr))}},Or=(n,s,r,c,i,w,_,S)=>{const C=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:F,orderKeys:B}=dt(n,s,r,c,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:F,splitCursor:L?Ge(L,B):null}}const{documents:g,orderKeys:q}=dt(n,s,r,c,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:C+1},S),I=g.length>C,R=I?g.slice(0,C):g,M=R.at(-1);return{continueCursor:I&&M?Ge(M,q):null,isDone:!I,page:R}},Qe=n=>{const s=new Map;return r=>{const c=s.get(r);if(c!==void 0)return c;const i=n(Ce(r));return s.set(r,i),i}},we=Ce(re),Hr=Qe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Nt=Qe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),Gr=Qe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),jr=Qe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),Kr="SELECT changes() AS changed",Qt=new Map,Nr="",Qr=n=>{const s=JSON.stringify(n),r=Qt.get(s);if(r!==void 0)return r;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${Nr}`),{sql:i}=sn("sqlite",a`${ft(c)} LIMIT 1`);return Qt.set(s,i),i},Vr=(n,s)=>s.map(()=>n),Jr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,zr=n=>{if(!Jr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Vt=50,un=500,Ue=Math.floor(cn.boundParams/3),Re=cn.boundParams,Yr=128,le=(n,s,r)=>{const c=s??un;if(n>c)throw new y("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},Xr=n=>{const s={eq:(r,c)=>(n.sqlConditions.push({comparator:"=",field:r,value:c}),s),gt:(r,c)=>(n.sqlConditions.push({comparator:">",field:r,value:c}),s),gte:(r,c)=>(n.sqlConditions.push({comparator:">=",field:r,value:c}),s),lt:(r,c)=>(n.sqlConditions.push({comparator:"<",field:r,value:c}),s),lte:(r,c)=>(n.sqlConditions.push({comparator:"<=",field:r,value:c}),s)};return s},Zr=n=>Math.max(n,J),fn=(n,s)=>{const r=n.filters.map(c=>a`${fe(c.field)} = ${Ie(c.value)}`);return s&&r.push(s),r},eo=(n,s,r,c,i)=>{const w=ht(r.query,ut(r.definition.language));if(w.length===0)return[];const _=Rn(s,r.indexName),S=`${_}__vocab`,C=w.length-1,g=w.map((B,L)=>{const W=Tr(B,L===C),j=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),q=w.map((B,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),I=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(q,a` + `)} AS ${a.identifier("__score__")} FROM (${ft(g)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(q.map(B=>a`${B} > 0`),a` AND `)}`,R=fn(r,i);let M=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${I}) s JOIN ${a.identifier(s)} m ON m.id = s.${a.identifier(qe)}`;R.length>0&&(M=a`${M} WHERE ${a.join(R,a` AND `)}`),M=a`${M} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const F=[];for(const B of G(n,M)){const L=on(B);if(L){const W=B.__score__;F.push({document:L,score:typeof W=="number"?W:Number(W??0)})}}return F},to=(n,s,r,c,i)=>{const w=ut(r.definition.language),_=ht(r.query,w);if(_.length===0)return[];const S=fn(r,i);let C=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(s)}`;S.length>0&&(C=a`${C} WHERE ${a.join(S,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Zr(c)))}`;const g=G(n,C).toArray(),q=[];for(const I of g){const R=on(I);if(!R)continue;const M=Rr(Tn(R,r.definition),_);M>0&&q.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return q.sort((I,R)=>R.score-I.score||R.creationTime-I.creationTime||I.id.localeCompare(R.id)),q.slice(0,c).map(I=>({document:I.doc,score:I.score}))},st=(n,s,r,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${r}": ${s} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},no=(n,s)=>{const r=n,c={near:(i,w)=>{if(r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near() or .within(), not both`);if(st(i,".near() point",s,r.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},c},within:i=>{if(r.near)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near() or .within(), not both`);if(st(i.sw,".within() sw corner",s,r.indexName),st(i.ne,".within() ne corner",s,r.indexName),i.sw.lat>i.ne.lat)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .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 r.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},c}};return c},ro=(n,s)=>{const r=n[s];if(r===null||typeof r!="object")return;const{lat:c,lng:i}=r;return typeof c=="number"&&typeof i=="number"?{lat:c,lng:i}:void 0},oo=(n,s)=>{const r=ro(n,s.definition.field);if(!r)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(s.near){const i=Kn(s.near.point,r);return i<=s.near.radiusMeters?{creationTime:c,distance:i}:void 0}return Nn(r,s.within)?{creationTime:c,distance:0}:void 0},io=(n,s,r,c)=>{if(!r.near&&!r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near(point, radius) or .within(box)`);const i=r.near?Gn(r.near.point,r.near.radiusMeters):jn(r.within),w=On(s,r.indexName),_=i.map(I=>a`(g.${a.identifier("__geohash__")} >= ${I} AND g.${a.identifier("__geohash__")} < ${`${I}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(s)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,g=G(n,C).toArray(),q=[];for(const I of g){const R=ve(I),M=R?oo(R,r):void 0;R&&M&&q.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return q.sort((I,R)=>I.distance-R.distance||R.creationTime-I.creationTime),q},hn=(n,s,r,c)=>{const i=[];for(const w of n)if(s.every(_=>_(c(w)))&&(i.push(w),typeof r=="number"&&i.length>=r))break;return i},so=(n,s,r,c,i,w=()=>{})=>{const _=r.within!==void 0,S=io(n,s,r,i).map(C=>({distanceMeters:_?null:C.distance,document:C.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},Jt=(n,s,r,c,i,w,_=()=>{})=>{const{geo:S}=r;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=i.length>0,g=so(n,s,S,C?void 0:w,c,_);return C?hn(g,i,w,q=>q.document):g},zt=(n,s,r)=>{const c=n.shape[s];if(c!==void 0&&$r(c))throw new y("BAD_REQUEST",`${r}: "${s}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},co=n=>{let s=0;const r=[],c={...Ne,relationExists:i=>{const{childWhere:w,negated:_,parentTable:S,relation:C}=i,g=`__rel_${String(s)}`,q=r.at(-1)??S;s+=1,n(C.table,O);const I=C.kind==="one"?C.field:C.references,R=C.kind==="one"?C.references:C.field,M=je(`${Dt(g,R)} = ${Dt(q,I)}`);r.push(g);const F=Y(w,c,Ke);r.pop();const B=F===void 0?M:Ae(M," AND ",F),L=Ae("EXISTS (SELECT 1 FROM ",Ut(C.table)," AS ",Ut(g)," WHERE ",B,")");return _?Ae("NOT ",L):L}};return c};class ao extends y{constructor(s="unique() found more than one matching document"){super("NOT_UNIQUE",s,{name:"NotUniqueError"})}}const lo=/\s/u,uo=String.fromCodePoint(0),Yt=(n,s,r)=>{if(!n.tables[s])throw new y("INTERNAL",`unknown table: ${s}`);return typeof r!="string"||r.length===0||lo.test(r)||r.includes(uo)?null:r},wn=(n,s,r,c=()=>{},i=()=>{},w=()=>{},_)=>{const S=s.tables[r];if(!S)throw new y("INTERNAL",`unknown table: ${r}`);const C=Te(S.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const $=N(C,g.pushedWhere);return $?Y($,ue):void 0},I=()=>{const $=N(C,g.pushedWhere);return $?Y($,Ne,Ke):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const F=$=>{const{search:x}=g;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");Mn(n,r,S);const b=g.inMemoryFilters.length>0,k=Dr(b?void 0:$),Q=Un(n);if(Q&&!Dn(n,r,x.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${x.indexName}" on table "${r}" 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 ne=q(),oe=Q?eo(n,r,x,k,ne):to(n,r,x,k,ne);!b&&$===void 0&&Ar(oe);const ge=R();return M=oe.length,ge.length>0?hn(oe,ge,$,ie=>ie.document):oe},B=$=>F($).map(x=>x.document),L=$=>{const x=br($);return Mr(B(Ir(x)),x)},W=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(cr(r,g.indexName,g.indexFields,g.sqlConditions,Ie))},j=$=>{W();let x=0;const b=(()=>{if(g.search){const k=B($);return x=M,k}return g.geo?Jt(n,r,g,q(),R(),$,k=>{x=k}).map(k=>k.document):dt(n,r,S,g,I(),{filters:R(),selective:g.inMemoryFilters.length>0,want:$===void 0?void 0:Math.max(0,Math.floor($))},k=>{x+=k}).documents})();return w(Math.max(x,b.length)),b},pe=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let $=0;const x=(()=>{if(g.search){const b=F(void 0);return $=M,b}return Jt(n,r,g,q(),R(),void 0,b=>{$=b})})();return w(Math.max($,x.length)),x},D={async*[Symbol.asyncIterator](){const $=wn(n,s,r,c,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await $.collect();return}let x;for(;;){const b=await $.paginate({cursor:x??null,numItems:Yr});if(yield*b.page,b.isDone||b.continueCursor===null)return;x=b.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return pe()},filter($){const x=ar($);return x!==void 0&&dr(x,S.shape)?(g.pushedWhere=N(g.pushedWhere,x),g.verifyFilters.push($)):g.inMemoryFilters.push($),D},async first(){return j(1)[0]??null},order($){return g.order=$==="desc"?"desc":"asc",D},async paginate($){let x=0;if(W(),g.search){const k=L($);return w(k.page.length),k}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Or(n,r,S,g,$,I(),{all:R(),selective:g.inMemoryFilters.length>0},k=>{x+=k});return w(Math.max(x,b.page.length)),b},async take($){return j($)},async unique(){const $=j(2);if($.length>1)throw new ao(`unique() on table "${r}" matched ${String($.length)} documents; expected at most one`);return $[0]??null},withGeoIndex($,x){const b=(S.geoIndexes??[]).find(Q=>Q.name===$);if(!b)throw new y("INTERNAL",`unknown geo index "${$}" on table "${r}"`);c(r,$,"geo");const k={definition:b,indexName:$};if(g.geo=k,x(no(k,r)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${$}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return D},withIndex($,x){const b=S.indexes.find(k=>k.name===$);if(!b)throw new y("INTERNAL",`unknown index "${$}" on table "${r}"`);return c(r,$,"index"),g.indexName=$,g.indexFields=b.fields,x&&x(Xr(g)),D},withSearchIndex($,x){const b=(S.searchIndexes??[]).find(Q=>Q.name===$);if(!b)throw new y("INTERNAL",`unknown search index "${$}" on table "${r}"`);c(r,$,"search");const k={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:$,query:""};if(g.search=k,x(vr(k,r,ut(b.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${$}" on table "${r}" requires a .search(field, query) call`);return D}};return D},Xt=(n,s,r)=>{const c={...s};for(const[i,w]of rn(n)){if(w.serverDefault){c[i]=w.serverDefault({auth:r});continue}c[i]===void 0&&(w.defaultFn?c[i]=w.defaultFn():"defaultValue"in w&&(c[i]=w.defaultValue))}return c},ct=(n,s,r,c)=>{const i=r;for(const[w,_]of rn(n)){if(_.serverDefault){w in s&&(i[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in s)&&(i[w]=_.onUpdateFn())}},Zt=5,en=(n,s)=>{for(const r of Object.keys(s))if(s[r]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${r}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},tn=["_commitSeq","_creationTime","_id"],Oe=n=>tn.some(s=>s in n)?Object.fromEntries(Object.entries(n).filter(([s])=>!tn.includes(s))):n,fo=/unique constraint failed/i,ho=n=>n instanceof Error&&fo.test(n.message),wo=/string or blob too big/iu,po=(n,s)=>{if(!(!(n instanceof Error)||!wo.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${s}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},lt=(n,s,r,c)=>{try{he(n,r,...c)}catch(i){throw ho(i)?new ce(`unique constraint violation on "${s}"`,"unique"):(po(i,s),i)}},He=(n,s,r,c)=>{if(lt(n,s,r,c),he(n,Kr).one().changed===0)throw new ce(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},nn=(n,s,r,c,i,w,_)=>{const S=[];for(let I=0;I<r.length+1;I+=1){const R=r[I],M=c[I],F=M?.direction==="desc"?"desc":"asc",B=R===void 0||M===void 0?a`${a.identifier(or)} < ${_}`:ir(R,w[I],F,!1);if(B===void 0)continue;const L=[];for(let j=0;j<I;j+=1)L.push(a`${a.identifier(r[j])} IS ${w[j]}`);L.push(B);const[W]=L;S.push(L.length===1&&W!==void 0?W:a`(${a.join(L,a` AND `)})`)}const C=S.length>0?a.join(S,a` OR `):a`1 = 0`,g=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(s)} WHERE ${a.identifier("__partition__")} = ${i} AND (${C})`).one(),q=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(s)} WHERE ${a.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:q.c}},go=n=>{const s=new Map;for(const[c,i]of Object.entries(n.tables))for(const w of Object.values(i.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&s.set(w.table,[...s.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const r=c=>{const i=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:C}of s.get(_)??[]){if(S===c||Gt(n,S,C))return!0;i.has(S)||(i.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,i])=>i.shardMode?.kind==="global"||Gt(n,c,"delete")||r(c)).map(([c])=>c))},ni=n=>{const{baselineSeq:s,onStalePatchDropped:r}=n,{sql:c}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=lr(i),S=wr(i,n.inTransaction),C=go(i);let g;const q=()=>n.inTransaction?.()===!0,I=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((g===void 0||!q())&&(g=Fn(c)),{[qn]:g}),R=(e,...t)=>{const o=i.tables[e]?.indexes;if(!o||o.length===0)return;const u=[];for(const h of t)h&&u.push(...sr(o,h,Ie));return u.length>0?u:void 0},{headroom:M}=n;let F=!1;const B=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},L=n.onRead??(()=>{}),W=e=>{bt(i.tables[e])&&L(Pt,Pt)},j=n.onReadRange??(e=>{L(e.table,O)}),pe=e=>{W(e.table),j(e)},D=(e,t)=>{t!==void 0&&t!==O&&!F&&M?.recordRead(1),W(e),L(e,t)},$=n.onIndexUse??(()=>{}),x=n.onWrite??(()=>{}),b=e=>{F||M?.recordWrite(e)},k=async e=>{b(e.doc),await x(e)},{cache:Q}=n,ne=n.clock??(()=>Date.now()),oe=n.idGenerator??(()=>crypto.randomUUID()),ge=n.scheduler??An,{globalDb:ie}=n,ye=n.auth??{identity:null,userId:null},wt=n.cdc??!1,Ve=ge,pn=Er({scheduler:typeof Ve.list=="function"&&typeof Ve.get=="function"?Ve:void 0,storage:n.storage}),$e=(e,t,o,u)=>{wt&&!bt(i.tables[e])&&kn(c,ne(),e,t,o,u)},pt=(e,t,o,u)=>{const h=i.tables[e];if(h?.dropStalePatchesMode!==!0||!wt)return!1;const f=s?.();if(f===void 0)return!1;const d=Ln(c,e,t,f);if(d===void 0)return!1;const l=zn(h,o);return Object.keys(Oe(o)).some(p=>!l.has(p)&&xt(kt(d,p))!==xt(kt(u,p)))},se=e=>i.tables[e]?.shardMode?.kind==="global",gt=(e,t)=>{if(se(e)){if(!ie)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ie}return P},Je=e=>gt(e,"cascade"),K=(e,t)=>{if(se(e)){if(!ie)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ie}},yt=async(e,t,o,u,h)=>{h&&b(o);const f=await e.insert(t,o,u);return w({key:f,op:"insert",row:{...o,_id:f},table:t}),f},ze=(e,t)=>gt(e,"relation load").findMany(e,t),$t=(e,t)=>(se(e)&&D(e,O),ze(e,t)),gn=e=>!se(e.table),Et=n.relationExistsPushDown??"auto",mt=Et!=="never",{maxRelationKeys:St}=n,xe=(e,t,o)=>fr(e,{fetcher:$t,maxRelationKeys:St,relationBaseWhere:o,schema:i,tableName:t}),_t=async(e,t,o,u)=>{const h=K(e,"relation grouped count");if(h)return D(e,O),gr((v,H)=>h.count(v,H),e,t,o,u);const f=i.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);D(e,O);const d=Te(f.softDeleteMode,void 0),l={[t]:{in:o}},p=N(N(l,u),d),A=await xe(p,e,void 0),E=Y(A,ue),T=fe(t);let m=a`SELECT ${T} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;E&&(m=a`${m} WHERE ${E}`),m=a`${m} GROUP BY ${T}`;const U=G(c,m).toArray();return new Map(U.map(v=>[v.__fk__,v.count]))};let be=0;const Rt=new Set;for(const[e,t]of Object.entries(i.tables))for(const o of Object.values(t.triggerMap??{}))Rt.add(`${e} ${o.timing} ${o.op}`);const X=(e,t,o)=>Rt.has(`${e} ${t} ${o}`),Z=async(e,t,o)=>{if(be+=1,be>Vt)throw be-=1,new ce(`trigger recursion exceeded ${String(Vt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await mr({ctx:Sn,event:o,op:t,schema:i,tableName:o.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Ye,ensureRankBackfilled:Xe,ensureRankBackfilledForTable:me,syncAggregates:Me,syncCompanionsForInsert:Tt,syncGeo:De,syncRanks:Se,syncSearch:ke}=Wn({broadcast:w,indexKeysFor:(e,t)=>R(e,t),invalidateCache:(e,t,o)=>Q?.invalidate(e,t,R(e,o)),recordCdc:$e,schema:i,sql:c}),vt=(e,t,o)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(o.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${o.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})},At=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||se(e)?ie:void 0,ee=(e,t)=>{const o=At(t);for(let u=0;u<o.length;u+=Re){const h=o.slice(u,u+Re),[f]=he(c,Qr(h),...Vr(e,h)).toArray();if(!f)continue;const d=f.__t__,l=ve(f);if(typeof d!="string"||!l)return;const p=f[re];return{docJson:typeof p=="string"?p:de(p??{}),row:l,tableName:d}}},yn=(e,t)=>{const o=[...new Set(e)],u=new Map;if(o.length===0)return u;const h=At(t);for(let f=0;f<h.length;f+=Re){const d=h.slice(f,f+Re),l=Math.floor(Re/d.length),p=Hn(a`${a.identifier("id")}`,o,!1,l),A=d.map(E=>a`SELECT ${a.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(E)} WHERE ${p}`);for(const E of G(c,ft(A))){const{id:T,__t__:m}=E;typeof m=="string"&&typeof T=="string"&&u.set(T,m)}}return u},It={assertRankPartitionLocal:vt,ensureRankBackfilled:Xe,onRead:D,rowToDocument:ve,schema:i,sql:c},$n=(e,t,o)=>{const u=Y(o,ue);return u===void 0||G(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},En=(e,t,o,u)=>pt(e,t,o,u)?(r?.({fields:Object.keys(Oe(o)),id:t,table:e}),!0):!1,mn=async(e,t,o,u,h)=>{const f=ee(t,e);if(!f)return{applied:!1,doc:null};if(D(e,t),!$n(e,t,o.where)||En(e,t,o.patch,f.row))return{applied:!1,doc:f.row};try{await h(o.patch)}catch(d){if(d instanceof ce&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ee(t,e)?.row??null}},Ct=async(e,t,o,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await hr(t,o,{canPushExists:mt?gn:void 0,existsPushMode:Et==="always"?"always":"auto",fetcher:$t,maxRelationKeys:St,schema:i,tableName:e}),p=mt?co(u):Ne,A=Y(l,p,Ke),E=an(e,A,dn(d),h);return{limit:f,orderKeys:d,statement:E}},P={system:pn,async aggregate(e,t){const o=K(e,"aggregate");if(o)return D(e,O),o.aggregate(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(We(t.op),t.op==="count")return P.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);D(e,O);const h=Te(u.softDeleteMode,void 0),f=N(N(t.baseWhere,t.where),h),d=await xe(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const v=bn(u.aggregateIndexes,t.op,t.field,t.where);if(v){Ye(e,v.index);const H=et(v.index.by??[],v.key),te=Ze(e,v.index.name),z=G(c,a`SELECT ${Be} AS value, ${rt} AS count FROM ${a.identifier(te)} WHERE ${Pe} = ${H}`).toArray()[0];return tt(t.op,z)}}zt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,ue),A=We(t.op),E=fe(t.field);let T=a`SELECT ${a.raw(A)}(${E}) AS value FROM ${a.identifier(e)}`;p&&(T=a`${T} WHERE ${p}`);const U=G(c,T).toArray()[0]?.value;return U??null},asId(e,t){const o=Yt(i,e,t);if(o===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return o},async count(e,t){const o=K(e,"count");if(o)return D(e,O),o.count(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=In(t);if(h.restrictsCounts)throw new nt(e);D(e,O);const f=Te(u.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),f),l=await xe(d,e,h.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!p){const m=xn(u.aggregateIndexes,h.where);if(m){Ye(e,m.index);const U=et(m.index.by??[],m.key),v=Ze(e,m.index.name),H=G(c,a`SELECT ${Be} AS value FROM ${a.identifier(v)} WHERE ${Pe} = ${U}`).toArray();return H[0]===void 0?0:H[0].value??0}}const A=Y(l,ue);let E=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return A&&(E=a`${E} WHERE ${A}`),G(c,E).one().count},async delete(e,t,o){const u=ee(e,t);if(!u){const T=_e(t);T&&(b(void 0),await T.delete(e,t,o));return}const{docJson:h,row:f,tableName:d}=u,l=i.tables[d],p=o?.hard===!0,A=!p&&l?.softDeleteMode?l:void 0,E=A?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(X(d,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:f,table:d}),await pr({deletedId:e,deletedReference:T=>f[T],findHolders:async(T,m,U)=>(await Je(T).findMany(T,{includeDeleted:p,where:{[m]:U}})).page,onCascade:(T,m)=>Je(T).delete(m,void 0,o),onRestrict:T=>{throw new ce(T,"restrict")},onSetNull:(T,m,U)=>Je(T).patch(m,{[U]:null}),schema:i,tableName:d}),Ee(d),me(d),A&&E){const T={[E]:ne()},m={...f,...I(d),...T,_id:e};ct(A,T,m,ye),He(c,d,Nt(d),[de(m),e,h]),ke(d,e,m,f),De(d,e,void 0),Me(d,f,m),Se(d,e,f,void 0),Q?.invalidate(d,e,R(d,f,m)),$e(d,e,"update",m),w({indexKeys:R(d,f,m),key:e,op:"update",row:m,table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await k({id:e,op:"delete",table:d});return}He(c,d,jr(d),[e,h]),ke(d,e,void 0),De(d,e,void 0),Me(d,f,void 0),Se(d,e,f,void 0),Q?.invalidate(d,e,R(d,f)),$e(d,e,"delete"),w({indexKeys:R(d,f),key:e,op:"delete",table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await k({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!i.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const o=Math.max(1,t?.chunkSize??un),u=t?.hard===void 0?void 0:{hard:t.hard},h=se(e)?void 0:e;let f=0;return await B(async()=>{for(;;){const l=(await P.findMany(e,{limit:o})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,h,u),f+=1;if(l.length<o)break}}),{deleted:f}},async deleteMany(e,t,o){le(e.length,t?.limit,"deleteMany");for(const u of e)await P.delete(u,o);return{deleted:e.length}},async deleteWhere(e,t,o){const f=(await(K(e,"deleteWhere")??P).findMany(e,{where:t})).page.map(d=>String(d._id));if(le(f.length,o?.limit,"deleteWhere"),P.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(f,o)},async findFirst(e,t={}){return(await P.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const o=await P.findFirst(e,t);if(o===null)throw new Qn(`findFirstOrThrow: no "${e}" document matched`);return o},async findMany(e,t={}){const o=K(e,"findMany");if(o)return D(e,O),o.findMany(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?D(e,O):D(e);const{limit:f,orderKeys:d,statement:l}=await Ct(e,u,t,D),p=he(c,l.text,...l.params).toArray();h&&!F&&M?.recordRead(p.length);const A=[];for(const U of p){const v=ve(U);v&&(A.push(v),!h&&typeof v._id=="string"&&D(e,v._id))}if(f===void 0)return t.with&&await Ot({groupedCounter:_t,fetcher:ze,parents:A,...Ht(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:qt(A,t.select,t.with)};const E=A.length>f,T=E?A.slice(0,f):A,m=T.at(-1);return t.with&&await Ot({fetcher:ze,groupedCounter:_t,parents:T,...Ht(t),schema:i,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?Ge(m,d):null,isDone:!E,page:qt(T,t.select,t.with)}},async explain(e,t={}){const o=K(e,"explain");if(o)return o.explain(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:h}=await Ct(e,u,t,()=>{}),f=he(c,`EXPLAIN QUERY PLAN ${h.text}`,...h.params).toArray();return{params:h.params,plan:f.map(d=>String(d.detail)),sql:h.text}},async get(e,t){const o=ee(e,t);if(!o){const u=_e(t);return u?u.get(e,t):null}return D(o.tableName,e),o.row},async lookupById(e,t){const o=ee(e,t);return o?(D(o.tableName,e),{row:o.row,tableName:o.tableName}):null},async groupBy(e,t){const o=K(e,"groupBy");if(o)return D(e,O),o.groupBy(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);D(e,O);const h=t.agg??{op:"count"};if(We(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 f=Te(u.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),f),l=await xe(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const v=Cn(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=v===void 0?0:Object.keys(v.partial).length,te=v?.index.by?.length??0;if(v&&(H===0||H===te)){Ye(e,v.index);const z=Ze(e,v.index.name),V=Object.keys(v.partial),ae=[];if(V.length===(v.index.by??[]).length&&V.length>0){const Le=et(v.index.by??[],v.partial),Fe=G(c,a`SELECT ${Be} AS value, ${rt} AS count FROM ${a.identifier(z)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ae.push({key:{...v.partial},value:tt(h.op,Fe[0])}),ae}const _n=G(c,a`SELECT ${Pe} AS key, ${Be} AS value, ${rt} AS count FROM ${a.identifier(z)}`).toArray();for(const Le of _n){const Fe=vn(JSON.parse(Le.key));ae.push({key:Fe,value:tt(h.op,Le)})}return ae}}for(const v of[...t.by,h.field]){if(v===void 0)continue;const H=v===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${v}" } })`:`groupBy(${e}, { by: [..."${v}"] })`;zt(u,v,H)}const A=Y(l,ue),E=t.by.map(v=>a`${fe(v)} AS ${a.identifier(v)}`);if(h.op==="count")E.push(a`COUNT(*) AS value`);else{const{field:v}=h;if(v===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(a`${a.raw(We(h.op))}(${fe(v)}) AS value`)}let T=a`SELECT ${a.join(E,a`, `)} FROM ${a.identifier(e)}`;A&&(T=a`${T} WHERE ${A}`),T=a`${T} GROUP BY ${a.join(t.by.map(v=>fe(v)),a`, `)}`;const m=G(c,T).toArray(),U=[];for(const v of m){const H={};for(const z of t.by)H[z]=Pn(u.shape[z],v[z]??null);const{value:te}=v;U.push({key:H,value:te==null?null:Number(te)})}return U},async insert(e,t,o){const u=K(e,"insert");if(u)return yt(u,e,t,o,!0);const h=i.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=Xt(h,t,ye);it(h,f);let d;o?.clientId!==void 0?(zr(o.clientId),d=o.clientId):o?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=oe();const l=o?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:ne(),p={...f,...I(e),_creationTime:l,_id:d};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:d,op:"insert",table:e}),Ee(e),me(e),lt(c,e,Hr(e),[d,l,de(p)]),Tt(e,d,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:d,op:"insert",table:e}),await k({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,o){if(le(t.length,o?.limit,"insertManyUnsafe"),t.length===0)return[];const u=K(e,"insert");if(u){const l=[];for(const p of t)b(p);for(const p of t){const A=await u.insert(e,p,{allowExplicitId:o?.allowExplicitId});w({key:A,op:"insert",row:{...p,_id:A},table:e}),l.push(A)}return l}const h=i.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const f=[];for(let l=0;l<t.length;l+=Ue)f.push(I(e));const d=t.map((l,p)=>{const A=Xt(h,l,ye),E=o?.allowExplicitId===!0&&typeof A._id=="string"?A._id:oe(),T=o?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:ne(),m={...A,...f[Math.floor(p/Ue)],_creationTime:T,_id:E};return{creationTime:T,document:m,id:E}});for(const l of d)b(l.document);for(let l=0;l<d.length;l+=Ue){const p=a.join(d.slice(l,l+Ue).map(E=>a`(${E.id}, ${E.creationTime}, ${de(E.document)})`),a`, `),A=sn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${p}`);lt(c,e,A.sql,A.params)}for(const{document:l,id:p}of d)Tt(e,p,l),await x({doc:l,id:p,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,o){le(t.length,o?.limit,"insertMany");const u=o?.skipDuplicates===!0,h=[],f=K(e,"insert");if(f)for(const l of t)b(l);const d=async l=>f?yt(f,e,l,void 0,!1):P.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(p){if(u&&p instanceof ce&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Yt(i,e,t)},async patch(e,t,o,u){const h=ee(e,o);if(!h){const T=_e(o);if(T){b(t),await T.patch(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=i.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(D(l,e),en("patch",t),pt(l,e,t,d)){r?.({fields:Object.keys(Oe(t)),id:e,table:l});return}const A=Vn(p,t,d),E={...d,...Oe(A),...I(l),_id:e};ct(p,A,E,ye),Jn(u,d,E),it(p,E,!0),X(l,"before","update")&&await Z("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),He(c,l,Nt(l),[de(E),e,f]),ke(l,e,E,d),De(l,e,E),Me(l,d,E),Se(l,e,d,E),Q?.invalidate(l,e,R(l,d,E)),$e(l,e,"update",E),w({indexKeys:R(l,d,E),key:e,op:"update",row:E,table:l}),X(l,"after","update")&&await Z("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await k({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,o){const u=K(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return b(o.patch),u.patchIf(e,t,o)}if(!i.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=Zt;h+=1){const f=await mn(e,t,o,h<Zt,d=>P.patch(t,d,e,{verify:o.verify}));if(f!==void 0)return f}throw new ce(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,o){le(e.length,t?.limit,"patchMany");for(const u of e)await P.patch(u.id,u.patch,o);return{patched:e.length}},async patchWhere(e,t,o){const f=(await(K(e,"patchWhere")??P).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(le(f.length,o?.limit,"patchWhere"),P.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(f,o),{patched:f.length}},async related(e,t){return ur(P,_,e,t)},relationEdges:_,deleteRereadTables:C,relationWrites:S,query(e){const t=K(e,"query");return t?(D(e,O),t.query(e)):wn(c,i,e,$,o=>{o?pe(o):D(e,O)},o=>{F||M?.recordRead(o)})},async rank(e,t,o){const u=K(e,"rank");if(u)return D(e,O),u.rank(e,t,o);$(e,t,"rank");const h=i.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(V=>V.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(vt(e,h,f),o.restrictsCounts)throw new nt(e);D(e,O),Xe(e,f);const d=typeof o.row=="string"?o.row:o.row._id;if(!d)return null;const l=Wt(e,f.name),p=f.sortBy.map((V,ae)=>Bt(ae)),A=p.map(V=>Ce(V)).join(", "),E=G(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(A)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[T]=E;if(T===void 0)return null;let m=T.__partition__;const U=N(o.baseWhere,o.where);ot(U,i,e,"rank");const v=nr(f,U);if(v){const V=rr(f.partitionBy??[],v);if(V!==m)return null;m=V}const H=p.map(V=>T[V]),{before:te,total:z}=nn(c,l,p,f.sortBy,m,H,d);return{position:te+1,total:z}},async rankBefore(e,t,o){if(se(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=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(p=>p.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(o.restrictsCounts)throw new nt(e);D(e,O),Xe(e,h);const f=Wt(e,h.name),d=h.sortBy.map((p,A)=>Bt(A)),l=h.sortBy.map((p,A)=>Ie(o.sortValues[A]??null));return nn(c,f,d,h.sortBy,o.partitionKey,l,o.rowId)},async rankPage(e,t,o={}){ot(N(o.baseWhere,o.where),i,e,"rankPage");const u=K(e,"rankPage");if(u)return D(e,O),u.rankPage(e,t,o);$(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=Mt(It,e,t,o);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,o={}){ot(N(o.baseWhere,o.where),i,e,"rankPage"),$(e,t,"rank");const{directions:u,hasMore:h,rows:f}=Mt(It,e,t,o);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const o=ee(e,t);if(!o){const f=_e(t);if(f?.restore){await f.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=i.tables[o.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${o.tableName}" is not a .softDelete() table`);const h=o.row[u]!==null&&o.row[u]!==void 0;await P.patch(e,{[u]:null},t),h&&Se(o.tableName,e,void 0,o.row)},async replace(e,t,o,u){const h=ee(e,o);if(!h){const U=_e(o);if(U){b(t),await U.replace(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=i.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);en("replace",t);const A=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,T=A??E??ne(),m={...t,...I(l),_creationTime:T,_id:e};ct(p,t,m,ye),it(p,m),X(l,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),He(c,l,Gr(l),[T,de(m),e,f]),ke(l,e,m,d),De(l,e,m),Me(l,d,m),Se(l,e,d,m),Q?.invalidate(l,e,R(l,d,m)),$e(l,e,"update",m),w({indexKeys:R(l,d,m),key:e,op:"update",row:m,table:l}),X(l,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await k({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),o=e?.tables,u=Object.entries(i.tables).filter(([l,p])=>t.has(l)||o!==void 0&&!o.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(o!==void 0){for(const l of o)if(!i.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=P;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,f+=p.deleted}return{deleted:f,tables:h}}},Sn={db:P,scheduler:ge};return n.enforceRls===!0?yr(P,i,(e,t)=>ee(e,t)?.tableName,(e,t)=>yn(e,t),_):P};export{di as CDC_LOG_TABLE,Mi as IDEMPOTENCY_TABLE,ao as NotUniqueError,Ii as advanceClientWatermark,li as applyCdcChanges,en as assertNoExplicitUndefined,zr as assertValidClientId,ii as backfillAggregateIndexes,si as backfillRankIndexes,ci as backfillSearchIndexes,ui as bumpCdcEpoch,fi as cdcCanVouchFor,hi as cdcForkedError,wi as cdcSeqLeavingRows,pi as cdcTouchesTables,gi as cdcTrimmedError,yi as compactCdcDocs,ni as createShardCtxDb,$i as cursorBelowRetainedFloor,Ci as migrateClientWatermark,Ei as minCdcReplayableSeq,mi as minCdcSeq,Yt as normalizeIdStructurally,Si as readCdcChangeKeys,_i as readCdcChanges,Ri as readCdcCursor,Ti as readCdcEpoch,xi as readClientWatermark,Di as readIdempotent,qi as runShardMigrations,Bi as selectShapeMembers,Pi as selectShapeRows,Oe as stripReservedPatchFields,vi as trimCdcChanges,ki as trimIdempotent,Li as writeIdempotent};
@@ -1 +0,0 @@
1
- import{stableWireKey as y}from"./stableWireKey-Bdh5JSdg.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-CTuiPWMD.mjs";import{keysTouchRanges as x}from"./buildIndexRange-6nIZDf4m.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 +0,0 @@
1
- import{stableWireKey as o}from"./stableWireKey-Bdh5JSdg.mjs";const s=r=>r.map(e=>`${String(e.length)}:${e}`).join(""),c=r=>o(r.effectiveWhere??null),g=(r,e,t)=>s([r,String(e),String(t)]),h=(r,e)=>{try{return s([c(r),e])}catch{return}};class d{keyScans=new Map;memberProbes=new Map;run=0;served=0;get probesRun(){return this.run}get probesServed(){return this.served}changedKeys(e,t){return this.getOrLoad(this.keyScans,e,t)}members(e,t,n){return this.getOrLoad(this.memberProbes,h(e,t),n)}getOrLoad(e,t,n){if(t!==void 0){const a=e.get(t);if(a!==void 0)return this.served+=1,a}this.run+=1;const i=n();return t!==void 0&&e.set(t,i),i}}const p=()=>new d,b=(r,e)=>{try{return s([r.table,c(r),o({identity:e.identity,userId:e.userId})])}catch{return}};export{d as ShapeDiffCache,p as createShapeDiffCache,b as globalShapeReadKey,g as shapeRangeKey};
@@ -1 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{e as i}from"./wire-codec-BYCSiazv.mjs";const a=BigInt(Number.MAX_SAFE_INTEGER),c=(e,t)=>e<t?-1:e>t?1:0,m=(e,t)=>`${e}__agg_${t}`,l=e=>{if(typeof e=="bigint"){if(e>a||e<-a)throw new g("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},v=(e,t,n,u)=>{const r=e.get(t)??{count:0,value:null};if(n.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const o=l(u[n.field??""]);if(n.op==="sum"||n.op==="avg"){o!==void 0&&(r.value=(r.value??0)+o,r.count+=1),e.set(t,r);return}r.count+=1,o!==void 0&&(r.value===null?r.value=o:r.value=n.op==="min"?Math.min(r.value,o):Math.max(r.value,o)),e.set(t,r)},d=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,A=(e,t)=>{if(e.length===0)return"";const n={};for(const u of e.toSorted(c))n[u]=t[u]??null;return JSON.stringify(i(n))};export{m as aggregateTableName,l as coerceAggregateNumber,c as compareStrings,A as encodeAggregateKey,v as foldAggregateTally,d as readAggregateValue};
@@ -1 +0,0 @@
1
- import{LunoraError as a}from"@lunora/errors";import{e as u}from"./effective-kind-BmG_zCAy.mjs";import{i as k}from"./wire-codec-BYCSiazv.mjs";import{i as m,r as $,F as g,e as R,s as F}from"./json-field-path-B2fjnGc3.mjs";const d={decrement:{apply:(t,e)=>t-e,kind:"number"},divide:{apply:(t,e)=>t/e,kind:"number"},increment:{apply:(t,e)=>t+e,kind:"number"},multiply:{apply:(t,e)=>t*e,kind:"number"},toggle:{kind:"boolean"}};class s extends Error{}const w=t=>{if(!k(t))return;const e=Object.keys(t),[n]=e;if(!(e.length!==1||n===void 0||!Object.hasOwn(d,n)))return{operand:t[n],operator:n}},b=t=>w(t)!==void 0,P=(t,e,n,o)=>{const r=d[e];if(r.apply===void 0){if(n!==!0)throw new s(`patch: use { toggle: true } on "${t}".`);if(typeof o!="boolean")throw new s(`patch: cannot toggle "${t}" — its current value is ${String(o)}; set a boolean first.`);return!o}if(typeof n!="number"||!Number.isFinite(n))throw new s(`patch: "${e}" on "${t}" needs a finite number, got ${String(n)}.`);if(typeof o!="number"||!Number.isFinite(o))throw new s(`patch: cannot ${e} "${t}" — its current value is ${String(o)}; set a number first.`);if(e==="divide"&&n===0)throw new s(`patch: cannot divide "${t}" by zero.`);const i=r.apply(o,n);if(!Number.isFinite(i))throw new s(`patch: "${e}" on "${t}" overflows to ${String(i)}.`);return i},v=(t,e)=>{const n=new Set;for(const[o,r]of Object.entries(t))e(o)!==void 0&&b(r)&&n.add(o);return n},E=(t,e,n)=>{let o;for(const r of v(t,n)){const{operand:i,operator:c}=w(t[r]),f=n(r);if(d[c].kind!==f)throw new s(`patch: "${c}" does not apply to the ${String(f)} column "${r}".`);o??={...t},o[r]=P(r,c,i,e[r])}return o??t},j=new Set(["date","number","timestamp"]),l=t=>t.kind==="optional"&&t._meta?.inner!==void 0?l(t._meta.inner):t,p=t=>{const e=l(t);if(e.kind!==void 0&&j.has(e.kind))return"number";if(e.kind==="boolean")return"boolean";if(e.kind!=="union")return;const n=new Set((e._meta?.members??[]).filter(r=>u(r)!=="null").map(r=>p(r))),[o]=n;return n.size===1?o:void 0},O=t=>e=>{const n=Object.hasOwn(t.shape,e)?t.shape[e]:void 0;return n===void 0?void 0:p(n)},A=(t,e)=>v(e,O(t)),I=(t,e,n)=>{try{return E(e,n,O(t))}catch(o){throw o instanceof s?new a("VALIDATION_ERROR",o.message):o}},h=t=>{throw t instanceof g?new a("VALIDATION_ERROR",t.message):t},y=t=>{if(t===void 0)return;const e=l(t);if(e.kind==="object")return e._meta?.shape;if(e.kind!=="union")return;const n=(e._meta?.members??[]).filter(o=>u(o)!=="null");return n.length===1?y(n[0]):void 0},N=(t,e)=>{let n=t.shape[e[0]??""];for(const o of e.slice(1)){const r=y(n);n=r!==void 0&&Object.hasOwn(r,o)?r[o]:void 0}return n},_=(t,e,n)=>{let o=[];try{o=F(e)}catch(i){h(i)}const r=N(t,o);if(r===void 0)throw new a("VALIDATION_ERROR",`patch: "${e}" is not a path into an object column of this table`);if(p(r)!==void 0&&b(n))throw new a("VALIDATION_ERROR",`patch: "${e}" is nested inside a column; operators like increment apply to a top-level column only`);if(typeof r.parse=="function")try{r.parse(n)}catch(i){throw new a("VALIDATION_ERROR",`patch: "${e}" ${i instanceof Error?i.message:"is invalid"}`)}},S=(t,e,n)=>{for(const[o,r]of Object.entries(e))m(o)&&_(t,o,r);try{return R(e,n)}catch(o){return h(o)}},x=(t,e,n)=>S(t,I(t,e,n),n),z=(t,e)=>A(t,e).size>0||Object.keys(e).some(n=>m(n)),K=(t,e,n)=>{if(t?.verify!==void 0&&!t.verify(e,n))throw new a("FORBIDDEN","update denied by policy")},B=(t,e)=>{try{return $(t,e)}catch(n){return h(n)}};export{K as assertPatchAllowed,A as operatorFields,z as patchDependsOnRow,B as readPatchField,x as resolvePatch};
@@ -1 +0,0 @@
1
- import{stableStringify as m}from"./stableStringify-DibjylKD.mjs";import{i as A,e as w,n as J}from"./wire-codec-BYCSiazv.mjs";const D="_id",p="_creationTime",y="page",_=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},F=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=_(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},L="__lunora__",E=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=E(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)},R=(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},P=(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(J(i)?w(i):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},T=(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}},k=(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(F(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=T(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===""?L:s,d=JSON.stringify(a),c=[...R(r,i,a,d),...P(r,i,a,d)];return k(r,i,c)?c:void 0},W=(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},G=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{G as awaitWsDrain,K as subscriptionFrames,W as subscriptionListDeltas,C as trySendFrame};
@@ -1 +0,0 @@
1
- const o=r=>{let n="";for(let t=0;t<r.length;t+=32768)n+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(n)},a=r=>{const n=atob(r),e=new Uint8Array(n.length);for(let t=0;t<n.length;t+=1)e[t]=n.codePointAt(t)??0;return e};export{a as f,o as t};
@@ -1 +0,0 @@
1
- import{e as h}from"./wire-codec-BYCSiazv.mjs";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const s of["_id","_creationTime",...e])Object.hasOwn(t,s)&&(a[s]=t[s]);return a},y=(t,e,a)=>{const{columns:s,table:p}=a,i=new Map,c=[];for(const{doc:n,id:r}of t){const o=u(n,s),d=JSON.stringify(h(o));i.set(r,d);const f=e.get(r);f===void 0?c.push({key:r,op:"insert",table:p,value:o}):f!==d&&c.push({key:r,op:"update",table:p,value:o})}for(const n of e.keys())i.has(n)||c.push({key:n,op:"delete",table:p});return{next:i,rowsPatch:c}},k=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:s,checkpoint:p,epoch:i,lastMutationId:c,pokeId:n}=e,r=[JSON.stringify({baseCheckpoint:s,epoch:i,pokeId:n,type:"pokeStart"})];for(const o of t){const d=a.preEncoded?o.rowsPatch:k(o.rowsPatch),f=o.baseCheckpoint??s;r.push(JSON.stringify({pokeId:n,rowsPatch:d,shapeId:o.shapeId,type:"pokePart",...c===void 0?{}:{lastMutationId:c},...f===void 0?{}:{baseCheckpoint:f},...o.reset===!0?{reset:!0}:{}}))}return r.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:n,type:"pokeEnd"})),r};export{b as buildPokeFrames,y as diffGlobalMembership,k as encodeRowsPatch,u as projectColumns};
@@ -1 +0,0 @@
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-BYCSiazv.mjs";import{runSql as p}from"./runDrizzle-B2GG3IJa.mjs";import{k as m,D as E}from"./do-sql-CeuVvE0W.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.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 +0,0 @@
1
- import"./json-field-path-B2fjnGc3.mjs";import"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{c as p,s}from"./where-sql-CxnXsLbt.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{p as compileWhereSql,s as serverInList};
@@ -1,17 +0,0 @@
1
- import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as a}from"./runDrizzle-B2GG3IJa.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
2
- key TEXT PRIMARY KEY,
3
- relay_idx INTEGER,
4
- connection_id TEXT,
5
- name TEXT NOT NULL,
6
- args TEXT NOT NULL,
7
- identity TEXT NOT NULL,
8
- cursor INTEGER NOT NULL
9
- )`)},s=e=>JSON.stringify(l(e)),c=e=>E(JSON.parse(e)),$=e=>a(e,i`SELECT key, relay_idx, connection_id, name, args, identity, cursor FROM ${i.identifier(t)}`).toArray().map(r=>({args:c(r.args),connectionId:r.connection_id??void 0,cursor:Number(r.cursor),identity:c(r.identity),key:r.key,name:r.name,relayIndex:r.relay_idx===null?void 0:Number(r.relay_idx)})),L=(e,n)=>{a(e,i`INSERT INTO ${i.identifier(t)} (key, relay_idx, connection_id, name, args, identity, cursor)
10
- VALUES (${n.key}, ${n.relayIndex??o}, ${n.connectionId??o}, ${n.name}, ${s(n.args)}, ${s(n.identity??{})}, ${n.cursor})
11
- ON CONFLICT(key) DO UPDATE SET
12
- relay_idx = excluded.relay_idx,
13
- connection_id = excluded.connection_id,
14
- name = excluded.name,
15
- args = excluded.args,
16
- identity = excluded.identity,
17
- cursor = excluded.cursor`)},S=(e,n,r)=>{a(e,i`UPDATE ${i.identifier(t)} SET cursor = ${r} WHERE key = ${n}`)},x=(e,n,r,d)=>{const y=d===void 0?i``:i` AND key = ${T(n,r,d)}`;a(e,i`DELETE FROM ${i.identifier(t)} WHERE relay_idx = ${n} AND connection_id = ${r}${y}`)},p=(e,n)=>{a(e,i`DELETE FROM ${i.identifier(t)} WHERE relay_idx = ${n}`)},O=e=>{a(e,i`DELETE FROM ${i.identifier(t)}`)};export{L as a,p as b,O as c,x as d,R as m,$ as r,S as w};
@@ -1 +0,0 @@
1
- import{stableStringify as u}from"./stableStringify-DibjylKD.mjs";const l=(t,s)=>{const o={_id:t._id};if(s){for(const e of s)Object.hasOwn(t,e)&&(o[e]=t[e]);return o}for(const[e,n]of Object.entries(t))e!=="_id"&&e!=="_creationTime"&&(o[e]=n);return o},j=(t,s,o)=>{const{columns:e,table:n}=o,c=[],d=new Map;for(const r of t){const i=l(r,e),f=String(i._id),a=u(i);d.set(f,a);const p=s.get(f);p===void 0?c.push({doc:i,id:f,op:"insert",seq:0,table:n,ts:0}):p!==a&&c.push({doc:i,id:f,op:"update",seq:0,table:n,ts:0})}for(const r of s.keys())d.has(r)||c.push({id:r,op:"delete",seq:0,table:n,ts:0});return{changes:c,nextBaseline:d}};export{j as diffExternalSource,l as projectExternalSourceRow};
@@ -1 +0,0 @@
1
- import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{e as T}from"./effective-kind-BmG_zCAy.mjs";import{S as h,i as A,s as $,F as O}from"./json-field-path-B2fjnGc3.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import{d as y,n as N,e as b}from"./wire-codec-BYCSiazv.mjs";import{runDrizzle as f}from"./runDrizzle-B2GG3IJa.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-BbZ5hKM7.mjs";import{sqlComparableProjection as j}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const L=/^[A-Za-z_$][\w$]*$/u,d=e=>L.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",i="__originals__",X=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[s,a]of Object.entries(e)){const _=j(a);_!==void 0&&(t??={...e},r??=Object.create(null),t[s]=_,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return N(n)?JSON.stringify(b(n)):JSON.stringify(n)}catch(s){throw new c("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},w=e=>{const t=y(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}},Y=(e,t)=>`${e}__geo_${t}`,D=e=>{try{return $(e)}catch(t){throw t instanceof O?new c("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(A(e)?D(e).map(r=>d(r)).join("."):d(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, ${S(t)})`,P=e=>E("",e),C=(e,t)=>`NULLIF(json_type(${l}, ${S(e)}), 'null') IN (${h[t]})`,R=e=>o.raw(P(e)),U=(e,t)=>o.raw(C(e,t)),G=(e,t)=>E(`${g(e)}.`,t),x=(e,t)=>o.raw(G(e,t)),H=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,u=o.identifier("__key__"),q=o.identifier("__value__"),v=o.identifier("__count__"),Z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${u}, ${q}, ${v}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${u}) DO UPDATE SET ${s}`,ee=(e,t)=>e===void 0||t!==0&&t!==1||T(e)!=="boolean"?t:t===1,m=new WeakMap,te=e=>{const t=m.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),m.set(e,r),r},F=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=w(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},re=e=>{try{return F(e)}catch{return}},p=new WeakMap,oe=e=>{const t=p.get(e);if(t!==void 0)return t;let r;try{f(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{f(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return p.set(e,r),r},ne={fieldRef:R,rangeTypeGuard:U,serialize:I};export{v as A,l as D,u as a,q as b,Z as c,H as d,R as e,x as f,Y as g,re as h,oe as i,P as j,X as k,w as l,ne as m,i as n,d as o,C as p,G as q,F as r,ee as s,te as t,U as u};
@@ -1 +0,0 @@
1
- import{i as d}from"./wire-codec-BYCSiazv.mjs";const c=4;class a extends Error{}const h=t=>t.includes("."),l=t=>{const n=t.split(".");if(n.length>c||n.includes(""))throw new a(`field path "${t}" must have 1 to ${String(c)} non-empty segments`);return n},b=(t,n)=>{if(!h(n))return t[n];let o=t;for(const r of l(n)){if(!d(o)||!Object.hasOwn(o,r))return;o=o[r]}return o},f=(t,n,o,r)=>{const[e,...s]=n;if(e===void 0)throw new a(`field path "${r}" is empty`);if(t!=null&&!d(t))throw new a(`cannot set "${r}": "${e}" sits inside a value that is not an object`);const i=t??{};return{...i,[e]:s.length===0?o:f(i[e],s,o,r)}},w=(t,n)=>{const o=Object.keys(t).filter(e=>h(e));if(o.length===0)return t;for(const e of o){const s=o.find(i=>i!==e&&i.startsWith(`${e}.`));if(s!==void 0)throw new a(`patch sets both "${e}" and "${s}", which overlap; set one or the other`)}const r={};for(const[e,s]of Object.entries(t))h(e)||(r[e]=s);for(const e of o){const[s="",...i]=l(e);if(Object.hasOwn(t,s))throw new a(`patch sets both "${s}" and "${e}"; set one or the other`);r[s]=f(Object.hasOwn(r,s)?r[s]:n[s],i,t[e],e)}return r},u=t=>{const n=typeof t;return n==="number"||n==="string"||n==="boolean"?n:void 0},g={boolean:"'true', 'false'",number:"'integer', 'real'",string:"'text'"};export{a as F,g as S,u as a,w as e,h as i,b as r,l as s};
@@ -1 +0,0 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CvInVdXu.mjs";import{selectShapeRows as m}from"./selectShapeMembers-DS28-P_Z.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 +0,0 @@
1
- import{sqlComparableProjection as o}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.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};
@@ -1 +0,0 @@
1
- const a=/["\\\u0000-\u001F\uD800-\uDFFF]/,f=t=>a.test(t)?JSON.stringify(t):`"${t}"`,y=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return f(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let r="[";for(let n=0;n<t.length;n++)n>0&&(r+=","),r+=y(t[n]);return r+"]"}const i=Object.getPrototypeOf(t);if(i!==null&&i!==Object.prototype){const r=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=t,c=Object.keys(o).sort();let e="{",s=!0;for(const r of c){const n=o[r];n!==void 0&&(s?s=!1:e+=",",e+=f(r),e+=":",e+=y(n))}return e+"}"};export{y as stableStringify};
@@ -1 +0,0 @@
1
- import{stableStringify as r}from"./stableStringify-DibjylKD.mjs";import{e as o}from"./wire-codec-BYCSiazv.mjs";const m=e=>r(o(e));export{m as stableWireKey};
@@ -1 +0,0 @@
1
- import{t as w,f as j}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",d=64,g=1024,p="__proto__",A={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},l={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},E=(e,t=0)=>{if(t>d)return!0;if(e===null)return!1;const f=typeof e;if(f==="string"||f==="boolean")return!1;if(f==="number")return!Number.isFinite(e);if(f!=="object")return!0;if(Array.isArray(e))return e.length>0&&e[0]===o?!0:e.some(a=>a===void 0||E(a,t+1));if(!O(e)||Object.hasOwn(e,p))return!0;for(const a of Object.keys(e)){const i=e[a];if(i!==void 0&&E(i,t+1))return!0}return!1},u=(e,t=0)=>{if(t>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const f=typeof e;if(f==="bigint"){const r=e.toString();if(r.length>g)throw new RangeError(`wire-codec: over-long bigint (max ${g} digits)`);return[o,"bigint",r]}if(f==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(f!=="object")return e;if(e instanceof Date)return[o,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n=u(Object.fromEntries(Object.keys(r).map(c=>[c,r[c]])),t+1),s=[o,"error",String(r.name),String(r.message),n];return r.cause!==void 0&&s.push(u(r.cause,t+1)),s}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>u(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,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[o,"bytes",w(s)]:[o,"bytes",w(s),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(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 a=e,i={};for(const r of Object.keys(a)){const n=a[r];if(n===void 0)continue;const s=u(n,t+1);r===p?Object.defineProperty(i,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):i[r]=s}return i},y=(e,t=0)=>{if(t>d)throw new RangeError(`wire-codec: value nesting exceeds the ${d}-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=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>g||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(l,r)?l[r]:void 0)??Error,c=new s(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const b=y(e[4],t+1);if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(b))m===p?Object.defineProperty(c,m,{configurable:!0,enumerable:!0,value:b[m],writable:!0}):c[m]=b[m];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=j(r);if(w(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(A,s)?A[s]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(i=>y(i,t+1))}const f=e,a={};for(const i of Object.keys(f)){const r=y(f[i],t+1);i===p?Object.defineProperty(a,i,{configurable:!0,enumerable:!0,value:r,writable:!0}):a[i]=r}return a};export{y as d,u as e,O as i,E as n};