@lunora/d1 1.0.0-alpha.213 → 1.0.0-alpha.214

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,128 +1,14 @@
1
1
  import { SchemaLike, DatabaseWriterLike } from '@lunora/shard-engine';
2
2
  export { applyCdcChanges } from '@lunora/shard-engine';
3
- import { SqlCtxDbOptions, SqlCtxExec, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, SqlDialect } from '@lunora/sql-store';
4
- export { type SqlCtxExec as D1Exec, type SqlCtxDbOptions, type SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
3
+ import { SqlCtxExec, ExportGlobalArgs, ExportRow, ImportGlobalArgs, ImportResult, SqlCtxDbOptions, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, 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
5
  import { D1DatabaseLike, D1SessionLike, D1PreparedStatementLike } from '@lunora/platform';
6
6
  export type { D1DatabaseLike, D1PreparedStatementLike, D1SessionLike } from '@lunora/platform';
7
7
  import { BatchItem, BatchResponse } from 'drizzle-orm/batch';
8
8
  import { DrizzleD1Database } from 'drizzle-orm/d1';
9
- /** The D1 store options — the shared store options minus `dialect` (the SQLite dialect is injected for you). */
10
- type D1ContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect">;
11
- /** Build a D1-backed `.global()` writer (the shared store core bound to the SQLite dialect). */
12
- declare const createD1ContextDatabase: (options: D1ContextDatabaseOptions) => ReturnType<typeof createSqlCtxDb>;
13
- /** Auto-provision the schema's `.global()` tables in D1 (idempotent `CREATE TABLE IF NOT EXISTS`). */
14
- declare const runD1GlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
15
- /** Materialize the `__agg_<index>` companion tables for the schema's aggregate indexes. */
16
- declare const runD1AggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
17
- /** Materialize the `__rank_<index>` companion tables for the schema's rank indexes. */
18
- declare const runD1RankMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
19
- /** Materialize (and backfill) the `__fts_<index>` fts5 shadow tables for the schema's search indexes. */
20
- declare const runD1SearchMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
21
- /** Index existing rows into every search companion, including the `staged: true` ones migrations leave empty. */
22
- declare const backfillD1SearchIndexes: (exec: SqlCtxExec, schema: SchemaLike) => Promise<SqlSearchBackfillResult>;
23
- /** Create the `__cdc_log` table in D1 (idempotent; only run when CDC is enabled). */
24
- declare const runD1CdcMigration: (exec: SqlCtxExec) => Promise<void>;
25
- /** Read changelog entries newer than `sinceSeq` in commit order. */
26
- declare const readD1CdcChanges: (exec: SqlCtxExec, options?: {
27
- limit?: number;
28
- sinceSeq?: number;
29
- }) => ReturnType<typeof readSqlCdcChanges>;
30
- /**
31
- * Delete `.global()` changelog entries older than `retentionMs`, if this writer
32
- * wins the fleet's sweep lease. See `sweepSqlCdcRetention`.
33
- *
34
- * Replaces the seq-based `trimD1CdcChanges`, which took a checkpoint no caller
35
- * could compute: the log is shared across every shard and region, so no single
36
- * caller knows a `seq` that is safe for all of them. A time window is a bound
37
- * they can all reason about, and the lease is what stops them racing.
38
- */
39
- declare const sweepD1CdcRetention: (exec: SqlCtxExec, retentionMs: number, now: number) => Promise<void>;
40
- /** One exported row: `doc` is reconstructed from the column tuple. */
41
- interface ExportRow {
42
- doc: Record<string, unknown>;
43
- /**
44
- * True physical source line, when the caller has it (e.g. a global row
45
- * pulled out of an interspersed NDJSON import stream by
46
- * `@lunora/runtime`'s `import-stream.ts`). When present this overrides the
47
- * position-derived line below — the caller-side positions of a
48
- * global-only subset don't line up with the original file once
49
- * non-global rows have been filtered out. Absent for callers with no
50
- * physical source to attribute (e.g. a fresh `exportGlobalRows` roundtrip
51
- * in tests), which keeps the positional fallback.
52
- */
53
- line?: number;
54
- table: string;
55
- }
56
- interface ImportError {
57
- code: string;
58
- line: number;
59
- message: string;
60
- table: string;
61
- }
62
- interface ImportResult {
63
- /** Skipped rows whose `_id` already exists. */
64
- conflicts: number;
65
- errors: ImportError[];
66
- inserted: Record<string, number>;
67
- }
68
- /**
69
- * Return every `.global()` table in the schema, optionally narrowed by an
70
- * allowlist. Shard-local tables are skipped here — they're handled by the DO
71
- * helpers — so callers get a clean separation between the two storage planes.
72
- */
73
- declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
74
- interface ExportGlobalArgs {
75
- batchSize?: number;
76
- tables?: ReadonlyArray<string>;
77
- }
78
- /**
79
- * Yield rows from every requested `.global()` table in batches.
80
- *
81
- * Keyset-paginates on the physical primary key (`id` — every `.global()` table
82
- * carries it, see `frameworkColumnDdl`): `WHERE "id" > ? ORDER BY "id" LIMIT ?`,
83
- * carrying the last id forward. A plain `LIMIT/OFFSET` scan would be wrong here —
84
- * SQLite gives no ordering guarantee for an unordered SELECT and each page is a
85
- * separate query, so pages could overlap or skip rows (and any concurrent
86
- * insert/delete would shift offsets and silently drop/duplicate rows in the
87
- * snapshot). Keyset paging is deterministic under concurrent writes and avoids
88
- * O(n^2) OFFSET scans on large tables.
89
- *
90
- * Tables are provisioned first (idempotent `CREATE … IF NOT EXISTS`): `.global()`
91
- * tables are created lazily on first write, so a fresh deployment — or any table
92
- * never written — would otherwise abort the stream with a raw `no such table`
93
- * instead of exporting it as empty.
94
- */
9
+ /** Yield every requested D1 `.global()` table's rows, keyset-paged; never-written tables export empty. */
95
10
  declare const exportGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
96
- interface ImportGlobalArgs {
97
- /**
98
- * Check the rows and report their shape errors, writing nothing. The conflict
99
- * probe and the insert are skipped, so an `_id` already in use and a foreign-key
100
- * or unique failure are only found by a real import.
101
- */
102
- dryRun?: boolean;
103
- /**
104
- * Optional direct exec handle to the same D1 database the writer targets.
105
- * When supplied, the conflict pre-probe issues a single
106
- * `SELECT 1 FROM <table> WHERE id = ? LIMIT 1` against the row's declared
107
- * table instead of falling back to an unscoped id probe, which scans every
108
- * global table looking for the id. Strongly recommended for large schemas
109
- * — the writer-fallback is O(N tables) per row.
110
- */
111
- exec?: D1ExecLike;
112
- rows: ReadonlyArray<ExportRow>;
113
- startLine?: number;
114
- }
115
- /** Minimal slice of `D1Exec` (declared locally to avoid a circular import). */
116
- interface D1ExecLike {
117
- all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
118
- }
119
- /**
120
- * Import rows into `.global()` tables via the schema-aware D1 writer. The
121
- * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
122
- * absent); we pre-probe each row's `_id` so a collision is reported as a
123
- * conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
124
- * `errors`; the rest land.
125
- */
11
+ /** Insert snapshot rows into D1 `.global()` tables; an existing `_id` is a conflict left unchanged unless `args.onConflict` is `"replace"`, which overwrites it. */
126
12
  declare const importGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportGlobalArgs) => Promise<ImportResult>;
127
13
  /**
128
14
  * Thin wrapper over a `D1DatabaseSession` exposing bookmark plumbing.
@@ -247,117 +133,42 @@ declare class D1Client {
247
133
  /** Direct access to the underlying binding (advanced use only). */
248
134
  get raw(): D1DatabaseLike;
249
135
  }
250
- /** A table plus its current row count. */
251
- interface GlobalTableInfo {
252
- name: string;
253
- rowCount: number;
254
- }
255
- /** A window of rows from one table, plus the column list and total size. */
256
- interface GlobalTablePage {
257
- columns: string[];
258
- /**
259
- * Foreign-key columns (local column → referenced table) for tables that carry
260
- * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
261
- * Schema `.global()` tables omit this (their refs come from `describeTables`);
262
- * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
263
- * schema diagram can draw their global→global FK edges.
264
- */
265
- refs?: Record<string, string>;
266
- rows: Record<string, unknown>[];
267
- total: number;
268
- }
269
- /**
270
- * One equality constraint a facet-value click adds to the global browser's view:
271
- * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
272
- * displayed column name, validated against the table's columns and mapped to its
273
- * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
274
- * value** the facet returned (a SQLite scalar — including a BLOB, which reaches
275
- * here as bytes because the facet payload is wire-encoded), normalised by
276
- * {@link sqliteEncode} and bound as a parameter, never interpolated.
277
- * AND-combined with the other clauses.
278
- *
279
- * Only `eq` is compiled on this path. `operator` and `path` exist so that a
280
- * request asking for anything else is refused by {@link buildEqPredicate} rather
281
- * than read as an equality: a `has` or `contains` clause matched as `= ?` would
282
- * return rows the caller did not ask for.
283
- */
284
- interface GlobalFilterClause {
285
- column: string;
286
- /** Must be absent or `"eq"`; any other operator is refused. */
287
- operator?: string;
288
- /** Must be absent or empty; a nested path is refused (D1 columns are physical). */
289
- path?: string[];
290
- value: unknown;
291
- }
292
- interface ReadGlobalTablePageOptions {
293
- filters?: GlobalFilterClause[];
294
- limit?: number;
295
- offset?: number;
296
- table: string;
297
- }
298
- /**
299
- * Options for {@link facetGlobalColumn} — the read-only "what values does this
300
- * column hold?" summary for the global (D1) browser. `column` is the displayed
301
- * column to group by (validated and mapped to its physical column, never
302
- * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
303
- * constraints so the facet reflects the **active view** (the same rows the
304
- * browser is previewing); `limit` caps the distinct values returned (clamped).
305
- */
306
- interface FacetGlobalColumnOptions {
307
- column: string;
308
- 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?: {
309
154
  limit?: number;
310
- table: string;
311
- }
312
- /** One distinct value of a faceted global column with its row count over the active view. */
313
- interface GlobalFacetValue {
314
- count: number;
315
- value: unknown;
316
- }
317
- /**
318
- * Payload of a {@link facetGlobalColumn} call: the top-N distinct `values` (each
319
- * with a `count`) ordered by frequency, plus `truncated` — `true` when more
320
- * distinct values existed beyond the cap, so the UI can say so rather than imply
321
- * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
322
- */
323
- interface GlobalFacetResult {
324
- truncated: boolean;
325
- values: GlobalFacetValue[];
326
- }
155
+ sinceSeq?: number;
156
+ }) => ReturnType<typeof readSqlCdcChanges>;
327
157
  /**
328
- * List every browsable D1 table with its row count, ordered by name. Surfaces
329
- * both the schema's `.global()` tables (provisioned first) and external tables
330
- * (auth, etc.); internal/companion tables are excluded.
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.
331
165
  */
166
+ declare const sweepD1CdcRetention: (exec: SqlCtxExec, retentionMs: number, now: number) => Promise<void>;
167
+ /** Every browsable D1 table with its row count (schema `.global()` tables provisioned first). */
332
168
  declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promise<GlobalTableInfo[]>;
333
- /**
334
- * Read a page of rows from one D1 table. The table is validated against the live
335
- * browsable-table list before its name is interpolated, so this can't be coerced
336
- * into reading an internal table or injecting SQL. `limit` is clamped to
337
- * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
338
- * matching each `column = value` eq constraint (a facet-value drill-down), bound
339
- * through {@link buildEqPredicate} so they never inject SQL.
340
- */
169
+ /** One page of a D1 table's rows, eq-filtered. */
341
170
  declare const readGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
342
- /**
343
- * Summarise the distinct values of one displayed column over the **active view**
344
- * (the same eq `filters` the global browser is previewing) — the D1 twin of the
345
- * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
346
- * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
347
- * against the table's displayed columns (typed 404 if unknown), mapped to its
348
- * physical column, and quoted — never interpolated from caller input. The extra
349
- * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
350
- * an external (non-schema) table is never grouped — it collapses to a single
351
- * redacted `•••` bucket — mirroring the page browser's value redaction so the
352
- * facet can't leak credentials. The returned `value` is the raw stored scalar, so
353
- * a click feeds it straight back as an eq filter.
354
- *
355
- * The payload is wire-encoded on the way out, like the page read's rows: a BLOB
356
- * column's stored value is bytes, and `Response.json` flattens those to `{}` —
357
- * which is not a display glitch but a broken drill-down, since the flattened
358
- * value is what the click sends back as the filter. `needsWireEncoding` leaves a
359
- * facet over an ordinary text/numeric column untouched.
360
- */
171
+ /** The distinct values of one D1 column over the active view. */
361
172
  declare const facetGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
362
173
  interface Migration {
363
174
  /** Human-readable name, e.g. `001_init` (used in logs). */
@@ -545,4 +356,4 @@ declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlC
545
356
  * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
546
357
  */
547
358
  declare const sqliteDialect: SqlDialect;
548
- export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, 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, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, selectGlobalTables, sqliteDialect, sweepD1CdcRetention, withD1Retry };
359
+ export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
package/dist/index.d.ts CHANGED
@@ -1,128 +1,14 @@
1
1
  import { SchemaLike, DatabaseWriterLike } from '@lunora/shard-engine';
2
2
  export { applyCdcChanges } from '@lunora/shard-engine';
3
- import { SqlCtxDbOptions, SqlCtxExec, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, SqlDialect } from '@lunora/sql-store';
4
- export { type SqlCtxExec as D1Exec, type SqlCtxDbOptions, type SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
3
+ import { SqlCtxExec, ExportGlobalArgs, ExportRow, ImportGlobalArgs, ImportResult, SqlCtxDbOptions, SqlSearchBackfillResult, createSqlCtxDb, readSqlCdcChanges, 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
5
  import { D1DatabaseLike, D1SessionLike, D1PreparedStatementLike } from '@lunora/platform';
6
6
  export type { D1DatabaseLike, D1PreparedStatementLike, D1SessionLike } from '@lunora/platform';
7
7
  import { BatchItem, BatchResponse } from 'drizzle-orm/batch';
8
8
  import { DrizzleD1Database } from 'drizzle-orm/d1';
9
- /** The D1 store options — the shared store options minus `dialect` (the SQLite dialect is injected for you). */
10
- type D1ContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect">;
11
- /** Build a D1-backed `.global()` writer (the shared store core bound to the SQLite dialect). */
12
- declare const createD1ContextDatabase: (options: D1ContextDatabaseOptions) => ReturnType<typeof createSqlCtxDb>;
13
- /** Auto-provision the schema's `.global()` tables in D1 (idempotent `CREATE TABLE IF NOT EXISTS`). */
14
- declare const runD1GlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
15
- /** Materialize the `__agg_<index>` companion tables for the schema's aggregate indexes. */
16
- declare const runD1AggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
17
- /** Materialize the `__rank_<index>` companion tables for the schema's rank indexes. */
18
- declare const runD1RankMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
19
- /** Materialize (and backfill) the `__fts_<index>` fts5 shadow tables for the schema's search indexes. */
20
- declare const runD1SearchMigrations: (exec: SqlCtxExec, schema: SchemaLike) => Promise<void>;
21
- /** Index existing rows into every search companion, including the `staged: true` ones migrations leave empty. */
22
- declare const backfillD1SearchIndexes: (exec: SqlCtxExec, schema: SchemaLike) => Promise<SqlSearchBackfillResult>;
23
- /** Create the `__cdc_log` table in D1 (idempotent; only run when CDC is enabled). */
24
- declare const runD1CdcMigration: (exec: SqlCtxExec) => Promise<void>;
25
- /** Read changelog entries newer than `sinceSeq` in commit order. */
26
- declare const readD1CdcChanges: (exec: SqlCtxExec, options?: {
27
- limit?: number;
28
- sinceSeq?: number;
29
- }) => ReturnType<typeof readSqlCdcChanges>;
30
- /**
31
- * Delete `.global()` changelog entries older than `retentionMs`, if this writer
32
- * wins the fleet's sweep lease. See `sweepSqlCdcRetention`.
33
- *
34
- * Replaces the seq-based `trimD1CdcChanges`, which took a checkpoint no caller
35
- * could compute: the log is shared across every shard and region, so no single
36
- * caller knows a `seq` that is safe for all of them. A time window is a bound
37
- * they can all reason about, and the lease is what stops them racing.
38
- */
39
- declare const sweepD1CdcRetention: (exec: SqlCtxExec, retentionMs: number, now: number) => Promise<void>;
40
- /** One exported row: `doc` is reconstructed from the column tuple. */
41
- interface ExportRow {
42
- doc: Record<string, unknown>;
43
- /**
44
- * True physical source line, when the caller has it (e.g. a global row
45
- * pulled out of an interspersed NDJSON import stream by
46
- * `@lunora/runtime`'s `import-stream.ts`). When present this overrides the
47
- * position-derived line below — the caller-side positions of a
48
- * global-only subset don't line up with the original file once
49
- * non-global rows have been filtered out. Absent for callers with no
50
- * physical source to attribute (e.g. a fresh `exportGlobalRows` roundtrip
51
- * in tests), which keeps the positional fallback.
52
- */
53
- line?: number;
54
- table: string;
55
- }
56
- interface ImportError {
57
- code: string;
58
- line: number;
59
- message: string;
60
- table: string;
61
- }
62
- interface ImportResult {
63
- /** Skipped rows whose `_id` already exists. */
64
- conflicts: number;
65
- errors: ImportError[];
66
- inserted: Record<string, number>;
67
- }
68
- /**
69
- * Return every `.global()` table in the schema, optionally narrowed by an
70
- * allowlist. Shard-local tables are skipped here — they're handled by the DO
71
- * helpers — so callers get a clean separation between the two storage planes.
72
- */
73
- declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
74
- interface ExportGlobalArgs {
75
- batchSize?: number;
76
- tables?: ReadonlyArray<string>;
77
- }
78
- /**
79
- * Yield rows from every requested `.global()` table in batches.
80
- *
81
- * Keyset-paginates on the physical primary key (`id` — every `.global()` table
82
- * carries it, see `frameworkColumnDdl`): `WHERE "id" > ? ORDER BY "id" LIMIT ?`,
83
- * carrying the last id forward. A plain `LIMIT/OFFSET` scan would be wrong here —
84
- * SQLite gives no ordering guarantee for an unordered SELECT and each page is a
85
- * separate query, so pages could overlap or skip rows (and any concurrent
86
- * insert/delete would shift offsets and silently drop/duplicate rows in the
87
- * snapshot). Keyset paging is deterministic under concurrent writes and avoids
88
- * O(n^2) OFFSET scans on large tables.
89
- *
90
- * Tables are provisioned first (idempotent `CREATE … IF NOT EXISTS`): `.global()`
91
- * tables are created lazily on first write, so a fresh deployment — or any table
92
- * never written — would otherwise abort the stream with a raw `no such table`
93
- * instead of exporting it as empty.
94
- */
9
+ /** Yield every requested D1 `.global()` table's rows, keyset-paged; never-written tables export empty. */
95
10
  declare const exportGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
96
- interface ImportGlobalArgs {
97
- /**
98
- * Check the rows and report their shape errors, writing nothing. The conflict
99
- * probe and the insert are skipped, so an `_id` already in use and a foreign-key
100
- * or unique failure are only found by a real import.
101
- */
102
- dryRun?: boolean;
103
- /**
104
- * Optional direct exec handle to the same D1 database the writer targets.
105
- * When supplied, the conflict pre-probe issues a single
106
- * `SELECT 1 FROM <table> WHERE id = ? LIMIT 1` against the row's declared
107
- * table instead of falling back to an unscoped id probe, which scans every
108
- * global table looking for the id. Strongly recommended for large schemas
109
- * — the writer-fallback is O(N tables) per row.
110
- */
111
- exec?: D1ExecLike;
112
- rows: ReadonlyArray<ExportRow>;
113
- startLine?: number;
114
- }
115
- /** Minimal slice of `D1Exec` (declared locally to avoid a circular import). */
116
- interface D1ExecLike {
117
- all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
118
- }
119
- /**
120
- * Import rows into `.global()` tables via the schema-aware D1 writer. The
121
- * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
122
- * absent); we pre-probe each row's `_id` so a collision is reported as a
123
- * conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
124
- * `errors`; the rest land.
125
- */
11
+ /** Insert snapshot rows into D1 `.global()` tables; an existing `_id` is a conflict left unchanged unless `args.onConflict` is `"replace"`, which overwrites it. */
126
12
  declare const importGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportGlobalArgs) => Promise<ImportResult>;
127
13
  /**
128
14
  * Thin wrapper over a `D1DatabaseSession` exposing bookmark plumbing.
@@ -247,117 +133,42 @@ declare class D1Client {
247
133
  /** Direct access to the underlying binding (advanced use only). */
248
134
  get raw(): D1DatabaseLike;
249
135
  }
250
- /** A table plus its current row count. */
251
- interface GlobalTableInfo {
252
- name: string;
253
- rowCount: number;
254
- }
255
- /** A window of rows from one table, plus the column list and total size. */
256
- interface GlobalTablePage {
257
- columns: string[];
258
- /**
259
- * Foreign-key columns (local column → referenced table) for tables that carry
260
- * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
261
- * Schema `.global()` tables omit this (their refs come from `describeTables`);
262
- * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
263
- * schema diagram can draw their global→global FK edges.
264
- */
265
- refs?: Record<string, string>;
266
- rows: Record<string, unknown>[];
267
- total: number;
268
- }
269
- /**
270
- * One equality constraint a facet-value click adds to the global browser's view:
271
- * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
272
- * displayed column name, validated against the table's columns and mapped to its
273
- * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
274
- * value** the facet returned (a SQLite scalar — including a BLOB, which reaches
275
- * here as bytes because the facet payload is wire-encoded), normalised by
276
- * {@link sqliteEncode} and bound as a parameter, never interpolated.
277
- * AND-combined with the other clauses.
278
- *
279
- * Only `eq` is compiled on this path. `operator` and `path` exist so that a
280
- * request asking for anything else is refused by {@link buildEqPredicate} rather
281
- * than read as an equality: a `has` or `contains` clause matched as `= ?` would
282
- * return rows the caller did not ask for.
283
- */
284
- interface GlobalFilterClause {
285
- column: string;
286
- /** Must be absent or `"eq"`; any other operator is refused. */
287
- operator?: string;
288
- /** Must be absent or empty; a nested path is refused (D1 columns are physical). */
289
- path?: string[];
290
- value: unknown;
291
- }
292
- interface ReadGlobalTablePageOptions {
293
- filters?: GlobalFilterClause[];
294
- limit?: number;
295
- offset?: number;
296
- table: string;
297
- }
298
- /**
299
- * Options for {@link facetGlobalColumn} — the read-only "what values does this
300
- * column hold?" summary for the global (D1) browser. `column` is the displayed
301
- * column to group by (validated and mapped to its physical column, never
302
- * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
303
- * constraints so the facet reflects the **active view** (the same rows the
304
- * browser is previewing); `limit` caps the distinct values returned (clamped).
305
- */
306
- interface FacetGlobalColumnOptions {
307
- column: string;
308
- 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?: {
309
154
  limit?: number;
310
- table: string;
311
- }
312
- /** One distinct value of a faceted global column with its row count over the active view. */
313
- interface GlobalFacetValue {
314
- count: number;
315
- value: unknown;
316
- }
317
- /**
318
- * Payload of a {@link facetGlobalColumn} call: the top-N distinct `values` (each
319
- * with a `count`) ordered by frequency, plus `truncated` — `true` when more
320
- * distinct values existed beyond the cap, so the UI can say so rather than imply
321
- * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
322
- */
323
- interface GlobalFacetResult {
324
- truncated: boolean;
325
- values: GlobalFacetValue[];
326
- }
155
+ sinceSeq?: number;
156
+ }) => ReturnType<typeof readSqlCdcChanges>;
327
157
  /**
328
- * List every browsable D1 table with its row count, ordered by name. Surfaces
329
- * both the schema's `.global()` tables (provisioned first) and external tables
330
- * (auth, etc.); internal/companion tables are excluded.
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.
331
165
  */
166
+ declare const sweepD1CdcRetention: (exec: SqlCtxExec, retentionMs: number, now: number) => Promise<void>;
167
+ /** Every browsable D1 table with its row count (schema `.global()` tables provisioned first). */
332
168
  declare const listGlobalTables: (exec: SqlCtxExec, schema: SchemaLike) => Promise<GlobalTableInfo[]>;
333
- /**
334
- * Read a page of rows from one D1 table. The table is validated against the live
335
- * browsable-table list before its name is interpolated, so this can't be coerced
336
- * into reading an internal table or injecting SQL. `limit` is clamped to
337
- * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
338
- * matching each `column = value` eq constraint (a facet-value drill-down), bound
339
- * through {@link buildEqPredicate} so they never inject SQL.
340
- */
169
+ /** One page of a D1 table's rows, eq-filtered. */
341
170
  declare const readGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
342
- /**
343
- * Summarise the distinct values of one displayed column over the **active view**
344
- * (the same eq `filters` the global browser is previewing) — the D1 twin of the
345
- * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
346
- * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
347
- * against the table's displayed columns (typed 404 if unknown), mapped to its
348
- * physical column, and quoted — never interpolated from caller input. The extra
349
- * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
350
- * an external (non-schema) table is never grouped — it collapses to a single
351
- * redacted `•••` bucket — mirroring the page browser's value redaction so the
352
- * facet can't leak credentials. The returned `value` is the raw stored scalar, so
353
- * a click feeds it straight back as an eq filter.
354
- *
355
- * The payload is wire-encoded on the way out, like the page read's rows: a BLOB
356
- * column's stored value is bytes, and `Response.json` flattens those to `{}` —
357
- * which is not a display glitch but a broken drill-down, since the flattened
358
- * value is what the click sends back as the filter. `needsWireEncoding` leaves a
359
- * facet over an ordinary text/numeric column untouched.
360
- */
171
+ /** The distinct values of one D1 column over the active view. */
361
172
  declare const facetGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
362
173
  interface Migration {
363
174
  /** Human-readable name, e.g. `001_init` (used in logs). */
@@ -545,4 +356,4 @@ declare const retryingExec: (exec: SqlCtxExec, options?: D1RetryOptions) => SqlC
545
356
  * the store core runs `sqliteEncode`/`sqliteDecode` on every engine.
546
357
  */
547
358
  declare const sqliteDialect: SqlDialect;
548
- export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, 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, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, selectGlobalTables, sqliteDialect, sweepD1CdcRetention, withD1Retry };
359
+ export { D1Client, type D1ContextDatabaseOptions as D1CtxDbOptions, type D1QueryCost, type D1RetryOptions, D1Session, D1TimeoutError, type Migration, MigrationRunner, type MigrationRunnerResult, backfillD1SearchIndexes, createD1ContextDatabase as createD1CtxDb, d1QueryTag, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, isTransientD1Error, listGlobalTables, readD1CdcChanges, readD1QueryCost, readGlobalTablePage, retryingExec, runD1AggregateMigrations, runD1CdcMigration, runD1GlobalTableMigrations, runD1RankMigrations, runD1SearchMigrations, sqliteDialect, sweepD1CdcRetention, withD1Retry };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportGlobalRows as o,importGlobalRows as t,selectGlobalTables as a}from"./packem_shared/exportGlobalRows-DDJVMV7O.mjs";import{D1Client as i,D1Session as n}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as D,createD1CtxDb as p,readD1CdcChanges as x,runD1AggregateMigrations as b,runD1CdcMigration as g,runD1GlobalTableMigrations as m,runD1RankMigrations as c,runD1SearchMigrations as f,sweepD1CdcRetention as u}from"./packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs";import{facetGlobalColumn as d,listGlobalTables as G,readGlobalTablePage as T}from"./packem_shared/facetGlobalColumn-wc_bLv00.mjs";import{MigrationRunner as M}from"./packem_shared/MigrationRunner-DADTo9Q8.mjs";import{d1QueryTag as h,emitD1QueryCost as w,readD1QueryCost as S}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as Q,isTransientD1Error as k,retryingExec as q,withD1Retry as A}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{default as P}from"./packem_shared/sqliteDialect-B_3JNtdq.mjs";import{applyCdcChanges as v}from"@lunora/shard-engine";import{createSqlCtxDb as B}from"@lunora/sql-store";export{i as D1Client,n as D1Session,Q as D1TimeoutError,M as MigrationRunner,v as applyCdcChanges,D as backfillD1SearchIndexes,p as createD1CtxDb,B as createSqlCtxDb,h as d1QueryTag,w as emitD1QueryCost,o as exportGlobalRows,d as facetGlobalColumn,t as importGlobalRows,k as isTransientD1Error,G as listGlobalTables,x as readD1CdcChanges,S as readD1QueryCost,T as readGlobalTablePage,q as retryingExec,b as runD1AggregateMigrations,g as runD1CdcMigration,m as runD1GlobalTableMigrations,c as runD1RankMigrations,f as runD1SearchMigrations,a as selectGlobalTables,P as sqliteDialect,u as sweepD1CdcRetention,A as withD1Retry};
1
+ import{exportGlobalRows as o,importGlobalRows as t}from"./packem_shared/exportGlobalRows-IncHgv-p.mjs";import{D1Client as l,D1Session as i}from"./packem_shared/D1Client-CzS0Qfa6.mjs";import{backfillD1SearchIndexes as s,createD1CtxDb as D,readD1CdcChanges as p,runD1AggregateMigrations as x,runD1CdcMigration as b,runD1GlobalTableMigrations as g,runD1RankMigrations as m,runD1SearchMigrations as c,sweepD1CdcRetention as f}from"./packem_shared/backfillD1SearchIndexes-BHgn1SNb.mjs";import{facetGlobalColumn as C,listGlobalTables as d,readGlobalTablePage as G}from"./packem_shared/facetGlobalColumn-BqK1_P3S.mjs";import{MigrationRunner as y}from"./packem_shared/MigrationRunner-DADTo9Q8.mjs";import{d1QueryTag as R,emitD1QueryCost as h,readD1QueryCost as w}from"./packem_shared/d1QueryTag-BcEGW4q1.mjs";import{D1TimeoutError as E,isTransientD1Error as Q,retryingExec as k,withD1Retry as q}from"./packem_shared/D1TimeoutError-D4YUqZPk.mjs";import{default as I}from"./packem_shared/sqliteDialect-B_3JNtdq.mjs";import{applyCdcChanges as j}from"@lunora/shard-engine";import{createSqlCtxDb as z,selectGlobalTables as B}from"@lunora/sql-store";export{l as D1Client,i as D1Session,E as D1TimeoutError,y as MigrationRunner,j as applyCdcChanges,s as backfillD1SearchIndexes,D as createD1CtxDb,z as createSqlCtxDb,R as d1QueryTag,h as emitD1QueryCost,o as exportGlobalRows,C as facetGlobalColumn,t as importGlobalRows,Q as isTransientD1Error,d as listGlobalTables,p as readD1CdcChanges,w as readD1QueryCost,G as readGlobalTablePage,k as retryingExec,x as runD1AggregateMigrations,b as runD1CdcMigration,g as runD1GlobalTableMigrations,m as runD1RankMigrations,c as runD1SearchMigrations,B as selectGlobalTables,I as sqliteDialect,f as sweepD1CdcRetention,q as withD1Retry};
@@ -0,0 +1 @@
1
+ import{exportSqlGlobalRows as e,importSqlGlobalRows as s}from"@lunora/sql-store";import{selectGlobalTables as c}from"@lunora/sql-store";import r from"./sqliteDialect-B_3JNtdq.mjs";const m=(o,l,t)=>e(o,l,r,t),b=(o,l,t)=>s(o,l,r,t);export{m as exportGlobalRows,b as importGlobalRows,c as selectGlobalTables};
@@ -0,0 +1 @@
1
+ import{facetSqlGlobalColumn as t,listSqlGlobalTables as b,readSqlGlobalTablePage as s}from"@lunora/sql-store";import e from"./sqliteDialect-B_3JNtdq.mjs";const i=(l,a)=>b(l,a,e),m=(l,a,o)=>s(l,a,e,o),G=(l,a,o)=>t(l,a,e,o);export{G as facetGlobalColumn,i as listGlobalTables,m as readGlobalTablePage};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/d1",
3
- "version": "1.0.0-alpha.213",
3
+ "version": "1.0.0-alpha.214",
4
4
  "description": "D1 adapter for Lunora .global() tables, wrapping the Sessions API for read-your-writes",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -52,9 +52,8 @@
52
52
  "dependencies": {
53
53
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
54
54
  "@lunora/platform": "1.0.0-alpha.75",
55
- "@lunora/shard-engine": "1.0.0-alpha.165",
56
- "@lunora/sql-store": "1.0.0-alpha.214",
57
- "@lunora/wire": "1.0.0-alpha.3",
55
+ "@lunora/shard-engine": "1.0.0-alpha.167",
56
+ "@lunora/sql-store": "1.0.0-alpha.215",
58
57
  "drizzle-orm": "1.0.0-rc.5"
59
58
  },
60
59
  "engines": {
@@ -1 +0,0 @@
1
- import{toErrorBody as p}from"@lunora/errors";import{needsWireEncoding as E,encodeWire as m,decodeWire as R}from"@lunora/wire";import{runD1GlobalTableMigrations as w}from"./backfillD1SearchIndexes-BHgn1SNb.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import{decodeGlobalRow as g}from"@lunora/sql-store";const k=200,O=(r,t)=>{const e=o=>r.tables[o]?.shardMode?.kind==="global";return t&&t.length>0?t.filter(o=>e(o)):Object.keys(r.tables).filter(o=>e(o))},h=(r,t,e)=>{const o=r.tables[t];return o?g(o,e):{_creationTime:e._creationTime,_id:e.id}},y=r=>E(r)?m(r):r,F=async function*(r,t,e){const o=O(t,e.tables),i=e.batchSize??k;await w(r,t);for(const s of o){const n=b(s);let c,l=!0;for(;l;){const a=c===void 0?await r.all(`SELECT * FROM ${n} ORDER BY "id" LIMIT ?`,[i]):await r.all(`SELECT * FROM ${n} WHERE "id" > ? ORDER BY "id" LIMIT ?`,[c,i]);for(const f of a)yield{doc:y(h(t,s,f)),table:s};const d=a.at(-1);d!==void 0&&(c=String(d.id)),l=a.length===i}}},u=r=>r?._meta?.column?.notNull===!1,I=(r,t)=>{const e=new Set;for(const[o,i]of Object.entries(r.shape)){if(t[o]!==null||i.kind!=="optional"||u(i))continue;const s=i._meta?.inner;u(s)||e.add(o)}return e.size===0?t:Object.fromEntries(Object.entries(t).filter(([o])=>!e.has(o)))},T=new Set(["_creationTime","_id"]),_=(r,t)=>Object.keys(t).find(e=>!T.has(e)&&!Object.hasOwn(r.shape,e)),S=(r,t,e)=>{const o=r.tables[t];if(!o)return`unknown table: ${t}`;const i=_(o,e);if(i!==void 0)return`unexpected field "${i}": not declared in table "${t}"`;for(const[s,n]of Object.entries(o.shape)){const c=e[s],l=n.kind==="optional";if(c===void 0&&l)continue;const a=n.parse;if(typeof a=="function")try{a(c)}catch(d){const f=d instanceof Error?d.message:String(d);return`field "${s}": ${f}`}}},v=async(r,t,e,o)=>{try{return t?(await t.all(`SELECT 1 AS hit FROM ${b(e)} WHERE "id" = ? LIMIT 1`,[o])).length>0:await r.get(e,o)!==null}catch{return!1}},A=async(r,t,e,o,i)=>{const{doc:s,table:n}=o;if(typeof n!="string"||n.length===0)return{error:{code:"BAD_ROW",line:i,message:"row is missing `table`",table:n},kind:"error"};if(t.tables[n]?.shardMode?.kind!=="global")return{kind:"skip"};if(!s||typeof s!="object"||Array.isArray(s))return{error:{code:"BAD_ROW",line:i,message:"row is missing or malformed `doc`",table:n},kind:"error"};let c;try{c=R(s)}catch(d){return{error:{code:"BAD_ROW",line:i,message:d instanceof Error?d.message:String(d),table:n},kind:"error"}}c=I(t.tables[n],c);const l=S(t,n,c);if(l!==void 0)return{error:{code:"VALIDATION_ERROR",line:i,message:l,table:n},kind:"error"};if(e.dryRun===!0)return{kind:"checked"};const a=typeof c._id=="string"?c._id:void 0;if(a!==void 0&&await v(r,e.exec,n,a))return{kind:"conflict"};try{return await r.insert(n,c,{allowExplicitId:!0}),{inserted:n,kind:"inserted"}}catch(d){const{body:f}=p(d,{fallbackCode:"INSERT_FAILED"});return{error:{code:f.code,line:i,message:f.message,table:n},kind:"error"}}},$=async(r,t,e)=>{const o=[],i={};let s=0,n=(e.startLine??1)-1;for(const c of e.rows){n+=1;const l=c.line??n,a=await A(r,t,e,c,l);switch(a.kind){case"conflict":{s+=1;break}case"error":{o.push(a.error);break}case"inserted":{i[a.inserted]=(i[a.inserted]??0)+1;break}}}return{conflicts:s,errors:o,inserted:i}};export{F as exportGlobalRows,$ as importGlobalRows,O as selectGlobalTables};
@@ -1 +0,0 @@
1
- import{LunoraError as d}from"@lunora/errors";import{isInternalTableName as U}from"@lunora/shard-engine";import{sqliteDecode as B,effectiveColumnKind as q,decodeGlobalRow as G,sqliteEncode as N}from"@lunora/sql-store";import{needsWireEncoding as _,encodeWire as R}from"@lunora/wire";import{runD1GlobalTableMigrations as M}from"./backfillD1SearchIndexes-BHgn1SNb.mjs";import{TRACKING_TABLE_NAME as P}from"./MigrationRunner-DADTo9Q8.mjs";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";const F=50,k=500,K=30,W=200,$=(t,o,n)=>Math.min(Math.max(t,o),n),X=t=>U(t)||t.startsWith("d1_")||t===P,v=/password|secret|token|hash|salt|credential/iu,u=(t,o)=>{const n=t.tables[o];return n?.shardMode?.kind==="global"?n:void 0},y=async t=>(await t.all("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name",[])).map(n=>String(n.name)).filter(n=>!X(n)),O=async(t,o,n)=>{if(await M(t,o),!(await y(t)).includes(n))throw new d("UNKNOWN_TABLE",`unknown table: ${n}`,{status:404})},A=async(t,o,n="",e=[])=>{const r=await t.all(`SELECT COUNT(*) AS c FROM ${o}${n}`,e);return Number(r[0]?.c??0)},C=(t,o,n)=>u(t,o)!==void 0&&n==="_id"?"id":n,I=(t,o,n)=>{const e=u(t,o)?.shape[n];return e===void 0?void 0:q(e)},Y=/^-?\d+$/u,S=100,h=(t,o)=>{if(o>S)throw new d("BAD_REQUEST",`the query over ${t} binds ${String(o)} parameters, and a statement takes at most ${String(S)} — remove some filters`)},j=(t,o)=>{if(o!=="bigint")return N(t);const n=typeof t=="number"||typeof t=="string"?String(t).trim():void 0;return N(n!==void 0&&Y.test(n)?BigInt(n):t,o)},Q=t=>{if(t.operator!==void 0&&t.operator!=="eq")throw new d("BAD_REQUEST",`operator "${t.operator}" is not supported on the global browser — only eq is`);if(t.path!==void 0&&!(Array.isArray(t.path)&&t.path.length===0))throw new d("BAD_REQUEST",`a nested path is not supported on the global browser, so ${t.column} must be a top-level column`)},L=(t,o,n,e)=>{const r=[],a=[];for(const s of e??[]){if(Q(s),!n.includes(s.column))throw new d("UNKNOWN_COLUMN",`unknown column: ${s.column}`,{status:404});if(u(t,o)===void 0&&v.test(s.column))throw new d("FORBIDDEN",`cannot filter on a redacted column: ${s.column}`,{status:403});const i=l(C(t,o,s.column));s.value===null||s.value===void 0?r.push(`${i} IS NULL`):(r.push(`${i} = ?`),a.push(j(s.value,I(t,o,s.column))))}return{params:a,where:r.length>0?` WHERE ${r.join(" AND ")}`:""}},H=(t,o,n)=>{const e=u(t,o);if(e)return G(e,n);const r={};for(const[a,s]of Object.entries(n))r[a]=s!=null&&v.test(a)?"•••":s;return r},D=async(t,o,n)=>{const e=u(o,n);return e?["_id","_creationTime",...Object.keys(e.shape)]:(await t.all(`PRAGMA table_info(${l(n)})`,[])).map(a=>String(a.name))},V=async(t,o,n)=>{if(u(o,n))return;const e=await t.all(`PRAGMA foreign_key_list(${l(n)})`,[]);if(e.length===0)return;const r={};for(const a of e){const s=String(a.from),i=String(a.table);r[s]??=i}return r},rt=async(t,o)=>{await M(t,o);const n=await y(t);return Promise.all(n.map(async e=>({name:e,rowCount:await A(t,l(e))})))},Z=async(t,o,n,e)=>{if(u(o,n)!==void 0)return l("id");const a=(await t.all(`PRAGMA table_info(${l(n)})`,[])).filter(s=>Number(s.pk??0)>0);return a.length===1?l(String(a[0]?.name)):e.includes("id")?l("id"):"rowid"},st=async(t,o,n)=>{const{table:e}=n;await O(t,o,e);const r=$(Math.trunc(n.limit??F),1,k),a=Math.max(0,Math.trunc(n.offset??0)),s=l(e),i=await D(t,o,e),{params:m,where:w}=L(o,e,i,n.filters);h(e,m.length+2);const f=await A(t,s,w,m),E=await Z(t,o,e,i),b=(await t.all(`SELECT * FROM ${s}${w} ORDER BY ${E} LIMIT ? OFFSET ?`,[...m,r,a])).map(p=>{const c=H(o,e,p);return _(c)?R(c):c}),T=await V(t,o,e);return T===void 0?{columns:i,rows:b,total:f}:{columns:i,refs:T,rows:b,total:f}},at=async(t,o,n)=>{const{column:e,table:r}=n;await O(t,o,r);const a=await D(t,o,r);if(!a.includes(e))throw new d("UNKNOWN_COLUMN",`unknown column: ${e}`,{status:404});const s=l(r),{params:i,where:m}=L(o,r,a,n.filters);if(h(r,i.length),u(o,r)===void 0&&v.test(e)){const c=await A(t,s,m,i);return{truncated:!1,values:c===0?[]:[{count:c,value:"•••"}]}}const w=$(Math.trunc(n.limit??K),1,W);h(r,i.length+1);const f=l(C(o,r,e)),E=await t.all(`SELECT ${f} AS value, COUNT(*) AS count FROM ${s}${m} GROUP BY ${f} ORDER BY count DESC, ${f} ASC LIMIT ?`,[...i,w+1]),g=E.length>w,b=g?E.slice(0,w):E,T=I(o,r,e)==="bigint",p=b.map(c=>({count:Number(c.count),value:T?B(c.value,"bigint"):c.value}));return{truncated:g,values:_(p)?R(p):p}};export{at as facetGlobalColumn,rt as listGlobalTables,st as readGlobalTablePage};