@jini-ai/db 0.7.2 → 0.7.3-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/CHANGELOG.md +1 -7
  2. package/README.md +33 -17
  3. package/dist/core/index.d.ts +1 -2
  4. package/dist/core/index.js +0 -1
  5. package/dist/core/pg-types.d.ts +4 -1
  6. package/dist/core/pg-types.js +1 -1
  7. package/dist/core/row-values.d.ts +0 -30
  8. package/dist/core/row-values.js +1 -41
  9. package/dist/data-modules/data-module.d.ts +260 -4
  10. package/dist/data-modules/data-module.js +105 -83
  11. package/dist/data-modules/disk-headroom.js +1 -1
  12. package/dist/data-modules/index.d.ts +2 -2
  13. package/dist/data-modules/index.js +2 -2
  14. package/dist/data-modules/migration-journal.js +6 -6
  15. package/dist/data-modules/migration-recovery.js +2 -2
  16. package/dist/data-modules/plugin-identity.js +5 -5
  17. package/dist/data-modules/plugin-store.d.ts +4 -4
  18. package/dist/data-modules/restore.js +5 -5
  19. package/dist/data-modules/snapshot.d.ts +1 -1
  20. package/dist/data-modules/snapshot.js +3 -3
  21. package/dist/events/change-set-repo.sql.d.ts +70 -0
  22. package/dist/events/change-set-repo.sql.js +72 -0
  23. package/dist/events/index.d.ts +4 -0
  24. package/dist/events/index.js +3 -0
  25. package/dist/events/outbox-repo.sql.d.ts +91 -0
  26. package/dist/events/outbox-repo.sql.js +108 -0
  27. package/dist/events/repo.rows.d.ts +44 -0
  28. package/dist/events/repo.rows.js +59 -0
  29. package/dist/gated-mutations/index.d.ts +3 -0
  30. package/dist/gated-mutations/index.js +2 -0
  31. package/dist/gated-mutations/repo.rows.d.ts +19 -0
  32. package/dist/gated-mutations/repo.rows.js +23 -0
  33. package/dist/gated-mutations/repo.sql.d.ts +67 -0
  34. package/dist/gated-mutations/repo.sql.js +71 -0
  35. package/dist/kernel/dialect.d.ts +53 -31
  36. package/dist/kernel/dialect.js +14 -36
  37. package/dist/kernel/index.d.ts +2 -2
  38. package/dist/kernel/index.js +1 -7
  39. package/dist/kernel/kernel-core.d.ts +7 -3
  40. package/dist/kernel/kernel-core.js +75 -66
  41. package/dist/kernel/ops.d.ts +9 -3
  42. package/dist/kernel/ops.js +2 -2
  43. package/dist/kernel/owned-transaction.d.ts +7 -7
  44. package/dist/kernel/owned-transaction.js +2 -2
  45. package/dist/kernel/pglite/driver.d.ts +2 -2
  46. package/dist/kernel/pglite/driver.js +18 -18
  47. package/dist/kernel/pglite/ops.d.ts +8 -3
  48. package/dist/kernel/pglite/ops.js +5 -5
  49. package/dist/kernel/port.d.ts +9 -76
  50. package/dist/kernel/port.js +1 -10
  51. package/dist/kernel/postgres/driver.d.ts +4 -2
  52. package/dist/kernel/postgres/driver.js +17 -17
  53. package/dist/kernel/postgres/ops.d.ts +5 -3
  54. package/dist/kernel/postgres/ops.js +3 -3
  55. package/dist/kernel/postgres/pglite-socket.d.ts +2 -2
  56. package/dist/kernel/postgres/pglite-socket.js +13 -13
  57. package/dist/kernel/schema-scope.d.ts +5 -2
  58. package/dist/kernel/schema-scope.js +1 -1
  59. package/dist/kernel/schema-shape.d.ts +7 -3
  60. package/dist/kernel/schema-shape.js +2 -2
  61. package/dist/kernel/session-lock.d.ts +6 -6
  62. package/dist/kernel/sqlite/driver.d.ts +16 -8
  63. package/dist/kernel/sqlite/driver.js +38 -38
  64. package/dist/kernel/sqlite/index.d.ts +1 -0
  65. package/dist/kernel/sqlite/index.js +1 -0
  66. package/dist/kernel/sqlite/ops.d.ts +4 -2
  67. package/dist/kernel/sqlite/ops.js +3 -3
  68. package/dist/kernel/sqlite/sqlite-only.d.ts +81 -0
  69. package/dist/kernel/sqlite/sqlite-only.js +58 -0
  70. package/dist/kernel/store-copy.d.ts +7 -7
  71. package/dist/kernel/store-copy.js +22 -14
  72. package/dist/kernel/typegen.d.ts +5 -3
  73. package/dist/kernel/typegen.js +1 -1
  74. package/dist/migrate/checksum.d.ts +3 -1
  75. package/dist/migrate/checksum.js +1 -1
  76. package/dist/migrate/index.d.ts +1 -1
  77. package/dist/migrate/legacy-ledger.d.ts +4 -4
  78. package/dist/migrate/runner.d.ts +12 -7
  79. package/dist/migrate/runner.js +7 -6
  80. package/dist/migrate/step.d.ts +3 -28
  81. package/dist/migrate/step.js +3 -3
  82. package/dist/owner-store/index.d.ts +47 -1
  83. package/dist/owner-store/index.js +28 -1
  84. package/dist/owner-store/migrations/0000_owner_store.d.ts +3 -2
  85. package/dist/owner-store/migrations/index.d.ts +1 -1
  86. package/dist/pglite/owner.d.ts +12 -4
  87. package/dist/pglite/owner.js +33 -27
  88. package/dist/pglite/socket-server.d.ts +5 -1
  89. package/dist/pglite/socket-server.js +5 -4
  90. package/dist/recovery/deep-link.d.ts +3 -3
  91. package/dist/recovery/degraded-banners.d.ts +3 -3
  92. package/dist/recovery/degraded-banners.js +3 -3
  93. package/dist/recovery/disclosure.d.ts +6 -6
  94. package/dist/recovery/disclosure.js +6 -6
  95. package/dist/recovery/evaluate-boot-migration-policy.d.ts +5 -5
  96. package/dist/recovery/evaluate-boot-migration-policy.js +5 -5
  97. package/dist/recovery/lookup-adapters.d.ts +1 -1
  98. package/dist/recovery/lookup-adapters.js +1 -1
  99. package/dist/recovery/migrate-forward-execute.d.ts +1 -1
  100. package/dist/recovery/migrate-forward-execute.js +5 -5
  101. package/dist/recovery/migrate-forward-hooks.d.ts +6 -6
  102. package/dist/recovery/migrate-forward-hooks.js +5 -5
  103. package/dist/recovery/operation-lock.d.ts +11 -11
  104. package/dist/recovery/operation-lock.js +3 -3
  105. package/dist/recovery/reconcile-interrupted-migration.d.ts +7 -7
  106. package/dist/recovery/reconcile-interrupted-migration.js +7 -7
  107. package/dist/recovery/recovery-orchestrator.d.ts +21 -21
  108. package/dist/recovery/recovery-orchestrator.js +9 -9
  109. package/dist/recovery/restore-hooks.d.ts +8 -8
  110. package/dist/recovery/restore-hooks.js +7 -7
  111. package/dist/recovery/restore-point-create.d.ts +3 -3
  112. package/dist/secrets-vault/repo.sql.d.ts +3 -3
  113. package/dist/secrets-vault/repo.sql.js +5 -4
  114. package/dist/settings/index.d.ts +3 -0
  115. package/dist/settings/index.js +2 -0
  116. package/dist/settings/repo.rows.d.ts +117 -0
  117. package/dist/settings/repo.rows.js +106 -0
  118. package/dist/settings/repo.sql.d.ts +99 -0
  119. package/dist/settings/repo.sql.js +219 -0
  120. package/dist/sqlite/checked-client.d.ts +1 -1
  121. package/dist/sqlite/checked-state.d.ts +3 -3
  122. package/dist/sqlite/db-ops.d.ts +1 -1
  123. package/dist/sqlite/db-ops.js +1 -1
  124. package/dist/sqlite/index.d.ts +1 -3
  125. package/dist/sqlite/index.js +2 -0
  126. package/dist/sqlite/inspect.d.ts +2 -2
  127. package/dist/sqlite/inspect.js +1 -1
  128. package/dist/sqlite/open.d.ts +1 -2
  129. package/dist/sqlite/stopped.d.ts +46 -0
  130. package/dist/sqlite/stopped.js +86 -0
  131. package/dist/sqlite/transaction.d.ts +2 -2
  132. package/dist/tools/database-catalog.d.ts +2 -2
  133. package/dist/tools/database-catalog.js +13 -3
  134. package/dist/tools/read-tools.js +70 -59
  135. package/dist/tools/restore-points.d.ts +1 -1
  136. package/dist/tools/transfer-tools.d.ts +0 -1
  137. package/dist/tools/transfer-tools.js +5 -4
  138. package/dist/transfer/copy-engine.js +10 -10
  139. package/dist/transfer/copy-order.d.ts +47 -0
  140. package/dist/transfer/copy-order.js +103 -0
  141. package/dist/transfer/index.d.ts +1 -0
  142. package/dist/transfer/index.js +1 -0
  143. package/dist/transfer/internal-ddl.d.ts +28 -6
  144. package/dist/transfer/internal-ddl.js +15 -15
  145. package/dist/transfer/postgres-ddl.js +6 -6
  146. package/dist/transfer/sqlite-source.d.ts +2 -3
  147. package/dist/transfer/sqlite-source.js +1 -1
  148. package/dist/verified-origin/index.d.ts +4 -0
  149. package/dist/verified-origin/index.js +3 -0
  150. package/dist/verified-origin/register.d.ts +43 -0
  151. package/dist/verified-origin/register.js +51 -0
  152. package/dist/verified-origin/repo.rows.d.ts +42 -0
  153. package/dist/verified-origin/repo.rows.js +47 -0
  154. package/dist/verified-origin/repo.sql.d.ts +67 -0
  155. package/dist/verified-origin/repo.sql.js +34 -0
  156. package/package.json +38 -11
  157. package/dist/sqlite/restore-types.d.ts +0 -46
  158. package/dist/sqlite/restore-types.js +0 -2
  159. package/dist/sqlite/sync-types.d.ts +0 -34
  160. package/dist/sqlite/sync-types.js +0 -2
  161. package/dist/sqlite/types.d.ts +0 -37
  162. package/dist/sqlite/types.js +0 -8
@@ -1,5 +1,6 @@
1
1
  import { type Expression, type RawBuilder } from "kysely";
2
- import type { StorageDialect, StorageKernel } from "./port.js";
2
+ import type { ColumnInfo, StorageDialect } from "@jini-ai/core/contracts/storage";
3
+ import type { KyselyKernel } from "./port.js";
3
4
  /**
4
5
  * @file Dialect helpers: the few places SQLite and Postgres spell the same thing differently, as
5
6
  * Kysely `sql` fragments or kernel queries. A repo that needs one of these calls the helper with
@@ -16,7 +17,7 @@ import type { StorageDialect, StorageKernel } from "./port.js";
16
17
  * @complexity O(n) time and space in DDL length, plus the database's execution cost.
17
18
  */
18
19
  export declare function executeDdl({ kernel, ddl }: {
19
- kernel: StorageKernel<unknown>;
20
+ kernel: KyselyKernel<unknown>;
20
21
  ddl: string;
21
22
  }, _options?: {}): Promise<void>;
22
23
  /**
@@ -27,7 +28,11 @@ export declare function executeDdl({ kernel, ddl }: {
27
28
  * Not for objects or arrays (each dialect prints those differently), nor for fractional numbers
28
29
  * whose spelling matters (`1.50` reads `1.50` on Postgres, `1.5` on SQLite).
29
30
  */
30
- export declare function jsonText(dialect: StorageDialect, column: Expression<unknown>, path: readonly string[]): RawBuilder<string | null>;
31
+ export declare function jsonText({ dialect, column, path }: {
32
+ dialect: StorageDialect;
33
+ column: Expression<unknown>;
34
+ path: readonly string[];
35
+ }, _optional?: Record<string, never>): RawBuilder<string | null>;
31
36
  /**
32
37
  * `column` at `path` equals the JSON scalar `value` (string, number or boolean), as a boolean
33
38
  * expression. SQLite has no JSON boolean type — `json_extract` reads `true`/`false` as `1`/`0` — so
@@ -35,43 +40,50 @@ export declare function jsonText(dialect: StorageDialect, column: Expression<unk
35
40
  * Postgres compares the two `jsonb` values, so `10` matches
36
41
  * `10.0` and a string never matches a number.
37
42
  */
38
- export declare function jsonScalarEquals(dialect: StorageDialect, column: Expression<unknown>, path: readonly string[], value: string | number | boolean): RawBuilder<boolean>;
43
+ export declare function jsonScalarEquals({ dialect, column, path, value }: {
44
+ dialect: StorageDialect;
45
+ column: Expression<unknown>;
46
+ path: readonly string[];
47
+ value: string | number | boolean;
48
+ }, _optional?: Record<string, never>): RawBuilder<boolean>;
39
49
  /**
40
50
  * A sort key for the value at `path`: SQLite's typed `json_extract`, Postgres' `jsonb` value, so
41
51
  * numbers sort as numbers (`9` before `10`) — unlike {@link jsonText}, whose text sorts `'10'` first.
42
52
  * A missing key is SQL NULL on both; pair with `nullsFirst()` (asc) / `nullsLast()` (desc) so NULLs
43
53
  * land where SQLite puts them by default.
44
54
  */
45
- export declare function jsonSortKey(dialect: StorageDialect, column: Expression<unknown>, path: readonly string[]): RawBuilder<unknown>;
55
+ export declare function jsonSortKey({ dialect, column, path }: {
56
+ dialect: StorageDialect;
57
+ column: Expression<unknown>;
58
+ path: readonly string[];
59
+ }, _optional?: Record<string, never>): RawBuilder<unknown>;
46
60
  /**
47
61
  * The column's JSON with `path` set to `value` (any JSON-serialisable value), creating the last key
48
62
  * if it is missing. A NULL column counts as `{}`. The parent object must already exist.
49
63
  */
50
- export declare function jsonSet(dialect: StorageDialect, column: Expression<unknown>, path: readonly string[], value: unknown): RawBuilder<string>;
64
+ export declare function jsonSet({ dialect, column, path, value }: {
65
+ dialect: StorageDialect;
66
+ column: Expression<unknown>;
67
+ path: readonly string[];
68
+ value: unknown;
69
+ }, _optional?: Record<string, never>): RawBuilder<string>;
51
70
  /** The statement's current time as `Date#toISOString()` text (UTC, milliseconds, `Z`). */
52
- export declare function nowIso(dialect: StorageDialect): RawBuilder<string>;
53
- /** A boolean column as read: `true`/`false` on Postgres, `1`/`0` on SQLite. NULL stays null. */
54
- export declare function toBool(value: boolean | number | null | undefined): boolean | null;
55
- /**
56
- * True iff `err` is a UNIQUE violation, from any driver: SQLite's `SQLITE_CONSTRAINT_UNIQUE` /
57
- * "UNIQUE constraint failed", Postgres SQLSTATE `23505` (node-postgres and PGlite both set `code`).
58
- * The message check also covers the in-memory test doubles, which throw SQLite's wording.
59
- */
60
- export declare function isUniqueViolation(err: unknown): boolean;
61
- /** A blob/bytea value as bytes, whichever shape the driver returned (Buffer, Uint8Array). */
62
- export declare function toBytes(value: unknown): Uint8Array;
63
- export interface ColumnInfo {
64
- name: string;
65
- /** The declared type, lower-case, in the dialect's own spelling (`text`, `integer`, `bigint`…). */
66
- type: string;
67
- notNull: boolean;
68
- primaryKey: boolean;
69
- }
71
+ export declare function nowIso({ dialect }: {
72
+ dialect: StorageDialect;
73
+ }, _optional?: Record<string, never>): RawBuilder<string>;
70
74
  /** User tables in the connection's current schema, sorted by name. Internal tables excluded. */
71
- export declare function listTables<DB>(kernel: StorageKernel<DB>): Promise<string[]>;
72
- export declare function tableExists<DB>(kernel: StorageKernel<DB>, table: string): Promise<boolean>;
75
+ export declare function listTables<DB>({ kernel }: {
76
+ kernel: KyselyKernel<DB>;
77
+ }, _optional?: Record<string, never>): Promise<string[]>;
78
+ export declare function tableExists<DB>({ kernel, table }: {
79
+ kernel: KyselyKernel<DB>;
80
+ table: string;
81
+ }, _optional?: Record<string, never>): Promise<boolean>;
73
82
  /** Columns in declaration order; empty when the table does not exist. */
74
- export declare function listColumns<DB>(kernel: StorageKernel<DB>, table: string): Promise<ColumnInfo[]>;
83
+ export declare function listColumns<DB>({ kernel, table }: {
84
+ kernel: KyselyKernel<DB>;
85
+ table: string;
86
+ }, _optional?: Record<string, never>): Promise<ColumnInfo[]>;
75
87
  /** The four SQLite storage classes a portable column declares (plugin data modules use these). */
76
88
  export type ColumnAffinity = "TEXT" | "INTEGER" | "REAL" | "BLOB";
77
89
  /**
@@ -79,15 +91,22 @@ export type ColumnAffinity = "TEXT" | "INTEGER" | "REAL" | "BLOB";
79
91
  * table created here reads back exactly as before; Postgres gets the same mapping as the frozen
80
92
  * Postgres baseline. Lower-cased, it is also what {@link listColumns} reports for that column.
81
93
  */
82
- export declare function columnTypeSql(dialect: StorageDialect, affinity: ColumnAffinity): string;
94
+ export declare function columnTypeSql({ dialect, affinity }: {
95
+ dialect: StorageDialect;
96
+ affinity: ColumnAffinity;
97
+ }, _optional?: Record<string, never>): string;
83
98
  /** A generated integer primary key column's type and constraints (write the column name before it). */
84
- export declare function autoIdColumnSql(dialect: StorageDialect): string;
99
+ export declare function autoIdColumnSql({ dialect }: {
100
+ dialect: StorageDialect;
101
+ }, _optional?: Record<string, never>): string;
85
102
  /**
86
103
  * Makes everything committed so far durable in the main database file. SQLite: a full WAL
87
104
  * checkpoint (must run outside a write transaction on this connection: SQLite refuses it with
88
105
  * "database table is locked"). Postgres: nothing to do, a commit is already durable.
89
106
  */
90
- export declare function checkpointWal<DB>(kernel: StorageKernel<DB>): Promise<void>;
107
+ export declare function checkpointWal<DB>({ kernel }: {
108
+ kernel: KyselyKernel<DB>;
109
+ }, _optional?: Record<string, never>): Promise<void>;
91
110
  export interface IndexInfo {
92
111
  name: string;
93
112
  /** Indexed columns in key order. */
@@ -99,5 +118,8 @@ export interface IndexInfo {
99
118
  * UNIQUE constraint makes on its own (SQLite origin `pk`/`u`, Postgres constraint-backed), which no
100
119
  * `CREATE INDEX` declared. Empty when the table does not exist.
101
120
  */
102
- export declare function listIndexes<DB>(kernel: StorageKernel<DB>, table: string): Promise<Map<string, IndexInfo>>;
121
+ export declare function listIndexes<DB>({ kernel, table }: {
122
+ kernel: KyselyKernel<DB>;
123
+ table: string;
124
+ }, _optional?: Record<string, never>): Promise<Map<string, IndexInfo>>;
103
125
  //# sourceMappingURL=dialect.d.ts.map
@@ -42,7 +42,7 @@ const pgPath = (path) => `{${checkedPath(path).join(",")}}`;
42
42
  * Not for objects or arrays (each dialect prints those differently), nor for fractional numbers
43
43
  * whose spelling matters (`1.50` reads `1.50` on Postgres, `1.5` on SQLite).
44
44
  */
45
- export function jsonText(dialect, column, path) {
45
+ export function jsonText({ dialect, column, path }, _optional = {}) {
46
46
  if (dialect === "postgres")
47
47
  return sql `(${column}::jsonb #>> ${pgPath(path)})`;
48
48
  const at = sqlitePath(path);
@@ -58,7 +58,7 @@ export function jsonText(dialect, column, path) {
58
58
  * Postgres compares the two `jsonb` values, so `10` matches
59
59
  * `10.0` and a string never matches a number.
60
60
  */
61
- export function jsonScalarEquals(dialect, column, path, value) {
61
+ export function jsonScalarEquals({ dialect, column, path, value }, _optional = {}) {
62
62
  if (dialect === "postgres")
63
63
  return sql `((${column}::jsonb #> ${pgPath(path)}) = ${JSON.stringify(value)}::jsonb)`;
64
64
  const bound = typeof value === "boolean" ? Number(value) : value;
@@ -72,7 +72,7 @@ export function jsonScalarEquals(dialect, column, path, value) {
72
72
  * A missing key is SQL NULL on both; pair with `nullsFirst()` (asc) / `nullsLast()` (desc) so NULLs
73
73
  * land where SQLite puts them by default.
74
74
  */
75
- export function jsonSortKey(dialect, column, path) {
75
+ export function jsonSortKey({ dialect, column, path }, _optional = {}) {
76
76
  return dialect === "postgres"
77
77
  ? sql `(${column}::jsonb #> ${pgPath(path)})`
78
78
  : sql `json_extract(${column}, ${sqlitePath(path)})`;
@@ -81,54 +81,32 @@ export function jsonSortKey(dialect, column, path) {
81
81
  * The column's JSON with `path` set to `value` (any JSON-serialisable value), creating the last key
82
82
  * if it is missing. A NULL column counts as `{}`. The parent object must already exist.
83
83
  */
84
- export function jsonSet(dialect, column, path, value) {
84
+ export function jsonSet({ dialect, column, path, value }, _optional = {}) {
85
85
  const encoded = JSON.stringify(value);
86
86
  return dialect === "sqlite"
87
87
  ? sql `json_set(coalesce(${column}, '{}'), ${sqlitePath(path)}, json(${encoded}))`
88
88
  : sql `jsonb_set(coalesce(${column}::jsonb, '{}'::jsonb), ${pgPath(path)}, ${encoded}::jsonb, true)`;
89
89
  }
90
90
  /** The statement's current time as `Date#toISOString()` text (UTC, milliseconds, `Z`). */
91
- export function nowIso(dialect) {
91
+ export function nowIso({ dialect }, _optional = {}) {
92
92
  return dialect === "sqlite"
93
93
  ? sql `strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`
94
94
  : sql `to_char(statement_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
95
95
  }
96
- /** A boolean column as read: `true`/`false` on Postgres, `1`/`0` on SQLite. NULL stays null. */
97
- export function toBool(value) {
98
- if (value === null || value === undefined)
99
- return null;
100
- return value === true || value === 1;
101
- }
102
- /**
103
- * True iff `err` is a UNIQUE violation, from any driver: SQLite's `SQLITE_CONSTRAINT_UNIQUE` /
104
- * "UNIQUE constraint failed", Postgres SQLSTATE `23505` (node-postgres and PGlite both set `code`).
105
- * The message check also covers the in-memory test doubles, which throw SQLite's wording.
106
- */
107
- export function isUniqueViolation(err) {
108
- if (!(err instanceof Error))
109
- return false;
110
- const code = err.code;
111
- return code === "SQLITE_CONSTRAINT_UNIQUE" || code === "23505" || err.message.includes("UNIQUE constraint failed");
112
- }
113
- /** A blob/bytea value as bytes, whichever shape the driver returned (Buffer, Uint8Array). */
114
- export function toBytes(value) {
115
- if (value instanceof Uint8Array)
116
- return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
117
- throw new Error(`expected a binary column value, got ${typeof value}`);
118
- }
96
+ // ---- Introspection ------------------------------------------------------------------------------
119
97
  /** User tables in the connection's current schema, sorted by name. Internal tables excluded. */
120
- export async function listTables(kernel) {
98
+ export async function listTables({ kernel }, _optional = {}) {
121
99
  const rows = await kernel.query(kernel.dialect === "sqlite"
122
100
  ? sql `SELECT name FROM sqlite_schema WHERE type = 'table' AND substr(name, 1, 7) <> 'sqlite_' ORDER BY name`
123
101
  : sql `SELECT table_name AS name FROM information_schema.tables
124
102
  WHERE table_schema = current_schema() AND table_type = 'BASE TABLE' ORDER BY table_name`);
125
103
  return rows.map((row) => row.name);
126
104
  }
127
- export async function tableExists(kernel, table) {
128
- return (await listColumns(kernel, table)).length > 0;
105
+ export async function tableExists({ kernel, table }, _optional = {}) {
106
+ return (await listColumns({ kernel, table })).length > 0;
129
107
  }
130
108
  /** Columns in declaration order; empty when the table does not exist. */
131
- export async function listColumns(kernel, table) {
109
+ export async function listColumns({ kernel, table }, _optional = {}) {
132
110
  const rows = await kernel.query(kernel.dialect === "sqlite"
133
111
  ? sql `SELECT name, type, "notnull" AS not_null, pk FROM pragma_table_info(${table}) ORDER BY cid`
134
112
  : sql `SELECT c.column_name AS name, c.data_type AS type, (c.is_nullable = 'NO') AS not_null,
@@ -161,11 +139,11 @@ const PG_COLUMN_TYPES = {
161
139
  * table created here reads back exactly as before; Postgres gets the same mapping as the frozen
162
140
  * Postgres baseline. Lower-cased, it is also what {@link listColumns} reports for that column.
163
141
  */
164
- export function columnTypeSql(dialect, affinity) {
142
+ export function columnTypeSql({ dialect, affinity }, _optional = {}) {
165
143
  return dialect === "sqlite" ? affinity : PG_COLUMN_TYPES[affinity];
166
144
  }
167
145
  /** A generated integer primary key column's type and constraints (write the column name before it). */
168
- export function autoIdColumnSql(dialect) {
146
+ export function autoIdColumnSql({ dialect }, _optional = {}) {
169
147
  return dialect === "sqlite" ? "INTEGER PRIMARY KEY AUTOINCREMENT" : "bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY";
170
148
  }
171
149
  /**
@@ -173,7 +151,7 @@ export function autoIdColumnSql(dialect) {
173
151
  * checkpoint (must run outside a write transaction on this connection: SQLite refuses it with
174
152
  * "database table is locked"). Postgres: nothing to do, a commit is already durable.
175
153
  */
176
- export async function checkpointWal(kernel) {
154
+ export async function checkpointWal({ kernel }, _optional = {}) {
177
155
  if (kernel.dialect === "sqlite")
178
156
  await kernel.query(sql `PRAGMA wal_checkpoint(FULL)`);
179
157
  }
@@ -182,7 +160,7 @@ export async function checkpointWal(kernel) {
182
160
  * UNIQUE constraint makes on its own (SQLite origin `pk`/`u`, Postgres constraint-backed), which no
183
161
  * `CREATE INDEX` declared. Empty when the table does not exist.
184
162
  */
185
- export async function listIndexes(kernel, table) {
163
+ export async function listIndexes({ kernel, table }, _optional = {}) {
186
164
  const rows = await kernel.query(kernel.dialect === "sqlite"
187
165
  ? sql `SELECT il.name AS name, il."unique" AS is_unique, ii.name AS column_name
188
166
  FROM pragma_index_list(${table}) il JOIN pragma_index_info(il.name) ii
@@ -3,10 +3,10 @@
3
3
  * dialect helpers and introspection, and the storage-ops contract. Imports kysely and Node builtins
4
4
  * only — never a database driver (`import-isolation.test.ts` and `loads-without-driver.test.ts` prove it).
5
5
  */
6
- export { type StorageCapabilities, type StorageCapability, type StorageDialect, type StorageKernel, type StorageTransport, UnsupportedCapabilityError, } from "./port.js";
6
+ export type { DbTransport, KyselyKernel } from "./port.js";
7
7
  export { buildKernel, type KernelDriver } from "./kernel-core.js";
8
8
  export { TurnLock } from "./turn-lock.js";
9
- export { autoIdColumnSql, checkpointWal, type ColumnAffinity, type ColumnInfo, columnTypeSql, type IndexInfo, isUniqueViolation, jsonScalarEquals, jsonSet, jsonSortKey, jsonText, listColumns, listIndexes, listTables, nowIso, tableExists, toBool, toBytes, } from "./dialect.js";
9
+ export { autoIdColumnSql, checkpointWal, type ColumnAffinity, columnTypeSql, type IndexInfo, jsonScalarEquals, jsonSet, jsonSortKey, jsonText, listColumns, listIndexes, listTables, nowIso, tableExists, } from "./dialect.js";
10
10
  export { scopeToSchema } from "./schema-scope.js";
11
11
  export { databaseFile, readSchemaShape, type SchemaShape, type TableShape } from "./schema-shape.js";
12
12
  export { renderDatabaseTypes } from "./typegen.js";
@@ -1,12 +1,6 @@
1
- /**
2
- * @file `@jini-ai/db/kernel`: the storage kernel port, the kernel core every driver builds on, the
3
- * dialect helpers and introspection, and the storage-ops contract. Imports kysely and Node builtins
4
- * only — never a database driver (`import-isolation.test.ts` and `loads-without-driver.test.ts` prove it).
5
- */
6
- export { UnsupportedCapabilityError, } from "./port.js";
7
1
  export { buildKernel } from "./kernel-core.js";
8
2
  export { TurnLock } from "./turn-lock.js";
9
- export { autoIdColumnSql, checkpointWal, columnTypeSql, isUniqueViolation, jsonScalarEquals, jsonSet, jsonSortKey, jsonText, listColumns, listIndexes, listTables, nowIso, tableExists, toBool, toBytes, } from "./dialect.js";
3
+ export { autoIdColumnSql, checkpointWal, columnTypeSql, jsonScalarEquals, jsonSet, jsonSortKey, jsonText, listColumns, listIndexes, listTables, nowIso, tableExists, } from "./dialect.js";
10
4
  export { scopeToSchema } from "./schema-scope.js";
11
5
  export { databaseFile, readSchemaShape } from "./schema-shape.js";
12
6
  export { renderDatabaseTypes } from "./typegen.js";
@@ -1,5 +1,7 @@
1
1
  import type { Kysely } from "kysely";
2
- import { type StorageCapabilities, type StorageDialect, type StorageKernel, type StorageTransport } from "./port.js";
2
+ import { type KyselyKernel } from "./port.js";
3
+ import { type StorageCapabilities, type StorageDialect } from "@jini-ai/core/contracts/storage";
4
+ import type { DbTransport } from "./port.js";
3
5
  import { TurnLock } from "./turn-lock.js";
4
6
  /**
5
7
  * @file The transaction rules every driver shares, so they cannot differ by dialect: a test that
@@ -12,7 +14,7 @@ import { TurnLock } from "./turn-lock.js";
12
14
  /** What a driver supplies. Everything else about a kernel is built here. */
13
15
  export interface KernelDriver<DB> {
14
16
  dialect: StorageDialect;
15
- transport: StorageTransport;
17
+ transport: DbTransport;
16
18
  capabilities: StorageCapabilities;
17
19
  ready: Promise<void>;
18
20
  base: Kysely<DB>;
@@ -41,5 +43,7 @@ export interface KernelDriver<DB> {
41
43
  backup?(destPath: string): Promise<void>;
42
44
  close(): Promise<void>;
43
45
  }
44
- export declare function buildKernel<DB>(driver: KernelDriver<DB>): StorageKernel<DB>;
46
+ export declare function buildKernel<DB>({ driver }: {
47
+ driver: KernelDriver<DB>;
48
+ }, _optional?: Record<string, never>): KyselyKernel<DB>;
45
49
  //# sourceMappingURL=kernel-core.d.ts.map
@@ -1,6 +1,7 @@
1
1
  import { registerKernelSessionDatabase } from "./session-lock.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
- import { UnsupportedCapabilityError, } from "./port.js";
3
+ import {} from "./port.js";
4
+ import { UnsupportedCapabilityError, } from "@jini-ai/core/contracts/storage";
4
5
  import { TurnLock } from "./turn-lock.js";
5
6
  import { registerOwnedTransaction } from "./owned-transaction.js";
6
7
  /** The turn locks the caller's async context holds, across every kernel in the process. */
@@ -24,64 +25,81 @@ async function takingTurn(lock, kind, body) {
24
25
  lock.release(kind);
25
26
  }
26
27
  }
27
- export function buildKernel(driver) {
28
- const scope = new AsyncLocalStorage();
29
- const lock = driver.oneConnection ? (driver.turnLock ?? new TurnLock()) : undefined;
30
- let ownTransactions = 0;
31
- const joinsForeign = () => ownTransactions === 0 && driver.foreignTransactionOpen?.() === true;
32
- function require(capability) {
33
- if (!driver.capabilities[capability])
34
- throw new UnsupportedCapabilityError(capability, driver.transport);
35
- }
36
- async function run(fn) {
37
- await driver.ready;
38
- const current = scope.getStore();
39
- if (current !== undefined)
40
- return fn(current.db);
41
- if (joinsForeign())
42
- return fn(driver.base);
43
- return takingTurn(lock, "shared", async () => scope.run({ kind: "run", db: driver.base }, () => fn(driver.base)));
28
+ function joinsForeign({ rt }) {
29
+ return rt.own.transactions === 0 && rt.driver.foreignTransactionOpen?.() === true;
30
+ }
31
+ function requireCapability({ rt, capability }) {
32
+ if (!rt.driver.capabilities[capability])
33
+ throw new UnsupportedCapabilityError(capability, rt.driver.transport);
34
+ }
35
+ function assertOwnedAvailable({ rt }) {
36
+ if (rt.scope.getStore() !== undefined || joinsForeign({ rt })) {
37
+ throw new Error("an owned transaction cannot join an existing run or foreign transaction");
44
38
  }
45
- function assertOwnedAvailable() {
46
- if (scope.getStore() !== undefined || joinsForeign()) {
47
- throw new Error("an owned transaction cannot join an existing run or foreign transaction");
48
- }
39
+ }
40
+ async function kernelRun({ rt, fn }) {
41
+ const { driver, scope, lock } = rt;
42
+ await driver.ready;
43
+ const current = scope.getStore();
44
+ if (current !== undefined)
45
+ return fn(current.db);
46
+ if (joinsForeign({ rt }))
47
+ return fn(driver.base);
48
+ return takingTurn(lock, "shared", async () => scope.run({ kind: "run", db: driver.base }, () => fn(driver.base)));
49
+ }
50
+ async function kernelTransaction({ rt, fn, owned }) {
51
+ const { driver, scope, lock } = rt;
52
+ requireCapability({ rt, capability: "interactiveTransactions" });
53
+ await driver.ready;
54
+ if (owned !== undefined)
55
+ assertOwnedAvailable({ rt });
56
+ const current = scope.getStore();
57
+ if (current?.kind === "transaction")
58
+ return fn();
59
+ if (current?.kind === "run") {
60
+ throw new Error("transaction() was called inside a run() body; start the transaction first and call run() inside it");
49
61
  }
50
- async function transaction(fn, owned) {
51
- require("interactiveTransactions");
52
- await driver.ready;
62
+ if (joinsForeign({ rt }))
63
+ return scope.run({ kind: "transaction", db: driver.base }, fn);
64
+ return takingTurn(lock, "exclusive", async () => {
53
65
  if (owned !== undefined)
54
- assertOwnedAvailable();
55
- const current = scope.getStore();
56
- if (current?.kind === "transaction")
57
- return fn();
58
- if (current?.kind === "run") {
59
- throw new Error("transaction() was called inside a run() body; start the transaction first and call run() inside it");
66
+ assertOwnedAvailable({ rt });
67
+ rt.own.transactions += 1;
68
+ try {
69
+ return await driver.begin((tx) => scope.run({ kind: "transaction", db: tx }, fn));
60
70
  }
61
- if (joinsForeign())
62
- return scope.run({ kind: "transaction", db: driver.base }, fn);
63
- return takingTurn(lock, "exclusive", async () => {
64
- if (owned !== undefined)
65
- assertOwnedAvailable();
66
- ownTransactions += 1;
67
- try {
68
- return await driver.begin((tx) => scope.run({ kind: "transaction", db: tx }, fn));
69
- }
70
- finally {
71
- ownTransactions -= 1;
72
- // Still inside the turn: the next queued caller must not see this owner's state.
73
- owned?.onSettled?.();
74
- }
75
- });
76
- }
77
- async function lockKey(key) {
78
- const current = scope.getStore();
79
- // A joined legacy transaction counts: it is the same `BEGIN IMMEDIATE` on SQLite.
80
- if (current?.kind !== "transaction" && !joinsForeign()) {
81
- throw new Error("lockKey() must be called inside transaction()");
71
+ finally {
72
+ rt.own.transactions -= 1;
73
+ // Still inside the turn: the next queued caller must not see this owner's state.
74
+ owned?.onSettled?.();
82
75
  }
83
- await driver.lockKey(current?.db ?? driver.base, key);
76
+ });
77
+ }
78
+ async function kernelLockKey({ rt, key }) {
79
+ const current = rt.scope.getStore();
80
+ // A joined legacy transaction counts: it is the same `BEGIN IMMEDIATE` on SQLite.
81
+ if (current?.kind !== "transaction" && !joinsForeign({ rt })) {
82
+ throw new Error("lockKey() must be called inside transaction()");
84
83
  }
84
+ await rt.driver.lockKey(current?.db ?? rt.driver.base, key);
85
+ }
86
+ async function kernelBackup({ rt, destPath }) {
87
+ const { driver, scope, lock } = rt;
88
+ requireCapability({ rt, capability: "backup" });
89
+ if (driver.backup === undefined)
90
+ throw new UnsupportedCapabilityError("backup", driver.transport);
91
+ if (scope.getStore()?.kind === "transaction")
92
+ throw new Error("backupTo() must be called outside a transaction");
93
+ await driver.ready;
94
+ // A copy must wait for unrelated work to commit or roll back on the shared connection.
95
+ await takingTurn(lock, "exclusive", () => driver.backup(destPath));
96
+ }
97
+ export function buildKernel({ driver }, _optional = {}) {
98
+ const lock = driver.oneConnection ? (driver.turnLock ?? new TurnLock()) : undefined;
99
+ const rt = { driver, scope: new AsyncLocalStorage(), lock, own: { transactions: 0 } };
100
+ const require = (capability) => requireCapability({ rt, capability });
101
+ const run = (fn) => kernelRun({ rt, fn });
102
+ const transaction = (fn, owned) => kernelTransaction({ rt, fn, owned });
85
103
  const kernel = {
86
104
  dialect: driver.dialect,
87
105
  transport: driver.transport,
@@ -89,27 +107,18 @@ export function buildKernel(driver) {
89
107
  ready: driver.ready,
90
108
  run,
91
109
  transaction,
92
- lockKey,
110
+ lockKey: (key) => kernelLockKey({ rt, key }),
93
111
  query: async (statement) => (await run((db) => statement.execute(db))).rows,
94
112
  execute: async (statement) => {
95
113
  await run((db) => statement.execute(db));
96
114
  },
97
- inTransaction: () => scope.getStore()?.kind === "transaction",
115
+ inTransaction: () => rt.scope.getStore()?.kind === "transaction",
98
116
  require,
99
- async backupTo(destPath) {
100
- require("backup");
101
- if (driver.backup === undefined)
102
- throw new UnsupportedCapabilityError("backup", driver.transport);
103
- if (scope.getStore()?.kind === "transaction")
104
- throw new Error("backupTo() must be called outside a transaction");
105
- await driver.ready;
106
- // A copy must wait for unrelated work to commit or roll back on the shared connection.
107
- await takingTurn(lock, "exclusive", () => driver.backup(destPath));
108
- },
117
+ backupTo: (destPath) => kernelBackup({ rt, destPath }),
109
118
  close: () => driver.close(),
110
119
  };
111
120
  registerOwnedTransaction({ kernel: kernel, control: {
112
- assertAvailable: assertOwnedAvailable,
121
+ assertAvailable: () => assertOwnedAvailable({ rt }),
113
122
  transaction: (work, optional = {}) => transaction(work, optional),
114
123
  } });
115
124
  registerKernelSessionDatabase({ kernel: kernel, database: driver.base, ...(driver.poolMax === undefined ? {} : { poolMax: driver.poolMax }) });
@@ -1,4 +1,5 @@
1
- import type { StorageKernel, StorageTransport } from "./port.js";
1
+ import type { KyselyKernel } from "./port.js";
2
+ import type { StorageTransport } from "@jini-ai/core/contracts/storage";
2
3
  /**
3
4
  * @file The storage ops port: whole-database FILE operations, which every dialect spells
4
5
  * differently and which are not queries (copying a database, compacting and sealing it). Queries go
@@ -36,7 +37,9 @@ export declare class StorageOpError extends Error {
36
37
  * A guard each op calls first: neither SQLite nor Postgres can `VACUUM` inside a transaction.
37
38
  * @throws {Error} when `kernel` is inside a transaction.
38
39
  */
39
- export declare function outsideTransactionOf(kernel: StorageKernel<unknown>): (op: keyof StorageOps) => void;
40
+ export declare function outsideTransactionOf({ kernel }: {
41
+ kernel: KyselyKernel<unknown>;
42
+ }, _optional?: Record<string, never>): (op: keyof StorageOps) => void;
40
43
  /**
41
44
  * The read-back that ends a Postgres-family compaction: the migration ledger the consumer names must
42
45
  * still be readable and non-empty. The ledger name is the consumer's (no default), because this
@@ -44,5 +47,8 @@ export declare function outsideTransactionOf(kernel: StorageKernel<unknown>): (o
44
47
  *
45
48
  * @throws {StorageOpError} the ledger cannot be read, or holds no rows.
46
49
  */
47
- export declare function verifyLedgerReadBack(kernel: StorageKernel<unknown>, ledgerTable: string): Promise<void>;
50
+ export declare function verifyLedgerReadBack({ kernel, ledgerTable }: {
51
+ kernel: KyselyKernel<unknown>;
52
+ ledgerTable: string;
53
+ }, _optional?: Record<string, never>): Promise<void>;
48
54
  //# sourceMappingURL=ops.d.ts.map
@@ -21,7 +21,7 @@ export class StorageOpError extends Error {
21
21
  * A guard each op calls first: neither SQLite nor Postgres can `VACUUM` inside a transaction.
22
22
  * @throws {Error} when `kernel` is inside a transaction.
23
23
  */
24
- export function outsideTransactionOf(kernel) {
24
+ export function outsideTransactionOf({ kernel }, _optional = {}) {
25
25
  return (op) => {
26
26
  if (kernel.inTransaction())
27
27
  throw new Error(`storage op ${op} must be called outside a transaction`);
@@ -34,7 +34,7 @@ export function outsideTransactionOf(kernel) {
34
34
  *
35
35
  * @throws {StorageOpError} the ledger cannot be read, or holds no rows.
36
36
  */
37
- export async function verifyLedgerReadBack(kernel, ledgerTable) {
37
+ export async function verifyLedgerReadBack({ kernel, ledgerTable }, _optional = {}) {
38
38
  let anyStep;
39
39
  try {
40
40
  // One row when the ledger holds any step, none when it is empty: no count to null-check.
@@ -1,4 +1,4 @@
1
- import type { StorageKernel } from "./port.js";
1
+ import type { KyselyKernel } from "./port.js";
2
2
  /** Private access to the kernel's scope checks; public transactions retain their join semantics. */
3
3
  export interface OwnedTransactionControl {
4
4
  assertAvailable(): void;
@@ -9,16 +9,16 @@ export interface OwnedTransactionControl {
9
9
  }
10
10
  /** Records the control of a kernel built by buildKernel. */
11
11
  export declare function registerOwnedTransaction({ kernel, control }: {
12
- kernel: StorageKernel<unknown>;
12
+ kernel: KyselyKernel<unknown>;
13
13
  control: OwnedTransactionControl;
14
- }): void;
14
+ }, _optional?: Record<string, never>): void;
15
15
  /** A kernel derived from another (schema-scoped, owned connection) shares its control, when it has one. */
16
16
  export declare function inheritOwnedTransaction({ from, to }: {
17
- from: StorageKernel<unknown>;
18
- to: StorageKernel<unknown>;
19
- }): void;
17
+ from: KyselyKernel<unknown>;
18
+ to: KyselyKernel<unknown>;
19
+ }, _optional?: Record<string, never>): void;
20
20
  /** Refuse unknown kernels rather than promising atomicity over an executor we do not own. */
21
21
  export declare function ownedTransactionOf({ kernel }: {
22
- kernel: StorageKernel<unknown>;
22
+ kernel: KyselyKernel<unknown>;
23
23
  }, _optional?: {}): OwnedTransactionControl;
24
24
  //# sourceMappingURL=owned-transaction.d.ts.map
@@ -1,10 +1,10 @@
1
1
  const ownedTransactions = new WeakMap();
2
2
  /** Records the control of a kernel built by buildKernel. */
3
- export function registerOwnedTransaction({ kernel, control }) {
3
+ export function registerOwnedTransaction({ kernel, control }, _optional = {}) {
4
4
  ownedTransactions.set(kernel, control);
5
5
  }
6
6
  /** A kernel derived from another (schema-scoped, owned connection) shares its control, when it has one. */
7
- export function inheritOwnedTransaction({ from, to }) {
7
+ export function inheritOwnedTransaction({ from, to }, _optional = {}) {
8
8
  const control = ownedTransactions.get(from);
9
9
  if (control !== undefined)
10
10
  ownedTransactions.set(to, control);
@@ -1,5 +1,5 @@
1
1
  import type { PGlite } from "@electric-sql/pglite";
2
- import { type StorageKernel } from "../index.js";
2
+ import { type KyselyKernel } from "../index.js";
3
3
  import type { PgliteClass } from "../../pglite/types.js";
4
4
  /**
5
5
  * @file The PGlite driver: one in-process Postgres (WASM) per data directory, behind the same
@@ -12,7 +12,7 @@ import type { PgliteClass } from "../../pglite/types.js";
12
12
  * Only ONE process may open a data dir; to share one, run an owner (`startPgliteOwner`) and connect
13
13
  * through its socket.
14
14
  */
15
- export type PgKernel<DB> = StorageKernel<DB>;
15
+ export type PgKernel<DB> = KyselyKernel<DB>;
16
16
  /**
17
17
  * Opens (and on first use creates) a PGlite database. Synchronous so it fits the synchronous
18
18
  * composition root; the async setup runs behind `ready`, which every kernel call awaits.
@@ -25,23 +25,23 @@ export function openPgliteKernel(required, optional = {}) {
25
25
  // Surfaced by every call that awaits `ready`; this only stops an unhandled-rejection crash when
26
26
  // nothing has called in yet.
27
27
  ready.catch(() => { });
28
- return buildKernel({
29
- dialect: "postgres",
30
- transport: "pglite",
31
- capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: true },
32
- ready,
33
- base,
34
- oneConnection: true,
35
- begin: (body) => base.transaction().execute((tx) => body(tx)),
36
- lockKey: postgresLockKey,
37
- async backup(destPath) {
38
- const dump = await client.dumpDataDir("none");
39
- await writeFile(destPath, Buffer.from(await dump.arrayBuffer()));
40
- },
41
- async close() {
42
- await ready.catch(() => { });
43
- await client.close();
44
- },
45
- });
28
+ return buildKernel({ driver: {
29
+ dialect: "postgres",
30
+ transport: "pglite",
31
+ capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: true },
32
+ ready,
33
+ base,
34
+ oneConnection: true,
35
+ begin: (body) => base.transaction().execute((tx) => body(tx)),
36
+ lockKey: postgresLockKey,
37
+ async backup(destPath) {
38
+ const dump = await client.dumpDataDir("none");
39
+ await writeFile(destPath, Buffer.from(await dump.arrayBuffer()));
40
+ },
41
+ async close() {
42
+ await ready.catch(() => { });
43
+ await client.close();
44
+ },
45
+ } });
46
46
  }
47
47
  //# sourceMappingURL=driver.js.map