@mandujs/core 0.20.10 → 0.22.0

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 (127) hide show
  1. package/README.md +2 -1
  2. package/package.json +28 -3
  3. package/src/auth/__tests__/login.test.ts +419 -0
  4. package/src/auth/__tests__/password.test.ts +122 -0
  5. package/src/auth/__tests__/reset.test.ts +296 -0
  6. package/src/auth/__tests__/tokens.test.ts +274 -0
  7. package/src/auth/__tests__/verification.test.ts +274 -0
  8. package/src/auth/index.ts +76 -0
  9. package/src/auth/login.ts +225 -0
  10. package/src/auth/password.ts +120 -0
  11. package/src/auth/reset.ts +243 -0
  12. package/src/auth/tokens.ts +612 -0
  13. package/src/auth/verification.ts +253 -0
  14. package/src/bundler/__tests__/cli-bench-utils.test.ts +149 -0
  15. package/src/bundler/__tests__/cold-start.test.ts +504 -0
  16. package/src/bundler/__tests__/csp-nonce.test.ts +278 -0
  17. package/src/bundler/__tests__/dev-reliability.test.ts +619 -0
  18. package/src/bundler/__tests__/extended-watch.test.ts +710 -0
  19. package/src/bundler/__tests__/fast-refresh.test.ts +596 -0
  20. package/src/bundler/__tests__/hdr.test.ts +353 -0
  21. package/src/bundler/__tests__/hmr-client.test.ts +532 -0
  22. package/src/bundler/__tests__/manifest-schema.test.ts +266 -0
  23. package/src/bundler/__tests__/prod-smoke.test.ts +138 -0
  24. package/src/bundler/__tests__/slot-dispatch.test.ts +573 -0
  25. package/src/bundler/__tests__/url-cap-and-slot-regex.test.ts +286 -0
  26. package/src/bundler/__tests__/vendor-cache.test.ts +455 -0
  27. package/src/bundler/build.test.ts +8 -1
  28. package/src/bundler/build.ts +495 -37
  29. package/src/bundler/css.ts +326 -323
  30. package/src/bundler/dev.ts +1671 -80
  31. package/src/bundler/fast-refresh-plugin.ts +307 -0
  32. package/src/bundler/hmr-types.ts +252 -0
  33. package/src/bundler/manifest-schema.ts +301 -0
  34. package/src/bundler/safe-build.test.ts +128 -0
  35. package/src/bundler/safe-build.ts +77 -0
  36. package/src/bundler/scenario-matrix.ts +229 -0
  37. package/src/bundler/types.ts +19 -0
  38. package/src/bundler/vendor-cache-types.ts +130 -0
  39. package/src/bundler/vendor-cache.ts +526 -0
  40. package/src/client/router.ts +214 -56
  41. package/src/config/validate.ts +1 -0
  42. package/src/db/__tests__/db.test.ts +485 -0
  43. package/src/db/index.ts +513 -0
  44. package/src/db/migrations/__tests__/runner.test.ts +661 -0
  45. package/src/db/migrations/history-table.ts +345 -0
  46. package/src/db/migrations/lock.ts +269 -0
  47. package/src/db/migrations/runner.ts +633 -0
  48. package/src/desktop/__tests__/smoke.test.ts +100 -0
  49. package/src/desktop/__tests__/window.test.ts +172 -0
  50. package/src/desktop/__tests__/worker.test.ts +266 -0
  51. package/src/desktop/index.ts +43 -0
  52. package/src/desktop/types.ts +158 -0
  53. package/src/desktop/window.ts +492 -0
  54. package/src/desktop/worker.ts +180 -0
  55. package/src/devtools/ai/mcp-connector.ts +18 -16
  56. package/src/devtools/client/components/mandu-character.tsx +4 -1
  57. package/src/devtools/client/components/panel/panel-container.tsx +20 -5
  58. package/src/email/__tests__/email.test.ts +355 -0
  59. package/src/email/index.ts +282 -0
  60. package/src/email/resend.ts +163 -0
  61. package/src/email/smtp.ts +64 -0
  62. package/src/filling/__tests__/session-sqlite.test.ts +454 -0
  63. package/src/filling/context.ts +72 -78
  64. package/src/filling/cookie-codec.ts +299 -0
  65. package/src/filling/deps.ts +25 -1
  66. package/src/filling/filling.ts +28 -3
  67. package/src/filling/session-sqlite.ts +617 -0
  68. package/src/filling/session.ts +265 -216
  69. package/src/guard/decision-memory.test.ts +52 -22
  70. package/src/id/__tests__/id.test.ts +120 -0
  71. package/src/id/index.ts +105 -0
  72. package/src/kitchen/index.ts +2 -2
  73. package/src/kitchen/kitchen-handler.ts +86 -0
  74. package/src/kitchen/stream/activity-sse.ts +2 -1
  75. package/src/middleware/csrf.ts +328 -0
  76. package/src/middleware/index.ts +40 -0
  77. package/src/middleware/oauth/__tests__/oauth.test.ts +574 -0
  78. package/src/middleware/oauth/index.ts +505 -0
  79. package/src/middleware/oauth/providers.ts +115 -0
  80. package/src/middleware/rate-limit/__tests__/rate-limit.test.ts +642 -0
  81. package/src/middleware/rate-limit/index.ts +522 -0
  82. package/src/middleware/rate-limit/sqlite-store.ts +382 -0
  83. package/src/middleware/secure/__tests__/secure.test.ts +360 -0
  84. package/src/middleware/secure/csp.ts +193 -0
  85. package/src/middleware/secure/index.ts +417 -0
  86. package/src/middleware/session.ts +174 -0
  87. package/src/observability/event-bus.ts +81 -79
  88. package/src/paths.ts +37 -0
  89. package/src/perf/hmr-markers.ts +215 -0
  90. package/src/perf/index.ts +104 -0
  91. package/src/resource/__tests__/generator.test.ts +603 -2
  92. package/src/resource/ddl/__tests__/diff.test.ts +639 -0
  93. package/src/resource/ddl/__tests__/emit.test.ts +799 -0
  94. package/src/resource/ddl/__tests__/snapshot.test.ts +499 -0
  95. package/src/resource/ddl/diff.ts +392 -0
  96. package/src/resource/ddl/emit.ts +548 -0
  97. package/src/resource/ddl/persistence-types.ts +218 -0
  98. package/src/resource/ddl/snapshot.ts +447 -0
  99. package/src/resource/ddl/type-map.ts +223 -0
  100. package/src/resource/ddl/types.ts +232 -0
  101. package/src/resource/generator-repo.ts +610 -0
  102. package/src/resource/generator-schema.ts +476 -0
  103. package/src/resource/generator.ts +117 -1
  104. package/src/resource/index.ts +17 -1
  105. package/src/resource/schema.ts +30 -0
  106. package/src/router/fs-scanner.ts +3 -0
  107. package/src/runtime/__tests__/error-boundary-redaction.test.ts +141 -0
  108. package/src/runtime/__tests__/hdr-client.test.ts +223 -0
  109. package/src/runtime/__tests__/http-errors.test.ts +117 -0
  110. package/src/runtime/__tests__/not-found.test.ts +152 -0
  111. package/src/runtime/boundary.tsx +21 -1
  112. package/src/runtime/fast-refresh-runtime.ts +322 -0
  113. package/src/runtime/fast-refresh-types.ts +128 -0
  114. package/src/runtime/hmr-client.ts +409 -0
  115. package/src/runtime/http-errors.ts +113 -0
  116. package/src/runtime/index.ts +6 -0
  117. package/src/runtime/logger.ts +678 -677
  118. package/src/runtime/not-found.ts +93 -0
  119. package/src/runtime/redirect.ts +133 -0
  120. package/src/runtime/server.ts +679 -23
  121. package/src/runtime/ssr.ts +340 -10
  122. package/src/runtime/streaming-ssr.ts +222 -19
  123. package/src/scheduler/__tests__/scheduler.test.ts +514 -0
  124. package/src/scheduler/index.ts +343 -0
  125. package/src/storage/s3/__tests__/s3.test.ts +479 -0
  126. package/src/storage/s3/index.ts +412 -0
  127. package/src/testing/index.ts +247 -189
@@ -0,0 +1,345 @@
1
+ /**
2
+ * @mandujs/core/db/migrations/history-table
3
+ *
4
+ * History table DDL + row-level query helpers for the migration runtime.
5
+ *
6
+ * The `__mandu_migrations` table is Mandu's internal Flyway-style schema
7
+ * history record. It exists in the user's database alongside their own
8
+ * tables and is the single source of truth for "which migrations have
9
+ * already been applied". Every row represents exactly one applied
10
+ * migration file.
11
+ *
12
+ * ## Column contract (stable across dialects)
13
+ *
14
+ * | Column | Type (dialect-mapped) | Notes |
15
+ * |----------------|----------------------------------|--------------------------------------------------------|
16
+ * | `version` | `TEXT PRIMARY KEY` | Zero-padded 4-digit sequence (e.g. `"0001"`). |
17
+ * | `filename` | `TEXT NOT NULL` | Migration filename relative to the migrations dir. |
18
+ * | `checksum` | `TEXT NOT NULL` | SHA-256 hex lowercase of the file's normalized SQL. |
19
+ * | `applied_at` | `TIMESTAMPTZ` / `DATETIME(6)` / `TEXT` | Dialect's high-precision timestamp. |
20
+ * | `execution_ms` | `INTEGER NOT NULL` | Pure SQL execution time (excludes fetch / checksum). |
21
+ * | `success` | `INTEGER NOT NULL` | `0` or `1` — stored as int for dialect parity. |
22
+ * | `installed_by` | `TEXT` | DB user or `MANDU_MIGRATION_USER` env; nullable. |
23
+ *
24
+ * ## Per-dialect DDL
25
+ *
26
+ * ### Postgres
27
+ * ```sql
28
+ * CREATE TABLE IF NOT EXISTS "__mandu_migrations" (
29
+ * "version" TEXT PRIMARY KEY,
30
+ * "filename" TEXT NOT NULL,
31
+ * "checksum" TEXT NOT NULL,
32
+ * "applied_at" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
33
+ * "execution_ms" INTEGER NOT NULL,
34
+ * "success" INTEGER NOT NULL,
35
+ * "installed_by" TEXT
36
+ * );
37
+ * ```
38
+ *
39
+ * ### MySQL
40
+ * ```sql
41
+ * CREATE TABLE IF NOT EXISTS `__mandu_migrations` (
42
+ * `version` VARCHAR(50) NOT NULL,
43
+ * `filename` VARCHAR(255) NOT NULL,
44
+ * `checksum` VARCHAR(64) NOT NULL,
45
+ * `applied_at` DATETIME(6) NOT NULL,
46
+ * `execution_ms` INTEGER NOT NULL,
47
+ * `success` INTEGER NOT NULL,
48
+ * `installed_by` VARCHAR(255),
49
+ * PRIMARY KEY (`version`)
50
+ * );
51
+ * ```
52
+ * (MySQL requires lengths on VARCHAR in primary keys — we pick conservative
53
+ * sizes that match Bun.SQL's `TEXT` parse in practice.)
54
+ *
55
+ * ### SQLite
56
+ * ```sql
57
+ * CREATE TABLE IF NOT EXISTS "__mandu_migrations" (
58
+ * "version" TEXT PRIMARY KEY,
59
+ * "filename" TEXT NOT NULL,
60
+ * "checksum" TEXT NOT NULL,
61
+ * "applied_at" TEXT NOT NULL,
62
+ * "execution_ms" INTEGER NOT NULL,
63
+ * "success" INTEGER NOT NULL,
64
+ * "installed_by" TEXT
65
+ * );
66
+ * ```
67
+ *
68
+ * @module db/migrations/history-table
69
+ */
70
+
71
+ import type { SqlProvider } from "../../resource/ddl/types";
72
+ import type { Db } from "../index";
73
+
74
+ // ─── Constants ──────────────────────────────────────────────────────────────
75
+
76
+ /** Default history-table name. Override via `MigrationRunnerOptions.historyTable`. */
77
+ export const DEFAULT_HISTORY_TABLE = "__mandu_migrations";
78
+
79
+ /**
80
+ * Identifier pattern for user-supplied history-table names. Because
81
+ * Bun.SQL cannot bind identifiers, the table name is interpolated into
82
+ * DDL/DML directly — we constrain it to `[A-Za-z_][A-Za-z0-9_]*` to
83
+ * eliminate any SQL-injection surface. Same pattern used by
84
+ * `filling/session-sqlite.ts:SAFE_IDENT_RE`.
85
+ */
86
+ export const SAFE_HISTORY_TABLE_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
87
+
88
+ // ─── Row shape ──────────────────────────────────────────────────────────────
89
+
90
+ /**
91
+ * Row shape for the history table. `success` is stored as an integer
92
+ * (`0` / `1`) across all three dialects so consumers see a uniform type —
93
+ * SQLite has no native boolean, and reusing the int form on PG/MySQL
94
+ * keeps `readAllHistory` producing identically-typed rows.
95
+ */
96
+ export interface HistoryRow {
97
+ version: string;
98
+ filename: string;
99
+ checksum: string;
100
+ applied_at: Date;
101
+ execution_ms: number;
102
+ success: number; // 0 or 1 — SQLite has no boolean
103
+ installed_by?: string | null;
104
+ // Index signature so the row satisfies `Record<string, unknown>` that
105
+ // Bun.SQL's generic expects. Property types above still win for known keys.
106
+ [key: string]: unknown;
107
+ }
108
+
109
+ // ─── Identifier quoting ─────────────────────────────────────────────────────
110
+
111
+ /**
112
+ * Quote a validated identifier for the target provider. Postgres/SQLite
113
+ * use double-quotes; MySQL uses backticks. Callers MUST validate the
114
+ * identifier against `SAFE_HISTORY_TABLE_RE` before quoting — this
115
+ * function assumes the input is already safe and does NOT re-escape.
116
+ */
117
+ function quoteIdent(name: string, provider: SqlProvider): string {
118
+ if (!SAFE_HISTORY_TABLE_RE.test(name)) {
119
+ throw new Error(
120
+ `[@mandujs/core/db/migrations] Invalid identifier ${JSON.stringify(
121
+ name,
122
+ )}. Must match ${SAFE_HISTORY_TABLE_RE}.`,
123
+ );
124
+ }
125
+ if (provider === "mysql") return `\`${name}\``;
126
+ return `"${name}"`;
127
+ }
128
+
129
+ // ─── DDL ────────────────────────────────────────────────────────────────────
130
+
131
+ /**
132
+ * Produce the `CREATE TABLE IF NOT EXISTS` DDL for the history table on
133
+ * the target provider. Idempotent — callers should execute on every boot;
134
+ * the `IF NOT EXISTS` clause prevents re-creation once the row exists.
135
+ *
136
+ * Column order is fixed across dialects. We choose per-column SQL types
137
+ * that match the `HistoryRow` contract as closely as each dialect
138
+ * permits. See the module JSDoc for the full per-dialect rendering.
139
+ *
140
+ * @throws when `tableName` fails the safe-identifier check.
141
+ */
142
+ export function historyTableDdl(tableName: string, provider: SqlProvider): string {
143
+ const qTable = quoteIdent(tableName, provider);
144
+
145
+ switch (provider) {
146
+ case "postgres": {
147
+ return [
148
+ `CREATE TABLE IF NOT EXISTS ${qTable} (`,
149
+ ` "version" TEXT PRIMARY KEY,`,
150
+ ` "filename" TEXT NOT NULL,`,
151
+ ` "checksum" TEXT NOT NULL,`,
152
+ ` "applied_at" TIMESTAMPTZ NOT NULL DEFAULT NOW(),`,
153
+ ` "execution_ms" INTEGER NOT NULL,`,
154
+ ` "success" INTEGER NOT NULL,`,
155
+ ` "installed_by" TEXT`,
156
+ `)`,
157
+ ].join("\n");
158
+ }
159
+ case "mysql": {
160
+ // MySQL demands a length on VARCHAR in a PRIMARY KEY. 50 chars is
161
+ // ample for `NNNN` today and leaves room for longer version schemes.
162
+ return [
163
+ `CREATE TABLE IF NOT EXISTS ${qTable} (`,
164
+ ` \`version\` VARCHAR(50) NOT NULL,`,
165
+ ` \`filename\` VARCHAR(255) NOT NULL,`,
166
+ ` \`checksum\` VARCHAR(64) NOT NULL,`,
167
+ ` \`applied_at\` DATETIME(6) NOT NULL,`,
168
+ ` \`execution_ms\` INTEGER NOT NULL,`,
169
+ ` \`success\` INTEGER NOT NULL,`,
170
+ ` \`installed_by\` VARCHAR(255),`,
171
+ ` PRIMARY KEY (\`version\`)`,
172
+ `)`,
173
+ ].join("\n");
174
+ }
175
+ case "sqlite": {
176
+ // SQLite accepts TEXT for timestamps — we insert ISO-8601 strings.
177
+ return [
178
+ `CREATE TABLE IF NOT EXISTS ${qTable} (`,
179
+ ` "version" TEXT PRIMARY KEY,`,
180
+ ` "filename" TEXT NOT NULL,`,
181
+ ` "checksum" TEXT NOT NULL,`,
182
+ ` "applied_at" TEXT NOT NULL,`,
183
+ ` "execution_ms" INTEGER NOT NULL,`,
184
+ ` "success" INTEGER NOT NULL,`,
185
+ ` "installed_by" TEXT`,
186
+ `)`,
187
+ ].join("\n");
188
+ }
189
+ }
190
+ }
191
+
192
+ // ─── Query helpers ──────────────────────────────────────────────────────────
193
+ //
194
+ // `@mandujs/core/db` exposes a tagged-template API. The SQL we emit here
195
+ // is dynamic in exactly one way (the table name) — SQLite/Postgres/MySQL
196
+ // do not bind identifiers, so we interpolate the (validated) table name
197
+ // into the SQL text and bind only real values through Bun.SQL placeholders.
198
+ //
199
+ // We reuse the same `splitPlaceholders` trick as
200
+ // `filling/session-sqlite.ts` so the query goes through the wrapper's
201
+ // parameter binding path (no string concat of values, ever).
202
+
203
+ /**
204
+ * Read every row in the history table, ordered by version. The row
205
+ * shape is the same across dialects — `applied_at` is coerced to `Date`
206
+ * when the dialect returns it as a string (SQLite).
207
+ */
208
+ export async function readAllHistory(
209
+ db: Db,
210
+ tableName: string,
211
+ ): Promise<HistoryRow[]> {
212
+ if (!SAFE_HISTORY_TABLE_RE.test(tableName)) {
213
+ throw new Error(
214
+ `[@mandujs/core/db/migrations] Invalid history table name ${JSON.stringify(
215
+ tableName,
216
+ )}.`,
217
+ );
218
+ }
219
+ const qTable = quoteIdent(tableName, db.provider);
220
+ const sql = `SELECT version, filename, checksum, applied_at, execution_ms, success, installed_by FROM ${qTable} ORDER BY version ASC`;
221
+ const rows = await execQuery<Record<string, unknown>>(db, sql, []);
222
+ return rows.map(coerceHistoryRow);
223
+ }
224
+
225
+ /**
226
+ * Insert a single history row. The `applied_at` column is serialized to
227
+ * ISO-8601 on SQLite (TEXT column) and passed through as-is on PG/MySQL
228
+ * (native timestamp types).
229
+ *
230
+ * Expected to be called inside a transaction by the runner so that a
231
+ * crash between SQL execution + history write leaves no partial state.
232
+ */
233
+ export async function insertHistory(
234
+ db: Db,
235
+ tableName: string,
236
+ row: Omit<HistoryRow, "applied_at"> & { applied_at: Date },
237
+ ): Promise<void> {
238
+ if (!SAFE_HISTORY_TABLE_RE.test(tableName)) {
239
+ throw new Error(
240
+ `[@mandujs/core/db/migrations] Invalid history table name ${JSON.stringify(
241
+ tableName,
242
+ )}.`,
243
+ );
244
+ }
245
+ const qTable = quoteIdent(tableName, db.provider);
246
+
247
+ // SQLite stores timestamps as TEXT in our schema; PG/MySQL accept Date.
248
+ const appliedAtParam =
249
+ db.provider === "sqlite" ? row.applied_at.toISOString() : row.applied_at;
250
+
251
+ const sql = `INSERT INTO ${qTable} (version, filename, checksum, applied_at, execution_ms, success, installed_by) VALUES ($1, $2, $3, $4, $5, $6, $7)`;
252
+ await execQuery<Record<string, unknown>>(db, sql, [
253
+ row.version,
254
+ row.filename,
255
+ row.checksum,
256
+ appliedAtParam,
257
+ row.execution_ms,
258
+ row.success,
259
+ row.installed_by ?? null,
260
+ ]);
261
+ }
262
+
263
+ // ─── Internals ──────────────────────────────────────────────────────────────
264
+
265
+ /**
266
+ * Normalize a raw row read from the DB into the `HistoryRow` contract.
267
+ * Bun.SQL returns SQLite TEXT timestamps as strings; PG/MySQL drivers
268
+ * return `Date` already. We unify on `Date`.
269
+ */
270
+ function coerceHistoryRow(raw: Record<string, unknown>): HistoryRow {
271
+ const appliedAtValue = raw.applied_at;
272
+ let appliedAt: Date;
273
+ if (appliedAtValue instanceof Date) {
274
+ appliedAt = appliedAtValue;
275
+ } else if (typeof appliedAtValue === "string") {
276
+ appliedAt = new Date(appliedAtValue);
277
+ } else if (typeof appliedAtValue === "number") {
278
+ appliedAt = new Date(appliedAtValue);
279
+ } else {
280
+ // Row with NULL applied_at shouldn't happen (NOT NULL in DDL), but
281
+ // handle defensively so consumers never crash on a garbage row.
282
+ appliedAt = new Date(0);
283
+ }
284
+
285
+ return {
286
+ version: String(raw.version ?? ""),
287
+ filename: String(raw.filename ?? ""),
288
+ checksum: String(raw.checksum ?? ""),
289
+ applied_at: appliedAt,
290
+ execution_ms: Number(raw.execution_ms ?? 0),
291
+ success: Number(raw.success ?? 0),
292
+ installed_by:
293
+ typeof raw.installed_by === "string" ? raw.installed_by : null,
294
+ };
295
+ }
296
+
297
+ /**
298
+ * Run a SQL string (with `$1, $2, …` placeholders) against the
299
+ * tagged-template `Db`. We construct a synthetic `TemplateStringsArray`
300
+ * by splitting on the placeholder markers — the same pattern used by
301
+ * `filling/session-sqlite.ts:splitPlaceholders`.
302
+ *
303
+ * This keeps the value-binding path identical to user-authored tagged
304
+ * template literals (`db\`SELECT ...\``) — the values are forwarded to
305
+ * Bun.SQL as bound parameters, never concatenated into the SQL string.
306
+ */
307
+ async function execQuery<T extends Record<string, unknown>>(
308
+ db: Db,
309
+ sql: string,
310
+ params: unknown[],
311
+ ): Promise<T[]> {
312
+ const parts = splitPlaceholders(sql, params.length);
313
+ const strings = Object.assign(parts.slice(), {
314
+ raw: parts.slice(),
315
+ }) as unknown as TemplateStringsArray;
316
+ return (await db<T>(strings, ...params)) as T[];
317
+ }
318
+
319
+ /**
320
+ * Split a SQL string with `$1`, `$2`, … markers into the string segments
321
+ * that bracket each placeholder. The resulting array has
322
+ * `placeholderCount + 1` entries — matches a real
323
+ * `TemplateStringsArray`'s shape.
324
+ *
325
+ * Throws if the detected placeholder count disagrees with the provided
326
+ * `params.length` — catches mismatched SQL/param pairs at call time
327
+ * rather than surfacing them as a confusing Bun.SQL error.
328
+ */
329
+ function splitPlaceholders(sql: string, expected: number): string[] {
330
+ const parts: string[] = [];
331
+ let rest = sql;
332
+ for (let i = 1; i <= expected; i++) {
333
+ const marker = `$${i}`;
334
+ const idx = rest.indexOf(marker);
335
+ if (idx === -1) {
336
+ throw new Error(
337
+ `[@mandujs/core/db/migrations] placeholder ${marker} missing in SQL: ${sql}`,
338
+ );
339
+ }
340
+ parts.push(rest.slice(0, idx));
341
+ rest = rest.slice(idx + marker.length);
342
+ }
343
+ parts.push(rest);
344
+ return parts;
345
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * @mandujs/core/db/migrations/lock
3
+ *
4
+ * Per-dialect serialization for the migration apply loop. Prevents two
5
+ * concurrent `MigrationRunner.apply()` calls — in the same process or
6
+ * (for PG/MySQL) across processes — from stepping on each other.
7
+ *
8
+ * ## Strategy matrix
9
+ *
10
+ * | Provider | Strategy | Mechanism |
11
+ * |-----------|-----------------------|------------------------------------------------------------------|
12
+ * | postgres | `pg_advisory_lock` | `pg_advisory_lock($1)` — lockId = `hashtext('mandu:migrations')` |
13
+ * | mysql | `mysql_get_lock` | `GET_LOCK('mandu:migrations', 60)` — blocks up to 60 s |
14
+ * | sqlite | `sqlite_immediate` | `BEGIN IMMEDIATE` on a dedicated connection |
15
+ * | (any) | `none` | No-op (tests / non-concurrent scenarios) |
16
+ *
17
+ * All strategies wrap the same conceptual lock — the lockId string
18
+ * (`"mandu:migrations"` by default) is stable across runs, so two
19
+ * processes agreeing on the same string will serialise. If callers pass
20
+ * a custom `lockId`, every participant MUST use the same value.
21
+ *
22
+ * ## Release semantics
23
+ *
24
+ * `acquireMigrationLock(...)` returns a `MigrationLock` whose
25
+ * `release()` is idempotent. Callers should invoke it in a `finally`
26
+ * block — the `MigrationRunner.apply()` implementation does exactly
27
+ * this. SQLite's `sqlite_immediate` releases by committing the wrapper
28
+ * transaction; the other strategies issue an explicit unlock statement.
29
+ *
30
+ * @module db/migrations/lock
31
+ */
32
+
33
+ import type { LockStrategy } from "../../resource/ddl/types";
34
+ import type { Db } from "../index";
35
+
36
+ // ─── Public API ─────────────────────────────────────────────────────────────
37
+
38
+ /** A held migration lock. Calling `release()` twice is a no-op. */
39
+ export interface MigrationLock {
40
+ release(): Promise<void>;
41
+ }
42
+
43
+ /**
44
+ * Default lockId — a stable string shared by every participant. For
45
+ * `pg_advisory_lock` we hash this to a bigint via `hashtext()`; the
46
+ * other dialects use the raw string.
47
+ */
48
+ export const DEFAULT_LOCK_ID = "mandu:migrations";
49
+
50
+ /** MySQL `GET_LOCK` default timeout in seconds. */
51
+ const MYSQL_LOCK_TIMEOUT_SECONDS = 60;
52
+
53
+ /**
54
+ * Acquire the migration lock for the configured dialect.
55
+ *
56
+ * - `pg_advisory_lock` blocks the connection until the lock is granted.
57
+ * - `mysql_get_lock` blocks up to {@link MYSQL_LOCK_TIMEOUT_SECONDS}; on
58
+ * timeout we throw a descriptive error.
59
+ * - `sqlite_immediate` enters a BEGIN IMMEDIATE transaction on a
60
+ * dedicated connection; if another writer holds the database lock,
61
+ * Bun.SQL surfaces `SQLITE_BUSY` which we rethrow.
62
+ * - `none` is a no-op — useful for tests and single-shot CLI runs.
63
+ *
64
+ * @throws on MySQL lock timeout (`GET_LOCK` returns `0`), on explicit
65
+ * `GET_LOCK` error (returns `null`), or on provider/strategy mismatch
66
+ * (e.g. requesting `pg_advisory_lock` while `db.provider === "sqlite"`).
67
+ */
68
+ export async function acquireMigrationLock(
69
+ db: Db,
70
+ strategy: LockStrategy,
71
+ lockId: string = DEFAULT_LOCK_ID,
72
+ ): Promise<MigrationLock> {
73
+ switch (strategy) {
74
+ case "pg_advisory_lock":
75
+ assertProvider(db, "postgres", strategy);
76
+ return await acquirePgAdvisoryLock(db, lockId);
77
+ case "mysql_get_lock":
78
+ assertProvider(db, "mysql", strategy);
79
+ return await acquireMysqlLock(db, lockId);
80
+ case "sqlite_immediate":
81
+ assertProvider(db, "sqlite", strategy);
82
+ return await acquireSqliteImmediate(db, lockId);
83
+ case "none":
84
+ return makeNoopLock();
85
+ }
86
+ }
87
+
88
+ // ─── Strategy impls ─────────────────────────────────────────────────────────
89
+
90
+ async function acquirePgAdvisoryLock(
91
+ db: Db,
92
+ lockId: string,
93
+ ): Promise<MigrationLock> {
94
+ // Postgres advisory locks take a bigint. We derive it from the lockId
95
+ // string via `hashtext()::bigint` so the value is deterministic for
96
+ // the same input across instances. `hashtext` returns int4; cast to
97
+ // bigint for compatibility with `pg_advisory_lock(bigint)`.
98
+ //
99
+ // `SELECT pg_advisory_lock(hashtext($1)::bigint)` is safer than
100
+ // computing the hash client-side because it keeps every participant
101
+ // in the same database agreeing on the value without language-specific
102
+ // hash-function reproduction.
103
+ await db`SELECT pg_advisory_lock(hashtext(${lockId})::bigint)`;
104
+
105
+ let released = false;
106
+ return {
107
+ async release(): Promise<void> {
108
+ if (released) return;
109
+ released = true;
110
+ try {
111
+ await db`SELECT pg_advisory_unlock(hashtext(${lockId})::bigint)`;
112
+ } catch (err) {
113
+ // Best-effort release — if the connection has already died or
114
+ // the lock is no longer held, we don't want to mask the caller's
115
+ // unwind path. Surface the error name for diagnostics.
116
+ const msg = err instanceof Error ? err.message : String(err);
117
+ console.warn(
118
+ `[@mandujs/core/db/migrations] pg_advisory_unlock failed: ${msg}`,
119
+ );
120
+ }
121
+ },
122
+ };
123
+ }
124
+
125
+ async function acquireMysqlLock(
126
+ db: Db,
127
+ lockId: string,
128
+ ): Promise<MigrationLock> {
129
+ // `GET_LOCK` returns:
130
+ // 1 — lock granted
131
+ // 0 — timeout (still blocked after the timeout)
132
+ // NULL — error (aborted, killed, etc.)
133
+ //
134
+ // Bun.SQL returns the single row as `[{ acquired: 1 }]`; we destructure
135
+ // defensively to handle any driver-side aliasing.
136
+ const timeoutSec = MYSQL_LOCK_TIMEOUT_SECONDS;
137
+ const rows = await db<{ acquired: number | bigint | null }>`
138
+ SELECT GET_LOCK(${lockId}, ${timeoutSec}) AS acquired
139
+ `;
140
+ const first = rows[0];
141
+ const value = first ? Number(first.acquired) : NaN;
142
+ if (value !== 1) {
143
+ throw new Error(
144
+ `[@mandujs/core/db/migrations] GET_LOCK(${JSON.stringify(lockId)}, ${timeoutSec}) ` +
145
+ `returned ${value === 0 ? "0 (timeout)" : "NULL (error)"}; ` +
146
+ `another migration runner may be holding the lock.`,
147
+ );
148
+ }
149
+
150
+ let released = false;
151
+ return {
152
+ async release(): Promise<void> {
153
+ if (released) return;
154
+ released = true;
155
+ try {
156
+ await db`SELECT RELEASE_LOCK(${lockId})`;
157
+ } catch (err) {
158
+ const msg = err instanceof Error ? err.message : String(err);
159
+ console.warn(
160
+ `[@mandujs/core/db/migrations] RELEASE_LOCK failed: ${msg}`,
161
+ );
162
+ }
163
+ },
164
+ };
165
+ }
166
+
167
+ /**
168
+ * Per-process mutex queues keyed by lockId. SQLite is single-writer at
169
+ * the engine level, so cross-process writes already serialise — the
170
+ * remaining failure mode is two `apply()` calls in the SAME process
171
+ * interleaving their `db.transaction(...)` calls. A process-local
172
+ * promise chain is the simplest correct coordinator.
173
+ *
174
+ * This is stored on `globalThis` rather than module scope so that
175
+ * multiple copies of the module (e.g. reloads under watch mode) still
176
+ * agree on the same queue.
177
+ */
178
+ const SQLITE_LOCK_REGISTRY_SYMBOL = Symbol.for(
179
+ "@mandujs/core/db/migrations/sqlite-locks",
180
+ );
181
+ interface SqliteLockRegistry {
182
+ /** Most-recent promise in each lockId's queue. */
183
+ chains: Map<string, Promise<void>>;
184
+ }
185
+ function getSqliteLockRegistry(): SqliteLockRegistry {
186
+ const g = globalThis as unknown as Record<symbol, unknown>;
187
+ let reg = g[SQLITE_LOCK_REGISTRY_SYMBOL] as SqliteLockRegistry | undefined;
188
+ if (!reg) {
189
+ reg = { chains: new Map() };
190
+ g[SQLITE_LOCK_REGISTRY_SYMBOL] = reg;
191
+ }
192
+ return reg;
193
+ }
194
+
195
+ async function acquireSqliteImmediate(
196
+ db: Db,
197
+ lockId: string,
198
+ ): Promise<MigrationLock> {
199
+ // Why an in-process mutex instead of `BEGIN IMMEDIATE`:
200
+ //
201
+ // - `BEGIN IMMEDIATE` at the handle level conflicts with the
202
+ // `db.transaction()` calls we issue per-migration — SQLite
203
+ // errors with "cannot start a transaction within a transaction".
204
+ // - SQLite is already single-writer at the engine level, so
205
+ // cross-process writes queue via the OS file lock; the only
206
+ // race we need to close is two concurrent `apply()` calls in
207
+ // the SAME process interleaving their statements.
208
+ // - A promise-chain mutex is the minimal correct mechanism for
209
+ // in-process serialisation. Every apply() awaits the previous
210
+ // holder's release before entering the critical section.
211
+ //
212
+ // Cross-process migration coordination is v2 per RFC 0001 §8.
213
+ //
214
+ // Sanity probe: executing a trivial statement on the handle at
215
+ // acquire time catches "pool closed" / handle validity issues
216
+ // before the caller commits resources to the apply loop.
217
+ await db`SELECT 1`;
218
+
219
+ const registry = getSqliteLockRegistry();
220
+ const previous = registry.chains.get(lockId) ?? Promise.resolve();
221
+
222
+ let release!: () => void;
223
+ const nextPromise = new Promise<void>((resolve) => {
224
+ release = resolve;
225
+ });
226
+ const tail = previous.then(() => nextPromise);
227
+ registry.chains.set(lockId, tail);
228
+
229
+ // Wait for the previous holder to release.
230
+ await previous;
231
+
232
+ let released = false;
233
+ return {
234
+ async release(): Promise<void> {
235
+ if (released) return;
236
+ released = true;
237
+ release();
238
+ // If no one queued behind us, drop the entry so the registry
239
+ // doesn't grow unbounded across many apply() cycles.
240
+ if (registry.chains.get(lockId) === tail) {
241
+ registry.chains.delete(lockId);
242
+ }
243
+ },
244
+ };
245
+ }
246
+
247
+ function makeNoopLock(): MigrationLock {
248
+ let released = false;
249
+ return {
250
+ async release(): Promise<void> {
251
+ released = true;
252
+ },
253
+ };
254
+ }
255
+
256
+ // ─── Helpers ────────────────────────────────────────────────────────────────
257
+
258
+ function assertProvider(
259
+ db: Db,
260
+ expected: Db["provider"],
261
+ strategy: LockStrategy,
262
+ ): void {
263
+ if (db.provider !== expected) {
264
+ throw new Error(
265
+ `[@mandujs/core/db/migrations] Lock strategy ${JSON.stringify(strategy)} requires ` +
266
+ `provider ${JSON.stringify(expected)}, but db.provider is ${JSON.stringify(db.provider)}.`,
267
+ );
268
+ }
269
+ }