@lunora/d1 1.0.0-alpha.24 → 1.0.0-alpha.240

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 (29) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +3 -3
  3. package/dist/dialect.d.mts +69 -30
  4. package/dist/dialect.d.ts +69 -30
  5. package/dist/dialect.mjs +1 -36
  6. package/dist/index.d.mts +402 -257
  7. package/dist/index.d.ts +402 -257
  8. package/dist/index.mjs +1 -7
  9. package/dist/packem_shared/ALLOW_DESTRUCTIVE_MARKER-CwYNPwK3.mjs +1 -0
  10. package/dist/packem_shared/D1Client-CzS0Qfa6.mjs +1 -0
  11. package/dist/packem_shared/D1TimeoutError-D4YUqZPk.mjs +1 -0
  12. package/dist/packem_shared/GlobalImportStagingError-d4vGUGYx.mjs +1 -0
  13. package/dist/packem_shared/MigrationRunner-CD5zcqp6.mjs +8 -0
  14. package/dist/packem_shared/OCC_VERSION_COLUMN-ByC64Jgx.mjs +1 -0
  15. package/dist/packem_shared/applySqlMigrationFiles-CUiRKrxP.mjs +8 -0
  16. package/dist/packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs +1 -0
  17. package/dist/packem_shared/d1QueryTag-BcEGW4q1.mjs +1 -0
  18. package/dist/packem_shared/exportGlobalRows-IncHgv-p.mjs +1 -0
  19. package/dist/packem_shared/facetGlobalColumn-BqK1_P3S.mjs +1 -0
  20. package/dist/packem_shared/quoteIdentifier-CObIFRhb.mjs +1 -0
  21. package/dist/packem_shared/sqliteDialect-B_3JNtdq.mjs +1 -0
  22. package/package.json +8 -6
  23. package/dist/packem_shared/D1Client-DA3flo1o.mjs +0 -143
  24. package/dist/packem_shared/MigrationRunner-BQx8HAGh.mjs +0 -154
  25. package/dist/packem_shared/createD1CtxDb-BMR8J0dT.mjs +0 -14
  26. package/dist/packem_shared/exportGlobalRows-BgfNSwCG.mjs +0 -122
  27. package/dist/packem_shared/facetGlobalColumn-C6u_WMIY.mjs +0 -142
  28. package/dist/packem_shared/quoteIdentifier-B-ZeSe1V.mjs +0 -3
  29. package/dist/packem_shared/sqliteDialect-DqYnHPuu.mjs +0 -27
package/dist/index.d.ts CHANGED
@@ -1,296 +1,232 @@
1
- import { SchemaLike, DatabaseWriterLike } from '@lunora/do';
2
- import { SqlCtxDbOptions, createSqlCtxDb, SqlCtxExec, readSqlCdcChanges, SqlDialect } from '@lunora/sql-store';
3
- export { type SqlCtxExec as D1Exec, type SqlCtxDbOptions, type SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
1
+ import { SchemaLike, DatabaseWriterLike } from '@lunora/shard-engine';
2
+ export { applyCdcChanges } from '@lunora/shard-engine';
3
+ import { SqlCtxExec, ExportGlobalArgs, ExportRow, ImportGlobalArgs, ImportResult, SqlCtxDbOptions, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, ImportError, FacetGlobalColumnOptions, GlobalFacetResult, GlobalTableInfo, ReadGlobalTablePageOptions, GlobalTablePage, SqlDialect } from '@lunora/sql-store';
4
+ export { type SqlCtxExec as D1Exec, type ExportGlobalArgs, type FacetGlobalColumnOptions, type ExportRow as GlobalExportRow, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type ImportError as GlobalImportError, type ImportResult as GlobalImportResult, type GlobalTableInfo, type GlobalTablePage, type ImportGlobalArgs, type ReadGlobalTablePageOptions, type SqlCtxDbOptions, type SqlCtxExec, createSqlCtxDb, selectGlobalTables } from '@lunora/sql-store';
5
+ import { D1DatabaseLike, D1SessionLike, D1PreparedStatementLike } from '@lunora/platform';
6
+ export type { D1DatabaseLike, D1PreparedStatementLike, D1SessionLike } from '@lunora/platform';
4
7
  import { BatchItem, BatchResponse } from 'drizzle-orm/batch';
5
8
  import { DrizzleD1Database } from 'drizzle-orm/d1';
6
- /** The D1 store options — the shared store options minus `dialect` (the SQLite dialect is injected for you). */
7
- type D1ContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect">;
8
- /** Build a D1-backed `.global()` writer (the shared store core bound to the SQLite dialect). */
9
- declare const createD1ContextDatabase: (options: D1ContextDatabaseOptions) => ReturnType<typeof createSqlCtxDb>;
10
- /** Auto-provision the schema's `.global()` tables in D1 (idempotent `CREATE TABLE IF NOT EXISTS`). */
11
- declare const runD1GlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
12
- /** Materialize the `__agg_&lt;index>` companion tables for the schema's aggregate indexes. */
13
- declare const runD1AggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
14
- /** Materialize the `__rank_&lt;index>` companion tables for the schema's rank indexes. */
15
- declare const runD1RankMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
16
- /** Materialize the `__fts_&lt;index>` fts5 shadow tables for the schema's search indexes (no-op without fts5). */
17
- declare const runD1SearchMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
18
- /** Create the `__cdc_log` table in D1 (idempotent; only run when CDC is enabled). */
19
- declare const runD1CdcMigration: (exec: SqlCtxExec) => Promise<void>;
20
- /** Read changelog entries newer than `sinceSeq` in commit order. */
21
- declare const readD1CdcChanges: (exec: SqlCtxExec, options?: {
22
- limit?: number;
23
- sinceSeq?: number;
24
- }) => ReturnType<typeof readSqlCdcChanges>;
25
- /** Drop changelog entries at or below a checkpointed `throughSeq`. */
26
- declare const trimD1CdcChanges: (exec: SqlCtxExec, throughSeq: number) => Promise<void>;
27
- /** One exported row: `doc` is reconstructed from the column tuple. */
28
- interface ExportRow {
29
- doc: Record<string, unknown>;
30
- table: string;
31
- }
32
- interface ImportError {
33
- code: string;
34
- line: number;
35
- message: string;
36
- table: string;
37
- }
38
- interface ImportResult {
39
- /** Skipped rows whose `_id` already exists. */
40
- conflicts: number;
41
- errors: ImportError[];
42
- inserted: Record<string, number>;
43
- }
44
- /**
45
- * Return every `.global()` table in the schema, optionally narrowed by an
46
- * allowlist. Shard-local tables are skipped here — they're handled by the DO
47
- * helpers — so callers get a clean separation between the two storage planes.
48
- */
49
- declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
50
- interface ExportGlobalArgs {
51
- batchSize?: number;
52
- tables?: ReadonlyArray<string>;
53
- }
54
- /**
55
- * Yield rows from every requested `.global()` table in batches. Uses
56
- * `LIMIT ?/OFFSET ?` because D1 globals don't have a stable keyset abstraction
57
- * here (the writer's `findMany` does, but at the cost of routing through the
58
- * full validator pipeline; for a snapshot stream a plain offset scan is
59
- * sufficient and predictable).
60
- */
9
+ /** Yield every requested D1 `.global()` table's rows, keyset-paged; never-written tables export empty. */
61
10
  declare const exportGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
62
- interface ImportGlobalArgs {
63
- /**
64
- * Optional direct exec handle to the same D1 database the writer targets.
65
- * When supplied, the conflict pre-probe issues a single
66
- * `SELECT 1 FROM &lt;table> WHERE id = ? LIMIT 1` against the row's declared
67
- * table instead of falling back to `writer.get(id)`, which scans every
68
- * global table looking for the id. Strongly recommended for large schemas
69
- * — the writer-fallback is O(N tables) per row.
70
- */
71
- exec?: D1ExecLike;
72
- rows: ReadonlyArray<ExportRow>;
73
- startLine?: number;
74
- }
75
- /** Minimal slice of `D1Exec` (declared locally to avoid a circular import). */
76
- interface D1ExecLike {
77
- all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
78
- }
79
- /**
80
- * Import rows into `.global()` tables via the schema-aware D1 writer. The
81
- * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
82
- * absent); we pre-probe each row's `_id` so a collision is reported as a
83
- * conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
84
- * `errors`; the rest land.
85
- */
11
+ /** Insert snapshot rows into D1 `.global()` tables; an existing `_id` is a conflict left unchanged unless `args.onConflict` is `"replace"`, which overwrites it. */
86
12
  declare const importGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportGlobalArgs) => Promise<ImportResult>;
87
13
  /**
88
- * Minimal structural projection of `D1Database` to keep the adapter
89
- * compatible with the real workers-types value as well as unit-test doubles.
90
- */
91
- interface D1DatabaseLike {
92
- batch?: (statements: D1PreparedStatementLike[]) => Promise<unknown[]>;
93
- exec?: (sql: string) => Promise<unknown>;
94
- prepare: (sql: string) => D1PreparedStatementLike;
95
- withSession: (bookmark?: string) => D1SessionLike;
96
- }
97
- interface D1SessionLike {
98
- batch?: (statements: D1PreparedStatementLike[]) => Promise<unknown[]>;
99
- getBookmark: () => string | null;
100
- prepare: (sql: string) => D1PreparedStatementLike;
101
- }
102
- interface D1PreparedStatementLike {
103
- all: <T = unknown>() => Promise<{
104
- results: T[];
105
- success: boolean;
106
- }>;
107
- bind: (...values: unknown[]) => D1PreparedStatementLike;
108
- first: <T = unknown>(column?: string) => Promise<T | null>;
109
- raw: <T = unknown>() => Promise<T[][]>;
110
- run: <T = unknown>() => Promise<{
111
- meta?: Record<string, unknown>;
112
- results?: T[];
113
- success: boolean;
114
- }>;
115
- }
116
- /** Thin wrapper over a `D1DatabaseSession` exposing bookmark plumbing. */
14
+ * Thin wrapper over a `D1DatabaseSession` exposing bookmark plumbing.
15
+ *
16
+ * `all` and `first` retry D1's expected transient failures — but only for a
17
+ * statement that is provably read-only. D1 produces a documented
18
+ * baseline of infrastructural errors even when healthy (Cloudflare's team calls
19
+ * a handful every few hours "not unexpected") and their guidance is to retry;
20
+ * a client that does not has adopted that error rate as the application's own.
21
+ *
22
+ * Nothing else on this class or on {@link D1Client} retries. `run` is the write
23
+ * path, and every transient D1 error is ambiguous about whether the statement
24
+ * applied — re-running a non-idempotent write after a lost response
25
+ * double-applies it. `all` is not a read path either: D1 runs
26
+ * `UPDATE … RETURNING` through it, so the retry is gated on the statement's
27
+ * leading keyword rather than on the method name. Wrap a genuinely idempotent
28
+ * write in {@link withD1Retry} yourself, per call.
29
+ */
117
30
  declare class D1Session {
118
31
  private readonly session;
119
32
  /** See {@link D1Client.stmtCache}. Scoped per session. */
120
33
  private readonly stmtCache;
121
34
  constructor(session: D1SessionLike);
122
35
  prepare(sql: string): D1PreparedStatementLike;
36
+ /**
37
+ * Execute a statement. **Not retried** — `run` is the write path, and a
38
+ * transient D1 error does not say whether the write applied.
39
+ */
123
40
  run<T = unknown>(sql: string, ...binds: unknown[]): Promise<{
124
41
  meta?: Record<string, unknown>;
125
42
  results?: T[];
126
43
  success: boolean;
127
44
  }>;
45
+ /**
46
+ * Read all rows, retrying D1's transient failures when `sql` is a
47
+ * read-only statement. An `UPDATE … RETURNING` runs through here too and is
48
+ * left unretried.
49
+ */
128
50
  all<T = unknown>(sql: string, ...binds: unknown[]): Promise<{
51
+ meta?: Record<string, unknown>;
129
52
  results: T[];
130
53
  success: boolean;
131
54
  }>;
55
+ /** Read the first row, retrying under the same read-only rule as {@link all}. */
132
56
  first<T = unknown>(sql: string, ...binds: unknown[]): Promise<T | null>;
133
57
  /**
134
- * Returns the most recent bookmark known to the session, or `undefined`
135
- * when D1 has not issued one yet.
136
- */
58
+ * Returns the most recent bookmark known to the session, or `undefined`
59
+ * when D1 has not issued one yet.
60
+ */
137
61
  getBookmark(): string | undefined;
138
62
  }
63
+ /**
64
+ * A D1 handle: prepared-statement caching, Sessions-API sessions, and the
65
+ * drizzle-typed accessors.
66
+ *
67
+ * **Nothing on this class retries.** `prepare`, `drizzle`, `drizzleSession`,
68
+ * `batch` and `raw` all hand back the underlying D1 surface untouched. The
69
+ * automatic retry lives on {@link D1Session.all} / {@link D1Session.first} and
70
+ * on `retryingExec` (the seam `.global()` tables read through); wrap anything
71
+ * else in {@link withD1Retry} yourself, and only when it is safe to run twice.
72
+ */
139
73
  declare class D1Client {
140
74
  private readonly db;
141
75
  /**
142
- * SQL string -> prepared statement. Prepared statements are reusable in
143
- * D1; preparing the same SQL twice forces the worker to round-trip the
144
- * statement plan. Caching is per-instance so unit-test isolation holds.
145
- * Bounded to {@link STMT_CACHE_CAPACITY} via LRU eviction.
146
- */
76
+ * SQL string -> prepared statement. D1 caches compiled statements
77
+ * server-side keyed by the SQL text — the JS `D1PreparedStatement` is
78
+ * inert and every execution carries the text + params over RPC anyway —
79
+ * so this cache buys no round trips: it only avoids re-allocating a
80
+ * statement object per call and hands repeated binds one object to start
81
+ * from. Caching is per-instance so unit-test isolation holds. Bounded to
82
+ * {@link STMT_CACHE_CAPACITY} via LRU eviction.
83
+ */
147
84
  private readonly stmtCache;
148
85
  /**
149
- * Lazily-built drizzle handle over the bare binding. Memoised so a single
150
- * `D1Client` reuses the same dialect/session machinery across calls.
151
- */
86
+ * Lazily-built drizzle handle over the bare binding. Memoised so a single
87
+ * `D1Client` reuses the same dialect/session machinery across calls.
88
+ */
152
89
  private drizzleHandle;
153
90
  constructor(database: D1DatabaseLike);
154
91
  /**
155
- * Open a Sessions-API scoped session. Pass the bookmark forwarded by
156
- * the client to opt into read-your-writes consistency.
157
- *
158
- * With no bookmark this is the first request of a session — there is no
159
- * prior write to read, so we open with the explicit `"first-unconstrained"`
160
- * constraint (Cloudflare's lowest-latency default: the first read may serve
161
- * from any replica). Read-your-writes for sequenced requests still flows
162
- * through the forwarded bookmark; a caller needing a strongly-consistent
163
- * very-first read should pass `"first-primary"` as the bookmark instead.
164
- */
92
+ * Open a Sessions-API scoped session. Pass the bookmark forwarded by
93
+ * the client to opt into read-your-writes consistency.
94
+ *
95
+ * With no bookmark this is the first request of a session — there is no
96
+ * prior write to read, so we open with the explicit `"first-unconstrained"`
97
+ * constraint (Cloudflare's lowest-latency default: the first read may serve
98
+ * from any replica). Read-your-writes for sequenced requests still flows
99
+ * through the forwarded bookmark; a caller needing a strongly-consistent
100
+ * very-first read should pass `"first-primary"` as the bookmark instead.
101
+ */
165
102
  withSession(bookmark?: string): D1Session;
166
103
  /**
167
- * Prepare a statement, reusing a cached one when the SQL text matches.
168
- * `bind()` on a prepared statement returns a new bound statement and
169
- * leaves the underlying prepared plan reusable, so cache hits are safe
170
- * even when the previous caller already called `.bind(...).run()`.
171
- */
104
+ * Prepare a statement, reusing a cached one when the SQL text matches.
105
+ * `bind()` on a prepared statement returns a new bound statement and
106
+ * leaves the cached one untouched, so cache hits are safe even when the
107
+ * previous caller already called `.bind(...).run()`.
108
+ */
172
109
  prepare(sql: string): D1PreparedStatementLike;
173
110
  /**
174
- * Drizzle handle over the bare `env.DB` binding. Used for typed queries
175
- * against generated `sqliteTable` schemas; does **not** participate in the
176
- * D1 Sessions API (no bookmark pinning). For bookmark-scoped reads, use
177
- * {@link drizzleSession} instead.
178
- */
179
- get drizzle(): DrizzleD1Database<Record<string, unknown>>;
111
+ * Drizzle handle over the bare `env.DB` binding. Used for typed queries
112
+ * against generated `sqliteTable` schemas; does **not** participate in the
113
+ * D1 Sessions API (no bookmark pinning). For bookmark-scoped reads, use
114
+ * {@link drizzleSession} instead.
115
+ */
116
+ get drizzle(): DrizzleD1Database;
180
117
  /**
181
- * Drizzle handle scoped to a D1 Sessions-API session. The bookmark, when
182
- * supplied, opts into read-your-writes consistency for follow-up reads on
183
- * the same session.
184
- *
185
- * A `D1DatabaseSession` exposes the same `prepare` / `batch` surface
186
- * drizzle calls into, so a single `unknown` cast lets us treat the session
187
- * as a `D1Database` for driver-construction purposes.
188
- */
189
- drizzleSession(bookmark?: string): DrizzleD1Database<Record<string, unknown>>;
118
+ * Drizzle handle scoped to a D1 Sessions-API session. The bookmark, when
119
+ * supplied, opts into read-your-writes consistency for follow-up reads on
120
+ * the same session.
121
+ *
122
+ * A `D1DatabaseSession` exposes the same `prepare` / `batch` surface
123
+ * drizzle calls into, so a single `unknown` cast lets us hand the session to
124
+ * the driver.
125
+ */
126
+ drizzleSession(bookmark?: string): DrizzleD1Database;
190
127
  /**
191
- * Atomic batch over the drizzle d1 driver. Mirrors `db.batch([...])`
192
- * exactly; exposed on the client so callers don't need to hold a drizzle
193
- * handle just to run a typed batch.
194
- */
128
+ * Atomic batch over the drizzle d1 driver. Mirrors `db.batch([...])`
129
+ * exactly; exposed on the client so callers don't need to hold a drizzle
130
+ * handle just to run a typed batch.
131
+ */
195
132
  batch<U extends BatchItem<"sqlite">, T extends Readonly<[U, ...U[]]>>(items: T): Promise<BatchResponse<T>>;
196
133
  /** Direct access to the underlying binding (advanced use only). */
197
134
  get raw(): D1DatabaseLike;
198
135
  }
199
- /** A table plus its current row count. */
200
- interface GlobalTableInfo {
201
- name: string;
202
- rowCount: number;
203
- }
204
- /** A window of rows from one table, plus the column list and total size. */
205
- interface GlobalTablePage {
206
- columns: string[];
207
- /**
208
- * Foreign-key columns (local column → referenced table) for tables that carry
209
- * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
210
- * Schema `.global()` tables omit this (their refs come from `describeTables`);
211
- * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
212
- * schema diagram can draw their global→global FK edges.
213
- */
214
- refs?: Record<string, string>;
215
- rows: Record<string, unknown>[];
216
- total: number;
217
- }
218
- /**
219
- * One equality constraint a facet-value click adds to the global browser's view:
220
- * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
221
- * displayed column name, validated against the table's columns and mapped to its
222
- * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
223
- * value** the facet returned (a SQLite scalar), bound as a parameter and never
224
- * interpolated. AND-combined with the other clauses.
225
- */
226
- interface GlobalFilterClause {
227
- column: string;
228
- value: unknown;
229
- }
230
- interface ReadGlobalTablePageOptions {
231
- filters?: GlobalFilterClause[];
136
+ /** The D1 store options — the shared store options minus `dialect` (the SQLite dialect is injected for you). */
137
+ type D1ContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect">;
138
+ /** Build a D1-backed `.global()` writer (the shared store core bound to the SQLite dialect). */
139
+ declare const createD1ContextDatabase: (options: D1ContextDatabaseOptions) => ReturnType<typeof createSqlCtxDb>;
140
+ /** Auto-provision the schema's `.global()` tables in D1 (idempotent `CREATE TABLE IF NOT EXISTS`). */
141
+ declare const runD1GlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
142
+ /** Materialize the `__agg_<index>` companion tables for the schema's aggregate indexes. */
143
+ declare const runD1AggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
144
+ /** Materialize the `__rank_<index>` companion tables for the schema's rank indexes. */
145
+ declare const runD1RankMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
146
+ /** Materialize (and backfill) the `__fts_<index>` fts5 shadow tables for the schema's search indexes. */
147
+ declare const runD1SearchMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
148
+ /** Index existing rows into every search companion, including the `staged: true` ones migrations leave empty. */
149
+ declare const backfillD1SearchIndexes: (exec: SqlCtxExec, schema: SchemaLike) => Promise<SqlSearchBackfillResult>;
150
+ /** Create the `__cdc_log` table in D1 (idempotent; only run when CDC is enabled). */
151
+ declare const runD1CdcMigration: (exec: SqlCtxExec) => Promise<void>;
152
+ /** Read changelog entries newer than `sinceSeq` in commit order. */
153
+ declare const readD1CdcChanges: (exec: SqlCtxExec, options?: {
232
154
  limit?: number;
233
- offset?: number;
234
- table: string;
235
- }
155
+ sinceSeq?: number;
156
+ }) => ReturnType<typeof readSqlCdcChanges>;
236
157
  /**
237
- * Options for {@link facetGlobalColumn} — the read-only "what values does this
238
- * column hold?" summary for the global (D1) browser. `column` is the displayed
239
- * column to group by (validated and mapped to its physical column, never
240
- * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
241
- * constraints so the facet reflects the **active view** (the same rows the
242
- * browser is previewing); `limit` caps the distinct values returned (clamped).
243
- */
244
- interface FacetGlobalColumnOptions {
245
- column: string;
246
- filters?: GlobalFilterClause[];
247
- limit?: number;
248
- table: string;
158
+ * Delete `.global()` changelog entries older than `retentionMs`, if this writer
159
+ * wins the fleet's sweep lease. See `sweepSqlCdcRetention`.
160
+ *
161
+ * Replaces the seq-based `trimD1CdcChanges`, which took a checkpoint no caller
162
+ * could compute: the log is shared across every shard and region, so no single
163
+ * caller knows a `seq` that is safe for all of them. A time window is a bound
164
+ * they can all reason about, and the lease is what stops them racing.
165
+ */
166
+ declare const sweepD1CdcRetention: (exec: SqlCtxExec, retentionMs: number, now: number) => Promise<void>;
167
+ /**
168
+ * What a staged commit reports. Its own shape, not `ImportResult`: a replace counts
169
+ * rows written per table (overwrites included) and rows pruned per table, which the
170
+ * runtime session totals across planes.
171
+ */
172
+ interface StagedCommitResult {
173
+ conflicts: number;
174
+ /** Rows pruned per table because the snapshot did not hold them. */
175
+ deleted: Record<string, number>;
176
+ errors: ImportError[];
177
+ inserted: Record<string, number>;
249
178
  }
250
- /** One distinct value of a faceted global column with its row count over the active view. */
251
- interface GlobalFacetValue {
252
- count: number;
253
- value: unknown;
179
+ /** A staged-replace failure the caller maps to its HTTP status. */
180
+ declare class GlobalImportStagingError extends Error {
181
+ readonly code: string;
182
+ constructor(code: string, message: string);
254
183
  }
255
- /**
256
- * Payload of a {@link facetGlobalColumn} call: the top-N distinct `values` (each
257
- * with a `count`) ordered by frequency, plus `truncated` — `true` when more
258
- * distinct values existed beyond the cap, so the UI can say so rather than imply
259
- * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
260
- */
261
- interface GlobalFacetResult {
262
- truncated: boolean;
263
- values: GlobalFacetValue[];
184
+ interface StageGlobalArgs {
185
+ /** The session's generation (see `@lunora/shard-engine`'s `import-staging`): rows of another one are refused. */
186
+ generation: string;
187
+ rows: ReadonlyArray<ExportRow>;
188
+ session: string;
189
+ startLine?: number;
190
+ /** The session's `.global()` replace scope. */
191
+ tables: ReadonlyArray<string>;
264
192
  }
265
193
  /**
266
- * List every browsable D1 table with its row count, ordered by name. Surfaces
267
- * both the schema's `.global()` tables (provisioned first) and external tables
268
- * (auth, etc.); internal/companion tables are excluded.
269
- */
270
- declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promise<GlobalTableInfo[]>;
194
+ * Validate and stage one request's `.global()` rows. Any refused row stages none
195
+ * of them — the session is then never committed.
196
+ */
197
+ declare const stageGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, args: StageGlobalArgs, now?: number) => Promise<{
198
+ errors: ImportError[];
199
+ staged: Record<string, number>;
200
+ }>;
271
201
  /**
272
- * Read a page of rows from one D1 table. The table is validated against the live
273
- * browsable-table list before its name is interpolated, so this can't be coerced
274
- * into reading an internal table or injecting SQL. `limit` is clamped to
275
- * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
276
- * matching each `column = value` eq constraint (a facet-value drill-down), bound
277
- * through {@link buildEqPredicate} so they never inject SQL.
278
- */
202
+ * Swap the session's staged rows in for `tables`: overwrite or insert each, then
203
+ * prune. Retry-safe — see the module doc for what holds on a failure. `staged`
204
+ * says whether the session staged any `.global()` row: a session that did must
205
+ * still hold them, one that did not empties the tables.
206
+ */
207
+ declare const commitStagedGlobalRows: (writer: DatabaseWriterLike, exec: SqlCtxExec, schema: SchemaLike, args: {
208
+ generation: string;
209
+ session: string;
210
+ staged: boolean;
211
+ tables: ReadonlyArray<string>;
212
+ }, now?: number) => Promise<StagedCommitResult>;
213
+ /** Forget a session of `generation`: its staged rows and its marker. Another generation's rows are left to their own expiry. */
214
+ declare const abortStagedGlobalRows: (exec: SqlCtxExec, session: string, generation: string) => Promise<void>;
215
+ /** Every browsable D1 table with its row count (schema `.global()` tables provisioned first). */
216
+ declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promise<GlobalTableInfo[]>;
217
+ /** One page of a D1 table's rows, eq-filtered. */
279
218
  declare const readGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
280
- /**
281
- * Summarise the distinct values of one displayed column over the **active view**
282
- * (the same eq `filters` the global browser is previewing) — the D1 twin of the
283
- * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
284
- * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
285
- * against the table's displayed columns (typed 404 if unknown), mapped to its
286
- * physical column, and quoted — never interpolated from caller input. The extra
287
- * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
288
- * an external (non-schema) table is never grouped — it collapses to a single
289
- * redacted `•••` bucket — mirroring the page browser's value redaction so the
290
- * facet can't leak credentials. The returned `value` is the raw stored scalar, so
291
- * a click feeds it straight back as an eq filter.
292
- */
219
+ /** The distinct values of one D1 column over the active view. */
293
220
  declare const facetGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
221
+ /**
222
+ * The line comment that confirms a migration's destructive statement is intended, matched exactly. It counts only on
223
+ * its own line before that statement; `lunora migrate generate` writes it there for each statement it confirms, so it
224
+ * stays with that statement when a generated file is split into one `Migration` per statement.
225
+ *
226
+ * Shared rather than imported from `@lunora/d1` by `@lunora/cli`, because the two are released independently: a CLI
227
+ * that read it from `@lunora/d1` at runtime could not load next to a published D1 that predates the export.
228
+ */
229
+ declare const ALLOW_DESTRUCTIVE_MARKER = "-- lunora:allow-destructive";
294
230
  interface Migration {
295
231
  /** Human-readable name, e.g. `001_init` (used in logs). */
296
232
  name: string;
@@ -310,30 +246,239 @@ interface MigrationRunnerResult {
310
246
  }[];
311
247
  }
312
248
  /**
313
- * Sequentially applies pending migrations against a D1 database via the
314
- * drizzle-orm/d1 driver. Each migration is hashed (SHA-256 over its SQL
315
- * text); the hash is stored in `__drizzle_migrations`, so re-applying the
316
- * same SQL under a different `version` is rejected and identical migrations
317
- * are skipped idempotently.
318
- */
249
+ * Sequentially applies pending migrations against a D1 database via the
250
+ * drizzle-orm/d1 driver, recording each one's `version` and SHA-256 in
251
+ * `__drizzle_migrations`.
252
+ *
253
+ * A migration is skipped when its VERSION is recorded, never by its text alone.
254
+ * Deduplicating by hash re-applied any migration whose text changed after it
255
+ * ran — a comment, a whitespace fix, a CRLF checkout — so a non-idempotent one
256
+ * (`SET balance = balance * 100`) ran twice. A recorded version whose hash no
257
+ * longer matches is refused as `MIGRATION_DRIFT` instead: the runner cannot
258
+ * tell a harmless edit from a changed migration, and running either again is
259
+ * the one outcome that is never right.
260
+ */
319
261
  declare class MigrationRunner {
320
262
  private readonly client;
321
263
  private readonly migrations;
322
264
  /**
323
- * Accepts either a {@link D1Client} (preferred — gets typed batches +
324
- * drizzle handle for free) or a raw `D1DatabaseLike` binding (wrapped on
325
- * the caller's behalf so existing `@lunora/cli` callers keep working).
326
- */
265
+ * Accepts either a {@link D1Client} (preferred — gets typed batches +
266
+ * drizzle handle for free) or a raw `D1DatabaseLike` binding (wrapped on
267
+ * the caller's behalf so existing `@lunora/cli` callers keep working).
268
+ */
327
269
  constructor(database: D1Client | D1DatabaseLike, migrations: Migration[]);
328
270
  run(): Promise<MigrationRunnerResult>;
271
+ /** Does the tracking table carry the `version` column yet? One catalog read. */
272
+ private hasVersionColumn;
273
+ /**
274
+ * Create the tracking table, or bring one written before `version` existed
275
+ * up to the current shape.
276
+ *
277
+ * Two runners can upgrade the same table at once (parallel deploys): both
278
+ * see no column, and the second `ADD COLUMN` fails with "duplicate column
279
+ * name". That failure is only accepted once a re-read shows the column
280
+ * really is there — any other failure of the `ALTER` still surfaces.
281
+ */
282
+ private ensureTrackingTable;
283
+ /**
284
+ * Read the tracking rows, first giving every row recorded before versions
285
+ * were tracked the version whose SQL it hashed — the only link to a version
286
+ * such a row has. A row whose hash matches no current migration stays
287
+ * unversioned, and {@link run} refuses to guess around it.
288
+ */
289
+ private readTrackingRows;
329
290
  private applyOne;
330
291
  private assertUniqueVersions;
331
292
  private assertUniqueSql;
332
293
  }
333
294
  /**
334
- * The canonical SQLite dialect: column affinities, the shared SQLite value
335
- * codec, `RETURNING` support (both D1 and `node:sqlite`), and `sqlite_master`
336
- * table probing. The rest of the per-statement shaping is drizzle's.
337
- */
295
+ * Derive a low-cardinality tag for a rendered statement — `select:users`,
296
+ * `insert:orders`, `select:unknown` when no table token is recognisable.
297
+ *
298
+ * Cardinality is the whole design constraint. The rendered SQL is unique per
299
+ * shape and near-unique per call site, so grouping on it produces a tag space
300
+ * that grows without bound and answers nothing; verb + table is the coarsest
301
+ * label that still points at a specific culprit.
302
+ */
303
+ declare const d1QueryTag: (sql: string) => string;
304
+ /** One statement's cost, read off D1's `meta`. */
305
+ interface D1QueryCost {
306
+ /** D1's own server-side duration in ms, when reported. */
307
+ durationMs?: number;
308
+ /** Rows D1 SCANNED — the billed number, and the one a missing index inflates. */
309
+ rowsRead: number;
310
+ /** Rows written by a DML statement; `0` for reads. */
311
+ rowsWritten: number;
312
+ }
313
+ /**
314
+ * Project D1's `meta` onto {@link D1QueryCost}, or `undefined` when the result
315
+ * carried no usable accounting — a test double, or a `batch()` leg that reports
316
+ * none. Callers skip the emit entirely in that case rather than logging zeroes,
317
+ * which would read as "this query was free".
318
+ */
319
+ declare const readD1QueryCost: (meta: Record<string, unknown> | undefined) => D1QueryCost | undefined;
320
+ /**
321
+ * Emit one structured cost event per D1 statement into Workers Logs, so
322
+ * "D1 reads spiked" resolves to a tag by group-by.
323
+ *
324
+ * Best-effort by contract, exactly like the request-log emit: a serialization
325
+ * hiccup must never turn a served query into a failed one, so the caller wraps
326
+ * this and swallows. Emitting one line per D1 statement is proportionate —
327
+ * every one of them is already a network round trip, so the line is noise-free
328
+ * next to the work it describes.
329
+ *
330
+ * The SQL text itself is NEVER emitted: it carries inlined literals on some
331
+ * render paths, and the tag is the groupable thing anyway.
332
+ */
333
+ declare const emitD1QueryCost: (sql: string, meta: Record<string, unknown> | undefined) => void;
334
+ /** Tuning for {@link withD1Retry}. */
335
+ interface D1RetryOptions {
336
+ /** Total attempts including the first. Default 3. Must be >= 1. */
337
+ attempts?: number;
338
+ /**
339
+ * Total budget across every attempt and backoff, in ms. An attempt still
340
+ * running when the budget expires is abandoned, and a backoff never sleeps
341
+ * past it.
342
+ *
343
+ * `timeoutMs` bounds one attempt; this bounds the operation.
344
+ */
345
+ deadlineMs?: number;
346
+ /** Sleep implementation. Injected so tests need no timers. */
347
+ sleep?: (ms: number) => Promise<void>;
348
+ /**
349
+ * Abandon a single attempt that has not settled within this many ms, and
350
+ * treat it as a transient failure.
351
+ *
352
+ * There is no default — a legitimate analytical query and a stalled one
353
+ * look identical from outside, so the value has to come from what your
354
+ * workload actually needs. Unset, {@link SLOW_FAILURE_MS} stops a slow
355
+ * failure from being retried rather than guessing a bound for you.
356
+ *
357
+ * Only ever applied to operations that are safe to abandon. It does not
358
+ * cancel the underlying D1 call.
359
+ */
360
+ timeoutMs?: number;
361
+ }
362
+ /**
363
+ * True when `error` looks like one of D1's expected transient failures.
364
+ *
365
+ * Deliberately conservative: an unrecognised error is treated as **permanent**
366
+ * and surfaces immediately. Retrying a genuine bug — a syntax error, a
367
+ * constraint violation — turns one fast failure into three slow ones and
368
+ * hides the cause.
369
+ */
370
+ declare const isTransientD1Error: (error: unknown) => boolean;
371
+ /**
372
+ * Thrown when an attempt is abandoned for exceeding
373
+ * {@link D1RetryOptions.timeoutMs}.
374
+ *
375
+ * Its own class so a caller can tell "D1 hung" apart from "D1 returned an
376
+ * error" — they have different remedies, and collapsing them hides which one
377
+ * is happening.
378
+ */
379
+ declare class D1TimeoutError extends Error {
380
+ /** Milliseconds waited before the attempt was abandoned. */
381
+ readonly timeoutMs: number;
382
+ constructor(timeoutMs: number);
383
+ }
384
+ /**
385
+ * Run `operation`, retrying D1's transient failures with exponential backoff
386
+ * and jitter.
387
+ *
388
+ * **Only wrap operations that are safe to run more than once.** Reads always
389
+ * are. A write is only if it is idempotent — an upsert keyed on a primary key,
390
+ * a delete by id, an `INSERT OR IGNORE`. A bare `INSERT` or a relative
391
+ * `UPDATE` is not, and re-running one after a lost response double-applies it.
392
+ */
393
+ declare const withD1Retry: <T>(operation: () => Promise<T>, options?: D1RetryOptions) => Promise<T>;
394
+ /**
395
+ * Wrap a `.global()` exec so its **read-only** statements retry D1's transient
396
+ * failures.
397
+ *
398
+ * This is where the retry has to live to reach an application: `.global()`
399
+ * tables run every read through the exec codegen builds over the raw D1
400
+ * binding, not through a `D1Client`. `run` and `batch` are passed straight
401
+ * through — they are the write path, and a transient D1 error does not say
402
+ * whether the write applied.
403
+ *
404
+ * `all` is not the read path either. It only retries when
405
+ * {@link isReadOnlyD1Sql} proves the statement is one, because `UPDATE …
406
+ * RETURNING` runs through `all` too.
407
+ */
408
+ declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlCtxExec;
409
+ /** One SQL file: its name under `lunora/migrations/` and its text. */
410
+ interface SqlMigrationFile {
411
+ name: string;
412
+ sql: string;
413
+ }
414
+ /**
415
+ * Where a file stands. `applied`: recorded with the same SQL, so skipped. `pending`: not recorded yet, so it runs.
416
+ * `changed`: recorded with different SQL, or its SQL is recorded under another name, which is refused rather than run
417
+ * again. `ran`: applied by this call. `baselined`: recorded by a baseline call, which records files without executing them.
418
+ */
419
+ type SqlMigrationState = "applied" | "baselined" | "changed" | "pending" | "ran";
420
+ interface SqlMigrationEntry {
421
+ /** Destructive statements (drops, renames, truncates, replaces), in file order. */
422
+ destructive: string[];
423
+ name: string;
424
+ /** Statements a migrations-scoped token may not run: anything but a new table, a non-unique index or an added column. */
425
+ rootOnly: string[];
426
+ /** Statements left out because the column they add is already there, provisioned by the runtime on first use. */
427
+ skipped: string[];
428
+ state: SqlMigrationState;
429
+ /** Statements this file would run, or ran, in file order. Empty for an applied or changed file. */
430
+ statements: string[];
431
+ }
432
+ interface SqlMigrationResult {
433
+ files: SqlMigrationEntry[];
434
+ /** A dry run only: the pending files a real run with the same options would refuse. Nothing is refused by a dry run. */
435
+ refused?: string[];
436
+ }
437
+ interface ApplySqlMigrationOptions {
438
+ /**
439
+ * Run only additive statements (a new table or index, an added column). A file with any other statement is refused
440
+ * before anything runs. Set for a caller that holds a migrations scope rather than the root token.
441
+ */
442
+ additiveOnly?: boolean;
443
+ /**
444
+ * Record every pending file as applied without running it. For a database whose files were applied by hand or
445
+ * predate this tracking. Drift is still refused; nothing is executed.
446
+ */
447
+ baseline?: boolean;
448
+ /**
449
+ * Like `baseline`, but only for the pending files up to and including the named one, in the order given. The
450
+ * files after it stay pending, so a later run can apply them, including destructive ones, on a database that now
451
+ * has a recorded file. Use it to record what already ran on a stage before a DROP that has not.
452
+ */
453
+ baselineThrough?: string;
454
+ /** Run files that hold destructive statements. Without it such a file is refused and nothing runs. */
455
+ confirmDestructive?: boolean;
456
+ /** Report each file's state and statements without running or recording anything. Never refuses. */
457
+ dryRun?: boolean;
458
+ /**
459
+ * The app's schema. A column a file adds to a `.global()` table is filled with the value its declaration gives, in the
460
+ * same batch, as the runtime does when it adds the column itself. Without it, the rows that predate the column read NULL.
461
+ */
462
+ schema?: SchemaLike;
463
+ }
464
+ /**
465
+ * Apply the pending SQL files, in the order given, against one D1 database.
466
+ *
467
+ * Every refusal is decided before the first file runs, so a drifted or unconfirmed file late in the list cannot leave
468
+ * the earlier ones applied. Each file's statements and its tracking row commit in one `batch()`. A second call finds
469
+ * every file recorded and runs nothing.
470
+ *
471
+ * Throws `MIGRATION_DRIFT` when an applied file's SQL changed or was renamed; `MIGRATION_DESTRUCTIVE` when a pending
472
+ * file cannot run (see {@link assertDestructiveConfirmed}); `MIGRATION_ROOT_REQUIRED` when an additive-only caller sends a
473
+ * file with any other statement; `VALIDATION_ERROR` for transaction control in a file that
474
+ * is applied, a `baselineThrough` that names no file, or a batch that failed and rolled back.
475
+ */
476
+ declare const applySqlMigrationFiles: (database: D1DatabaseLike, files: ReadonlyArray<SqlMigrationFile>, options?: ApplySqlMigrationOptions) => Promise<SqlMigrationResult>;
477
+ /**
478
+ * The canonical SQLite dialect: column affinities, `RETURNING` support (both D1
479
+ * and `node:sqlite`), and `sqlite_master` table probing. The rest of the
480
+ * per-statement shaping is drizzle's. The value codec is NOT a dialect member —
481
+ * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
482
+ */
338
483
  declare const sqliteDialect: SqlDialect;
339
- export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1DatabaseLike, type D1PreparedStatementLike, D1Session, type D1SessionLike, type ExportGlobalArgs, type FacetGlobalColumnOptions, type ExportRow as GlobalExportRow, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type ImportError as GlobalImportError, type ImportResult as GlobalImportResult, type GlobalTableInfo, type GlobalTablePage, type ImportGlobalArgs, type Migration, MigrationRunner, type MigrationRunnerResult, type ReadGlobalTablePageOptions, createD1ContextDatabase as createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, selectGlobalTables, sqliteDialect, trimD1CdcChanges };
484
+ export { ALLOW_DESTRUCTIVE_MARKER, type ApplySqlMigrationOptions, D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, GlobalImportStagingError, type Migration, MigrationRunner, type MigrationRunnerResult, type SqlMigrationEntry, type SqlMigrationFile, type SqlMigrationResult, type SqlMigrationState, type StageGlobalArgs, type StagedCommitResult, abortStagedGlobalRows, applySqlMigrationFiles, backfillD1SearchIndexes, commitStagedGlobalRows, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, stageGlobalRows, sweepD1CdcRetention, withD1Retry };