@lunora/shard-engine 1.0.0-alpha.212 → 1.0.0-alpha.214

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 (88) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +4 -930
  3. package/dist/index.d.ts +4 -930
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-olXwJWFQ.mjs → ADMIN_FUNCTIONS-voPpYb3p.mjs} +1 -1
  6. package/dist/packem_shared/AGG_COUNT-DzvM-UU5.mjs +1 -0
  7. package/dist/packem_shared/{AUDIT_LOG_TABLE-BFJ65SRS.mjs → AUDIT_LOG_TABLE-CGyZ2LNx.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-fCPCjSE4.mjs → CDC_LOG_TABLE-DchHJJ5G.mjs} +6 -6
  9. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-De7z_OHV.mjs → CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs} +1 -1
  10. package/dist/packem_shared/{COMMIT_SEQ_FIELD-Da1DjGqo.mjs → COMMIT_SEQ_FIELD-lEe6aaMv.mjs} +1 -1
  11. package/dist/packem_shared/CompanionMemo-CYnosDCb.mjs +1 -0
  12. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-CPWZjliE.mjs → DATA_MIGRATION_STATE_TABLE-D5giMetp.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-xz76_vX6.mjs → DEFAULT_MAX_RELATION_KEYS-UrlFzZB3.mjs} +1 -1
  14. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-BZLpaaq1.mjs → DEFAULT_MAX_RELAYS-BcyWWSdU.mjs} +1 -1
  15. package/dist/packem_shared/DOC_COLUMN-BNhw3l1X.mjs +1 -0
  16. package/dist/packem_shared/{DurableStreamRunner-MMlV5qKQ.mjs → DurableStreamRunner-BikgXQLq.mjs} +1 -1
  17. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-Cdq1nHtu.mjs} +1 -1
  18. package/dist/packem_shared/{IDEMPOTENCY_TABLE-BVosXEq_.mjs → IDEMPOTENCY_TABLE-DyKgfnGa.mjs} +1 -1
  19. package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-g0o4UIT_.mjs +1 -0
  20. package/dist/packem_shared/{MAIL_RETENTION-DMolrLYt.mjs → MAIL_RETENTION-C0LZvTbG.mjs} +3 -3
  21. package/dist/packem_shared/NotUniqueError-DlNAfu1a.mjs +1 -0
  22. package/dist/packem_shared/{QUEUE_TABLE-C-goXtGd.mjs → QUEUE_TABLE-CWUNphDm.mjs} +3 -3
  23. package/dist/packem_shared/RANK_TIEBREAK-BknRdgt8.mjs +1 -0
  24. package/dist/packem_shared/{REACTOR_STATE_TABLE-D2Mn204f.mjs → REACTOR_STATE_TABLE-B2x69RYJ.mjs} +1 -1
  25. package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs → SCHEDULE_OUTBOX_TABLE-BPs0yEDb.mjs} +1 -1
  26. package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs → SCHEMA_HISTORY_MAX_VERSIONS-Cgw1Tg1r.mjs} +1 -1
  27. package/dist/packem_shared/{SEARCH_STATE_TABLE-D7w8mRsm.mjs → SEARCH_STATE_TABLE-DJywWtgJ.mjs} +1 -1
  28. package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs → SHAPE_POKE_CURSOR_TABLE-CKl7syse.mjs} +1 -1
  29. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-CxiEhH8V.mjs +1 -0
  30. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs +1 -0
  31. package/dist/packem_shared/{adminTokenExists-CQ0qedmu.mjs → adminTokenExists-CDwEWaFF.mjs} +1 -1
  32. package/dist/packem_shared/{appendStreamChunk-BZYgGE9Y.mjs → appendStreamChunk-DIxOE9q_.mjs} +1 -1
  33. package/dist/packem_shared/{applyInsertDefaults-CaVH3fJ7.mjs → applyInsertDefaults-Bt6LYmPD.mjs} +1 -1
  34. package/dist/packem_shared/{archiveCdcSegment-Cr8oGLfB.mjs → archiveCdcSegment-B3UKVQ9U.mjs} +1 -1
  35. package/dist/packem_shared/backfillAggregateIndexes-BkCo8Dpf.mjs +1 -0
  36. package/dist/packem_shared/buildReprojectionMigration-CCr-Pv9T.mjs +1 -0
  37. package/dist/packem_shared/{buildShapeDiff-DrXTkXKH.mjs → buildShapeDiff-CrLtKTuR.mjs} +1 -1
  38. package/dist/packem_shared/{clearMemoryTables-aMRERF0w.mjs → clearMemoryTables-CIfrwTj8.mjs} +1 -1
  39. package/dist/packem_shared/compileWhereSql-CEy6QwJx.mjs +1 -0
  40. package/dist/packem_shared/computeRankPage-De_JKnna.mjs +1 -0
  41. package/dist/packem_shared/createCompanionSync-D5cqtwqR.mjs +1 -0
  42. package/dist/packem_shared/{createReplicaLink-BapaAUfm.mjs → createReplicaLink-auEtD_6G.mjs} +1 -1
  43. package/dist/packem_shared/{ctx-db-relay-shapes-DBobAek2.mjs → ctx-db-relay-shapes-V1HnPPPX.mjs} +1 -1
  44. package/dist/packem_shared/{ctx-db-search-state-CPKPy8N6.mjs → ctx-db-search-state-Bv_NxB1g.mjs} +1 -1
  45. package/dist/packem_shared/{defineEngineContractSuite-BnnvYfoI.mjs → defineEngineContractSuite-C_pEZ8_E.mjs} +1 -1
  46. package/dist/packem_shared/describeRelationWrites-BKd7YU5R.mjs +1 -0
  47. package/dist/packem_shared/do-sql-DT8JBpG8.mjs +1 -0
  48. package/dist/packem_shared/{exportShardRows-BEzRTBwD.mjs → exportShardRows-BxhBKedl.mjs} +1 -1
  49. package/dist/packem_shared/fts-companion-Cfz-hJum.mjs +1 -0
  50. package/dist/packem_shared/ftsCompanionDdl-NFICsmqs.mjs +1 -0
  51. package/dist/packem_shared/ftsRowidMapName-CGnFBC6P.mjs +1 -0
  52. package/dist/packem_shared/{isSoftDeleted-By7iuPdW.mjs → isSoftDeleted-Dc3VHgrR.mjs} +1 -1
  53. package/dist/packem_shared/isTtlExpired-ktYeluAa.mjs +1 -0
  54. package/dist/packem_shared/{materializeExternalRows-gZqs4Rsj.mjs → materializeExternalRows-LugivbOG.mjs} +1 -1
  55. package/dist/packem_shared/param-Y0zw_1Cv.mjs +1 -0
  56. package/dist/packem_shared/rankPivotConditionSql-CUX4Vuhv.mjs +1 -0
  57. package/dist/packem_shared/runDrizzle-DAtZbzBn.mjs +1 -0
  58. package/dist/packem_shared/runShardMigrations-DeOECCjz.mjs +5 -0
  59. package/dist/packem_shared/runSql-BBRXi81G.mjs +1 -0
  60. package/dist/packem_shared/selectShapeMembers-BP30uxpp.mjs +1 -0
  61. package/dist/packem_shared/sql-engine.d-DN1kL76Y.d.mts +886 -0
  62. package/dist/packem_shared/sql-engine.d-DN1kL76Y.d.ts +886 -0
  63. package/dist/packem_shared/where-sql-AVR5KloI.mjs +1 -0
  64. package/dist/sql.d.mts +47 -0
  65. package/dist/sql.d.ts +47 -0
  66. package/dist/sql.mjs +1 -0
  67. package/package.json +5 -1
  68. package/dist/packem_shared/AGG_COUNT-BaMXGlVQ.mjs +0 -1
  69. package/dist/packem_shared/CompanionMemo-jmlDbPlr.mjs +0 -1
  70. package/dist/packem_shared/IMPORT_MANIFEST_TTL_MS-BrNT0vUO.mjs +0 -1
  71. package/dist/packem_shared/NotUniqueError-DceH7dQi.mjs +0 -1
  72. package/dist/packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs +0 -1
  73. package/dist/packem_shared/VECTOR_BACKFILL_MAX_PAGES-DbNHRd5m.mjs +0 -1
  74. package/dist/packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs +0 -1
  75. package/dist/packem_shared/backfillAggregateIndexes-BfJ2FeLv.mjs +0 -1
  76. package/dist/packem_shared/buildReprojectionMigration-wSas3lLT.mjs +0 -1
  77. package/dist/packem_shared/compileWhereSql--dIcrS0b.mjs +0 -1
  78. package/dist/packem_shared/computeRankPage-B6umzbg4.mjs +0 -1
  79. package/dist/packem_shared/createCompanionSync-DmciS_rv.mjs +0 -1
  80. package/dist/packem_shared/describeRelationWrites-omar6-u9.mjs +0 -1
  81. package/dist/packem_shared/do-sql-Cf2rnuLV.mjs +0 -1
  82. package/dist/packem_shared/fts-companion-CE3EmIjk.mjs +0 -1
  83. package/dist/packem_shared/ftsCompanionDdl-B0bFCy6d.mjs +0 -1
  84. package/dist/packem_shared/isTtlExpired-Bymg2-13.mjs +0 -1
  85. package/dist/packem_shared/runDrizzle-RC09zZrh.mjs +0 -1
  86. package/dist/packem_shared/runShardMigrations-4_ene2xR.mjs +0 -5
  87. package/dist/packem_shared/selectShapeMembers-Ce6pOHKe.mjs +0 -1
  88. package/dist/packem_shared/where-sql-Cb_dSAMj.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-RC09zZrh.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
1
+ import{orNull as a,decodeJsonColumn as _}from"./runDrizzle-DAtZbzBn.mjs";import o from"./runSql-BBRXi81G.mjs";const s="__lunora_queue_messages",n=500,E=128*1024,T="… [truncated by the dev queue catcher]",c="[unserializable message body]",R=e=>{if(e===void 0)return"null";try{const r=JSON.stringify(e);return r.length>E?JSON.stringify(`${r.slice(0,E)}${T}`):r}catch{return JSON.stringify(c)}},g=e=>typeof e=="string"&&(e===c||e.endsWith(T)),u=e=>{o(e,`CREATE TABLE IF NOT EXISTS "${s}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  captured_at INTEGER NOT NULL,
4
4
  message_id TEXT NOT NULL,
@@ -10,8 +10,8 @@ import{runSql as o,orNull as a,decodeJsonColumn as _}from"./runDrizzle-RC09zZrh.
10
10
  error TEXT,
11
11
  dead_lettered INTEGER NOT NULL,
12
12
  message_ts INTEGER NOT NULL
13
- )`)},p=(e,r,d)=>{u(e);for(const t of r)o(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
13
+ )`)},y=(e,r,d)=>{u(e);for(const t of r)o(e,`INSERT INTO "${s}" (id, captured_at, message_id, queue, export_name, body, attempts, outcome, error, dead_lettered, message_ts)
14
14
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,crypto.randomUUID(),d,t.messageId,t.queue,a(t.exportName),R(t.body),t.attempts,t.outcome,a(t.error),t.deadLettered===!0?1:0,t.timestamp);return o(e,`DELETE FROM "${s}"
15
15
  WHERE id NOT IN (
16
16
  SELECT id FROM "${s}" ORDER BY captured_at DESC, id DESC LIMIT ?
17
- )`,n),{recorded:r.length}},i=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),y=(e,r={})=>{u(e);const d=Math.min(Math.max(r.limit??100,1),n),t=typeof r.queue=="string"&&r.queue.length>0?r.queue:void 0,m=t===void 0?"":"WHERE queue = ?",N=t===void 0?[d]:[t,d];return{entries:o(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(L=>i(L))}},S=(e,r)=>{u(e);const t=o(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,r).toArray()[0];return t===void 0?void 0:i(t)},U=e=>(u(e),o(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,n as QUEUE_RETENTION,s as QUEUE_TABLE,U as clearQueueMessages,u as ensureQueueTable,g as isLossyBody,S as readQueueMessageById,y as readQueueMessages,p as recordQueueMessages};
17
+ )`,n),{recorded:r.length}},i=e=>({attempts:e.attempts,body:_(e.body),capturedAt:e.captured_at,deadLettered:e.dead_lettered===1,error:e.error??void 0,exportName:e.export_name??void 0,id:e.id,messageId:e.message_id,outcome:e.outcome,queue:e.queue,timestamp:e.message_ts}),S=(e,r={})=>{u(e);const d=Math.min(Math.max(r.limit??100,1),n),t=typeof r.queue=="string"&&r.queue.length>0?r.queue:void 0,m=t===void 0?"":"WHERE queue = ?",N=t===void 0?[d]:[t,d];return{entries:o(e,`SELECT * FROM "${s}" ${m} ORDER BY captured_at DESC, id DESC LIMIT ?`,...N).toArray().map(L=>i(L))}},U=(e,r)=>{u(e);const t=o(e,`SELECT * FROM "${s}" WHERE id = ? LIMIT 1`,r).toArray()[0];return t===void 0?void 0:i(t)},M=e=>(u(e),o(e,`DELETE FROM "${s}"`),{cleared:!0});export{E as MAX_BODY_CHARS,n as QUEUE_RETENTION,s as QUEUE_TABLE,M as clearQueueMessages,u as ensureQueueTable,g as isLossyBody,U as readQueueMessageById,S as readQueueMessages,y as recordQueueMessages};
@@ -0,0 +1 @@
1
+ import{matchesStaticWhere as a}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{compareStrings as l}from"./aggregateTableName-B_CtIQCS.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-DeoBMpZ2.mjs";const c=Symbol("not-resolvable"),y=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:c}return r},m=(r,t)=>{if(r.length===0)return"";const o={};for(const n of r.toSorted(l))o[n]=t[n]??null;return JSON.stringify(o)},k="__id__",d=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const o=r.partitionBy??[],n=t??{};for(const e of Object.keys(n))if(e==="AND"||e==="OR"||e==="NOT")return;const s={};for(const e of o)if(e in n){const i=y(n[e]);if(i===c)return;s[e]=i}else if(r.where&&e in r.where)s[e]=r.where[e];else return;return s},S=(r,t)=>`${r}__rank_${t}`,K=(r,t)=>({partitionKey:m(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),N=a;export{k as RANK_TIEBREAK,m as encodePartitionKey,N as matchesRankStaticWhere,K as rankKeyFromDoc,S as rankTableName,h as resolveRankPartition,d as sortColumnName};
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-RC09zZrh.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-DAtZbzBn.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
2
2
  path TEXT PRIMARY KEY,
3
3
  digest TEXT NOT NULL,
4
4
  tables TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{LunoraError as $}from"@lunora/errors";import{isPlainObject as S}from"@lunora/wire";import{sql as n}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const a="__schedule_outbox",h=t=>{d(t,n`CREATE TABLE IF NOT EXISTS ${n.identifier(a)} (
1
+ import{LunoraError as $}from"@lunora/errors";import{isPlainObject as S}from"@lunora/wire";import{sql as n}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-DAtZbzBn.mjs";const a="__schedule_outbox",h=t=>{d(t,n`CREATE TABLE IF NOT EXISTS ${n.identifier(a)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  envelope_json TEXT NOT NULL,
4
4
  attempts INTEGER NOT NULL,
@@ -1,4 +1,4 @@
1
- import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as n}from"./runDrizzle-RC09zZrh.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
1
+ import{quoteIdentifier as i}from"./quoteIdentifier-CObIFRhb.mjs";import n from"./runSql-BBRXi81G.mjs";const p="__lunora_schema_history",c=50,e=i(p),E=t=>({appliedAt:typeof t.applied_at=="number"?t.applied_at:0,hash:typeof t.hash=="string"?t.hash:"",seq:typeof t.seq=="number"?t.seq:0}),a=t=>{n(t,`CREATE TABLE IF NOT EXISTS ${e} (
2
2
  hash TEXT PRIMARY KEY,
3
3
  seq INTEGER NOT NULL,
4
4
  snapshot_json TEXT NOT NULL,
@@ -1 +1 @@
1
- import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-CPKPy8N6.mjs";import"./runDrizzle-RC09zZrh.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
1
+ import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-Bv_NxB1g.mjs";import"./runDrizzle-DAtZbzBn.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
@@ -1,4 +1,4 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-DAtZbzBn.mjs";import{WORKERD_SQLITE_LIMITS as d}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";const c="__shape_poke_cursor",L=r=>{s(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  cursor INTEGER NOT NULL,
@@ -0,0 +1 @@
1
+ import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-Bv_NxB1g.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{runDrizzle as p}from"./runDrizzle-DAtZbzBn.mjs";import{a as k}from"./do-sql-DT8JBpG8.mjs";const u="__lunora_vector_backfill",m=50,w=20,h=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=k(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,w),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,h),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{w as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
@@ -0,0 +1 @@
1
+ const e={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5};export{e as WORKERD_SQLITE_LIMITS};
@@ -1,4 +1,4 @@
1
- import{ADMIN_TOKEN_TABLE as n}from"./ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{c as T}from"./constant-time-equal-BRh9yUCr.mjs";import{runSql as r}from"./runDrizzle-RC09zZrh.mjs";const u=["migrations"],A=e=>u.some(t=>t===e),m=6e4,d=new WeakSet,o=e=>{if(r(e,`CREATE TABLE IF NOT EXISTS "${n}" (
1
+ import{ADMIN_TOKEN_TABLE as n}from"./ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{c as T}from"./constant-time-equal-BRh9yUCr.mjs";import r from"./runSql-BBRXi81G.mjs";const u=["migrations"],A=e=>u.some(t=>t===e),m=6e4,d=new WeakSet,o=e=>{if(r(e,`CREATE TABLE IF NOT EXISTS "${n}" (
2
2
  name TEXT PRIMARY KEY,
3
3
  digest TEXT NOT NULL,
4
4
  created_at REAL NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-RC09zZrh.mjs";const E="__stream_runs",i="__stream_chunks",N=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-DAtZbzBn.mjs";const E="__stream_runs",i="__stream_chunks",N=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
2
2
  run_key TEXT PRIMARY KEY,
3
3
  status TEXT NOT NULL,
4
4
  last_seq INTEGER NOT NULL DEFAULT 0,
@@ -1,2 +1,2 @@
1
- import{LunoraError as S}from"@lunora/errors";import{t as F}from"./do-sql-Cf2rnuLV.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const z=Symbol.for("lunora.relations.fanOutBudget"),me=e=>({fanOutBudget:e[z],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),W=(e,t)=>t.select?Y(e,t.select,t.with):e,be=async(e,t,n,o,s)=>{const i=await Promise.all(o.map(async c=>{const f=s?{AND:[{[n]:c},s]}:{[n]:c};return[c,await e(t,f)]}));return new Map(i)},ee=32,E=1e4,te=(e,t,n)=>{const o=new Map;for(const s of e)for(const i of n(s)){const c=i[t],f=o.get(c);f?f.push(i):o.set(c,[i])}return o},x=(e,t)=>({...e,[z]:t}),ne=(e,t)=>{const n=new Map;for(const[s,i]of e)for(const c of i){const f=n.get(c);f?f.push(s):n.set(c,[s])}const o=new Map;for(const s of t)for(const i of n.get(s._id)??[]){const c=o.get(i);c?c.push(s):o.set(i,[s])}return o},j=(e,t)=>{const n=new Set;for(const o of e){const s=o[t];s!=null&&n.add(s)}return[...n]},ve=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:o,parents:s,relationBaseWhere:i,relationMask:c,schema:f,tableName:h,with:m}=e,g=n??{remaining:ee},b=(l,r)=>c?.(l,r)??r;if(s.length===0)return;const A=f.tables[h];if(!A)throw new S("INTERNAL",`unknown table: ${h}`);const $=A.relationMap??{},G=(l,r)=>{const a=d=>f.tables[d]?.shardMode?.kind??"root";return a(l)===a(r)&&a(l)!=="shardBy"},R=l=>{const r=$[l];if(!r)throw new S("INTERNAL",`unknown relation "${l}" on table "${h}"`);return r},X=async(l,r,a)=>{const d=j(s,r.field);if(d.length===0){for(const p of s)p[l]=null;return}const{page:u}=await o(r.table,x({baseWhere:i?.(r.table),relationBaseWhere:i,relationMask:c,where:{[r.references]:{in:d}},with:a.with},g)),w=new Map;for(const p of b(r.table,u))w.set(p[r.references],p);for(const p of s){const O=w.get(p[r.field]);p[l]=O?W([O],a)[0]??null:null}},_=async(l,r,a,d)=>{const{page:u}=await o(l,x({baseWhere:i?.(l),limit:d,orderBy:r.orderBy,relationBaseWhere:i,relationMask:c,where:r.where?{AND:[r.where,a]}:a,with:r.with},g));return u},T=(l,r,a,d,u)=>{for(const w of s){const p=u.get(w[d])??[];w[l]=W(a===void 0?p:p.slice(0,a),r)}},q=async(l,r,a)=>{const d=j(s,r.references);if(d.length===0){for(const y of s)y[l]=[];return}const u=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,w=(y,k)=>_(r.table,a,y,k);if(u===0){for(const y of s)y[l]=[];return}const p=u!==void 0&&d.length<=g.remaining;p&&(g.remaining-=d.length);const O=p?await Promise.all(d.map(async y=>w({[r.field]:y},u))):[await w({[r.field]:{in:d}},void 0)],v=te(O,r.field,y=>b(r.table,y));T(l,a,u,r.references,v)},I=async l=>{const{from:r,table:a,to:d}=l.through,u=new Map,w=j(s,"_id");if(w.length===0)return u;const p=await _(a,{},{[r]:{in:w}},E+1);if(p.length>E)throw new S("INTERNAL",`loading "${h}" relations through "${a}" read more than ${String(E)} join rows for one page; load fewer ${h} rows at a time`);for(const O of b(a,p)){const v=O[r],y=O[d];if(v==null||y===null||y===void 0)continue;const k=u.get(v);k?k.add(y):u.set(v,new Set([y]))}return u},K=async(l,r,a)=>{const d=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,u=d===0?new Map:await I(r),w=(O,v)=>_(r.table,a,{_id:{in:[...O]}},v);let p=new Map;if(u.size>0&&d!==void 0&&u.size<=g.remaining){g.remaining-=u.size;const O=[...u.keys()],v=await Promise.all([...u.values()].map(async y=>w(y,d)));p=new Map(O.map((y,k)=>[y,b(r.table,v[k]??[])]))}else if(u.size>0){const O=new Set([...u.values()].flatMap(v=>[...v]));p=ne(u,b(r.table,await w(O,void 0)))}T(l,a,d,"_id",p)},Z=async(l,r)=>{const a=[...r];if(a.length===0)return new Set;if(G(h,l)){const u=await t(l,"_id",a,i?.(l),i);return new Set(a.filter(w=>(u.get(w)??0)>0))}const d=await _(l,{},{_id:{in:a}},void 0);return new Set(d.map(u=>u._id))},J=async(l,r)=>{const a=await I(r),d=await Z(r.table,new Set([...a.values()].flatMap(u=>[...u])));for(const u of s){const w=u._count??{};w[l]=[...a.get(u._id)??[]].filter(p=>d.has(p)).length,u._count=w}},Q=async l=>{for(const r of Object.keys(l)){const a=R(r);if(a.through!==void 0){await J(r,a);continue}const[d,u]=a.kind==="many"?[a.field,a.references]:[a.references,a.field],w=i?.(a.table),p=j(s,u),O=p.length===0?new Map:await t(a.table,d,p,w,i);for(const v of s){const y=v._count??{},k=v[u];y[r]=k==null?0:O.get(k)??0,v._count=y}}};for(const[l,r]of Object.entries(m)){if(r===void 0||r===!1)continue;if(l==="_count"){await Q(r);continue}const a=R(l),d=r===!0?{}:r;a.through===void 0?await(a.kind==="one"?X(l,a,d):q(l,a,d)):await K(l,a,d)}},D=1e4,U=500,oe=async(e,t,n,o,s)=>{const i=new Set;let c=s;for(;;){const f=c!==void 0,h=c??await e();let m=!1;c=void 0;for(const g of h){const b=g._id;if(!(typeof b!="string"||i.has(b))){if(i.add(b),m=!0,i.size>D)throw n();await t(b)}}if(!f){if(h.length<U)return;if(!m)throw new S("INTERNAL",o)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(D)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),se=async(e,t,n,o)=>{const{deletedId:s,deletedReference:i,findHolders:c,onRestrict:f,tableName:h}=e,m=n.references==="_id"?s:i(n.references);if(m==null)return;const{field:g}=n,b=`"${t}.${g}"`,A=await c(t,g,m,{limit:o==="restrict"?1:D+1,select:["_id"]});if(A.length!==0){if(o==="restrict")return f(`cannot delete "${h}" row: ${b} still references it`);if(A.length>D)throw H(h,b,o);return{action:o,field:g,holderTable:t,label:b,probe:A,referencedValue:m}}},re=async(e,t,n)=>{const{findHolders:o,onCascade:s,onSetNull:i,tableName:c}=e,{action:f,field:h,holderTable:m,label:g,probe:b,referencedValue:A}=t;await oe(()=>o(m,h,A,{limit:U}),$=>f==="cascade"?s(m,$):i(m,$,h),()=>H(c,g,f),`onDelete on "${c}" made no progress: ${g} rows still match after being processed`,n?b:void 0)},Oe=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const o=[];for(const[s,i]of Object.entries(t.tables)){const c=i.relationMap;if(c)for(const f of Object.values(c)){if(f.kind!=="one"||f.table!==n||!f.onDelete)continue;const h=await se(e,s,f,f.onDelete);h&&o.push(h)}}for(const[s,i]of o.entries())await re(e,i,s===0)},L=new WeakMap,B=e=>{const t=L.get(e);if(t!==void 0)return t;const n=e._meta,o=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],s=e.kind==="from"||o.some(i=>i!==void 0&&B(i));return L.set(e,s),s},C=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},P=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,V=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=P(e),o=P(t);if(n!==void 0||o!==void 0)return n!==void 0&&o!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===o.length&&n.every((f,h)=>f===o[h]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((f,h)=>V(f,t[h]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!C(e)||!C(t))return!1;const s=e,i=t,c=Object.keys(s);return c.length===Object.keys(i).length&&c.every(f=>f in i&&V(s[f],i[f]))},N=new WeakMap,Ae=e=>{if(N.has(e))return N.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,o])=>B(o))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return N.set(e,n),n},ae=e=>{let t;return(n,o)=>e===void 0?!1:(t??=e()??{},n in t&&V(o,t[n]))},ie=(e,t)=>{const n=new Set(Object.keys(t).filter(o=>t[o]!==void 0));for(const[o,s]of F(e))s.serverDefault&&n.delete(o);return n},ce=(e,t,n,o,s)=>n.trusted===!0||o!==void 0&&!o.has(e)||s(e,t),M=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>M(t)):e instanceof Map?new Map([...e].map(([t,n])=>[M(t),M(n)])):e instanceof Set?new Set([...e].map(t=>M(t))):C(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,M(n)])):e,ke=(e,t,n)=>{const o={...t};for(const[s,i]of F(e)){if(i.serverDefault){o[s]=i.serverDefault({auth:n});continue}if(o[s]===void 0){if(i.defaultFn)o[s]=i.defaultFn();else if("defaultValue"in i){const{defaultValue:c}=i;o[s]=M(c)}}}return o},fe=e=>e.map((t,n)=>typeof t=="number"?`[${String(t)}]`:n===0?t:`.${t}`).join(""),le=(e,t,n,o)=>o.patched===void 0?"":o.patched.has(e)?n?" (set by the column's server default, which replaces what this patch sent)":" (set by this patch)":Object.is(o.previous?.()?.[e],t)?" (a stored value this patch does not set: the row already holds it, and every patch of the row fails until it is fixed)":" (not set by this patch: an update hook assigned it)",ue=e=>e.message.startsWith("object has ")?"object":e.received.startsWith("object")?e.received:e.received.split(" ")[0]??e.received,de=e=>e instanceof Error&&e.code==="VALIDATION_ERROR"&&Array.isArray(e.path)&&typeof e.expected=="string"&&typeof e.received=="string",he=(e,t,n)=>{const{field:o,serverDefault:s,value:i}=t,c=[o,...e.path],f=`${n.table===void 0?"":`${n.table}.`}${fe(c)}`,h=e.message.startsWith(`Expected ${e.expected} at `)&&e.message.endsWith(`, received ${e.received}`),m=ue(e),g=h?`expected ${e.expected}, received ${m}`:e.message,b=e.constructor,A=new b(`${f}: ${g}${le(o,i,s,n)}`,{expected:e.expected,path:c,received:m}),$=e.stack?.indexOf(`
1
+ import{LunoraError as S}from"@lunora/errors";import{t as F}from"./do-sql-DT8JBpG8.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-rOdoinP8.mjs";const z=Symbol.for("lunora.relations.fanOutBudget"),me=e=>({fanOutBudget:e[z],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),W=(e,t)=>t.select?Y(e,t.select,t.with):e,be=async(e,t,n,o,s)=>{const i=await Promise.all(o.map(async c=>{const f=s?{AND:[{[n]:c},s]}:{[n]:c};return[c,await e(t,f)]}));return new Map(i)},ee=32,E=1e4,te=(e,t,n)=>{const o=new Map;for(const s of e)for(const i of n(s)){const c=i[t],f=o.get(c);f?f.push(i):o.set(c,[i])}return o},x=(e,t)=>({...e,[z]:t}),ne=(e,t)=>{const n=new Map;for(const[s,i]of e)for(const c of i){const f=n.get(c);f?f.push(s):n.set(c,[s])}const o=new Map;for(const s of t)for(const i of n.get(s._id)??[]){const c=o.get(i);c?c.push(s):o.set(i,[s])}return o},j=(e,t)=>{const n=new Set;for(const o of e){const s=o[t];s!=null&&n.add(s)}return[...n]},ve=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:o,parents:s,relationBaseWhere:i,relationMask:c,schema:f,tableName:h,with:m}=e,g=n??{remaining:ee},b=(l,r)=>c?.(l,r)??r;if(s.length===0)return;const A=f.tables[h];if(!A)throw new S("INTERNAL",`unknown table: ${h}`);const $=A.relationMap??{},G=(l,r)=>{const a=d=>f.tables[d]?.shardMode?.kind??"root";return a(l)===a(r)&&a(l)!=="shardBy"},R=l=>{const r=$[l];if(!r)throw new S("INTERNAL",`unknown relation "${l}" on table "${h}"`);return r},X=async(l,r,a)=>{const d=j(s,r.field);if(d.length===0){for(const p of s)p[l]=null;return}const{page:u}=await o(r.table,x({baseWhere:i?.(r.table),relationBaseWhere:i,relationMask:c,where:{[r.references]:{in:d}},with:a.with},g)),w=new Map;for(const p of b(r.table,u))w.set(p[r.references],p);for(const p of s){const O=w.get(p[r.field]);p[l]=O?W([O],a)[0]??null:null}},_=async(l,r,a,d)=>{const{page:u}=await o(l,x({baseWhere:i?.(l),limit:d,orderBy:r.orderBy,relationBaseWhere:i,relationMask:c,where:r.where?{AND:[r.where,a]}:a,with:r.with},g));return u},T=(l,r,a,d,u)=>{for(const w of s){const p=u.get(w[d])??[];w[l]=W(a===void 0?p:p.slice(0,a),r)}},q=async(l,r,a)=>{const d=j(s,r.references);if(d.length===0){for(const y of s)y[l]=[];return}const u=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,w=(y,k)=>_(r.table,a,y,k);if(u===0){for(const y of s)y[l]=[];return}const p=u!==void 0&&d.length<=g.remaining;p&&(g.remaining-=d.length);const O=p?await Promise.all(d.map(async y=>w({[r.field]:y},u))):[await w({[r.field]:{in:d}},void 0)],v=te(O,r.field,y=>b(r.table,y));T(l,a,u,r.references,v)},I=async l=>{const{from:r,table:a,to:d}=l.through,u=new Map,w=j(s,"_id");if(w.length===0)return u;const p=await _(a,{},{[r]:{in:w}},E+1);if(p.length>E)throw new S("INTERNAL",`loading "${h}" relations through "${a}" read more than ${String(E)} join rows for one page; load fewer ${h} rows at a time`);for(const O of b(a,p)){const v=O[r],y=O[d];if(v==null||y===null||y===void 0)continue;const k=u.get(v);k?k.add(y):u.set(v,new Set([y]))}return u},K=async(l,r,a)=>{const d=typeof a.limit=="number"?Math.max(0,Math.floor(a.limit)):void 0,u=d===0?new Map:await I(r),w=(O,v)=>_(r.table,a,{_id:{in:[...O]}},v);let p=new Map;if(u.size>0&&d!==void 0&&u.size<=g.remaining){g.remaining-=u.size;const O=[...u.keys()],v=await Promise.all([...u.values()].map(async y=>w(y,d)));p=new Map(O.map((y,k)=>[y,b(r.table,v[k]??[])]))}else if(u.size>0){const O=new Set([...u.values()].flatMap(v=>[...v]));p=ne(u,b(r.table,await w(O,void 0)))}T(l,a,d,"_id",p)},Z=async(l,r)=>{const a=[...r];if(a.length===0)return new Set;if(G(h,l)){const u=await t(l,"_id",a,i?.(l),i);return new Set(a.filter(w=>(u.get(w)??0)>0))}const d=await _(l,{},{_id:{in:a}},void 0);return new Set(d.map(u=>u._id))},J=async(l,r)=>{const a=await I(r),d=await Z(r.table,new Set([...a.values()].flatMap(u=>[...u])));for(const u of s){const w=u._count??{};w[l]=[...a.get(u._id)??[]].filter(p=>d.has(p)).length,u._count=w}},Q=async l=>{for(const r of Object.keys(l)){const a=R(r);if(a.through!==void 0){await J(r,a);continue}const[d,u]=a.kind==="many"?[a.field,a.references]:[a.references,a.field],w=i?.(a.table),p=j(s,u),O=p.length===0?new Map:await t(a.table,d,p,w,i);for(const v of s){const y=v._count??{},k=v[u];y[r]=k==null?0:O.get(k)??0,v._count=y}}};for(const[l,r]of Object.entries(m)){if(r===void 0||r===!1)continue;if(l==="_count"){await Q(r);continue}const a=R(l),d=r===!0?{}:r;a.through===void 0?await(a.kind==="one"?X(l,a,d):q(l,a,d)):await K(l,a,d)}},D=1e4,U=500,oe=async(e,t,n,o,s)=>{const i=new Set;let c=s;for(;;){const f=c!==void 0,h=c??await e();let m=!1;c=void 0;for(const g of h){const b=g._id;if(!(typeof b!="string"||i.has(b))){if(i.add(b),m=!0,i.size>D)throw n();await t(b)}}if(!f){if(h.length<U)return;if(!m)throw new S("INTERNAL",o)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(D)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),se=async(e,t,n,o)=>{const{deletedId:s,deletedReference:i,findHolders:c,onRestrict:f,tableName:h}=e,m=n.references==="_id"?s:i(n.references);if(m==null)return;const{field:g}=n,b=`"${t}.${g}"`,A=await c(t,g,m,{limit:o==="restrict"?1:D+1,select:["_id"]});if(A.length!==0){if(o==="restrict")return f(`cannot delete "${h}" row: ${b} still references it`);if(A.length>D)throw H(h,b,o);return{action:o,field:g,holderTable:t,label:b,probe:A,referencedValue:m}}},re=async(e,t,n)=>{const{findHolders:o,onCascade:s,onSetNull:i,tableName:c}=e,{action:f,field:h,holderTable:m,label:g,probe:b,referencedValue:A}=t;await oe(()=>o(m,h,A,{limit:U}),$=>f==="cascade"?s(m,$):i(m,$,h),()=>H(c,g,f),`onDelete on "${c}" made no progress: ${g} rows still match after being processed`,n?b:void 0)},Oe=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const o=[];for(const[s,i]of Object.entries(t.tables)){const c=i.relationMap;if(c)for(const f of Object.values(c)){if(f.kind!=="one"||f.table!==n||!f.onDelete)continue;const h=await se(e,s,f,f.onDelete);h&&o.push(h)}}for(const[s,i]of o.entries())await re(e,i,s===0)},L=new WeakMap,B=e=>{const t=L.get(e);if(t!==void 0)return t;const n=e._meta,o=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],s=e.kind==="from"||o.some(i=>i!==void 0&&B(i));return L.set(e,s),s},C=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},P=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,V=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=P(e),o=P(t);if(n!==void 0||o!==void 0)return n!==void 0&&o!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===o.length&&n.every((f,h)=>f===o[h]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((f,h)=>V(f,t[h]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!C(e)||!C(t))return!1;const s=e,i=t,c=Object.keys(s);return c.length===Object.keys(i).length&&c.every(f=>f in i&&V(s[f],i[f]))},N=new WeakMap,Ae=e=>{if(N.has(e))return N.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,o])=>B(o))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return N.set(e,n),n},ae=e=>{let t;return(n,o)=>e===void 0?!1:(t??=e()??{},n in t&&V(o,t[n]))},ie=(e,t)=>{const n=new Set(Object.keys(t).filter(o=>t[o]!==void 0));for(const[o,s]of F(e))s.serverDefault&&n.delete(o);return n},ce=(e,t,n,o,s)=>n.trusted===!0||o!==void 0&&!o.has(e)||s(e,t),M=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>M(t)):e instanceof Map?new Map([...e].map(([t,n])=>[M(t),M(n)])):e instanceof Set?new Set([...e].map(t=>M(t))):C(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,M(n)])):e,ke=(e,t,n)=>{const o={...t};for(const[s,i]of F(e)){if(i.serverDefault){o[s]=i.serverDefault({auth:n});continue}if(o[s]===void 0){if(i.defaultFn)o[s]=i.defaultFn();else if("defaultValue"in i){const{defaultValue:c}=i;o[s]=M(c)}}}return o},fe=e=>e.map((t,n)=>typeof t=="number"?`[${String(t)}]`:n===0?t:`.${t}`).join(""),le=(e,t,n,o)=>o.patched===void 0?"":o.patched.has(e)?n?" (set by the column's server default, which replaces what this patch sent)":" (set by this patch)":Object.is(o.previous?.()?.[e],t)?" (a stored value this patch does not set: the row already holds it, and every patch of the row fails until it is fixed)":" (not set by this patch: an update hook assigned it)",ue=e=>e.message.startsWith("object has ")?"object":e.received.startsWith("object")?e.received:e.received.split(" ")[0]??e.received,de=e=>e instanceof Error&&e.code==="VALIDATION_ERROR"&&Array.isArray(e.path)&&typeof e.expected=="string"&&typeof e.received=="string",he=(e,t,n)=>{const{field:o,serverDefault:s,value:i}=t,c=[o,...e.path],f=`${n.table===void 0?"":`${n.table}.`}${fe(c)}`,h=e.message.startsWith(`Expected ${e.expected} at `)&&e.message.endsWith(`, received ${e.received}`),m=ue(e),g=h?`expected ${e.expected}, received ${m}`:e.message,b=e.constructor,A=new b(`${f}: ${g}${le(o,i,s,n)}`,{expected:e.expected,path:c,received:m}),$=e.stack?.indexOf(`
2
2
  at `)??-1;return $!==-1&&e.stack!==void 0&&(A.stack=`${A.name}: ${A.message}${e.stack.slice($)}`),A},pe=(e,t,n)=>{try{return e(t.value)}catch(o){throw de(o)?he(o,t,n):o}},$e=(e,t,n={})=>{let o;const s=ae(n.previous),i=n.only??(n.supplied===void 0?void 0:ie(e,n.supplied));for(const[c,f]of Object.entries(e.shape)){if(!(c in t)||typeof f.parse!="function")continue;const h=B(f);if(h&&ce(c,t[c],n,i,s)||n.tolerateStoredNull===!0&&t[c]===null&&f.kind==="optional")continue;const m=pe(g=>f.parse?.(g),{field:c,serverDefault:f._meta?.column?.serverDefault!==void 0,value:t[c]},n);h&&(o??={...t},o[c]=m)}return o??t};export{D as CASCADE_MAX_ROWS,E as MAX_LINK_ROWS,ke as applyInsertDefaults,Oe as applyOnDelete,j as distinctValues,be as fanOutScalarCounts,me as relationHooks,ve as resolveWith,$e as runRowValidators,Ae as transformOnlyDefinition};
@@ -1,4 +1,4 @@
1
- import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
1
+ import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-DAtZbzBn.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  seq INTEGER NOT NULL
4
4
  )`)},$=t=>(g(t),d(t,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),w=(t,n)=>{g(t),d(t,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${n}) ON CONFLICT (id) DO UPDATE SET seq = ${n}`)},L=async(t,n,e)=>{const o=e[0]?.seq,r=e.at(-1)?.seq;o===void 0||r===void 0||await t.put(y(n,r),JSON.stringify({changes:e,from:o,to:r}),{httpMetadata:{contentType:"application/json"}})},j=async(t,n,e)=>{const o=f(n);return(await t.list({limit:1,prefix:o,startAfter:`${o}${h(e)}.json`})).objects.length>0},S=t=>{let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null)return;const e=n;return typeof e.from=="number"&&typeof e.to=="number"&&Array.isArray(e.changes)?e:void 0},_=(t,n)=>{const e=[];for(const o of t.changes)if(!(o.seq<=n)){if(o.op!=="delete"&&o.doc===void 0)break;e.push(o)}return e},I=(t,n,e)=>{let o=e;for(const r of n){if(r.seq!==o+1)break;t.push(r),o=r.seq}return o},b=async(t,n)=>{const e=await t.get(n);return e===null?void 0:S(await e.text())},q=async(t,n,e,o)=>{const r=f(n),p=Math.max(1,Math.min(o??R,v)),A=await t.list({limit:T,prefix:r,startAfter:`${r}${h(e)}.json`}),c=[];let i=e;for(const l of A.objects){const a=await b(t,l.key);if(a===void 0)break;const m=_(a,i);if(i=I(c,m,i),c.length>=p||i!==a.to)break}if(c[0]?.seq!==e+1)return;const u=c.slice(0,p);return{changes:u,cursor:u.at(-1)?.seq??e}};export{L as archiveCdcSegment,j as cdcArchiveRewound,q as readArchivedCdcChanges,$ as readCdcArchivedThrough,w as writeCdcArchivedThrough};
@@ -0,0 +1 @@
1
+ import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-Bv_NxB1g.mjs";import{S as I,b as L,c as b,d as x,a as k}from"./fts-companion-Cfz-hJum.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as _,ensureRankCompanion as y}from"./createCompanionSync-D5cqtwqR.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-DAtZbzBn.mjs";import{i as M,D as m,a as A}from"./do-sql-DT8JBpG8.mjs";import{sqliteInList as B}from"./param-Y0zw_1Cv.mjs";import{groupUnmappedRows as U}from"./ftsRowidMapName-CGnFBC6P.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])_(e,r,t,n.softDeleteMode?.field)},Z=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])y(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?b(n,u,x(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=U(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${B(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?b(n,s,x(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},q=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},ee=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ne=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{X as backfillAggregateIndexes,Z as backfillRankIndexes,ne as backfillSearchIndexes,ee as backfillSearchIndexesForTable,H as readKeysetPage,q as searchIndexCoversTable};
@@ -0,0 +1 @@
1
+ import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}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 m,D as E}from"./do-sql-DT8JBpG8.mjs";import p from"./runSql-BBRXi81G.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(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=d(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-Ce6pOHKe.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BP30uxpp.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -1 +1 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-RC09zZrh.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-DAtZbzBn.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
@@ -0,0 +1 @@
1
+ import"./json-field-path-DeJW4U9z.mjs";import"./param-Y0zw_1Cv.mjs";import"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{c as t,s}from"./where-sql-AVR5KloI.mjs";import"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";export{t as compileWhereSql,s as serverInList};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as A}from"./runDrizzle-DAtZbzBn.mjs";import{sqliteInList as O}from"./param-Y0zw_1Cv.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-BknRdgt8.mjs";import X from"./rankPivotConditionSql-CUX4Vuhv.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[p,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[p]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},mo=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const p=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(p)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{mo as computeRankPage,Q as resolveRankSeekTuple};
@@ -0,0 +1 @@
1
+ import{N as uo,S as $o,c as Eo,d as go,a as po}from"./fts-companion-Cfz-hJum.mjs";import{sql as o}from"drizzle-orm";import{r as Q}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as J,aggregateSqlFunction as mo}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as B,foldAggregateTally as Z,encodeAggregateKey as v,coerceAggregateNumber as H}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as ho,readCompanionSignature as N,rankSignature as So,writeCompanionSignature as x}from"./CompanionMemo-CYnosDCb.mjs";import{runAll as _o,runDrizzle as g}from"./runDrizzle-DAtZbzBn.mjs";import{i as yo,g as Ro,D as oo,u as eo,r as no}from"./do-sql-DT8JBpG8.mjs";import{AGG_KEY as D,AGG_VALUE as A,AGG_COUNT as _,aggUpsertSql as j,jsonPathSql as q}from"./AGG_COUNT-DzvM-UU5.mjs";import{param as G}from"./param-Y0zw_1Cv.mjs";import{encodeGeohash as To,GEO_DEFAULT_PRECISION as Ao}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as W}from"./CURSOR_PREFIX-rOdoinP8.mjs";import{rankTableName as P,matchesRankStaticWhere as to,sortColumnName as wo,encodePartitionKey as Co}from"./RANK_TIEBREAK-BknRdgt8.mjs";import{WORKERD_SQLITE_LIMITS as ro}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";import{mayHoldProjectedValue as Io}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as io}from"./serializeSqlValue-DeoBMpZ2.mjs";const Oo=(i,f,t)=>[...i.partitionBy??[],...i.sortBy.map(l=>l.field),...i.where?Object.keys(i.where):[]].every(l=>Q(f,l)===Q(t,l)),so=i=>o.join(["__id__","__partition__",...i.sortBy.map((f,t)=>wo(t))].map(f=>o.identifier(f)),o`, `),co=(i,f,t)=>{const u=Co(i.partitionBy??[],t),l=i.sortBy.map(r=>io(t[r.field]??null)),a=o.join([f,u,...l].map(r=>G(r)),o`, `);return o`(${a})`},ko=(i,f,t,u,l,a)=>{g(i,o`INSERT INTO ${o.identifier(f)} (${u}) VALUES ${co(t,l,a)}`)},X=1e3,ao=function*(f,t,u,l){let a;for(;;){const r=a===void 0?o``:o` WHERE id > ${G(a)}`,m=[...g(eo(f),o`SELECT id, _creationTime, ${o.identifier(oo)} FROM ${o.identifier(t)}${r} ORDER BY id LIMIT ${G(X)}`)];for(const h of m){const R=no(h);R&&W(R,u)&&l(R)&&(yield R)}if(m.length<X)return;a=String(m.at(-1)?.id)}},vo=(i,f,t,u,l)=>{const a=B(f,t.name),r=t.by??[],m=new Map;for(const w of ao(i,f,u,I=>!t.where||J(I,t.where)))Z(m,v(r,w),t,w);g(i,o`DELETE FROM ${o.identifier(a)}`);const h=Math.floor(ro.boundParams/3),R=[...m];for(let w=0;w<R.length;w+=h){const I=R.slice(w,w+h),V=o.join(I.map(([U,F])=>o`(${U}, ${F.value}, ${F.count})`),o`, `);g(i,o`INSERT INTO ${o.identifier(a)} (${D}, ${A}, ${_}) VALUES ${V}`)}x(i,a,l)},Lo=(i,f,t,u)=>{const l=ho(t,u);N(i,B(f,t.name))!==l&&vo(i,f,t,u,l)},Do=(i,f,t,u,l)=>{const a=P(f,t.name),r=so(t);g(i,o`DELETE FROM ${o.identifier(a)}`);const m=Math.max(1,Math.floor(ro.boundParams/(2+t.sortBy.length)));let h=[];const R=()=>{h.length>0&&(g(i,o`INSERT INTO ${o.identifier(a)} (${r}) VALUES ${o.join(h,o`, `)}`),h=[])};for(const w of ao(i,f,u,I=>!t.where||to(I,t.where)))h.push(co(t,w._id,w)),h.length>=m&&R();R(),x(i,a,l)},Fo=(i,f,t,u)=>{const l=So(t,u);N(i,P(f,t.name))!==l&&Do(i,f,t,u,l)},Mo=(i,f,t,u,l,a,r)=>{if(a&&r&&W(a,u)===W(r,u)&&Oo(t,a,r))return;const m=P(f,t.name);a&&g(i,o`DELETE FROM ${o.identifier(m)} WHERE ${o.identifier("__id__")} = ${l}`),!(!r||!W(r,u)||t.where&&!to(r,t.where))&&ko(i,m,t,so(t),l,r)},No=i=>{const{broadcast:f,indexKeysFor:t,invalidateCache:u,recordCdc:l,schema:a,sql:r}=i,m=i.verified??new Set,h=e=>a.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const c=B(e,n.name);m.has(c)||(Lo(r,e,n,h(e)),m.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",E=[],y=(s,$)=>{const S=io($);S===null?E.push(o`${q(s)} IS NULL`):E.push(o`${q(s)} = ${S}`)};for(const s of p)y(s,c[s]??null);const C=h(e);C!==void 0&&y(C,null);for(const[s,$]of Object.entries(n.where??{}))y(s,$!==null&&typeof $=="object"&&!Array.isArray($)?$.eq:$);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&Io(M)){const s=g(eo(r),o`SELECT id, _creationTime, ${o.identifier(oo)} FROM ${o.identifier(e)}${L}`).toArray(),$=new Map;for(const S of s){const k=no(S);k&&Z($,"",n,k)}return{value:$.get("")?.value??null}}const b=mo(n.op),T=q(d);return{value:g(r,o`SELECT ${o.raw(b)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,c,p)=>{const d=B(e,n.name),{op:E}=n,y=n.field??"",C=s=>{g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${D} = ${s} AND ${_} <= 0`)},L=h(e),M=s=>!n.where||J(s,n.where),b=s=>W(s,L)&&M(s);p!==void 0&&E!=="count"&&M(p)&&H(p[y]);const T=c&&b(c)?c:void 0,O=p&&b(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[s,$]of[[T,-1],[O,1]]){if(!s)continue;const S=v(n.by??[],s);g(r,j(d,S,$,$,o`${A} = ${A} + excluded.${A}, ${_} = ${_} + excluded.${_}`))}T&&C(v(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[s,$]of[[T,-1],[O,1]]){if(!s)continue;const S=H(s[y]);if(S===void 0)continue;const k=v(n.by??[],s);g(r,j(d,k,$*S,$,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${_} = ${_} + excluded.${_}`))}T&&C(v(n.by??[],T));return}if(T){const s=v(n.by??[],T),$=H(T[y]),S=g(r,o`SELECT ${A} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${D} = ${s}`).toArray()[0],k=(S?.count??0)-1;if(k<=0)g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${D} = ${s}`);else if(S&&$!==void 0&&S.value!==null&&$===S.value){const lo=w(e,n,T);g(r,o`UPDATE ${o.identifier(d)} SET ${A} = ${lo.value}, ${_} = ${k} WHERE ${D} = ${s}`)}else g(r,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${D} = ${s}`)}if(O){const s=v(n.by??[],O),$=H(O[y]);if($===void 0)g(r,j(d,s,null,1,o`${_} = ${_} + 1`));else{const S=E==="min"?"MIN":"MAX";g(r,j(d,s,$,1,o`${A} = ${o.raw(S)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${_} = ${_} + 1`))}}}},V=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])R(e,n)},U=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])I(e,p,n,c)},F=(e,n)=>{const c=P(e,n.name);m.has(c)||(Fo(r,e,n,h(e)),m.add(c))},fo=e=>{for(const n of a.tables[e]?.rankIndexes??[])F(e,n)},K=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Mo(r,e,d,h(e),n,c,p)},z=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!yo(r)))for(const E of d){if(uo(p,c,E))continue;const y=$o(e,E.name);_o(r,c?Eo(y,n,go(c,E)):po(y,n))}},Y=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=Ro(e,p.name);g(r,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=c?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:y,lng:C}=E,L=To({lat:y,lng:C},p.precision??Ao);g(r,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${y}, ${C})`)}}};return{ensureBackfilledForTable:V,ensureBackfilledIndex:R,ensureRankBackfilled:F,ensureRankBackfilledForTable:fo,syncAggregates:U,syncCompanionsForInsert:(e,n,c)=>{z(e,n,c),Y(e,n,c),U(e,void 0,c),K(e,n,void 0,c),u(e,n,c),l(e,n,"insert",c),f({indexKeys:t(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:Y,syncRanks:K,syncSearch:z}};export{No as createCompanionSync,Lo as ensureAggregateCompanion,Fo as ensureRankCompanion};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-C-C35VXL.mjs";import{siblingStub as L}from"./stubByName-DQSivmvb.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
1
+ import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-C-C35VXL.mjs";import{siblingStub as L}from"./stubByName-DQSivmvb.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -1,4 +1,4 @@
1
- import{encodeWire as l,decodeWire as E}from"@lunora/wire";import{sql as i}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-RC09zZrh.mjs";import{a as T}from"./relay-CKEdfUjH.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
1
+ import{encodeWire as l,decodeWire as E}from"@lunora/wire";import{sql as i}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-DAtZbzBn.mjs";import{a as T}from"./relay-CKEdfUjH.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
2
2
  key TEXT PRIMARY KEY,
3
3
  relay_idx INTEGER,
4
4
  connection_id TEXT,
@@ -1 +1 @@
1
- import{q as E}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{d(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);const r=new Set(d(i,e`PRAGMA table_info(${e.identifier(n)})`).toArray().map(o=>o.name));r.has("profile")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`),r.has("covered")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`),d(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",m=(i,r)=>{const o=d(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const t=d(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return t?{cursor:t.cursor??void 0,done:s(t.done),profile:t.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),O=(i,r,o,f,t)=>{const $=o??null,a=T(u(i,r).profile,t)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;d(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${t}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,m as a,l as b,S as c,N as l,R as m,u as r,O as w};
1
+ import{q as E}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-DAtZbzBn.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{d(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);const r=new Set(d(i,e`PRAGMA table_info(${e.identifier(n)})`).toArray().map(o=>o.name));r.has("profile")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`),r.has("covered")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`),d(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",m=(i,r)=>{const o=d(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const t=d(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return t?{cursor:t.cursor??void 0,done:s(t.done),profile:t.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),O=(i,r,o,f,t)=>{const $=o??null,a=T(u(i,r).profile,t)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;d(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${t}, ${f?1:0}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("covered")} = ${a}`)};export{n as S,m as a,l as b,S as c,N as l,R as m,u as r,O as w};
@@ -1 +1 @@
1
- import{createShardCtxDb as C}from"./NotUniqueError-DceH7dQi.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BZLpaaq1.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-4_ene2xR.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as C}from"./NotUniqueError-DlNAfu1a.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-BcyWWSdU.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-DeOECCjz.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ import{v}from"./accepts-null-D1zmJbyR.mjs";const j=(t,n,o)=>t.some(e=>e.unique===!0&&e.fields.length===2&&e.fields.includes(n)&&e.fields.includes(o)),b=(t,n)=>{const o=t.shardMode??{kind:"root"},e=n.shardMode??{kind:"root"};return o.kind!=="global"&&o.kind===e.kind&&o.field===e.field},p=(t,n)=>{const o=t?.shape[n];return o!==void 0&&v(o)},g=(t,n,o)=>Object.entries(t?.shape??{}).filter(([e,r])=>e!==n&&e!==o&&!e.startsWith("_")&&r.kind!=="optional"&&r._meta?.column?.serverDefault===void 0).map(([e])=>e),m="a many-to-many write is several row writes and only a mutation's transaction makes them atomic; run it in a mutation",N=(t,n,o)=>t!==void 0&&t.indexes.filter(e=>e.unique===!0).every(e=>j([e],n,o))&&!Object.values(t.shape).some(e=>e._meta?.column?.unique===!0),k=(t,n)=>{const o={};for(const[e,r]of Object.entries(t.tables))for(const[i,s]of Object.entries(r.relationMap??{})){const a=t.tables[s.table],f=o[e]??{};if(o[e]=f,s.through!==void 0){const{from:l,table:d,to:c}=s.through,u=t.tables[d],h=g(u,l,c);f[i]={colocated:a!==void 0&&u!==void 0&&b(r,a)&&b(r,u),kind:"many",pairIsOnlyUnique:N(u,l,c),refusalNow:()=>n?.()===!0?void 0:m,table:s.table,through:{from:l,table:d,to:c},...h.length===0?{}:{refusal:`"${d}" has required columns besides "${l}" and "${c}" (${h.join(", ")}); write its rows directly`}};continue}const O=s.kind==="one"?r:a;f[i]={field:s.field,kind:s.kind,nullable:p(O,s.field),references:s.references,table:s.table,colocated:a!==void 0&&b(r,a)}}return o},w=t=>{const n=k(t),o=[];for(const[e,r]of Object.entries(n)){for(const i of Object.values(r))i.through!==void 0&&Object.freeze(i.through),Object.freeze(i);Object.freeze(r),Object.values(r).some(i=>i.through!==void 0)&&o.push(e)}return{map:Object.freeze(n),throughTables:Object.freeze(o)}},q=(t,n)=>{if(t.throughTables.length===0)return t.map;const o=()=>n?.()===!0?void 0:m,e={...t.map};for(const r of t.throughTables){const i={...t.map[r]};for(const[s,a]of Object.entries(i))a.through!==void 0&&(i[s]=Object.freeze({...a,refusalNow:o}));e[r]=Object.freeze(i)}return Object.freeze(e)};export{q as bindRelationWrites,k as describeRelationWrites,w as describeSchemaRelationWrites};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{WIRE_TAG as S,decodeWire as E,needsWireEncoding as A,encodeWire as T}from"@lunora/wire";import{sql as s}from"drizzle-orm";import{e as y}from"./effective-kind-BmG_zCAy.mjs";import{S as b,i as $,s as O,F as g}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as j}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as i}from"./runDrizzle-DAtZbzBn.mjs";import{sqlComparableProjection as L}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import"./serializeSqlValue-DeoBMpZ2.mjs";const I=/^[A-Za-z_$][\w$]*$/u,_=e=>I.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,f="__doc__",c="__originals__",z=e=>{if(Object.hasOwn(e,c))throw new u("BAD_REQUEST",`"${c}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[o,a]of Object.entries(e)){const d=L(a);d!==void 0&&(t??={...e},r??=Object.create(null),t[o]=d,r[o]=a)}t&&r&&(t[c]=r);const n=t??e;try{return A(n)?JSON.stringify(T(n)):JSON.stringify(n)}catch(o){throw new u("BAD_REQUEST",`this document cannot be stored: ${o instanceof Error?o.message:String(o)}`)}},w=e=>{const t=JSON.parse(e),r=e.includes(S)||e.includes(String.raw`\u`)?E(t):t,n=r[c];if(n===null||typeof n!="object"||Array.isArray(n))return r;const o={...r};return delete o[c],{...o,...n}},G=(e,t)=>`${e}__geo_${t}`,N=e=>{try{return O(e)}catch(t){throw t instanceof g?new u("VALIDATION_ERROR",t.message):t}},p=e=>`'$.${($(e)?N(e).map(r=>_(r)).join("."):_(e)).replaceAll("'","''")}'`,h=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${f}, ${p(t)})`,Q=e=>h("",e),K=(e,t)=>`NULLIF(json_type(${f}, ${p(e)}), 'null') IN (${b[t]})`,V=(e,t)=>h(`${j(e)}.`,t),k=(e,t)=>e===void 0||t!==0&&t!==1||y(e)!=="boolean"?t:t===1,m=new WeakMap,H=e=>{const t=m.get(e);if(t!==void 0)return t;const r=[];for(const[n,o]of Object.entries(e.shape)){const a=o._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),m.set(e,r),r},P=e=>{if(!e)return;const t=e[f];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 o=e._creationTime;return typeof o=="number"&&(r._creationTime=o),r},X=e=>{try{return P(e)}catch{return}},l=new WeakMap,R=Symbol("lunora.wrappedSql"),D=e=>e[R]??e,Y=(e,t)=>{const r=D(e),n=l.get(r);if(n!==void 0)return n;if(t!==void 0)try{return i(r,s`SELECT 1 FROM ${s.identifier(t)} LIMIT 0`).toArray(),l.set(r,!0),!0}catch{}let o;try{i(r,s`CREATE VIRTUAL TABLE IF NOT EXISTS ${s.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{i(r,s`DROP TABLE IF EXISTS ${s.identifier("__lunora_fts_probe")}`)}catch{}}return l.set(r,o),o};export{f as D,R as W,X as a,K as b,c,w as d,z as e,_ as f,G as g,k as h,Y as i,Q as j,V as q,P as r,H as t,D as u};
@@ -1 +1 @@
1
- import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as u}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";const y=200,_=(e,t)=>{const o=r=>{const s=e.tables[r];return s!==void 0&&s.shardMode?.kind!=="global"};return(t&&t.length>0?[...t]:Object.keys(e.tables)).filter(r=>o(r))},h=async function*(e,t,o=y){let r=null,s=!1;for(;!s;){const n=await e.findMany(t,{cursor:r,includeDeleted:!0,limit:o});for(const i of n.page)yield{doc:i,table:t};r=n.continueCursor,s=n.isDone||r===null}},W=async function*(e,t,o){const r=_(t,o.tables),s=o.batchSize??y;for(const n of r)yield*h(e,n,s)},E=new Set(["_creationTime","_id"]),R=(e,t)=>{for(const[o,r]of Object.entries(e.shape)){const s=t[o];if(s===void 0&&r.kind==="optional")continue;const n=r.parse;if(typeof n=="function")try{n(s)}catch(i){const a=i instanceof Error?i.message:String(i);return`field "${o}": ${a}`}}},A=(e,t,o)=>{const r=e.tables[t];if(!r)return`unknown table: ${t}`;if(r.shardMode?.kind==="global")return`table "${t}" is a global (.global()) table and is not importable through the shard import path`;const s=Object.fromEntries(Object.entries(o).filter(([n])=>!E.has(n)));for(const n of Object.keys(s))if(!Object.hasOwn(r.shape,n))return`unexpected field "${n}": not declared in table "${t}"`;return R(r,s)},k=async(e,t,o)=>{if(e.lookupById){const r=await e.lookupById(o);return r===null?void 0:r.tableName}return await e.get(t,o)===null?void 0:t},S=async(e,t,o)=>{try{return await k(e,t,o)}catch{return}},v=e=>u in e?Object.fromEntries(Object.entries(e).filter(([t])=>t!==u)):e,m=(e,t,o)=>{const{table:r}=t;if(typeof r!="string"||r.length===0)return{code:"BAD_ROW",line:o,message:"row is missing `table`",table:r};if(!t.doc||typeof t.doc!="object"||Array.isArray(t.doc))return{code:"BAD_ROW",line:o,message:"row is missing or malformed `doc`",table:r};const s=A(e,r,v(t.doc));return s===void 0?void 0:{code:"VALIDATION_ERROR",line:o,message:s,table:r}},g=(e,t,o)=>{const r=e.tables[t.table];return r===void 0?{code:"BAD_ROW",line:o,message:`unknown table: ${t.table}`,table:t.table}:r.shardMode?.kind==="global"?{code:"BAD_ROW",line:o,message:`table "${t.table}" is a global (.global()) table and is not importable through the shard import path`,table:t.table}:typeof t.doc?._id=="string"?void 0:{code:"BAD_ROW",line:o,message:"a delete row needs the `_id` to delete",table:t.table}},I=async(e,t,o,r)=>{const s=g(t,o,r);if(s!==void 0)return{error:s,kind:"error"};const n=o.doc._id;try{const i=await k(e,o.table,n);return i===void 0?{kind:"absent"}:i!==o.table?{error:{code:"ID_COLLISION",line:r,message:`_id "${n}" belongs to table "${i}", not "${o.table}"`,table:o.table},kind:"error"}:(await e.delete(o.table,n,{hard:!0,skipOnDelete:!0}),{kind:"deleted"})}catch(i){const{body:a}=b(i,{fallbackCode:"DELETE_FAILED"});return{error:{code:a.code,line:r,message:a.message,table:o.table},kind:"error"}}},D=async(e,t,o,r,s)=>{const n=m(t,o,r);if(n!==void 0)return{error:n,kind:"error"};const{table:i}=o,a=v(o.doc),l=typeof a._id=="string"?a._id:void 0,d=l===void 0?void 0:await S(e,i,l);if(d!==void 0&&d!==i)return{error:{code:"ID_COLLISION",line:r,message:`_id "${String(l)}" already belongs to table "${d}"`,table:i},kind:"error"};if(d===i&&l!==void 0){if(s!=="replace")return{kind:"conflict"};try{const c={...a};return delete c._id,await e.replace(i,l,c,{allowExplicitId:!0}),{kind:"replaced"}}catch(c){const{body:f}=b(c,{fallbackCode:"REPLACE_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}}try{return await e.insert(i,a,{allowExplicitId:!0}),{kind:"inserted",table:i}}catch(c){const{body:f}=b(c,{fallbackCode:"INSERT_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}},O=(e,t,o)=>e.op==="delete"?o?void 0:{code:"BAD_ROW",line:t,message:'a row with `op: "delete"` needs `deletes: true` on the import',table:e.table}:e.op===void 0?void 0:{code:"BAD_ROW",line:t,message:`row \`op\` must be "delete" when set, got ${JSON.stringify(e.op)}`,table:e.table},L=async(e,t,o)=>{const r={};for(const s of t){const n=[];for await(const{doc:i}of h(e,s)){const a=i._id;typeof a=="string"&&!o.has(a)&&n.push(a)}for(const i of n)await e.delete(s,i,{hard:!0});r[s]=n.length}return r},$=(e,t)=>e.has(t.table)?typeof t.doc?._id=="string"?void 0:"a replace import row must carry its `_id`":`table "${t.table}" is not in this replace import's tables`,C=async(e,t,o,r,s,n)=>{const i=O(o,r,n);return i!==void 0?{error:i,kind:"error"}:o.op==="delete"?I(e,t,o,r):D(e,t,o,r,s)},B=(e,t,o,r)=>{const s=n=>{e.inserted[n]=(e.inserted[n]??0)+1};switch(t.kind){case"absent":break;case"conflict":{e.conflicts+=1;break}case"deleted":{e.deleted+=1;break}case"error":{e.errors.push(t.error);break}case"replaced":{r?s(o):e.replaced+=1;break}default:s(t.table)}},T=(e,t)=>t?.filter(o=>{const r=e.tables[o];return r!==void 0&&r.shardMode?.kind!=="global"}),j=(e,t,o,r)=>O(t,o,r)??(t.op==="delete"?g(e,t,o):m(e,t,o)),F=async(e,t,o)=>{const r={conflicts:0,deleted:0,errors:[],inserted:{},replaced:0};let s=(o.startLine??1)-1;const n=T(t,o.replaceTables),i=new Set(n),a=n===void 0?o.onConflict??"skip":"replace";for(const d of o.rows){s+=1;const c=n===void 0?void 0:$(i,d);if(c!==void 0){r.errors.push({code:"BAD_ROW",line:s,message:c,table:d.table});continue}if(o.dryRun===!0){const p=j(t,d,s,o.deletes===!0);p!==void 0&&r.errors.push(p);continue}const f=await C(e,t,d,s,a,o.deletes===!0);B(r,f,d.table,n!==void 0)}if(n===void 0||o.keepIds===void 0||r.errors.length>0||o.dryRun===!0)return r;const l=new Set([...o.keepIds,...o.rows.flatMap(d=>d.op!=="delete"&&typeof d.doc._id=="string"?[d.doc._id]:[])]);return{...r,pruned:await L(e,n,l)}},N=e=>{const t=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:t}},w=e=>e===void 0?{}:{op:typeof e=="string"?e:JSON.stringify(e)},z=e=>{const t=Array.isArray(e.rows)?e.rows:[],o=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;if(typeof n.table!="string"||!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)){o.push({doc:n.doc??{},table:typeof n.table=="string"?n.table:""});continue}o.push({doc:n.doc,...w(n.op),table:n.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{deletes:e.deletes===!0,dryRun:e.dryRun===!0,onConflict:e.onConflict==="replace"?"replace":"skip",rows:o,startLine:r}};export{W as exportShardRows,F as importShardRows,N as parseExportShardArgs,z as parseImportShardArgs,$ as replaceRefusal,_ as selectExportTables,A as validateImportRow};
1
+ import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as u}from"./COMMIT_SEQ_FIELD-lEe6aaMv.mjs";const y=200,_=(e,t)=>{const o=r=>{const s=e.tables[r];return s!==void 0&&s.shardMode?.kind!=="global"};return(t&&t.length>0?[...t]:Object.keys(e.tables)).filter(r=>o(r))},h=async function*(e,t,o=y){let r=null,s=!1;for(;!s;){const n=await e.findMany(t,{cursor:r,includeDeleted:!0,limit:o});for(const i of n.page)yield{doc:i,table:t};r=n.continueCursor,s=n.isDone||r===null}},W=async function*(e,t,o){const r=_(t,o.tables),s=o.batchSize??y;for(const n of r)yield*h(e,n,s)},E=new Set(["_creationTime","_id"]),R=(e,t)=>{for(const[o,r]of Object.entries(e.shape)){const s=t[o];if(s===void 0&&r.kind==="optional")continue;const n=r.parse;if(typeof n=="function")try{n(s)}catch(i){const a=i instanceof Error?i.message:String(i);return`field "${o}": ${a}`}}},A=(e,t,o)=>{const r=e.tables[t];if(!r)return`unknown table: ${t}`;if(r.shardMode?.kind==="global")return`table "${t}" is a global (.global()) table and is not importable through the shard import path`;const s=Object.fromEntries(Object.entries(o).filter(([n])=>!E.has(n)));for(const n of Object.keys(s))if(!Object.hasOwn(r.shape,n))return`unexpected field "${n}": not declared in table "${t}"`;return R(r,s)},k=async(e,t,o)=>{if(e.lookupById){const r=await e.lookupById(o);return r===null?void 0:r.tableName}return await e.get(t,o)===null?void 0:t},S=async(e,t,o)=>{try{return await k(e,t,o)}catch{return}},v=e=>u in e?Object.fromEntries(Object.entries(e).filter(([t])=>t!==u)):e,m=(e,t,o)=>{const{table:r}=t;if(typeof r!="string"||r.length===0)return{code:"BAD_ROW",line:o,message:"row is missing `table`",table:r};if(!t.doc||typeof t.doc!="object"||Array.isArray(t.doc))return{code:"BAD_ROW",line:o,message:"row is missing or malformed `doc`",table:r};const s=A(e,r,v(t.doc));return s===void 0?void 0:{code:"VALIDATION_ERROR",line:o,message:s,table:r}},g=(e,t,o)=>{const r=e.tables[t.table];return r===void 0?{code:"BAD_ROW",line:o,message:`unknown table: ${t.table}`,table:t.table}:r.shardMode?.kind==="global"?{code:"BAD_ROW",line:o,message:`table "${t.table}" is a global (.global()) table and is not importable through the shard import path`,table:t.table}:typeof t.doc?._id=="string"?void 0:{code:"BAD_ROW",line:o,message:"a delete row needs the `_id` to delete",table:t.table}},I=async(e,t,o,r)=>{const s=g(t,o,r);if(s!==void 0)return{error:s,kind:"error"};const n=o.doc._id;try{const i=await k(e,o.table,n);return i===void 0?{kind:"absent"}:i!==o.table?{error:{code:"ID_COLLISION",line:r,message:`_id "${n}" belongs to table "${i}", not "${o.table}"`,table:o.table},kind:"error"}:(await e.delete(o.table,n,{hard:!0,skipOnDelete:!0}),{kind:"deleted"})}catch(i){const{body:a}=b(i,{fallbackCode:"DELETE_FAILED"});return{error:{code:a.code,line:r,message:a.message,table:o.table},kind:"error"}}},D=async(e,t,o,r,s)=>{const n=m(t,o,r);if(n!==void 0)return{error:n,kind:"error"};const{table:i}=o,a=v(o.doc),l=typeof a._id=="string"?a._id:void 0,d=l===void 0?void 0:await S(e,i,l);if(d!==void 0&&d!==i)return{error:{code:"ID_COLLISION",line:r,message:`_id "${String(l)}" already belongs to table "${d}"`,table:i},kind:"error"};if(d===i&&l!==void 0){if(s!=="replace")return{kind:"conflict"};try{const c={...a};return delete c._id,await e.replace(i,l,c,{allowExplicitId:!0}),{kind:"replaced"}}catch(c){const{body:f}=b(c,{fallbackCode:"REPLACE_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}}try{return await e.insert(i,a,{allowExplicitId:!0}),{kind:"inserted",table:i}}catch(c){const{body:f}=b(c,{fallbackCode:"INSERT_FAILED"});return{error:{code:f.code,line:r,message:f.message,table:i},kind:"error"}}},O=(e,t,o)=>e.op==="delete"?o?void 0:{code:"BAD_ROW",line:t,message:'a row with `op: "delete"` needs `deletes: true` on the import',table:e.table}:e.op===void 0?void 0:{code:"BAD_ROW",line:t,message:`row \`op\` must be "delete" when set, got ${JSON.stringify(e.op)}`,table:e.table},L=async(e,t,o)=>{const r={};for(const s of t){const n=[];for await(const{doc:i}of h(e,s)){const a=i._id;typeof a=="string"&&!o.has(a)&&n.push(a)}for(const i of n)await e.delete(s,i,{hard:!0});r[s]=n.length}return r},$=(e,t)=>e.has(t.table)?typeof t.doc?._id=="string"?void 0:"a replace import row must carry its `_id`":`table "${t.table}" is not in this replace import's tables`,C=async(e,t,o,r,s,n)=>{const i=O(o,r,n);return i!==void 0?{error:i,kind:"error"}:o.op==="delete"?I(e,t,o,r):D(e,t,o,r,s)},B=(e,t,o,r)=>{const s=n=>{e.inserted[n]=(e.inserted[n]??0)+1};switch(t.kind){case"absent":break;case"conflict":{e.conflicts+=1;break}case"deleted":{e.deleted+=1;break}case"error":{e.errors.push(t.error);break}case"replaced":{r?s(o):e.replaced+=1;break}default:s(t.table)}},T=(e,t)=>t?.filter(o=>{const r=e.tables[o];return r!==void 0&&r.shardMode?.kind!=="global"}),j=(e,t,o,r)=>O(t,o,r)??(t.op==="delete"?g(e,t,o):m(e,t,o)),F=async(e,t,o)=>{const r={conflicts:0,deleted:0,errors:[],inserted:{},replaced:0};let s=(o.startLine??1)-1;const n=T(t,o.replaceTables),i=new Set(n),a=n===void 0?o.onConflict??"skip":"replace";for(const d of o.rows){s+=1;const c=n===void 0?void 0:$(i,d);if(c!==void 0){r.errors.push({code:"BAD_ROW",line:s,message:c,table:d.table});continue}if(o.dryRun===!0){const p=j(t,d,s,o.deletes===!0);p!==void 0&&r.errors.push(p);continue}const f=await C(e,t,d,s,a,o.deletes===!0);B(r,f,d.table,n!==void 0)}if(n===void 0||o.keepIds===void 0||r.errors.length>0||o.dryRun===!0)return r;const l=new Set([...o.keepIds,...o.rows.flatMap(d=>d.op!=="delete"&&typeof d.doc._id=="string"?[d.doc._id]:[])]);return{...r,pruned:await L(e,n,l)}},N=e=>{const t=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:t}},w=e=>e===void 0?{}:{op:typeof e=="string"?e:JSON.stringify(e)},z=e=>{const t=Array.isArray(e.rows)?e.rows:[],o=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;if(typeof n.table!="string"||!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)){o.push({doc:n.doc??{},table:typeof n.table=="string"?n.table:""});continue}o.push({doc:n.doc,...w(n.op),table:n.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{deletes:e.deletes===!0,dryRun:e.dryRun===!0,onConflict:e.onConflict==="replace"?"replace":"skip",rows:o,startLine:r}};export{W as exportShardRows,F as importShardRows,N as parseExportShardArgs,z as parseImportShardArgs,$ as replaceRefusal,_ as selectExportTables,A as validateImportRow};
@@ -0,0 +1 @@
1
+ import{q as L}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as o}from"./param-Y0zw_1Cv.mjs";import{ftsRowidMapName as n}from"./ftsRowidMapName-CGnFBC6P.mjs";const A=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const f of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[f]}return r},a=(i,t)=>`${i}__fts_${t}`,N="__text__",d="__id__",O=1e3,u=(i,t)=>t.document(i),S=(i,t)=>A(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&S(i,r.field)===S(t,r.field),l=(i,t)=>u(_(S(i,t.field)),L(t.language)).slice(0,O),F=(i,t)=>l(i,t).join(" "),c=50,T="__rowid__",E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,I=(i,t,{guard:r,unmappedRowids:f})=>{const $=n(i),s=r===void 0?e``:e` AND ${r}`,R=f===void 0?e`${E(i,"rowid")} > 0`:o(E(i,"rowid"),f,!1,c);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,d)} AS TEXT) = ${t}${s}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E($,T)} FROM ${e.identifier($)} WHERE ${E($,d)} = ${t}) AND ${E(i,d)} = ${t}${s}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(N)}, ${e.identifier(d)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n(i))} (${e.identifier(T)} INTEGER PRIMARY KEY, ${e.identifier(d)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(N)}, ${e.identifier(d)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],W=(i,t,r,f={})=>{const $=n(i),s=f.guard===void 0?e``:e` AND ${f.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E($,T)}) FROM ${e.identifier($)}), 0), 0) - 1`;return[...I(i,t,f),e`INSERT OR REPLACE INTO ${e.identifier($)} (${e.identifier(T)}, ${e.identifier(d)}) SELECT ${R}, ${t} WHERE 1 = 1${s}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(N)}, ${e.identifier(d)}) SELECT ${E($,T)}, ${r}, ${E($,d)} FROM ${e.identifier($)} WHERE ${E($,d)} = ${t}${s}`]},y=(i,t,r={})=>{const f=n(i),$=r.guard===void 0?e``:e` AND ${r.guard}`;return[...I(i,t,r),e`DELETE FROM ${e.identifier(f)} WHERE ${E(f,d)} = ${t}${$}`]},H=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,d)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,d)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`;export{w as N,a as S,y as a,H as b,W as c,F as d,U as f,d as l,l as s};
@@ -0,0 +1 @@
1
+ import{f as e,a as m,b as f,c as p}from"./fts-companion-Cfz-hJum.mjs";import"./param-Y0zw_1Cv.mjs";import"./ftsRowidMapName-CGnFBC6P.mjs";export{e as ftsCompanionDdl,m as ftsPurgeDocument,f as ftsUnmappedPage,p as ftsWriteDocument};
@@ -0,0 +1 @@
1
+ const s=o=>`${o}__ids`,e=o=>{const t=new Map;for(const n of o){const r=String(n.id);t.set(r,[...t.get(r)??[],Number(n.rowid)])}return t};export{s as ftsRowidMapName,e as groupUnmappedRows};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-gZqs4Rsj.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-DAtZbzBn.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-LugivbOG.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -0,0 +1 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-DAtZbzBn.mjs";import{jsonPathSql as d}from"./AGG_COUNT-DzvM-UU5.mjs";const s=(o,e)=>{const i=e-(o.after??0),r=[t`${d(o.field)} IS NOT NULL`,t`${d(o.field)} < ${i}`];return o.softDeleteField!==void 0&&r.push(t`${d(o.softDeleteField)} IS NULL`),r},L=(o,e,i,r)=>{const n=t`SELECT id FROM ${t.identifier(e.table)} WHERE ${t.join(s(e,i),t` AND `)} LIMIT ${t.raw(String(Math.max(0,Math.floor(r))+1))}`,f=l(o,n).toArray(),a=f.length>r,E=f.slice(0,r).map($=>$.id);return{hasMore:a,ids:E}},S=(o,e,i,r)=>{const n=t`SELECT 1 AS hit FROM ${t.identifier(e.table)} WHERE id = ${i} AND ${t.join(s(e,r),t` AND `)}`;return l(o,n).toArray().length>0},c=(o,e)=>{const i=e.softDeleteField===void 0?t``:t` WHERE ${d(e.softDeleteField)} IS NULL`,r=t`SELECT MIN(${d(e.field)}) AS expiry FROM ${t.identifier(e.table)}${i}`,n=l(o,r).toArray()[0]?.expiry;return typeof n=="number"?n+(e.after??0):void 0};export{S as isTtlExpired,c as nextTtlExpiry,L as selectExpiredIds};
@@ -1 +1 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-fCPCjSE4.mjs";import{selectShapeRows as m}from"./selectShapeMembers-Ce6pOHKe.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";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(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BP30uxpp.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";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(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
@@ -0,0 +1 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{SQLiteDialect as u}from"drizzle-orm/sqlite-core";import{WORKERD_SQLITE_LIMITS as s}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";const S=new u,d=s.boundParams/2,p=n=>n===null||typeof n=="boolean"?!0:typeof n=="number"?Number.isFinite(n):typeof n=="string"&&n.isWellFormed(),h=n=>{const t=[];for(const o of n){if(!(o instanceof Uint8Array))return;t.push(Array.from(o,r=>r.toString(16).padStart(2,"0")).join(""))}return JSON.stringify(t)},y=(n,t)=>{if(n!=="sqlite")throw new f("INTERNAL",`renderSql only renders SQLite; use SqlDialect.render for "${n}"`);const{params:o,sql:r}=S.sqlToQuery(t);return{params:o,sql:r}},L=n=>e`${n}`,I=n=>{if(n.length===0)throw new Error("unionAll: expected at least one branch");let t=[...n];for(;t.length>s.compoundSelect;){const o=[];for(let r=0;r<t.length;r+=s.compoundSelect){const i=e.join(t.slice(r,r+s.compoundSelect),e` UNION ALL `);o.push(e`SELECT * FROM (${i}) ${e.identifier("__u__")}`)}t=o}return e.join(t,e` UNION ALL `)},T=(n,t,o,r=d)=>{const i=o?e` NOT IN `:e` IN `,a=t.every(l=>p(l)),c=t.length>r&&!a?h(t):void 0;if(c!==void 0)return e`${n}${i}(SELECT unhex(${e.identifier("value")}) FROM json_each(${c}))`;if(t.length>r&&!a)throw new f("BAD_REQUEST",`an "in" list of ${String(t.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(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(r)} values or fewer.`);return t.length<=r?e`${n}${i}(${e.join(t.map(l=>L(l)),e`, `)})`:e`${n}${i}(SELECT ${e.identifier("value")} FROM json_each(${JSON.stringify(t)}))`};export{h as bytesAsHexJson,p as isJsonSafe,L as param,y as renderSql,T as sqliteInList,I as unionAll};
@@ -0,0 +1 @@
1
+ import{sql as i}from"drizzle-orm";const s=(n,r,e,d)=>{const t=e!=="desc"===d;if(r==null)return t?i`${i.identifier(n)} IS NOT NULL`:void 0;const o=i`${i.identifier(n)} ${i.raw(t?">":"<")} ${r}`;return t?o:i`(${o} OR ${i.identifier(n)} IS NULL)`};export{s as default};
@@ -0,0 +1 @@
1
+ import{renderSql as e}from"./param-Y0zw_1Cv.mjs";import l from"./runSql-BBRXi81G.mjs";const s=(r,o)=>{const{params:n,sql:t}=e("sqlite",o);return l(r,t,...n)},i=(r,o)=>{for(const n of o)s(r,n)},d=r=>r??null,m=r=>{if(!(r==null||r===""))try{return JSON.parse(r)}catch{return}};export{m as decodeJsonColumn,d as orNull,i as runAll,s as runDrizzle};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as w}from"@lunora/errors";import{f as X,S as y}from"./fts-companion-Cfz-hJum.mjs";import{sql as n}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as k}from"./backfillAggregateIndexes-BkCo8Dpf.mjs";import{migrateCdcLog as B,migrateCdcMeta as G}from"./CDC_LOG_TABLE-DchHJJ5G.mjs";import{migrateClientWatermark as v}from"./CLIENT_WATERMARK_TABLE-CMUFBMfO.mjs";import{migrateCommitSeq as P}from"./COMMIT_SEQ_FIELD-lEe6aaMv.mjs";import{migrateCompanionState as Y}from"./CompanionMemo-CYnosDCb.mjs";import{migrateGlobalShapeSnapshot as q}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Cdq1nHtu.mjs";import{migrateIdempotency as j}from"./IDEMPOTENCY_TABLE-DyKgfnGa.mjs";import{m as K}from"./ctx-db-relay-shapes-V1HnPPPX.mjs";import{migrateScheduleOutbox as V}from"./SCHEDULE_OUTBOX_TABLE-BPs0yEDb.mjs";import{m as W}from"./ctx-db-search-state-Bv_NxB1g.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-CKl7syse.mjs";import{runDrizzle as _,runAll as z}from"./runDrizzle-DAtZbzBn.mjs";import{D as Q,t as Z,i as J,g as ee}from"./do-sql-DT8JBpG8.mjs";import{createIndexSql as p,jsonPathSql as u,AGG_KEY as te,AGG_VALUE as oe,AGG_COUNT as x}from"./AGG_COUNT-DzvM-UU5.mjs";import{renderSql as L}from"./param-Y0zw_1Cv.mjs";import{migrateDurableStreams as ne}from"./appendStreamChunk-DIxOE9q_.mjs";import{rankTableName as $,sortColumnName as re}from"./RANK_TIEBREAK-BknRdgt8.mjs";import{migrateReactorState as ie}from"./REACTOR_STATE_TABLE-B2x69RYJ.mjs";import{recordSchemaVersion as de}from"./SCHEMA_HISTORY_MAX_VERSIONS-Cgw1Tg1r.mjs";const h=n`_creationTime, id`,F="__by_creation",ae="__ttl",se=`, ${L("sqlite",h).sql})`,g="__lunora_framework_indexes",c=e=>e.replaceAll(/[A-Z]/gu,t=>t.toLowerCase()),ce=/^CREATE\s+VIRTUAL\s+TABLE\b/iu,le=/\bUSING\s+fts5\b/iu,fe=e=>e!==null&&ce.test(e)&&le.test(e),me=e=>{const t=new Map,o=c(g);let d=!1,r;for(const i of _(e,n`SELECT type, name, tbl_name, sql FROM sqlite_master`))i.type==="index"?t.set(c(i.name),{name:i.name,sql:i.sql,tableFolded:c(i.tbl_name)}):i.type==="table"&&(c(i.name)===o&&(d=!0),r===void 0&&fe(i.sql)&&(r=i.name));return{existingFtsTable:r,indexes:t,ledgerExists:d}},I=(e,t,o,d,r)=>{const i=p(t,o,d,r);_(e.sql,i);const a=c(t);e.catalog.has(a)||e.catalog.set(a,{name:t,sql:L("sqlite",i).sql,tableFolded:c(o)})},U=(e,t)=>{_(e.sql,n`DROP INDEX IF EXISTS ${n.identifier(t)}`),e.catalog.delete(c(t))};class b extends w{}const N=(e,t,o,d,r,i)=>{const a=n.join(r.map(f=>n`${f} IS NOT NULL`),n` AND `);if(_(e,n`SELECT 1 FROM ${n.identifier(o)} WHERE ${a} GROUP BY ${d} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new b("UNIQUE_INDEX_DUPLICATES",`unique index "${t}" on "${o}" ${i}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},S=(e,t,o,d,r,i)=>{const a=e.catalog.get(c(t)),l=a?.tableFolded===c(o)?a.sql:void 0;if(l==null)return;const f=E=>{const T=E.indexOf("(");return T===-1?void 0:E.slice(T,E.lastIndexOf(")")+1)},s=f(L("sqlite",p(t,o,d,r)).sql),m=f(l);s===void 0||m===void 0||s===m||(r&&N(e.sql,t,o,d,i,"cannot be re-created with its new column list"),U(e,t))},D=(e,t,o)=>e.get(c(t))?.tableFolded===c(o),R=(e,t,o,d,r,i)=>{r&&!D(e.catalog,t,o)&&N(e.sql,t,o,d,i,"cannot be created"),I(e,t,o,d,r)},C=(e,t)=>{try{t()}catch(o){if(e===void 0||!(o instanceof b))throw o;e.push(o.message)}},_e=(e,t,o)=>c(t).startsWith(`${c(e)}_`)&&c(t)!==c(`${e}${F}`)&&o!==null&&(o.includes("json_extract(")||o.trimEnd().endsWith(se)),Ee=e=>{const t=new Map;for(const o of _(e,n`SELECT name, table_name FROM ${n.identifier(g)}`))t.set(c(o.name),{name:o.name,tableFolded:c(o.table_name)});return t},A=(e,t,o)=>{const d=c(t);e.ledger.has(d)||(_(e.sql,n`INSERT OR IGNORE INTO ${n.identifier(g)} (name, table_name) VALUES (${t}, ${o})`),e.ledger.set(d,{name:t,tableFolded:c(o)}))},Te=(e,t)=>e.has(c(t)),ge=(e,t,o)=>{if(_(e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(g)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),t.ledgerExists)return Ee(e);const d={ledger:new Map,sql:e},r=new Map(o.map(i=>[c(i),i]));for(const i of t.indexes.values()){if(i.sql===null)continue;const a=r.get(i.tableFolded);a!==void 0&&_e(a,i.name,i.sql)&&A(d,i.name,a)}return d.ledger},ue=(e,t,o)=>{const d=c(t),r=new Set([...o].map(i=>c(i)));for(const[i,a]of e.ledger)a.tableFolded!==d||r.has(i)||(U(e,a.name),_(e.sql,n`DELETE FROM ${n.identifier(g)} WHERE ${n.identifier(g)}."name" = ${a.name}`),e.ledger.delete(i))},Ie=(e,t)=>t===void 0?u(e):n`${u(t)}, ${u(e)}`,Se=(e,t,o,d)=>{const r=`${t}${ae}`,i=new Set([...d].map(l=>c(l)));if(o.ttlPolicy===void 0||i.has(c(r))||D(e.catalog,r,t)&&!Te(e.ledger,r))return;const a=Ie(o.ttlPolicy.field,o.softDeleteMode?.field);d.add(r);try{S(e,r,t,a,!1,[]),I(e,r,t,a,!1),A(e,r,t)}catch{}},Ae=(e,t,o,d)=>{const r=new Set;for(const i of o.indexes){const a=`${t}_${i.name}`,l=i.unique??!1,f=i.fields.map(E=>u(E)),s=n.join(f,n`, `),m=l?s:n`${s}, ${h}`;r.add(a),C(d,()=>{S(e,a,t,m,l,f),R(e,a,t,m,l,f),A(e,a,t)})}for(const[i,a]of Z(o)){if(!a.unique)continue;const l=u(i),f=`${t}_unique_${i}`;r.add(f),C(d,()=>{S(e,f,t,l,!0,[l]),R(e,f,t,l,!0,[l]),A(e,f,t)})}Se(e,t,o,r),ue(e,t,r)},Le=(e,t,o,d)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!J(e,d))){for(const r of o.searchIndexes)z(e,X(y(t,r.name)));k(e,t,o)}},he=(e,t,o)=>{if(o.geoIndexes)for(const d of o.geoIndexes){const r=ee(t,d.name);_(e.sql,n`CREATE TABLE IF NOT EXISTS ${n.identifier(r)} (${n.identifier("__id__")} TEXT PRIMARY KEY, ${n.identifier("__geohash__")} TEXT NOT NULL, ${n.identifier("__lat__")} REAL NOT NULL, ${n.identifier("__lng__")} REAL NOT NULL)`);const i=`${t}__geo_${d.name}__btree`;I(e,i,r,n`${n.identifier("__geohash__")} ASC, ${n.identifier("__id__")} ASC`,!1)}},xe=(e,t,o)=>{if(o.aggregateIndexes)for(const d of o.aggregateIndexes){const r=O(t,d.name);_(e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(r)} (${te} TEXT PRIMARY KEY, ${oe} REAL, ${x} INTEGER NOT NULL DEFAULT 0)`),_(e,n`PRAGMA table_info(${n.identifier(r)})`).toArray().some(a=>a.name==="__count__")||_(e,n`ALTER TABLE ${n.identifier(r)} ADD COLUMN ${x} INTEGER NOT NULL DEFAULT 0`)}},Re=(e,t,o)=>{const d=_(e.sql,n`PRAGMA table_info(${n.identifier(t)})`).toArray().map(r=>r.name).filter(r=>r.startsWith("__sort_k"));if(d.length>0&&(d.length!==o.length||d.some((r,i)=>r!==o[i]))){_(e.sql,n`DROP TABLE ${n.identifier(t)}`);const r=c(t);for(const[i,a]of e.catalog)a.tableFolded===r&&e.catalog.delete(i)}},Ce=(e,t,o)=>{if(o.rankIndexes)for(const d of o.rankIndexes){const r=$(t,d.name),i=d.sortBy.map((E,T)=>re(T)),a=i.map(E=>n`${n.identifier(E)} BLOB`),l=a.length>0?n`, ${n.join(a,n`, `)}`:n``;Re(e,r,i),_(e.sql,n`CREATE TABLE IF NOT EXISTS ${n.identifier(r)} (${n.identifier("__id__")} TEXT PRIMARY KEY, ${n.identifier("__partition__")} TEXT NOT NULL${l})`);const f=[n`${n.identifier("__partition__")} ASC`];for(const[E,T]of i.entries()){const M=d.sortBy[E]?.direction;f.push(n`${n.identifier(T)} ${n.raw(M==="desc"?"DESC":"ASC")}`)}f.push(n`${n.identifier("__id__")} ASC`);const s=`${t}__rank_${d.name}__btree`,m=n.join(f,n`, `);S(e,s,r,m,!1,[]),I(e,s,r,m,!1)}},He=(e,t,o={})=>{const d=o.deferBlockedUniqueIndexes?[]:void 0;o.schemaSnapshot!==void 0&&de(e,o.schemaSnapshot.hash,o.schemaSnapshot.json);const r=me(e),i=Object.entries(t.tables).filter(([,s])=>s.shardMode?.kind!=="global");W(e);const a=ge(e,r,i.map(([s])=>s)),l={catalog:r.indexes,ledger:a,sql:e},f=[];for(const[s,m]of i)_(e,n`CREATE TABLE IF NOT EXISTS ${n.identifier(s)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${n.identifier(Q)} TEXT NOT NULL
5
+ )`),I(l,`${s}${F}`,s,h,!1),Ae(l,s,m,d),Le(e,s,m,r.existingFtsTable),he(l,s,m),xe(e,s,m),Ce(l,s,m),f.push(...(m.aggregateIndexes??[]).map(E=>O(s,E.name)),...(m.rankIndexes??[]).map(E=>$(s,E.name)));return Y(e,f),o.cdc&&(B(e,{rowHistoryIndex:Object.values(t.tables).some(s=>s.dropStalePatchesMode===!0)}),G(e),v(e),H(e),K(e)),Object.values(t.tables).some(s=>s.commitOrderedMode===!0)&&P(e),ie(e),j(e),V(e),q(e),ne(e),d??[]};export{He as runShardMigrations};
@@ -0,0 +1 @@
1
+ import{LunoraError as o}from"@lunora/errors";import{WORKERD_SQLITE_LIMITS as t}from"./WORKERD_SQLITE_LIMITS-C9dUlw3o.mjs";const h=(r,e,...n)=>{if(e.length*3>t.sqlTextLength){const i=new TextEncoder().encode(e).length;if(i>t.sqlTextLength)throw new o("INTERNAL",`SQL statement is ${String(i)} bytes, over this runtime's ${String(t.sqlTextLength)}-byte limit`)}if(n.length>t.boundParams)throw new o("INTERNAL",`SQL statement binds ${String(n.length)} parameters, over this runtime's limit of ${String(t.boundParams)}`);return r.exec.call(r,e,...n)};export{h as default};
@@ -0,0 +1 @@
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-DAtZbzBn.mjs";import{D as l,r as u}from"./do-sql-DT8JBpG8.mjs";import{doWhereSqlStrategy as h}from"./AGG_COUNT-DzvM-UU5.mjs";import{sqliteInList as w}from"./param-Y0zw_1Cv.mjs";import{c as $}from"./where-sql-AVR5KloI.mjs";const C=e=>{if(e.length!==0)return w(o`${o.identifier("id")}`,e,!1)},a=(e,i)=>{const r=[];i&&r.push(i);const t=$(e,h);return t&&r.push(t),r.length===0?o``:o` WHERE ${o.join(r,o` AND `)}`},T=(e,i,r)=>{const t=a(r,void 0),n=d(e,o`SELECT id, _creationTime, ${o.identifier(l)} FROM ${o.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=u(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},q=(e,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=a(r,C(t)),m=d(e,o`SELECT id, _creationTime, ${o.identifier(l)} FROM ${o.identifier(i)}${f}`).toArray();for(const s of m){const c=u(s),{id:p}=s;c!==void 0&&typeof p=="string"&&n.set(p,c)}return n};export{q as selectShapeMembers,T as selectShapeRows};