@lunora/sql-store 1.0.0-alpha.6 → 1.0.0-alpha.61

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,121 +1,133 @@
1
- import { ServerDefaultContextLike, DatabaseWriterLike, SchedulerLike, SchemaLike, TableDefinitionLike, ValidatorLike } from '@lunora/do';
2
- import { SqlDialect, SqlRunResult } from "./dialect.mjs";
1
+ import { TableDefinitionLike, SchemaLike, ServerDefaultContextLike, DatabaseWriterLike, SchedulerLike, ValidatorLike } from '@lunora/shard-engine';
2
+ import { SqlRunResult, SqlDialect } from "./dialect.mjs";
3
3
  export type { SqlExec } from "./dialect.mjs";
4
4
  import 'drizzle-orm';
5
5
  /**
6
- * Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
7
- * Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
8
- * adapter in tests, so the query logic runs against a real SQLite engine.
9
- */
6
+ * Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
7
+ * Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
8
+ * adapter in tests, so the query logic runs against a real SQLite engine.
9
+ */
10
10
  interface SqlCtxExec {
11
11
  all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
12
+ batch?: (statements: ReadonlyArray<{
13
+ params: ReadonlyArray<unknown>;
14
+ sql: string;
15
+ }>) => Promise<void>;
12
16
  run: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<SqlRunResult | void>;
13
17
  }
18
+ /**
19
+ * Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
20
+ * preserved, and every column run through the shared {@link sqliteDecode} so the
21
+ * stored form is reversed back into its JS shape. Exported so the data-browser
22
+ * (`introspect.ts`) and admin export/import paths share the exact same decode.
23
+ *
24
+ * The decode is engine-agnostic: every backend stores SQLite-shaped values
25
+ * (boolean → 1/0, JSON → text, bigint → decimal string), and `sqliteDecode` is
26
+ * robust to a driver returning either the stored string OR a natively-parsed
27
+ * value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
28
+ * correct on SQLite, Postgres and MySQL.
29
+ */
30
+ declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
31
+ /**
32
+ * Provision the search companions, then index one bounded page of the rows that
33
+ * predate each index — unless it is declared `staged: true`, which leaves the
34
+ * whole backfill to {@link backfillSqlSearchIndexes}.
35
+ *
36
+ * Idempotent (`CREATE … IF NOT EXISTS` throughout, and the backfill resumes
37
+ * from recorded progress).
38
+ */
39
+ declare const runSqlSearchMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
40
+ /**
41
+ * Run every declared search index — including the `staged: true` ones the
42
+ * migration pass skips — through to completion. The entry point a host calls
43
+ * out-of-band after deploying a search index over a table too large to index a
44
+ * page at a time.
45
+ *
46
+ * Idempotent and resumable: an index recorded as complete is skipped, and an
47
+ * interrupted run picks up from its cursor.
48
+ */
49
+ declare const backfillSqlSearchIndexes: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
14
50
  interface SqlCtxDbOptions {
15
51
  /**
16
- * Resolved request auth handed to `.serverDefault(fn)` column factories so
17
- * server-trusted columns (owner/tenant ids) stamp from the verified caller,
18
- * never the client. The generated worker passes the per-request identity;
19
- * absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
20
- */
52
+ * Resolved request auth handed to `.serverDefault(fn)` column factories so
53
+ * server-trusted columns (owner/tenant ids) stamp from the verified caller,
54
+ * never the client. The generated worker passes the per-request identity;
55
+ * absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
56
+ */
21
57
  auth?: ServerDefaultContextLike["auth"];
22
58
  /**
23
- * Opt into change-data-capture: when `true`, every committed write appends a
24
- * post-image to the `__cdc_log` table (created lazily alongside the other
25
- * companion tables). Backs CDC streaming export for `.global()` tables — the
26
- * log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
27
- * the platform's own Time Travel (`wrangler d1 time-travel restore`), an
28
- * atomic restore, not a changelog replay. Leave undefined for zero-cost
29
- * legacy behaviour.
30
- */
59
+ * Opt into change-data-capture: when `true`, every committed write appends a
60
+ * post-image to the `__cdc_log` table (created lazily alongside the other
61
+ * companion tables). Backs CDC streaming export for `.global()` tables — the
62
+ * log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
63
+ * the platform's own Time Travel (`wrangler d1 time-travel restore`), an
64
+ * atomic restore, not a changelog replay. Leave undefined for zero-cost
65
+ * legacy behaviour.
66
+ */
31
67
  cdc?: boolean;
32
68
  clock?: () => number;
33
69
  /**
34
- * Cross-shard counter for **reverse cross-backend relations** — the `_count`
35
- * mirror of the `crossShardReader` option below.
36
- */
70
+ * Cross-shard counter for **reverse cross-backend relations** — the `_count`
71
+ * mirror of the `crossShardReader` option below.
72
+ */
37
73
  crossShardCounter?: DatabaseWriterLike["count"];
38
74
  /**
39
- * Optional cross-shard reader for **reverse cross-backend relations**: a
40
- * `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
41
- * Such a child's rows are partitioned across every shard DO, so the local D1
42
- * writer can't resolve it. When provided, the relation loader routes the
43
- * child's read through this (the host wires it to the Query Coordinator's
44
- * RLS-correct `fanOut`, with identity forwarded so each shard applies its own
45
- * RLS). Absent it, loading such a relation throws a clear "not supported"
46
- * error (legacy behaviour). The forward direction (shard-local parent →
47
- * global child) and same-backend relations never touch this.
48
- */
75
+ * Optional cross-shard reader for **reverse cross-backend relations**: a
76
+ * `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
77
+ * Such a child's rows are partitioned across every shard DO, so the local D1
78
+ * writer can't resolve it. When provided, the relation loader routes the
79
+ * child's read through this (the host wires it to the Query Coordinator's
80
+ * RLS-correct `fanOut`, with identity forwarded so each shard applies its own
81
+ * RLS). Absent it, loading such a relation throws a clear "not supported"
82
+ * error (legacy behaviour). The forward direction (shard-local parent →
83
+ * global child) and same-backend relations never touch this.
84
+ */
49
85
  crossShardReader?: DatabaseWriterLike["findMany"];
50
86
  /**
51
- * The SQL dialect that shapes every statement (identifier quoting, value
52
- * encode/decode, column types, upserts, RETURNING vs affected-rows).
53
- * `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
54
- * passes its Postgres/MySQL dialect. Required — the core is engine-blind.
55
- */
87
+ * The SQL dialect that shapes every statement (identifier quoting, value
88
+ * encode/decode, column types, upserts, RETURNING vs affected-rows).
89
+ * `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
90
+ * passes its Postgres/MySQL dialect. Required — the core is engine-blind.
91
+ */
56
92
  dialect: SqlDialect;
57
93
  exec: SqlCtxExec;
58
94
  idGenerator?: () => string;
59
95
  /**
60
- * Ceiling on the number of child join keys a relation-crossing `where`
61
- * predicate may materialize before the semijoin pre-resolver fails closed
62
- * (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
63
- * push-down, so an overflow here can only fail closed — never truncate the
64
- * `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
65
- * key cap when omitted.
66
- */
96
+ * Ceiling on the number of child join keys a relation-crossing `where`
97
+ * predicate may materialize before the semijoin pre-resolver fails closed
98
+ * (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
99
+ * push-down, so an overflow here can only fail closed — never truncate the
100
+ * `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
101
+ * key cap when omitted.
102
+ */
67
103
  maxRelationKeys?: number;
68
104
  /**
69
- * Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
70
- * Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
71
- * triggers on `.global()` tables need to enqueue follow-up work.
72
- */
105
+ * Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
106
+ * Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
107
+ * triggers on `.global()` tables need to enqueue follow-up work.
108
+ */
73
109
  scheduler?: SchedulerLike;
74
110
  schema: SchemaLike;
75
111
  }
76
- /**
77
- * Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
78
- * preserved, and every column run through the shared {@link sqliteDecode} so the
79
- * stored form is reversed back into its JS shape. Exported so the data-browser
80
- * (`introspect.ts`) and admin export/import paths share the exact same decode.
81
- *
82
- * The decode is engine-agnostic: every backend stores SQLite-shaped values
83
- * (boolean → 1/0, JSON → text, bigint → decimal string), and `sqliteDecode` is
84
- * robust to a driver returning either the stored string OR a natively-parsed
85
- * value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
86
- * correct on SQLite, Postgres and MySQL.
87
- */
88
- declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
89
112
  declare const runSqlGlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
90
113
  /**
91
- * Materialize the `__agg_&lt;index>` companion tables for every declared
92
- * `aggregateIndex` on a global table. Global tables in Lunora ship their own
93
- * DDL — counter tables are opt-in so production hosts can decide where they
94
- * live. Tests and dev hosts can call this once after their schema migration to
95
- * unlock O(1) counts.
96
- *
97
- * Idempotent (`CREATE TABLE IF NOT EXISTS`).
98
- */
114
+ * Materialize the `__agg_&lt;index>` companion tables for every declared
115
+ * `aggregateIndex` on a global table. Global tables in Lunora ship their own
116
+ * DDL — counter tables are opt-in so production hosts can decide where they
117
+ * live. Tests and dev hosts can call this once after their schema migration to
118
+ * unlock O(1) counts.
119
+ *
120
+ * Idempotent (`CREATE TABLE IF NOT EXISTS`).
121
+ */
99
122
  declare const runSqlAggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
100
123
  /**
101
- * Materialize the `__rank_&lt;index>` companion tables for every declared
102
- * `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
103
- * opt-in pattern so production hosts decide whether to spend the DDL.
104
- *
105
- * Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
106
- */
124
+ * Materialize the `__rank_&lt;index>` companion tables for every declared
125
+ * `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
126
+ * opt-in pattern so production hosts decide whether to spend the DDL.
127
+ *
128
+ * Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
129
+ */
107
130
  declare const runSqlRankMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
108
- /**
109
- * Materialize the `__fts_&lt;index>` FTS5 shadow tables for every declared
110
- * `.searchIndex()` on a global table. Mirrors `runSqlAggregateMigrations` — same
111
- * opt-in pattern so production hosts decide whether to spend the DDL. Only runs
112
- * on engines that ship FTS5 (D1 does; the `node:sqlite` test runner doesn't,
113
- * where `.search()` transparently falls back to a scan). `__text__` holds the
114
- * indexed field; `__id__` (UNINDEXED) joins back to the row.
115
- *
116
- * Idempotent (`CREATE VIRTUAL TABLE IF NOT EXISTS`).
117
- */
118
- declare const runSqlSearchMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
119
131
  /** One change-data-capture entry: a committed mutation, in monotonic `seq` order. Mirrors the DO twin. */
120
132
  interface CdcChange {
121
133
  /** Post-image document for insert/update; absent for delete (the `id` identifies the removed row). */
@@ -131,9 +143,9 @@ interface CdcChange {
131
143
  /** Create the `__cdc_log` table. Idempotent; only run when CDC is enabled. */
132
144
  declare const runSqlCdcMigration: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
133
145
  /**
134
- * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
135
- * (clamped to [1, 10000]); plus the cursor to resume from.
136
- */
146
+ * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
147
+ * (clamped to [1, 10000]); plus the cursor to resume from.
148
+ */
137
149
  declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
138
150
  limit?: number;
139
151
  sinceSeq?: number;
@@ -144,6 +156,10 @@ declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
144
156
  /** Drop changelog entries at or below a checkpointed `throughSeq` (retention). */
145
157
  declare const trimSqlCdcChanges: (exec: SqlCtxExec, throughSeq: number, dialect: SqlDialect) => Promise<void>;
146
158
  declare const createSqlCtxDb: (options: SqlCtxDbOptions) => DatabaseWriterLike;
159
+ /** Reserved table holding one backfill-progress row per search companion. */
160
+ declare const SEARCH_STATE_TABLE = "__lunora_search_state";
161
+ /** Create the progress table. Idempotent; runs alongside the companion DDL. */
162
+ declare const migrateSearchState: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
147
163
  /** Map a JS value onto its SQLite storage form — SQLite has no boolean, so true/false → 1/0. */
148
164
  declare const sqliteEncode: (value: unknown) => unknown;
149
165
  /** Parse `raw` as JSON, returning `raw` unchanged when it is not valid JSON. */
@@ -151,24 +167,35 @@ declare const tryJsonParse: (raw: string) => unknown;
151
167
  /** Decode a `bigint` column: a decimal string back into a `BigInt`, else verbatim. */
152
168
  declare const decodeBigint: (raw: unknown) => unknown;
153
169
  /**
154
- * Resolve the *effective* storage kind of a column validator. Encoding keys off
155
- * the runtime value's JS type, so a `v.optional(inner)` column stores its
156
- * present value exactly as `inner` would. The validator's own `kind` is
157
- * `"optional"`, which hides that — unwrap to the inner validator's kind so the
158
- * decode reverses the real storage form. The inner validator is stashed on
159
- * `_meta.inner` by `@lunora/values`' `createValidator`.
160
- */
170
+ * Resolve the *effective* storage kind of a column validator. Encoding keys off
171
+ * the runtime value's JS type, so a `v.optional(inner)` column stores its
172
+ * present value exactly as `inner` would. The validator's own `kind` is
173
+ * `"optional"`, which hides that — unwrap to the inner validator's kind so the
174
+ * decode reverses the real storage form. The inner validator is stashed on
175
+ * `_meta.inner` by `@lunora/values`' `createValidator`.
176
+ */
161
177
  declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefined;
162
178
  /**
163
- * Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
164
- * form, driven by the field's effective validator `kind`:
165
- *
166
- * - `boolean`: 1/0 → true/false (SQLite has no boolean type).
167
- * - `bigint`: decimal string → `BigInt`.
168
- * - `object`/`array`/`record`: JSON string → parsed value.
169
- * - `union`/`any`: parsed back only when the stored string is a JSON non-scalar
170
- * (a scalar union member round-trips through SQLite's native column type).
171
- * - everything else (string/number/date/timestamp/id/literal): verbatim.
172
- */
179
+ * Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
180
+ * form, driven by the field's effective validator `kind`:
181
+ *
182
+ * - `boolean`: 1/0 → true/false (SQLite has no boolean type).
183
+ * - `bigint`: decimal string → `BigInt`.
184
+ * - `object`/`array`/`record`: JSON string → parsed value.
185
+ * - `union`/`any`/`from`: parsed back only when the stored string is a JSON
186
+ * non-scalar (a scalar member round-trips through SQLite's native column type).
187
+ * `from` belongs to THIS group, not to `object`/`array`/`record`: an external
188
+ * Standard Schema can describe a string just as easily as an object, and
189
+ * {@link sqliteEncode} keys off the runtime JS type — so a `v.from(z.string())`
190
+ * column holding `"123"` is stored verbatim, and unconditional parsing would
191
+ * read it back as the NUMBER 123.
192
+ * CAVEAT: a union/any/from member is stored verbatim by {@link sqliteEncode}, so
193
+ * a legitimate *string* value that itself looks like JSON (`'{"a":1}'`, `'[1,2]'`)
194
+ * is ambiguous on read and decodes back to the parsed object/array, not the
195
+ * original string. This is inherent to sharing one TEXT column between a string
196
+ * and an object member; disambiguating would require a breaking storage-format
197
+ * change (tagging encoded non-scalars), so it is documented rather than fixed.
198
+ * - everything else (string/number/date/timestamp/id/literal): verbatim.
199
+ */
173
200
  declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
174
- export { type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, trimSqlCdcChanges, tryJsonParse };
201
+ export { SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, migrateSearchState, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, trimSqlCdcChanges, tryJsonParse };
package/dist/index.d.ts CHANGED
@@ -1,121 +1,133 @@
1
- import { ServerDefaultContextLike, DatabaseWriterLike, SchedulerLike, SchemaLike, TableDefinitionLike, ValidatorLike } from '@lunora/do';
2
- import { SqlDialect, SqlRunResult } from "./dialect.js";
1
+ import { TableDefinitionLike, SchemaLike, ServerDefaultContextLike, DatabaseWriterLike, SchedulerLike, ValidatorLike } from '@lunora/shard-engine';
2
+ import { SqlRunResult, SqlDialect } from "./dialect.js";
3
3
  export type { SqlExec } from "./dialect.js";
4
4
  import 'drizzle-orm';
5
5
  /**
6
- * Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
7
- * Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
8
- * adapter in tests, so the query logic runs against a real SQLite engine.
9
- */
6
+ * Async SQL surface the D1 ORM needs: `all` for reads, `run` for writes.
7
+ * Satisfied by a `D1Session`/`D1Client` in production and a `node:sqlite`
8
+ * adapter in tests, so the query logic runs against a real SQLite engine.
9
+ */
10
10
  interface SqlCtxExec {
11
11
  all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
12
+ batch?: (statements: ReadonlyArray<{
13
+ params: ReadonlyArray<unknown>;
14
+ sql: string;
15
+ }>) => Promise<void>;
12
16
  run: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<SqlRunResult | void>;
13
17
  }
18
+ /**
19
+ * Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
20
+ * preserved, and every column run through the shared {@link sqliteDecode} so the
21
+ * stored form is reversed back into its JS shape. Exported so the data-browser
22
+ * (`introspect.ts`) and admin export/import paths share the exact same decode.
23
+ *
24
+ * The decode is engine-agnostic: every backend stores SQLite-shaped values
25
+ * (boolean → 1/0, JSON → text, bigint → decimal string), and `sqliteDecode` is
26
+ * robust to a driver returning either the stored string OR a natively-parsed
27
+ * value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
28
+ * correct on SQLite, Postgres and MySQL.
29
+ */
30
+ declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
31
+ /**
32
+ * Provision the search companions, then index one bounded page of the rows that
33
+ * predate each index — unless it is declared `staged: true`, which leaves the
34
+ * whole backfill to {@link backfillSqlSearchIndexes}.
35
+ *
36
+ * Idempotent (`CREATE … IF NOT EXISTS` throughout, and the backfill resumes
37
+ * from recorded progress).
38
+ */
39
+ declare const runSqlSearchMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
40
+ /**
41
+ * Run every declared search index — including the `staged: true` ones the
42
+ * migration pass skips — through to completion. The entry point a host calls
43
+ * out-of-band after deploying a search index over a table too large to index a
44
+ * page at a time.
45
+ *
46
+ * Idempotent and resumable: an index recorded as complete is skipped, and an
47
+ * interrupted run picks up from its cursor.
48
+ */
49
+ declare const backfillSqlSearchIndexes: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
14
50
  interface SqlCtxDbOptions {
15
51
  /**
16
- * Resolved request auth handed to `.serverDefault(fn)` column factories so
17
- * server-trusted columns (owner/tenant ids) stamp from the verified caller,
18
- * never the client. The generated worker passes the per-request identity;
19
- * absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
20
- */
52
+ * Resolved request auth handed to `.serverDefault(fn)` column factories so
53
+ * server-trusted columns (owner/tenant ids) stamp from the verified caller,
54
+ * never the client. The generated worker passes the per-request identity;
55
+ * absent it, server-trusted columns stamp the anonymous slice (`userId: null`).
56
+ */
21
57
  auth?: ServerDefaultContextLike["auth"];
22
58
  /**
23
- * Opt into change-data-capture: when `true`, every committed write appends a
24
- * post-image to the `__cdc_log` table (created lazily alongside the other
25
- * companion tables). Backs CDC streaming export for `.global()` tables — the
26
- * log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
27
- * the platform's own Time Travel (`wrangler d1 time-travel restore`), an
28
- * atomic restore, not a changelog replay. Leave undefined for zero-cost
29
- * legacy behaviour.
30
- */
59
+ * Opt into change-data-capture: when `true`, every committed write appends a
60
+ * post-image to the `__cdc_log` table (created lazily alongside the other
61
+ * companion tables). Backs CDC streaming export for `.global()` tables — the
62
+ * log is for export/CDC consumers, NOT point-in-time recovery: D1's PITR is
63
+ * the platform's own Time Travel (`wrangler d1 time-travel restore`), an
64
+ * atomic restore, not a changelog replay. Leave undefined for zero-cost
65
+ * legacy behaviour.
66
+ */
31
67
  cdc?: boolean;
32
68
  clock?: () => number;
33
69
  /**
34
- * Cross-shard counter for **reverse cross-backend relations** — the `_count`
35
- * mirror of the `crossShardReader` option below.
36
- */
70
+ * Cross-shard counter for **reverse cross-backend relations** — the `_count`
71
+ * mirror of the `crossShardReader` option below.
72
+ */
37
73
  crossShardCounter?: DatabaseWriterLike["count"];
38
74
  /**
39
- * Optional cross-shard reader for **reverse cross-backend relations**: a
40
- * `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
41
- * Such a child's rows are partitioned across every shard DO, so the local D1
42
- * writer can't resolve it. When provided, the relation loader routes the
43
- * child's read through this (the host wires it to the Query Coordinator's
44
- * RLS-correct `fanOut`, with identity forwarded so each shard applies its own
45
- * RLS). Absent it, loading such a relation throws a clear "not supported"
46
- * error (legacy behaviour). The forward direction (shard-local parent →
47
- * global child) and same-backend relations never touch this.
48
- */
75
+ * Optional cross-shard reader for **reverse cross-backend relations**: a
76
+ * `.global()` (D1) parent loading a shard-local (`.shardBy()`/root) child.
77
+ * Such a child's rows are partitioned across every shard DO, so the local D1
78
+ * writer can't resolve it. When provided, the relation loader routes the
79
+ * child's read through this (the host wires it to the Query Coordinator's
80
+ * RLS-correct `fanOut`, with identity forwarded so each shard applies its own
81
+ * RLS). Absent it, loading such a relation throws a clear "not supported"
82
+ * error (legacy behaviour). The forward direction (shard-local parent →
83
+ * global child) and same-backend relations never touch this.
84
+ */
49
85
  crossShardReader?: DatabaseWriterLike["findMany"];
50
86
  /**
51
- * The SQL dialect that shapes every statement (identifier quoting, value
52
- * encode/decode, column types, upserts, RETURNING vs affected-rows).
53
- * `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
54
- * passes its Postgres/MySQL dialect. Required — the core is engine-blind.
55
- */
87
+ * The SQL dialect that shapes every statement (identifier quoting, value
88
+ * encode/decode, column types, upserts, RETURNING vs affected-rows).
89
+ * `@lunora/d1` passes its `sqliteDialect`; the PlanetScale/Hyperdrive backend
90
+ * passes its Postgres/MySQL dialect. Required — the core is engine-blind.
91
+ */
56
92
  dialect: SqlDialect;
57
93
  exec: SqlCtxExec;
58
94
  idGenerator?: () => string;
59
95
  /**
60
- * Ceiling on the number of child join keys a relation-crossing `where`
61
- * predicate may materialize before the semijoin pre-resolver fails closed
62
- * (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
63
- * push-down, so an overflow here can only fail closed — never truncate the
64
- * `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
65
- * key cap when omitted.
66
- */
96
+ * Ceiling on the number of child join keys a relation-crossing `where`
97
+ * predicate may materialize before the semijoin pre-resolver fails closed
98
+ * (`relation predicate … exceeding the N-key limit`). D1 has no EXISTS
99
+ * push-down, so an overflow here can only fail closed — never truncate the
100
+ * `IN (...)` and silently mis-match. Defaults to the pre-resolver's shared
101
+ * key cap when omitted.
102
+ */
67
103
  maxRelationKeys?: number;
68
104
  /**
69
- * Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
70
- * Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
71
- * triggers on `.global()` tables need to enqueue follow-up work.
72
- */
105
+ * Scheduler exposed to global-table trigger handlers as `ctx.scheduler`.
106
+ * Absent it, `ctx.scheduler` is a stub that throws on use — pass one when
107
+ * triggers on `.global()` tables need to enqueue follow-up work.
108
+ */
73
109
  scheduler?: SchedulerLike;
74
110
  schema: SchemaLike;
75
111
  }
76
- /**
77
- * Decode a SELECTed row back into a document: `id` → `_id`, `_creationTime`
78
- * preserved, and every column run through the shared {@link sqliteDecode} so the
79
- * stored form is reversed back into its JS shape. Exported so the data-browser
80
- * (`introspect.ts`) and admin export/import paths share the exact same decode.
81
- *
82
- * The decode is engine-agnostic: every backend stores SQLite-shaped values
83
- * (boolean → 1/0, JSON → text, bigint → decimal string), and `sqliteDecode` is
84
- * robust to a driver returning either the stored string OR a natively-parsed
85
- * value (e.g. mysql2 returns JSON columns pre-parsed) — so the same decoder is
86
- * correct on SQLite, Postgres and MySQL.
87
- */
88
- declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
89
112
  declare const runSqlGlobalTableMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
90
113
  /**
91
- * Materialize the `__agg_&lt;index>` companion tables for every declared
92
- * `aggregateIndex` on a global table. Global tables in Lunora ship their own
93
- * DDL — counter tables are opt-in so production hosts can decide where they
94
- * live. Tests and dev hosts can call this once after their schema migration to
95
- * unlock O(1) counts.
96
- *
97
- * Idempotent (`CREATE TABLE IF NOT EXISTS`).
98
- */
114
+ * Materialize the `__agg_&lt;index>` companion tables for every declared
115
+ * `aggregateIndex` on a global table. Global tables in Lunora ship their own
116
+ * DDL — counter tables are opt-in so production hosts can decide where they
117
+ * live. Tests and dev hosts can call this once after their schema migration to
118
+ * unlock O(1) counts.
119
+ *
120
+ * Idempotent (`CREATE TABLE IF NOT EXISTS`).
121
+ */
99
122
  declare const runSqlAggregateMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
100
123
  /**
101
- * Materialize the `__rank_&lt;index>` companion tables for every declared
102
- * `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
103
- * opt-in pattern so production hosts decide whether to spend the DDL.
104
- *
105
- * Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
106
- */
124
+ * Materialize the `__rank_&lt;index>` companion tables for every declared
125
+ * `rankIndex` on a global table. Mirrors `runSqlAggregateMigrations` — same
126
+ * opt-in pattern so production hosts decide whether to spend the DDL.
127
+ *
128
+ * Idempotent (`CREATE TABLE IF NOT EXISTS` + `createIndexIfNotExists`).
129
+ */
107
130
  declare const runSqlRankMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
108
- /**
109
- * Materialize the `__fts_&lt;index>` FTS5 shadow tables for every declared
110
- * `.searchIndex()` on a global table. Mirrors `runSqlAggregateMigrations` — same
111
- * opt-in pattern so production hosts decide whether to spend the DDL. Only runs
112
- * on engines that ship FTS5 (D1 does; the `node:sqlite` test runner doesn't,
113
- * where `.search()` transparently falls back to a scan). `__text__` holds the
114
- * indexed field; `__id__` (UNINDEXED) joins back to the row.
115
- *
116
- * Idempotent (`CREATE VIRTUAL TABLE IF NOT EXISTS`).
117
- */
118
- declare const runSqlSearchMigrations: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<void>;
119
131
  /** One change-data-capture entry: a committed mutation, in monotonic `seq` order. Mirrors the DO twin. */
120
132
  interface CdcChange {
121
133
  /** Post-image document for insert/update; absent for delete (the `id` identifies the removed row). */
@@ -131,9 +143,9 @@ interface CdcChange {
131
143
  /** Create the `__cdc_log` table. Idempotent; only run when CDC is enabled. */
132
144
  declare const runSqlCdcMigration: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
133
145
  /**
134
- * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
135
- * (clamped to [1, 10000]); plus the cursor to resume from.
136
- */
146
+ * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
147
+ * (clamped to [1, 10000]); plus the cursor to resume from.
148
+ */
137
149
  declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
138
150
  limit?: number;
139
151
  sinceSeq?: number;
@@ -144,6 +156,10 @@ declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
144
156
  /** Drop changelog entries at or below a checkpointed `throughSeq` (retention). */
145
157
  declare const trimSqlCdcChanges: (exec: SqlCtxExec, throughSeq: number, dialect: SqlDialect) => Promise<void>;
146
158
  declare const createSqlCtxDb: (options: SqlCtxDbOptions) => DatabaseWriterLike;
159
+ /** Reserved table holding one backfill-progress row per search companion. */
160
+ declare const SEARCH_STATE_TABLE = "__lunora_search_state";
161
+ /** Create the progress table. Idempotent; runs alongside the companion DDL. */
162
+ declare const migrateSearchState: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
147
163
  /** Map a JS value onto its SQLite storage form — SQLite has no boolean, so true/false → 1/0. */
148
164
  declare const sqliteEncode: (value: unknown) => unknown;
149
165
  /** Parse `raw` as JSON, returning `raw` unchanged when it is not valid JSON. */
@@ -151,24 +167,35 @@ declare const tryJsonParse: (raw: string) => unknown;
151
167
  /** Decode a `bigint` column: a decimal string back into a `BigInt`, else verbatim. */
152
168
  declare const decodeBigint: (raw: unknown) => unknown;
153
169
  /**
154
- * Resolve the *effective* storage kind of a column validator. Encoding keys off
155
- * the runtime value's JS type, so a `v.optional(inner)` column stores its
156
- * present value exactly as `inner` would. The validator's own `kind` is
157
- * `"optional"`, which hides that — unwrap to the inner validator's kind so the
158
- * decode reverses the real storage form. The inner validator is stashed on
159
- * `_meta.inner` by `@lunora/values`' `createValidator`.
160
- */
170
+ * Resolve the *effective* storage kind of a column validator. Encoding keys off
171
+ * the runtime value's JS type, so a `v.optional(inner)` column stores its
172
+ * present value exactly as `inner` would. The validator's own `kind` is
173
+ * `"optional"`, which hides that — unwrap to the inner validator's kind so the
174
+ * decode reverses the real storage form. The inner validator is stashed on
175
+ * `_meta.inner` by `@lunora/values`' `createValidator`.
176
+ */
161
177
  declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefined;
162
178
  /**
163
- * Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
164
- * form, driven by the field's effective validator `kind`:
165
- *
166
- * - `boolean`: 1/0 → true/false (SQLite has no boolean type).
167
- * - `bigint`: decimal string → `BigInt`.
168
- * - `object`/`array`/`record`: JSON string → parsed value.
169
- * - `union`/`any`: parsed back only when the stored string is a JSON non-scalar
170
- * (a scalar union member round-trips through SQLite's native column type).
171
- * - everything else (string/number/date/timestamp/id/literal): verbatim.
172
- */
179
+ * Inverse of {@link sqliteEncode}: map a SQLite storage value back onto its JS
180
+ * form, driven by the field's effective validator `kind`:
181
+ *
182
+ * - `boolean`: 1/0 → true/false (SQLite has no boolean type).
183
+ * - `bigint`: decimal string → `BigInt`.
184
+ * - `object`/`array`/`record`: JSON string → parsed value.
185
+ * - `union`/`any`/`from`: parsed back only when the stored string is a JSON
186
+ * non-scalar (a scalar member round-trips through SQLite's native column type).
187
+ * `from` belongs to THIS group, not to `object`/`array`/`record`: an external
188
+ * Standard Schema can describe a string just as easily as an object, and
189
+ * {@link sqliteEncode} keys off the runtime JS type — so a `v.from(z.string())`
190
+ * column holding `"123"` is stored verbatim, and unconditional parsing would
191
+ * read it back as the NUMBER 123.
192
+ * CAVEAT: a union/any/from member is stored verbatim by {@link sqliteEncode}, so
193
+ * a legitimate *string* value that itself looks like JSON (`'{"a":1}'`, `'[1,2]'`)
194
+ * is ambiguous on read and decodes back to the parsed object/array, not the
195
+ * original string. This is inherent to sharing one TEXT column between a string
196
+ * and an object member; disambiguating would require a breaking storage-format
197
+ * change (tagging encoded non-scalars), so it is documented rather than fixed.
198
+ * - everything else (string/number/date/timestamp/id/literal): verbatim.
199
+ */
173
200
  declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
174
- export { type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, trimSqlCdcChanges, tryJsonParse };
201
+ export { SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, migrateSearchState, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, trimSqlCdcChanges, tryJsonParse };
package/dist/index.mjs CHANGED
@@ -1,2 +1 @@
1
- export { createSqlCtxDb, decodeGlobalRow, readSqlCdcChanges, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, trimSqlCdcChanges } from './packem_shared/createSqlCtxDb-DYqDyPq8.mjs';
2
- export { decodeBigint, effectiveColumnKind, sqliteDecode, sqliteEncode, tryJsonParse } from './packem_shared/decodeBigint-Dedu92k4.mjs';
1
+ import{createSqlCtxDb as o,readSqlCdcChanges as a,runSqlAggregateMigrations as t,runSqlCdcMigration as i,runSqlGlobalTableMigrations as l,runSqlRankMigrations as n,trimSqlCdcChanges as S}from"./packem_shared/createSqlCtxDb-f3EuqB_7.mjs";import{A as s,B as d}from"./packem_shared/ctx-db-search-BtMzaLPK.mjs";import{SEARCH_STATE_TABLE as q,migrateSearchState as f}from"./packem_shared/SEARCH_STATE_TABLE-CCP41ykz.mjs";import{decodeBigint as C,effectiveColumnKind as x,sqliteDecode as u,sqliteEncode as b,tryJsonParse as h}from"./packem_shared/decodeBigint-C8KbFPjD.mjs";import{decodeGlobalRow as A}from"./packem_shared/decodeGlobalRow-C3kYJHSB.mjs";export{q as SEARCH_STATE_TABLE,s as backfillSqlSearchIndexes,o as createSqlCtxDb,C as decodeBigint,A as decodeGlobalRow,x as effectiveColumnKind,f as migrateSearchState,a as readSqlCdcChanges,t as runSqlAggregateMigrations,i as runSqlCdcMigration,l as runSqlGlobalTableMigrations,n as runSqlRankMigrations,d as runSqlSearchMigrations,u as sqliteDecode,b as sqliteEncode,S as trimSqlCdcChanges,h as tryJsonParse};
@@ -0,0 +1 @@
1
+ import{sql as i}from"drizzle-orm";import{queryRun as $,queryAll as E}from"./decodeGlobalRow-C3kYJHSB.mjs";const a="__lunora_search_state",T=async(e,r)=>{const{integer:n,key:t}=r.companionTypes,o=async()=>{try{await $(e,r,i`ALTER TABLE ${i.identifier(a)} ADD COLUMN ${i.identifier("profile")} ${i.raw(t)}`)}catch{}};await $(e,r,i`CREATE TABLE IF NOT EXISTS ${i.identifier(a)} (${i.identifier("companion")} ${i.raw(t)} PRIMARY KEY, ${i.identifier("cursor")} ${i.raw(t)}, ${i.identifier("done")} ${i.raw(n)} NOT NULL DEFAULT 0, ${i.identifier("profile")} ${i.raw(t)})`),await o()},l=e=>e===1||e===!0||e==="1",S=async(e,r,n)=>{const t=(await E(e,r,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(a)} WHERE ${i.identifier("companion")} = ${n}`))[0];if(!t)return{cursor:void 0,done:!1,profile:void 0};const{cursor:o,profile:f}=t;return{cursor:typeof o=="string"?o:void 0,done:l(t.done),profile:typeof f=="string"?f:void 0}},w=async(e,r,n,t,o,f)=>{const d=t??null,c=i`UPDATE ${i.identifier(a)} SET ${i.identifier("cursor")} = ${d}, ${i.identifier("done")} = ${o?1:0}, ${i.identifier("profile")} = ${f} WHERE ${i.identifier("companion")} = ${n}`;if((await E(e,r,i`SELECT ${i.identifier("companion")} FROM ${i.identifier(a)} WHERE ${i.identifier("companion")} = ${n}`)).length>0){await $(e,r,c);return}try{await $(e,r,i`INSERT INTO ${i.identifier(a)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${n}, ${d}, ${o?1:0}, ${f})`)}catch(s){if(!r.isUniqueViolation(s))throw s;await $(e,r,c)}};export{a as SEARCH_STATE_TABLE,T as migrateSearchState,S as readSearchBackfillState,w as writeSearchBackfillState};
@@ -0,0 +1 @@
1
+ import{A as o,F as t,v as s,B as l}from"./ctx-db-search-BtMzaLPK.mjs";import"@lunora/errors";import"drizzle-orm";import"./SEARCH_STATE_TABLE-CCP41ykz.mjs";import"./decodeGlobalRow-C3kYJHSB.mjs";export{o as backfillSqlSearchIndexes,t as createSearchSync,s as runSqlSearch,l as runSqlSearchMigrations};