@lunora/sql-store 1.0.0-alpha.22 → 1.0.0-alpha.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,174 +1,684 @@
1
- import { ServerDefaultContextLike, DatabaseWriterLike, SchedulerLike, SchemaLike, TableDefinitionLike, ValidatorLike } from '@lunora/do';
2
- import { SqlDialect, SqlRunResult } from "./dialect.js";
1
+ import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
2
+ import { SqlRunResult, SqlDialect } from "./dialect.js";
3
3
  export type { SqlExec } from "./dialect.js";
4
4
  import 'drizzle-orm';
5
5
  /**
6
- * Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
7
- * Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
8
- * adapter in tests, so the query logic runs against a real SQLite engine.
9
- */
6
+ * Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
7
+ * Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
8
+ * adapter in tests, so the query logic runs against a real SQLite engine.
9
+ */
10
10
  interface SqlCtxExec {
11
11
  all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
12
+ batch?: (statements: ReadonlyArray<{
13
+ params: ReadonlyArray<unknown>;
14
+ sql: string;
15
+ }>) => Promise<void>;
12
16
  run: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<SqlRunResult | void>;
13
17
  }
18
+ /**
19
+ * Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
20
+ * preserved, and every column run through the shared {@link sqliteDecode} so the
21
+ * stored form is reversed back into its JS shape. Exported so the data-browser
22
+ * (`introspect.ts`) and admin export/import paths share the exact same decode.
23
+ *
24
+ * The decode is engine-agnostic: every backend stores SQLite-shaped values
25
+ * (boolean → 1/0, JSON → text, bigint → an order-preserving text key), and `sqliteDecode` is
26
+ * robust to a driver returning either the stored string OR a natively-parsed
27
+ * value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
28
+ * correct on SQLite, Postgres and MySQL.
29
+ */
30
+ declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
31
+ /** One exported row: `doc` is reconstructed from the column tuple. */
32
+ interface ExportRow {
33
+ doc: Record<string, unknown>;
34
+ /**
35
+ * True physical source line, when the caller has it (e.g. a global row
36
+ * pulled out of an interspersed NDJSON import stream by
37
+ * `@lunora/runtime`'s `import-stream.ts`). When present this overrides the
38
+ * position-derived line below — the caller-side positions of a
39
+ * global-only subset don't line up with the original file once
40
+ * non-global rows have been filtered out. Absent for callers with no
41
+ * physical source to attribute (e.g. a fresh `exportSqlGlobalRows` roundtrip
42
+ * in tests), which keeps the positional fallback.
43
+ */
44
+ line?: number;
45
+ table: string;
46
+ }
47
+ interface ImportError {
48
+ code: string;
49
+ line: number;
50
+ message: string;
51
+ table: string;
52
+ }
53
+ interface ImportResult {
54
+ /** Skipped rows whose `_id` already exists (the default `onConflict: "skip"`). */
55
+ conflicts: number;
56
+ errors: ImportError[];
57
+ inserted: Record<string, number>;
58
+ /** Existing rows overwritten under `onConflict: "replace"`. */
59
+ replaced: number;
60
+ }
61
+ /**
62
+ * Return every `.global()` table in the schema, optionally narrowed by an
63
+ * allowlist. Shard-local tables are skipped here — they're handled by the DO
64
+ * helpers — so callers get a clean separation between the two storage planes.
65
+ */
66
+ declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
67
+ interface ExportGlobalArgs {
68
+ batchSize?: number;
69
+ tables?: ReadonlyArray<string>;
70
+ }
71
+ /**
72
+ * Yield rows from every requested `.global()` table in batches.
73
+ *
74
+ * Keyset-paginates on the physical primary key (`id` — every `.global()` table
75
+ * carries it): `WHERE id > ? ORDER BY id LIMIT n`, carrying the last id forward.
76
+ * A plain `LIMIT/OFFSET` scan would be wrong here — no engine guarantees an
77
+ * order for an unordered SELECT and each page is a separate query, so pages
78
+ * could overlap or skip rows (and any concurrent insert/delete would shift
79
+ * offsets and silently drop/duplicate rows in the snapshot). Keyset paging is
80
+ * deterministic under concurrent writes and avoids O(n^2) OFFSET scans.
81
+ *
82
+ * Tables are provisioned first (idempotent `CREATE … IF NOT EXISTS`): `.global()`
83
+ * tables are created lazily on first write, so a fresh deployment — or any table
84
+ * never written — would otherwise abort the stream with a raw `no such table`
85
+ * instead of exporting it as empty.
86
+ */
87
+ declare const exportSqlGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
88
+ interface ImportGlobalArgs {
89
+ /**
90
+ * Check the rows and report their shape errors, writing nothing. The conflict
91
+ * probe and the insert are skipped, so an `_id` already in use and a foreign-key
92
+ * or unique failure are only found by a real import.
93
+ */
94
+ dryRun?: boolean;
95
+ /**
96
+ * Optional direct exec handle to the same database the writer targets.
97
+ * When supplied, the conflict pre-probe issues a single
98
+ * `SELECT 1 FROM <table> WHERE id = ? LIMIT 1` against the row's declared
99
+ * table instead of falling back to an unscoped id probe, which scans every
100
+ * global table looking for the id. Strongly recommended for large schemas
101
+ * — the writer-fallback is O(N tables) per row.
102
+ */
103
+ exec?: SqlCtxExec;
104
+ /**
105
+ * What a row whose `_id` already exists in its table does: `"skip"` (the
106
+ * default) counts it as a conflict and leaves the stored row unchanged;
107
+ * `"replace"` overwrites the stored row with the snapshot's fields, keeping
108
+ * its `_id` and taking the snapshot's `_creationTime`. A dry run probes
109
+ * nothing, so the mode does not change its answer.
110
+ */
111
+ onConflict?: ImportConflictMode;
112
+ rows: ReadonlyArray<ExportRow>;
113
+ startLine?: number;
114
+ }
115
+ /**
116
+ * Import rows into `.global()` tables via the schema-aware writer. The
117
+ * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
118
+ * absent); we pre-probe each row's `_id` so a collision is reported as a
119
+ * conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
120
+ * `errors`; the rest land.
121
+ */
122
+ declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
14
123
  interface SqlCtxDbOptions {
15
124
  /**
16
- * Resolved request auth handed to `.serverDefault(fn)` column factories so
17
- * server-trusted columns (owner/tenant ids) stamp from the verified caller,
18
- * never the client. The generated worker passes the per-request identity;
19
- * absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
20
- */
125
+ * Resolved request auth handed to `.serverDefault(fn)` column factories so
126
+ * server-trusted columns (owner/tenant ids) stamp from the verified caller,
127
+ * never the client. The generated worker passes the per-request identity;
128
+ * absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
129
+ */
21
130
  auth?: ServerDefaultContextLike["auth"];
22
131
  /**
23
- * Opt into change-data-capture: when `true`, every committed write appends a
24
- * post-image to the `__cdc_log` table (created lazily alongside the other
25
- * companion tables). Backs CDC streaming export for `.global()` tables — the
26
- * log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
27
- * the platform's own Time Travel (`wrangler d1 time-travel restore`), an
28
- * atomic restore, not a changelog replay. Leave undefined for zero-cost
29
- * legacy behaviour.
30
- */
132
+ * Opt into change-data-capture: when `true`, every committed write appends a
133
+ * post-image to the `__cdc_log` table (created lazily alongside the other
134
+ * companion tables). Backs CDC streaming export for `.global()` tables — the
135
+ * log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
136
+ * the platform's own Time Travel (`wrangler d1 time-travel restore`), an
137
+ * atomic restore, not a changelog replay. Leave undefined for zero-cost
138
+ * legacy behaviour.
139
+ */
31
140
  cdc?: boolean;
141
+ /**
142
+ * How long `.global()` changelog entries are kept, in milliseconds. Absent
143
+ * (the default) means forever — the log grows for the life of the database.
144
+ *
145
+ * Opt-in for the same reason the shard-local windows are, and the reason is
146
+ * not caution: this log's streaming-export consumers hold opaque cursors
147
+ * issued outside this deployment, and nothing here can see where they sit.
148
+ * A default window would be a guess whose failure mode is silent data loss
149
+ * in someone's warehouse. A deployment that wants the log bounded states a
150
+ * window it knows covers its consumers; `.global()` shape pollers are then
151
+ * protected exactly, by the floor this read path reports rather than by the
152
+ * window. See `sweepSqlCdcRetention`.
153
+ *
154
+ * Time rather than rows because the log is SHARED: every shard in every
155
+ * region writes it, so a row count is not a bound any single consumer can
156
+ * reason about, while "older than N" is exactly what they compare their own
157
+ * lag against.
158
+ *
159
+ * Setting it costs one index write per `.global()` write: the first sweep
160
+ * builds `__cdc_log_ts` so a pass with nothing expired is one index seek
161
+ * rather than a walk of the log (on D1, a billed row written per append
162
+ * against reads of the whole log per pass).
163
+ */
164
+ cdcRetentionMs?: number;
32
165
  clock?: () => number;
33
166
  /**
34
- * Cross-shard counter for **reverse cross-backend relations** — the `_count`
35
- * mirror of the `crossShardReader` option below.
36
- */
167
+ * Cross-shard counter for **reverse cross-backend relations** — the `_count`
168
+ * mirror of the `crossShardReader` option below.
169
+ */
37
170
  crossShardCounter?: DatabaseWriterLike["count"];
38
171
  /**
39
- * Optional cross-shard reader for **reverse cross-backend relations**: a
40
- * `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
41
- * Such a child's rows are partitioned across every shard DO, so the local D1
42
- * writer can't resolve it. When provided, the relation loader routes the
43
- * child's read through this (the host wires it to the Query Coordinator's
44
- * RLS-correct `fanOut`, with identity forwarded so each shard applies its own
45
- * RLS). Absent it, loading such a relation throws a clear "not supported"
46
- * error (legacy behaviour). The forward direction (shard-local parent →
47
- * global child) and same-backend relations never touch this.
48
- */
49
- crossShardReader?: DatabaseWriterLike["findMany"];
172
+ * Optional cross-shard reader for **reverse cross-backend relations**: a
173
+ * `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
174
+ * Such a child's rows are partitioned across every shard DO, so the local D1
175
+ * writer can't resolve it. When provided, the relation loader routes the
176
+ * child's read through this (the host wires it to the Query Coordinator's
177
+ * RLS-correct `fanOut`, with identity forwarded so each shard applies its own
178
+ * RLS). Absent it, loading such a relation throws a clear "not supported"
179
+ * error (legacy behaviour). The forward direction (shard-local parent →
180
+ * global child) and same-backend relations never touch this.
181
+ *
182
+ * Takes {@link CrossShardReadArgs}, not `QueryArgs`: the hop is JSON, so the
183
+ * RLS filters are handed over as data (see that type's docblock).
184
+ */
185
+ crossShardReader?: (table: string, args: CrossShardReadArgs) => Promise<QueryPage>;
50
186
  /**
51
- * The SQL dialect that shapes every statement (identifier quoting, value
52
- * encode/decode, column types, upserts, RETURNING vs affected-rows).
53
- * `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
54
- * passes its Postgres/MySQL dialect. Required — the core is engine-blind.
55
- */
187
+ * The SQL dialect that shapes every statement (identifier quoting, value
188
+ * encode/decode, column types, upserts, RETURNING vs affected-rows).
189
+ * `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
190
+ * passes its Postgres/MySQL dialect. Required — the core is engine-blind.
191
+ */
56
192
  dialect: SqlDialect;
57
193
  exec: SqlCtxExec;
58
194
  idGenerator?: () => string;
59
195
  /**
60
- * Ceiling on the number of child join keys a relation-crossing `where`
61
- * predicate may materialize before the semijoin pre-resolver fails closed
62
- * (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
63
- * push-down, so an overflow here can only fail closed — never truncate the
64
- * `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
65
- * key cap when omitted.
66
- */
196
+ * Ceiling on the number of child join keys a relation-crossing `where`
197
+ * predicate may materialize before the semijoin pre-resolver fails closed
198
+ * (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
199
+ * push-down, so an overflow here can only fail closed — never truncate the
200
+ * `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
201
+ * key cap when omitted.
202
+ */
67
203
  maxRelationKeys?: number;
68
204
  /**
69
- * Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
70
- * Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
71
- * triggers on `.global()` tables need to enqueue follow-up work.
72
- */
205
+ * Object identifying the database this store provisions, so the one-shot
206
+ * `CREATE TABLE/INDEX IF NOT EXISTS` sweep is shared by every ctx-db built
207
+ * against it instead of repeating per instance.
208
+ *
209
+ * Hosts build a ctx-db **per request** (the writer captures the caller's
210
+ * identity and D1 bookmark), so without this the sweep — one round trip per
211
+ * global table plus one per index — runs again on the first `.global()`
212
+ * access of every request. On a 50-table schema that is ~1s in `lunora dev`
213
+ * and a real latency floor in production.
214
+ *
215
+ * WHAT TO PASS: something that outlives the request AND names one database
216
+ * (and one configuration). The D1 binding off `env` and the declaration
217
+ * object a host builds once both qualify; the result of a per-request
218
+ * factory does not — it keys the memo on a fresh object every time and
219
+ * shares nothing (which is silent, and looks exactly like not passing it).
220
+ *
221
+ * INVARIANT, unenforced: one scope ⇒ one `schema`, `dialect` and `cdc`. The
222
+ * memoised run closes over the FIRST writer's, so a later writer sharing a
223
+ * scope with `cdc: true` behind one with `cdc: false` never gets
224
+ * `__cdc_log`. Hosts pass app-level constants for all three, which is why
225
+ * this is a note rather than a composite key.
226
+ *
227
+ * Two behaviours change with a shared memo, both benign and both worth
228
+ * knowing: the DDL runs in the FIRST writer's D1 session, so a later
229
+ * session's first read is no longer implicitly pinned behind a write of its
230
+ * own (on a replicated binding that can mean one transient stale read on a
231
+ * freshly-provisioned database); and a database reset out from under a live
232
+ * isolate is no longer healed by the next request, since the entry lives as
233
+ * long as the scope does.
234
+ *
235
+ * The aggregate-counter and rank-companion rebuilds share the scope too, so
236
+ * a counter skewed by a lost companion write heals on the next isolate
237
+ * rather than the next request. The per-write deltas keep it exact between
238
+ * rebuilds, and a rebuild racing another isolate's write is itself what
239
+ * skews it, so rebuilding less often is the safer direction.
240
+ *
241
+ * Omit it and the memo stays per ctx-db — slower, never wrong, and what the
242
+ * tests want (they pair a fresh database with a reused schema object).
243
+ */
244
+ provisionScope?: object;
245
+ /**
246
+ * Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
247
+ * Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
248
+ * triggers on `.global()` tables need to enqueue follow-up work.
249
+ */
73
250
  scheduler?: SchedulerLike;
74
251
  schema: SchemaLike;
75
252
  }
253
+ /** Create the `__cdc_log` table. Idempotent; only run when CDC is enabled. */
254
+ declare const runSqlCdcMigration: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
76
255
  /**
77
- * Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
78
- * preserved, and every column run through the shared {@link sqliteDecode} so the
79
- * stored form is reversed back into its JS shape. Exported so the data-browser
80
- * (`introspect.ts`) and admin export/import paths share the exact same decode.
81
- *
82
- * The decode is engine-agnostic: every backend stores SQLite-shaped values
83
- * (boolean → 1/0, JSON → text, bigint → decimal string), and `sqliteDecode` is
84
- * robust to a driver returning either the stored string OR a natively-parsed
85
- * value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
86
- * correct on SQLite, Postgres and MySQL.
87
- */
88
- declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
256
+ * Delete `.global()` changelog entries older than `retentionMs`, at most
257
+ * {@link GLOBAL_CDC_SWEEP_MAX_ROWS} per pass, and only if this writer wins the lease.
258
+ *
259
+ * **Time, not rows.** The shard-local twin bounds its log by row count because
260
+ * one shard owns it and a row count is a memory bound on that one object. This
261
+ * log is shared, so a row count means nothing to any individual consumer — but
262
+ * "older than N" is directly what every consumer needs to reason about, and it
263
+ * is the unit an operator can compare against their own connector's lag.
264
+ *
265
+ * **Which consumers this can strand, and what protects each:**
266
+ *
267
+ * - `.global()` shape pollers hold in-memory cursors this store cannot see. They
268
+ * are protected EXACTLY rather than approximately: {@link readSqlCdcChangedTables}
269
+ * reports the retained floor, and a poller below it treats the tick as "no
270
+ * visibility" and re-reads every shape. That is the same self-healing path a
271
+ * changelog error already takes, so a trimmed poller is slow for one tick, not
272
+ * wrong. No cursor registry, no assumption about how far behind a shard can be.
273
+ * - Streaming-export / warehouse consumers hold opaque cursors issued outside
274
+ * this deployment. Nothing here can see them, so nothing here guesses:
275
+ * {@link readSqlCdcChanges} refuses a page below the floor rather than serving
276
+ * the surviving tail, and retention stays OFF unless an operator states a
277
+ * window they know covers their connector.
278
+ */
279
+ declare const sweepSqlCdcRetention: (exec: SqlCtxExec, dialect: SqlDialect, retentionMs: number, now: number) => Promise<void>;
280
+ /** Oldest `seq` still retained in the `.global()` changelog, or `undefined` when it is empty. */
281
+ declare const readSqlCdcFloor: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<number | undefined>;
282
+ /**
283
+ * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
284
+ * (clamped to [1, 10000]); plus the cursor to resume from.
285
+ *
286
+ * On Postgres and MySQL the page also stops at the first late-commit hole: an
287
+ * allocated `seq` not yet visible, followed by a row younger than
288
+ * {@link CDC_LATE_COMMIT_WINDOW_MS} (see "Late commits" on
289
+ * {@link readSqlCdcChangedTables}). The cursor is a consumer's only record of
290
+ * what it has seen, so handing out rows past an in-flight append would skip that
291
+ * append for good. Stopping the page instead of just the cursor keeps the
292
+ * cursor the `seq` of the last change returned. A permanent hole (a failed
293
+ * append) holds the page back for one window only.
294
+ */
295
+ declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
296
+ limit?: number;
297
+ now?: number;
298
+ sinceSeq?: number;
299
+ }, dialect: SqlDialect) => Promise<{
300
+ changes: CdcChange[];
301
+ cursor: number;
302
+ }>;
303
+ /**
304
+ * Which tables the changelog recorded a write to after `sinceSeq`, plus the
305
+ * cursor to resume from. Metadata only — it reads no `doc`, so its cost is
306
+ * index seeks (on SQLite, see {@link sqliteChangedTablesSql}) rather than the
307
+ * size of the documents in it.
308
+ *
309
+ * The `.global()` shape poll asks this once per tick for the whole shard, and a
310
+ * shape whose table is absent from the answer skips its membership read
311
+ * entirely.
312
+ *
313
+ * **One statement, and the cursor comes out of the same rows as the tables.**
314
+ * Reading the head separately — in either order — opens a window where a write
315
+ * commits between the two round trips and ends up absent from `tables` while
316
+ * sitting at or below the adopted `cursor`, which loses it for good. Deriving
317
+ * the cursor as the max `seq` actually returned closes that window by
318
+ * construction: the caller can never advance past a row this scan did not see.
319
+ *
320
+ * **Late commits.** Postgres and MySQL allocate `seq` at INSERT, not at commit,
321
+ * so an append holding `N` can commit after one holding `N + 1`. A poll that
322
+ * adopts `N + 1` while `N` is still in flight skips `N` until the next resync
323
+ * pass. So on those engines the cursor stops below the first HOLE in `seq`
324
+ * rather than at the highest row seen: a hole is an allocated `seq` that is not
325
+ * (yet) visible, which is exactly what an in-flight append looks like. Tables
326
+ * above the hole are still reported, so nothing is delayed — rows past the
327
+ * cursor are just reported again next tick.
328
+ *
329
+ * A hole can also be permanent (a failed append burns its `seq`), and a cursor
330
+ * pinned under one forever would re-report everything above it on every tick.
331
+ * So a hole only holds the cursor while the first row after it is younger than
332
+ * {@link CDC_LATE_COMMIT_WINDOW_MS}: that row's append started before its own
333
+ * `seq` was allocated, which is after the hole's, so once it is that old the
334
+ * hole's owner has either committed (and is visible) or never will. An append
335
+ * slower than the window falls back to the resync interval, as before. A MySQL
336
+ * `auto_increment_increment` above 1 makes every step a hole, which holds the
337
+ * cursor one window behind the head: correct, just less narrowing.
338
+ *
339
+ * D1 skips all of this: single writer, `AUTOINCREMENT`, and `withSession` gives
340
+ * both reads one snapshot, so there is no hole to wait for — and D1 bills rows
341
+ * read.
342
+ */
343
+ declare const readSqlCdcChangedTables: (exec: SqlCtxExec, sinceSeq: number, dialect: SqlDialect, options?: {
344
+ cursorOnly?: boolean;
345
+ now?: number;
346
+ retained?: boolean;
347
+ }) => Promise<{
348
+ cursor: number;
349
+ floor?: number;
350
+ tables: string[];
351
+ }>;
352
+ declare const createSqlCtxDb: (options: SqlCtxDbOptions) => DatabaseWriterLike;
353
+ /**
354
+ * Auto-provision every `.global()` table from the schema, in as few round trips as the engine allows.
355
+ *
356
+ * `CREATE TABLE IF NOT EXISTS` with the physical `id`/`_creationTime`/row-version columns plus a typed column per declared
357
+ * field, then its secondary, default-order and `.unique()` indexes. The D1 twin of `@lunora/do`'s `runShardMigrations`: it
358
+ * makes the schema the single source of truth for global tables, so a fresh database serves them without a hand-applied
359
+ * migration. Idempotent (`IF NOT EXISTS`, `OR IGNORE`), additive only: it never drops or retypes a column.
360
+ *
361
+ * With an exec that exposes `batch` on SQLite this reads the catalog once and writes the missing DDL in a handful of
362
+ * atomic batches; otherwise, and for any table that needs more than additive DDL, it runs the original sequence.
363
+ */
89
364
  declare const runSqlGlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
90
365
  /**
91
- * Materialize the `__agg_&lt;index>` companion tables for every declared
92
- * `aggregateIndex` on a global table. Global tables in Lunora ship their own
93
- * DDL — counter tables are opt-in so production hosts can decide where they
94
- * live. Tests and dev hosts can call this once after their schema migration to
95
- * unlock O(1) counts.
96
- *
97
- * Idempotent (`CREATE TABLE IF NOT EXISTS`).
98
- */
366
+ * Materialize the `__agg_<index>` companion tables for every declared
367
+ * `aggregateIndex` on a global table. Global tables in Lunora ship their own
368
+ * DDL — counter tables are opt-in so production hosts can decide where they
369
+ * live. Tests and dev hosts can call this once after their schema migration to
370
+ * unlock O(1) counts.
371
+ *
372
+ * Idempotent (`CREATE TABLE IF NOT EXISTS`).
373
+ */
99
374
  declare const runSqlAggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
100
375
  /**
101
- * Materialize the `__rank_&lt;index>` companion tables for every declared
102
- * `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
103
- * opt-in pattern so production hosts decide whether to spend the DDL.
104
- *
105
- * Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
106
- */
376
+ * Materialize the `__rank_<index>` companion tables for every declared
377
+ * `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
378
+ * opt-in pattern so production hosts decide whether to spend the DDL.
379
+ *
380
+ * Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
381
+ */
107
382
  declare const runSqlRankMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
383
+ /** What {@link backfillSqlSearchIndexes} could not finish. */
384
+ interface SqlSearchBackfillResult {
385
+ /**
386
+ * Inverted companions that still lack their unique `(token, id)` key. Writes
387
+ * keep working without it, but two backfills racing over one row can index
388
+ * it twice; the warning logged for each says why the key was refused.
389
+ */
390
+ uniqueKeyMissing: string[];
391
+ /** A previous build's rows left unmigrated because every attempt at them lost to a concurrent write. */
392
+ unmappedSkipped: number;
393
+ }
108
394
  /**
109
- * Materialize the `__fts_&lt;index>` FTS5 shadow tables for every declared
110
- * `.searchIndex()` on a global table. Mirrors `runSqlAggregateMigrations` — same
111
- * opt-in pattern so production hosts decide whether to spend the DDL. Only runs
112
- * on engines that ship FTS5 (D1 does; the `node:sqlite` test runner doesn't,
113
- * where `.search()` transparently falls back to a scan). `__text__` holds the
114
- * indexed field; `__id__` (UNINDEXED) joins back to the row.
115
- *
116
- * Idempotent (`CREATE VIRTUAL TABLE IF NOT EXISTS`).
117
- */
395
+ * Provision the search companions, then index one bounded page of the rows that
396
+ * predate each index — unless it is declared `staged: true`, which leaves the
397
+ * whole backfill to {@link backfillSqlSearchIndexes}.
398
+ *
399
+ * Idempotent (`CREATE … IF NOT EXISTS` throughout, and the backfill resumes
400
+ * from recorded progress).
401
+ */
118
402
  declare const runSqlSearchMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
119
- /** One change-data-capture entry: a committed mutation, in monotonic `seq` order. Mirrors the DO twin. */
120
- interface CdcChange {
121
- /** Post-image document for insert/update; absent for delete (the `id` identifies the removed row). */
122
- doc?: Record<string, unknown>;
123
- id: string;
124
- op: "delete" | "insert" | "update";
125
- /** Monotonic per-database cursor — strictly increasing, never reused. */
126
- seq: number;
403
+ /**
404
+ * Run every declared search index — including the `staged: true` ones the
405
+ * migration pass skips — through to completion. The entry point a host calls
406
+ * out-of-band after deploying a search index over a table too large to index a
407
+ * page at a time.
408
+ *
409
+ * Idempotent and resumable: an index recorded as complete is skipped, and an
410
+ * interrupted run picks up from its cursor.
411
+ */
412
+ declare const backfillSqlSearchIndexes: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<SqlSearchBackfillResult>;
413
+ /** Reserved table holding one backfill-progress row per search companion. */
414
+ declare const SEARCH_STATE_TABLE = "__lunora_search_state";
415
+ /** Create the progress table. Idempotent; runs alongside the companion DDL. */
416
+ declare const migrateSearchState: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
417
+ /** A table plus its current row count. */
418
+ interface GlobalTableInfo {
419
+ name: string;
420
+ rowCount: number;
421
+ }
422
+ /** A window of rows from one table, plus the column list and total size. */
423
+ interface GlobalTablePage {
424
+ columns: string[];
425
+ /**
426
+ * Foreign-key columns (local column → referenced table) for tables that carry
427
+ * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
428
+ * Schema `.global()` tables omit this (their refs come from `describeTables`);
429
+ * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
430
+ * schema diagram can draw their global→global FK edges.
431
+ */
432
+ refs?: Record<string, string>;
433
+ rows: Record<string, unknown>[];
434
+ total: number;
435
+ }
436
+ /**
437
+ * One equality constraint a facet-value click adds to the global browser's view:
438
+ * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
439
+ * displayed column name, validated against the table's columns and mapped to its
440
+ * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
441
+ * value** the facet returned (a SQLite scalar — including a BLOB, which reaches
442
+ * here as bytes because the facet payload is wire-encoded), normalised by
443
+ * {@link sqliteEncode} and bound as a parameter, never interpolated.
444
+ * AND-combined with the other clauses.
445
+ *
446
+ * Only `eq` is compiled on this path. `operator` and `path` exist so that a
447
+ * request asking for anything else is refused by {@link buildEqPredicate} rather
448
+ * than read as an equality: a `has` or `contains` clause matched as `= ?` would
449
+ * return rows the caller did not ask for.
450
+ */
451
+ interface GlobalFilterClause {
452
+ column: string;
453
+ /** Must be absent or `"eq"`; any other operator is refused. */
454
+ operator?: string;
455
+ /** Must be absent or empty; a nested path is refused (D1 columns are physical). */
456
+ path?: string[];
457
+ value: unknown;
458
+ }
459
+ interface ReadGlobalTablePageOptions {
460
+ filters?: GlobalFilterClause[];
461
+ limit?: number;
462
+ offset?: number;
127
463
  table: string;
128
- /** Wall-clock millis when the change committed (the ctx-db `clock`). */
129
- ts: number;
130
464
  }
131
- /** Create the `__cdc_log` table. Idempotent; only run when CDC is enabled. */
132
- declare const runSqlCdcMigration: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
133
465
  /**
134
- * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
135
- * (clamped to [1, 10000]); plus the cursor to resume from.
136
- */
137
- declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
466
+ * Options for {@link facetSqlGlobalColumn} — the read-only "what values does this
467
+ * column hold?" summary for the global (D1) browser. `column` is the displayed
468
+ * column to group by (validated and mapped to its physical column, never
469
+ * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
470
+ * constraints so the facet reflects the **active view** (the same rows the
471
+ * browser is previewing); `limit` caps the distinct values returned (clamped).
472
+ */
473
+ interface FacetGlobalColumnOptions {
474
+ column: string;
475
+ filters?: GlobalFilterClause[];
138
476
  limit?: number;
139
- sinceSeq?: number;
140
- }, dialect: SqlDialect) => Promise<{
141
- changes: CdcChange[];
142
- cursor: number;
143
- }>;
144
- /** Drop changelog entries at or below a checkpointed `throughSeq` (retention). */
145
- declare const trimSqlCdcChanges: (exec: SqlCtxExec, throughSeq: number, dialect: SqlDialect) => Promise<void>;
146
- declare const createSqlCtxDb: (options: SqlCtxDbOptions) => DatabaseWriterLike;
477
+ table: string;
478
+ }
479
+ /** One distinct value of a faceted global column with its row count over the active view. */
480
+ interface GlobalFacetValue {
481
+ count: number;
482
+ value: unknown;
483
+ }
484
+ /**
485
+ * Payload of a {@link facetSqlGlobalColumn} call: the top-N distinct `values` (each
486
+ * with a `count`) ordered by frequency, plus `truncated` — `true` when more
487
+ * distinct values existed beyond the cap, so the UI can say so rather than imply
488
+ * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
489
+ */
490
+ interface GlobalFacetResult {
491
+ truncated: boolean;
492
+ values: GlobalFacetValue[];
493
+ }
494
+ /**
495
+ * List every browsable D1 table with its row count, ordered by name. Surfaces
496
+ * both the schema's `.global()` tables (provisioned first) and external tables
497
+ * (auth, etc.); internal/companion tables are excluded.
498
+ */
499
+ declare const listSqlGlobalTables: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<GlobalTableInfo[]>;
500
+ /**
501
+ * Read a page of rows from one D1 table. The table is validated against the live
502
+ * browsable-table list before its name is interpolated, so this can't be coerced
503
+ * into reading an internal table or injecting SQL. `limit` is clamped to
504
+ * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
505
+ * matching each `column = value` eq constraint (a facet-value drill-down), bound
506
+ * through {@link buildEqPredicate} so they never inject SQL.
507
+ */
508
+ declare const readSqlGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
509
+ /**
510
+ * Summarise the distinct values of one displayed column over the **active view**
511
+ * (the same eq `filters` the global browser is previewing) — the D1 twin of the
512
+ * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
513
+ * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
514
+ * against the table's displayed columns (typed 404 if unknown), mapped to its
515
+ * physical column, and quoted — never interpolated from caller input. The extra
516
+ * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
517
+ * an external (non-schema) table is never grouped — it collapses to a single
518
+ * redacted `•••` bucket — mirroring the page browser's value redaction so the
519
+ * facet can't leak credentials. The returned `value` is the raw stored scalar, so
520
+ * a click feeds it straight back as an eq filter.
521
+ *
522
+ * The payload is wire-encoded on the way out, like the page read's rows: a BLOB
523
+ * column's stored value is bytes, and `Response.json` flattens those to `{}` —
524
+ * which is not a display glitch but a broken drill-down, since the flattened
525
+ * value is what the click sends back as the filter. `needsWireEncoding` leaves a
526
+ * facet over an ordinary text/numeric column untouched.
527
+ */
528
+ declare const facetSqlGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
147
529
  /** Map a JS value onto its SQLite storage form — SQLite has no boolean, so true/false → 1/0. */
148
- declare const sqliteEncode: (value: unknown) => unknown;
530
+ declare const sqliteEncode: (value: unknown, kind?: string) => unknown;
149
531
  /** Parse `raw` as JSON, returning `raw` unchanged when it is not valid JSON. */
150
532
  declare const tryJsonParse: (raw: string) => unknown;
151
- /** Decode a `bigint` column: a decimal string back into a `BigInt`, else verbatim. */
533
+ /**
534
+ * Decode a `bigint` column: the order-preserving key {@link bigintSqlKey} writes,
535
+ * or — for a row stored by a build that wrote plain decimal text — the decimal
536
+ * string, else verbatim.
537
+ */
152
538
  declare const decodeBigint: (raw: unknown) => unknown;
153
539
  /**
154
- * Resolve the *effective* storage kind of a column validator. Encoding keys off
155
- * the runtime value's JS type, so a `v.optional(inner)` column stores its
156
- * present value exactly as `inner` would. The validator's own `kind` is
157
- * `"optional"`, which hides that — unwrap to the inner validator's kind so the
158
- * decode reverses the real storage form. The inner validator is stashed on
159
- * `_meta.inner` by `@lunora/values`' `createValidator`.
160
- */
540
+ * Resolve the *effective* storage kind of a column validator: `v.optional(inner)`
541
+ * unwrapped to `inner`'s kind, since encoding keys off the runtime value's JS
542
+ * type and the validator's own `kind` of `"optional"` hides that.
543
+ *
544
+ * A thin alias over `shared/effective-kind`, which is where the rule lives so
545
+ * the DO row store applies the identical one — it reads the same validators and
546
+ * has the same failure mode, and two copies drifted the last time.
547
+ */
161
548
  declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefined;
162
549
  /**
163
- * Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
164
- * form, driven by the field's effective validator `kind`:
165
- *
166
- * - `boolean`: 1/0 → true/false (SQLite has no boolean type).
167
- * - `bigint`: decimal string → `BigInt`.
168
- * - `object`/`array`/`record`: JSON string → parsed value.
169
- * - `union`/`any`: parsed back only when the stored string is a JSON non-scalar
170
- * (a scalar union member round-trips through SQLite's native column type).
171
- * - everything else (string/number/date/timestamp/id/literal): verbatim.
172
- */
550
+ * Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
551
+ * form, driven by the field's effective validator `kind`:
552
+ *
553
+ * - `boolean`: 1/0 → true/false (SQLite has no boolean type).
554
+ * - `bigint`: decimal string → `BigInt`.
555
+ * - `bytes`: normalizes any driver return shape to a genuine `ArrayBuffer` — a
556
+ * view (`Uint8Array`/`Buffer`/…) is sliced to its own byte window, a plain
557
+ * `ArrayBuffer` passes through, and an array of byte values is packed into a
558
+ * fresh buffer. Required because `v.bytes()` validates
559
+ * `value instanceof ArrayBuffer` and different backends return different BLOB
560
+ * shapes: the D1 binding `Array<number>`, workerd's raw SQLite `ArrayBuffer`,
561
+ * node:sqlite `Uint8Array`, pg/mysql2 `Buffer`. The D1 one is the shape only a
562
+ * real binding produces, so the array case has its test in the workerd suite.
563
+ * - `object`/`array`/`record`/`geoPoint`: JSON string → parsed value. `geoPoint`
564
+ * belongs here because {@link sqliteEncode} keys off the runtime JS type and
565
+ * stores the `{ lat, lng }` object as JSON in a TEXT column; without the case
566
+ * it fell through to `default:` and every client read back the raw JSON text.
567
+ * - `union`/`any`/`from`: parsed back when the stored string is a JSON
568
+ * non-scalar, or when it carries the {@link WIRE_PREFIX} marker.
569
+ * A `number` or `boolean` does NOT round-trip through the column's native
570
+ * type — all three kinds store as TEXT on every engine, which coerces a bound
571
+ * `42` to the text `42.0` — so {@link sqliteEncode} writes those two in the
572
+ * marked form and this branch reverses them by the marker alone. A number's
573
+ * marked payload is `float64SqlKey`, so its text order is numeric order; the
574
+ * marked JSON an earlier build wrote is still read back here, which is what
575
+ * makes a table correct between the format change and the rewrite pass.
576
+ * `from` belongs to THIS group, not to `object`/`array`/`record`: an external
577
+ * Standard Schema can describe a string just as easily as an object, and
578
+ * {@link sqliteEncode} keys off the runtime JS type — so a `v.from(z.string())`
579
+ * column holding `"123"` is stored verbatim, and unconditional parsing would
580
+ * read it back as the NUMBER 123.
581
+ * A `bigint` member decodes too, by SHAPE: {@link sqliteEncode} keys off the
582
+ * runtime type, so a bigint here is stored as the same order-preserving key a
583
+ * declared `v.bigint()` column gets, and returning that verbatim handed the
584
+ * caller 40 characters of padding instead of the value it wrote. See the
585
+ * ambiguity this buys, and why the wire marker cannot carry it instead, below.
586
+ * CAVEAT: a union/any/from member is stored verbatim by {@link sqliteEncode}, so
587
+ * a legitimate *string* value that itself looks like JSON (`'{"a":1}'`, `'[1,2]'`)
588
+ * is ambiguous on read and decodes back to the parsed object/array, not the
589
+ * original string. The bigint test admits the same class of ambiguity, narrower
590
+ * but real: `decodeBigintSqlKey` accepts EXACTLY 40 characters — `"0"` or `"1"`,
591
+ * then 39 digits — and a stored *string* of that shape (a zero-padded account
592
+ * number, a numeric external id) is byte-identical on disk to a key and reads
593
+ * back as a `bigint`. Pinned by a test in `ctx-db.test.ts` so the trade is
594
+ * visible rather than rediscovered.
595
+ *
596
+ * Preferred anyway, because the alternative is not "no ambiguity" but
597
+ * guaranteed corruption: WITHOUT the test, every bigint any code writes to an
598
+ * untyped column comes back as padding, on every read. The narrow false
599
+ * positive costs a specific 40-character digit string its type; the absent test
600
+ * cost every such column its value.
601
+ *
602
+ * The unambiguous {@link WIRE_PREFIX} marker cannot carry this instead. It is
603
+ * not reached: {@link sqliteEncode} returns at its `bigint` branch first, and it
604
+ * takes no `kind`, so it cannot encode an untyped column differently from a
605
+ * declared one. It is also `serializeColumnValue`, which builds every WHERE
606
+ * binding — a prefixed bigint would never match a row stored as a key, and the
607
+ * padded key is order-preserving on purpose (indexes, range predicates, MIN/MAX
608
+ * all read it). Two storage forms for one runtime type breaks comparison
609
+ * between them. Disambiguating properly means tagging every encoded non-scalar,
610
+ * a breaking storage-format change, so it is documented rather than fixed.
611
+ * - everything else (string/number/date/timestamp/id/literal): verbatim.
612
+ */
173
613
  declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
174
- export { type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, trimSqlCdcChanges, tryJsonParse };
614
+ export {
615
+ /**
616
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
617
+ * shared by Lunora's `.global()` table backends.
618
+ *
619
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
620
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
621
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
622
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
623
+ * whose `broadcast` hook drives live queries regardless of engine.
624
+ *
625
+ * This package is internal: consumers depend on `@lunora/d1` or
626
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
627
+ */
628
+ type ExportGlobalArgs,
629
+ /**
630
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
631
+ * shared by Lunora's `.global()` table backends.
632
+ *
633
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
634
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
635
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
636
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
637
+ * whose `broadcast` hook drives live queries regardless of engine.
638
+ *
639
+ * This package is internal: consumers depend on `@lunora/d1` or
640
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
641
+ */
642
+ type ExportRow, type FacetGlobalColumnOptions, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type GlobalTableInfo, type GlobalTablePage,
643
+ /**
644
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
645
+ * shared by Lunora's `.global()` table backends.
646
+ *
647
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
648
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
649
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
650
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
651
+ * whose `broadcast` hook drives live queries regardless of engine.
652
+ *
653
+ * This package is internal: consumers depend on `@lunora/d1` or
654
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
655
+ */
656
+ type ImportError,
657
+ /**
658
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
659
+ * shared by Lunora's `.global()` table backends.
660
+ *
661
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
662
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
663
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
664
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
665
+ * whose `broadcast` hook drives live queries regardless of engine.
666
+ *
667
+ * This package is internal: consumers depend on `@lunora/d1` or
668
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
669
+ */
670
+ type ImportGlobalArgs,
671
+ /**
672
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
673
+ * shared by Lunora's `.global()` table backends.
674
+ *
675
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
676
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
677
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
678
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
679
+ * whose `broadcast` hook drives live queries regardless of engine.
680
+ *
681
+ * This package is internal: consumers depend on `@lunora/d1` or
682
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
683
+ */
684
+ type ImportResult, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };