@hop-top/kit 0.5.0-alpha.11 → 0.5.0-alpha.13

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 (102) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +5 -5
  3. package/dist/bus-D2bAOPYz.d.ts +55 -0
  4. package/dist/bus.d.ts +1 -0
  5. package/dist/bus.js +13 -0
  6. package/dist/chunk-74E6RNOI.js +82 -0
  7. package/dist/chunk-B7XTFDBB.js +17 -0
  8. package/dist/chunk-CAONBSPO.js +497 -0
  9. package/dist/chunk-F7RSL4N4.js +88 -0
  10. package/dist/chunk-I6XDPSXQ.js +75 -0
  11. package/dist/chunk-IDM6YZXN.js +204 -0
  12. package/dist/chunk-P3Y46PYF.js +138 -0
  13. package/dist/chunk-VKQCOVKI.js +880 -0
  14. package/dist/cli.js +3 -3
  15. package/dist/id/index.d.ts +1 -1
  16. package/dist/id/index.js +4 -2
  17. package/dist/index-BqZ7WGQf.d.ts +731 -0
  18. package/dist/{index-VLDcI5NF.d.ts → index-D9zpUrpE.d.ts} +18 -6
  19. package/dist/index.d.ts +5 -2
  20. package/dist/index.js +27 -13
  21. package/dist/upgrade/drivers/configfile.d.ts +45 -0
  22. package/dist/upgrade/drivers/configfile.js +78 -0
  23. package/dist/upgrade/drivers/fsdir.d.ts +61 -0
  24. package/dist/upgrade/drivers/fsdir.js +170 -0
  25. package/dist/upgrade/drivers/postgres.d.ts +121 -0
  26. package/dist/upgrade/drivers/postgres.js +195 -0
  27. package/dist/upgrade/drivers/sqlite.d.ts +101 -0
  28. package/dist/upgrade/drivers/sqlite.js +241 -0
  29. package/dist/upgrade/index.d.ts +2 -0
  30. package/dist/upgrade/index.js +73 -0
  31. package/dist/uri-IJ_AoY3d.d.ts +144 -0
  32. package/dist/uri.d.ts +1 -0
  33. package/dist/uri.js +37 -0
  34. package/dist/version-DEJ3pbiO.d.ts +10 -0
  35. package/dist/wizard-Bf_qHc31.d.ts +159 -0
  36. package/dist/wizard.d.ts +1 -0
  37. package/dist/wizard.js +39 -0
  38. package/package.json +78 -19
  39. package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +19 -0
  40. package/skills/hop-top-kit-ts/SKILL.md +117 -0
  41. package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.expected +2 -0
  42. package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.ts +20 -0
  43. package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.expected +13 -0
  44. package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.ts +26 -0
  45. package/skills/hop-top-kit-ts/gym.json +5 -0
  46. package/skills/hop-top-kit-ts/references/ai-and-agents.md +45 -0
  47. package/skills/hop-top-kit-ts/references/cli-and-console.md +63 -0
  48. package/skills/hop-top-kit-ts/references/coverage.md +56 -0
  49. package/skills/hop-top-kit-ts/references/guardrails-and-trust.md +60 -0
  50. package/skills/hop-top-kit-ts/references/other-ports.md +31 -0
  51. package/skills/hop-top-kit-ts/references/serving-and-transports.md +49 -0
  52. package/skills/hop-top-kit-ts/scripts/detect-port.sh +168 -0
  53. package/src/id/README.md +2 -2
  54. package/src/id/contract.test.ts +11 -8
  55. package/src/id/differential.test.ts +54 -0
  56. package/src/id/index.ts +123 -17
  57. package/src/index.test.ts +48 -2
  58. package/src/index.ts +6 -1
  59. package/src/published-types.test.ts +8 -0
  60. package/src/serve.stopped-order.test.ts +156 -0
  61. package/src/upgrade/README.md +42 -0
  62. package/src/upgrade/backup.ts +174 -0
  63. package/src/upgrade/conformance.test.ts +310 -0
  64. package/src/upgrade/document.ts +229 -0
  65. package/src/upgrade/driver.ts +66 -0
  66. package/src/upgrade/drivers/README.md +47 -0
  67. package/src/upgrade/drivers/configfile.test.ts +112 -0
  68. package/src/upgrade/drivers/configfile.ts +107 -0
  69. package/src/upgrade/drivers/fsdir.test.ts +188 -0
  70. package/src/upgrade/drivers/fsdir.ts +216 -0
  71. package/src/upgrade/drivers/isolation.test.ts +18 -0
  72. package/src/upgrade/drivers/postgres.integration.test.ts +395 -0
  73. package/src/upgrade/drivers/postgres.test.ts +272 -0
  74. package/src/upgrade/drivers/postgres.ts +284 -0
  75. package/src/upgrade/drivers/sqlite.integration.test.ts +492 -0
  76. package/src/upgrade/drivers/sqlite.ts +300 -0
  77. package/src/upgrade/drivers/version.ts +21 -0
  78. package/src/upgrade/errors.ts +117 -0
  79. package/src/upgrade/events.ts +117 -0
  80. package/src/{upgrade.test.ts → upgrade/index.test.ts} +102 -1
  81. package/src/{upgrade.ts → upgrade/index.ts} +96 -27
  82. package/src/upgrade/migration.ts +89 -0
  83. package/src/upgrade/migrator.test.ts +391 -0
  84. package/src/upgrade/migrator.ts +527 -0
  85. package/src/upgrade/options.ts +59 -0
  86. package/src/upgrade/semver.ts +90 -0
  87. package/test/skill-snippets.test.ts +60 -0
  88. package/test/upgrade/conformance-migrator.ts +439 -0
  89. package/test/upgrade/conformance-support.ts +44 -0
  90. package/test/upgrade/driver-support.ts +44 -0
  91. package/test/upgrade/pg-container.ts +64 -0
  92. package/test/upgrade/pg-race-worker.ts +48 -0
  93. package/test/upgrade/race-helper.ts +36 -0
  94. package/test/upgrade/sqlite-support.ts +41 -0
  95. package/test/upgrade/testdata/go-fsdir-mydata.tar.gz +0 -0
  96. package/vitest.config.ts +26 -0
  97. package/dist/chunk-4GPCWBBA.js +0 -143
  98. package/dist/chunk-L23O2FFE.js +0 -51
  99. package/dist/upgrade-C3RWGwRi.d.ts +0 -125
  100. package/dist/upgrade.d.ts +0 -1
  101. package/dist/upgrade.js +0 -7
  102. package/dist/{chunk-MFVUENZR.js → chunk-KV7FYEAF.js} +2 -2
@@ -17,8 +17,10 @@
17
17
  * ### Error handling philosophy
18
18
  * Version checking is a best-effort, non-critical operation. Any failure —
19
19
  * network error, bad JSON, HTTP error, filesystem error, invalid semver — is
20
- * silently discarded. The function always resolves without throwing. If
21
- * something goes wrong the user sees neither a notice nor an error.
20
+ * silently discarded by `notifyIfAvailable`, which always resolves without
21
+ * throwing. `check()` is the strict variant: it rejects with an
22
+ * {@link UpgradeCheckError} so callers (e.g. `upgrade --check`) can tell a
23
+ * failed lookup from "up to date".
22
24
  *
23
25
  * ### Notice format
24
26
  * ```
@@ -100,11 +102,41 @@ export interface CheckerOptions {
100
102
  includePrereleases?: boolean;
101
103
  }
102
104
 
105
+ /** Outcome of {@link Checker.check}. */
106
+ export interface UpgradeCheckResult {
107
+ /** Running version, as configured. */
108
+ current: string;
109
+ /** Latest release version (no leading `v` / tag prefix). */
110
+ latest: string;
111
+ /** True when `latest` is strictly greater than `current`. */
112
+ updateAvailable: boolean;
113
+ /** Release page to link to. */
114
+ url: string;
115
+ }
116
+
117
+ /** Rejection of {@link Checker.check}; the underlying error is in `cause`. */
118
+ export class UpgradeCheckError extends Error {
119
+ constructor(message: string, options?: { cause?: unknown }) {
120
+ super(message, options);
121
+ this.name = 'UpgradeCheckError';
122
+ }
123
+ }
124
+
103
125
  /**
104
126
  * Returned by {@link createChecker}. Call {@link Checker.notifyIfAvailable}
105
127
  * at the end of a CLI command to surface upgrade notices non-intrusively.
106
128
  */
107
129
  export interface Checker {
130
+ /**
131
+ * Looks up the latest release and resolves with the outcome. Unlike
132
+ * {@link Checker.notifyIfAvailable} it never swallows failures: network,
133
+ * HTTP, parse and "no matching release" errors reject with an
134
+ * {@link UpgradeCheckError}, so callers can tell a failed lookup from
135
+ * "up to date". Honours `tagPrefix`, `includePrereleases` and the cache;
136
+ * pass `cacheTTL: 0` to bypass the cache.
137
+ */
138
+ check(): Promise<UpgradeCheckResult>;
139
+
108
140
  /**
109
141
  * Checks for a newer GitHub release and writes a one-line notice to `out`
110
142
  * if one is available. Silently swallows all errors.
@@ -218,7 +250,7 @@ export function createChecker(opts: CheckerOptions): Checker {
218
250
  tag?: string;
219
251
  }
220
252
 
221
- async function fetchLatestVersion(): Promise<Latest | null> {
253
+ async function fetchLatestVersion(): Promise<Latest> {
222
254
  const controller = new AbortController();
223
255
  const timer = setTimeout(() => controller.abort(), timeout);
224
256
  try {
@@ -227,10 +259,10 @@ export function createChecker(opts: CheckerOptions): Checker {
227
259
  signal: controller.signal,
228
260
  headers: { Accept: 'application/vnd.github+json' },
229
261
  });
230
- if (!res.ok) return null;
262
+ if (!res.ok) throw new UpgradeCheckError(`release lookup failed: HTTP ${res.status}`);
231
263
  const body = (await res.json()) as { tag_name?: string };
232
264
  const tag = body.tag_name;
233
- if (typeof tag !== 'string') return null;
265
+ if (typeof tag !== 'string') throw new UpgradeCheckError('release lookup failed: no tag_name');
234
266
  // Strip leading 'v' so semver.gt works with or without prefix.
235
267
  return { version: tag.replace(/^v/, '') };
236
268
  } finally {
@@ -243,7 +275,7 @@ export function createChecker(opts: CheckerOptions): Checker {
243
275
  * among non-draft releases whose tag starts with `tagPrefix`; prereleases
244
276
  * only when `includePrereleases` is set.
245
277
  */
246
- async function fetchHighestRelease(signal: AbortSignal): Promise<Latest | null> {
278
+ async function fetchHighestRelease(signal: AbortSignal): Promise<Latest> {
247
279
  let best: Latest | null = null;
248
280
  for (let page = 1; page <= MAX_PAGES; page++) {
249
281
  const res = await fetch(`${listURL}?per_page=${PAGE_SIZE}&page=${page}`, {
@@ -252,11 +284,14 @@ export function createChecker(opts: CheckerOptions): Checker {
252
284
  });
253
285
  if (!res.ok) {
254
286
  // Page 1 failing is a failed check; a later page keeps what we have.
255
- if (page === 1) return null;
287
+ if (page === 1) throw new UpgradeCheckError(`release lookup failed: HTTP ${res.status}`);
256
288
  break;
257
289
  }
258
290
  const body = (await res.json()) as unknown;
259
- if (!Array.isArray(body)) return page === 1 ? null : best;
291
+ if (!Array.isArray(body)) {
292
+ if (page === 1) throw new UpgradeCheckError('release lookup failed: unexpected response');
293
+ break;
294
+ }
260
295
  for (const rel of body as GitHubRelease[]) {
261
296
  if (rel === null || typeof rel !== 'object') continue;
262
297
  if (rel.draft === true || typeof rel.tag_name !== 'string') continue;
@@ -271,44 +306,78 @@ export function createChecker(opts: CheckerOptions): Checker {
271
306
  }
272
307
  if (body.length < PAGE_SIZE) break;
273
308
  }
309
+ if (best === null) throw new UpgradeCheckError('no matching release found');
274
310
  return best;
275
311
  }
276
312
 
277
- // ── notifyIfAvailable ──────────────────────────────────────────────────────
313
+ // ── check ──────────────────────────────────────────────────────────────────
278
314
 
279
- async function notifyIfAvailable(out: NodeJS.WritableStream): Promise<void> {
315
+ async function check(): Promise<UpgradeCheckResult> {
280
316
  try {
281
- let latestVersion: string | null = null;
317
+ let latestVersion: string;
282
318
  let latestTag: string | undefined;
283
319
 
284
- // Check cache first.
285
320
  const cached = readCache();
286
321
  if (cached !== null && Date.now() - cached.checkedAt < cacheTTL) {
287
322
  latestVersion = cached.version;
288
323
  latestTag = cached.tag;
289
324
  } else {
290
325
  const latest = await fetchLatestVersion();
291
- if (latest !== null) {
292
- latestVersion = latest.version;
293
- latestTag = latest.tag;
294
- writeCache(latest.version, latest.tag);
295
- }
326
+ latestVersion = latest.version;
327
+ latestTag = latest.tag;
328
+ writeCache(latest.version, latest.tag);
296
329
  }
297
330
 
298
- if (latestVersion === null) return;
299
-
300
- // Only notify when latest is strictly greater than current.
301
- if (!semver.gt(latestVersion, currentVersion)) return;
331
+ return {
332
+ current: currentVersion,
333
+ latest: latestVersion,
334
+ // Only strictly greater counts as an update.
335
+ updateAvailable: semver.gt(latestVersion, currentVersion),
336
+ url: noticeURL(latestTag),
337
+ };
338
+ } catch (err) {
339
+ if (err instanceof UpgradeCheckError) throw err;
340
+ throw new UpgradeCheckError(
341
+ `upgrade check failed: ${err instanceof Error ? err.message : String(err)}`,
342
+ { cause: err },
343
+ );
344
+ }
345
+ }
302
346
 
303
- const notice =
304
- `\nA new release of ${name} is available: v${currentVersion} → v${latestVersion}\n` +
305
- `${noticeURL(latestTag)}\n`;
347
+ // ── notifyIfAvailable ──────────────────────────────────────────────────────
306
348
 
307
- out.write(notice);
349
+ async function notifyIfAvailable(out: NodeJS.WritableStream): Promise<void> {
350
+ try {
351
+ const r = await check();
352
+ if (!r.updateAvailable) return;
353
+ out.write(
354
+ `\nA new release of ${name} is available: v${r.current} → v${r.latest}\n` +
355
+ `${r.url}\n`,
356
+ );
308
357
  } catch {
309
- // Any unexpected error is silently swallowed.
358
+ // Best-effort: any failure is silently swallowed.
310
359
  }
311
360
  }
312
361
 
313
- return { notifyIfAvailable };
362
+ return { check, notifyIfAvailable };
314
363
  }
364
+
365
+ // ─── Migrations ───────────────────────────────────────────────────────────────
366
+
367
+ export * from './semver';
368
+ export * from './migration';
369
+ export * from './document';
370
+ export * from './errors';
371
+ export * from './driver';
372
+ export {
373
+ DEFAULT_MIGRATION_TOPICS,
374
+ PUBLISH_SOURCE,
375
+ topicsFromPrefix,
376
+ type EventPublisher,
377
+ type MigrationPayload,
378
+ type MigrationRunPayload,
379
+ type MigrationTopics,
380
+ } from './events';
381
+ export * from './options';
382
+ export * from './migrator';
383
+ export { readVersionFile, writeVersionFile, defaultDataDir } from './backup';
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Versioned schema migrations and the registry that holds them, ported
3
+ * from Go `core/upgrade`. The registry selects what is pending between two
4
+ * versions; running them is the Migrator's job.
5
+ */
6
+
7
+ import { compareSemver, parseSemver, trimV } from './semver';
8
+
9
+ /** A versioned schema migration. */
10
+ export interface Migration {
11
+ /** Semver, pre-release allowed. A leading `v` is dropped when ordering. */
12
+ version: string;
13
+ /** Matches the schema driver's name. */
14
+ schema: string;
15
+ /**
16
+ * A failed `up` is an applied step that cannot be downed: the run
17
+ * restores the backup it took (none on a server database or a handle:
18
+ * the run ends not restored), so keep an `up` atomic where there is none.
19
+ */
20
+ up(signal?: AbortSignal): void | Promise<void>;
21
+ /**
22
+ * Undoes a completed `up` (after a failed `verify`, version record or
23
+ * final verify). Never called for a step whose own `up` failed. Absent
24
+ * means the rollback falls back to the backup.
25
+ */
26
+ down?(signal?: AbortSignal): void | Promise<void>;
27
+ /**
28
+ * When set, runs after `up` and before the version is recorded. A failure
29
+ * counts as a failed step and the rollback includes this migration.
30
+ */
31
+ verify?(signal?: AbortSignal): void | Promise<void>;
32
+ }
33
+
34
+ /**
35
+ * Holds migrations for one or more Migrators. {@link registerMigration}
36
+ * feeds {@link defaultRegistry}; a Migrator reads that one unless given
37
+ * another, made with `new Registry()`.
38
+ */
39
+ export class Registry {
40
+ private migrations: Migration[] = [];
41
+
42
+ /** Adds a migration. Throws a TypeError when `up` is not a function. */
43
+ register(m: Migration): void {
44
+ if (typeof m.up !== 'function') {
45
+ throw new TypeError(`upgrade: migration ${m.version} has nil Up function`);
46
+ }
47
+ this.migrations.push(m);
48
+ }
49
+
50
+ /** Empties the registry. */
51
+ reset(): void {
52
+ this.migrations = [];
53
+ }
54
+
55
+ /**
56
+ * Migrations of `schema` whose version v satisfies from < v <= to,
57
+ * ascending by version, versions as registered. Equal versions have no
58
+ * defined order.
59
+ */
60
+ pending(schema: string, from: string, to: string): Migration[] {
61
+ const fromV = parseSemver(trimV(from));
62
+ const toV = parseSemver(trimV(to));
63
+ const out: { m: Migration; v: ReturnType<typeof parseSemver> }[] = [];
64
+ for (const m of this.migrations) {
65
+ if (m.schema !== schema) continue;
66
+ const v = parseSemver(trimV(m.version));
67
+ if (compareSemver(v, fromV) > 0 && compareSemver(v, toV) <= 0) out.push({ m, v });
68
+ }
69
+ out.sort((a, b) => compareSemver(a.v, b.v));
70
+ return out.map((e) => e.m);
71
+ }
72
+ }
73
+
74
+ const defaultReg = new Registry();
75
+
76
+ /** The registry {@link registerMigration} adds to. */
77
+ export function defaultRegistry(): Registry {
78
+ return defaultReg;
79
+ }
80
+
81
+ /** Adds a migration to the default registry. */
82
+ export function registerMigration(m: Migration): void {
83
+ defaultReg.register(m);
84
+ }
85
+
86
+ /** Clears the default registry. For tests only. */
87
+ export function resetRegistryForTest(): void {
88
+ defaultReg.reset();
89
+ }
@@ -0,0 +1,391 @@
1
+ import { mkdtempSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
6
+
7
+ import { createBus } from '../bus';
8
+ import {
9
+ BackupUnsupportedError,
10
+ Migrator,
11
+ Registry,
12
+ abortError,
13
+ isBackupUnsupported,
14
+ isCanceled,
15
+ isNotRestored,
16
+ isVerifyError,
17
+ readVersionFile,
18
+ type SchemaDriver,
19
+ type Unlock,
20
+ } from './index';
21
+
22
+ let dir: string;
23
+ beforeEach(() => {
24
+ dir = mkdtempSync(join(tmpdir(), 'migrator-test-'));
25
+ });
26
+ afterEach(() => rmSync(dir, { recursive: true, force: true }));
27
+
28
+ const tick = (ms = 5) => new Promise<void>((r) => setTimeout(r, ms));
29
+
30
+ /** An async, lockable, version-storing driver over one shared store. */
31
+ class SharedStore {
32
+ version = '';
33
+ log: string[] = [];
34
+ private held = false;
35
+ private waiters: (() => void)[] = [];
36
+
37
+ async acquire(signal?: AbortSignal): Promise<Unlock> {
38
+ while (this.held) {
39
+ await new Promise<void>((resolve, reject) => {
40
+ const onAbort = () => reject(abortError(signal as AbortSignal));
41
+ if (signal?.aborted) return onAbort();
42
+ signal?.addEventListener('abort', onAbort, { once: true });
43
+ this.waiters.push(() => {
44
+ signal?.removeEventListener('abort', onAbort);
45
+ resolve();
46
+ });
47
+ });
48
+ }
49
+ this.held = true;
50
+ return () => {
51
+ this.held = false;
52
+ this.log.push('unlock');
53
+ this.waiters.shift()?.();
54
+ };
55
+ }
56
+
57
+ driver(name = 'db'): SchemaDriver {
58
+ return {
59
+ name: () => name,
60
+ storesVersion: true,
61
+ version: async () => {
62
+ await tick(1);
63
+ return this.version;
64
+ },
65
+ setVersion: async (v) => {
66
+ await tick(1);
67
+ this.version = v;
68
+ },
69
+ backup: () => {
70
+ throw new BackupUnsupportedError();
71
+ },
72
+ restore: () => {
73
+ throw new BackupUnsupportedError();
74
+ },
75
+ lock: (signal) => this.acquire(signal),
76
+ };
77
+ }
78
+ }
79
+
80
+ function registryWith(upLog: string[], ...versions: string[]): Registry {
81
+ const reg = new Registry();
82
+ for (const v of versions) {
83
+ reg.register({
84
+ schema: 'db',
85
+ version: v,
86
+ up: async () => {
87
+ upLog.push('up ' + v);
88
+ await tick(20);
89
+ },
90
+ });
91
+ }
92
+ return reg;
93
+ }
94
+
95
+ describe('Migrator concurrency', () => {
96
+ it('a second run awaits the first unlock, then finds nothing pending', async () => {
97
+ const store = new SharedStore();
98
+ const ups: string[] = [];
99
+ const reg = registryWith(ups, '1.1.0', '1.2.0');
100
+ const a = new Migrator('t', '1.2.0', { registry: reg, dataDir: dir });
101
+ const b = new Migrator('t', '1.2.0', { registry: reg, dataDir: dir });
102
+ a.addDriver(store.driver());
103
+ b.addDriver(store.driver());
104
+
105
+ let bDone = false;
106
+ const first = a.run();
107
+ await tick(2); // a holds the lock now
108
+ const second = b.run().then(() => {
109
+ bDone = true;
110
+ });
111
+ await tick(10);
112
+ expect(bDone, 'b must still wait while a holds the lock').toBe(false);
113
+ await first;
114
+ await second;
115
+
116
+ expect(ups).toEqual(['up 1.1.0', 'up 1.2.0']);
117
+ expect(a.history()).toHaveLength(2);
118
+ expect(b.history()).toHaveLength(0);
119
+ expect(store.version).toBe('1.2.0');
120
+ expect(store.log).toEqual(['unlock', 'unlock']);
121
+ });
122
+
123
+ it('a waiting lock fails with the signal text when the run is aborted', async () => {
124
+ const store = new SharedStore();
125
+ const ups: string[] = [];
126
+ const reg = registryWith(ups, '1.1.0');
127
+ const a = new Migrator('t', '1.1.0', { registry: reg, dataDir: dir });
128
+ const b = new Migrator('t', '1.1.0', { registry: reg, dataDir: dir });
129
+ a.addDriver(store.driver());
130
+ b.addDriver(store.driver());
131
+ const first = a.run();
132
+ await tick(2);
133
+ const ctl = new AbortController();
134
+ const second = b.run(ctl.signal);
135
+ await tick(2);
136
+ ctl.abort();
137
+ const err = await second.then(
138
+ () => undefined,
139
+ (e: unknown) => e,
140
+ );
141
+ expect((err as Error).message).toBe('migrate db: lock: context canceled');
142
+ expect(isCanceled(err)).toBe(true);
143
+ await first;
144
+ expect(store.log).toEqual(['unlock']);
145
+ });
146
+ });
147
+
148
+ describe('Migrator error paths', () => {
149
+ function lockable(log: string[]): SchemaDriver {
150
+ let version = '1.0.0';
151
+ return {
152
+ name: () => 'db',
153
+ version: () => version,
154
+ setVersion: (v) => {
155
+ version = v;
156
+ },
157
+ backup: () => {},
158
+ restore: () => {},
159
+ lock: () => {
160
+ log.push('lock');
161
+ return () => {
162
+ log.push('unlock');
163
+ };
164
+ },
165
+ };
166
+ }
167
+
168
+ for (const thrown of ['boom', { code: 7 }, null, 42, undefined]) {
169
+ it(`releases the lock when a migration throws ${JSON.stringify(thrown) ?? 'undefined'}`, async () => {
170
+ const log: string[] = [];
171
+ const reg = new Registry();
172
+ reg.register({
173
+ schema: 'db',
174
+ version: '1.1.0',
175
+ up: () => {
176
+ throw thrown;
177
+ },
178
+ });
179
+ const m = new Migrator('t', '1.1.0', { registry: reg, dataDir: dir, manualRollback: true });
180
+ m.addDriver(lockable(log));
181
+ const err = await m.run().then(
182
+ () => undefined,
183
+ (e: unknown) => e as Error,
184
+ );
185
+ expect(err?.message).toBe(`migrate db: up 1.1.0 failed: ${String(thrown)}`);
186
+ expect(log).toEqual(['lock', 'unlock']);
187
+ });
188
+ }
189
+
190
+ it('type guards see not restored, unsupported and verify through the run error', async () => {
191
+ const reg = new Registry();
192
+ reg.register({ schema: 'db', version: '1.1.0', up: () => {}, verify: () => { throw new Error('nope'); } });
193
+ const unsupported: SchemaDriver = {
194
+ name: () => 'db',
195
+ version: () => '1.0.0',
196
+ setVersion: () => {},
197
+ backup: () => {
198
+ throw new BackupUnsupportedError();
199
+ },
200
+ restore: () => {},
201
+ };
202
+ const m = new Migrator('t', '1.1.0', { registry: reg, dataDir: dir });
203
+ m.addDriver(unsupported);
204
+ const err = await m.run().then(
205
+ () => undefined,
206
+ (e: unknown) => e,
207
+ );
208
+ expect((err as Error).message).toBe(
209
+ 'migrate db: verify 1.1.0 failed: nope (rollback also failed: not restored: no backup was taken)',
210
+ );
211
+ expect(isNotRestored(err)).toBe(true);
212
+ expect(isBackupUnsupported(err)).toBe(true);
213
+ expect(isVerifyError(err)).toBe(true);
214
+ expect(isCanceled(err)).toBe(false);
215
+ });
216
+
217
+ it('an aborted timeout signal reads as a deadline', async () => {
218
+ const reg = new Registry();
219
+ reg.register({ schema: 'db', version: '1.1.0', up: () => {} });
220
+ const m = new Migrator('t', '1.1.0', { registry: reg, dataDir: dir });
221
+ m.addDriver(lockable([]));
222
+ const ctl = new AbortController();
223
+ ctl.abort(new DOMException('slow', 'TimeoutError'));
224
+ const err = await m.run(ctl.signal).then(
225
+ () => undefined,
226
+ (e: unknown) => e as Error,
227
+ );
228
+ expect(err?.message).toBe('migrate db: up 1.1.0 canceled: context deadline exceeded');
229
+ });
230
+ });
231
+
232
+ describe('Migrator wiring', () => {
233
+ it('publishes on a kit bus under a custom prefix and keeps the version file layout', async () => {
234
+ const bus = createBus();
235
+ const seen: string[] = [];
236
+ bus.subscribe('app.core.migration.#', (e) => {
237
+ seen.push(e.topic);
238
+ });
239
+ const reg = new Registry();
240
+ reg.register({ schema: 'cfg', version: '1.1.0', up: () => {} });
241
+ let stored = '1.0.0';
242
+ const m = new Migrator('t', 'v1.1.0', { registry: reg, dataDir: dir, publisher: bus, topicPrefix: 'app.core.migration' });
243
+ m.addDriver({
244
+ name: () => 'cfg',
245
+ version: () => stored,
246
+ setVersion: (v) => {
247
+ stored = v;
248
+ },
249
+ backup: () => {},
250
+ restore: () => {},
251
+ });
252
+ await m.run();
253
+ expect(m.version).toBe('1.1.0');
254
+ expect(seen).toEqual([
255
+ 'app.core.migration.run_started',
256
+ 'app.core.migration.started',
257
+ 'app.core.migration.applied',
258
+ 'app.core.migration.run_completed',
259
+ ]);
260
+ expect(await readVersionFile(dir, 'cfg')).toBe('1.1.0');
261
+ });
262
+
263
+ it('rollbackLatest is refused outside manual mode', async () => {
264
+ const m = new Migrator('t', '1.0.0', { dataDir: dir });
265
+ await expect(m.rollbackLatest()).rejects.toThrow('rollback: only available in manual rollback mode');
266
+ });
267
+ });
268
+
269
+ describe('Migrator failed up', () => {
270
+ /** A recording driver at 1.0.0; `backup` may be unsupported. */
271
+ function recording(backupUnsupported = false) {
272
+ const d: { version: string; restored: boolean; driver: SchemaDriver } = {
273
+ version: '1.0.0',
274
+ restored: false,
275
+ driver: {
276
+ name: () => 'db',
277
+ storesVersion: true,
278
+ version: () => d.version,
279
+ setVersion: (v: string) => {
280
+ d.version = v;
281
+ },
282
+ backup: () => {
283
+ if (backupUnsupported) throw new BackupUnsupportedError();
284
+ },
285
+ restore: () => {
286
+ d.restored = true;
287
+ },
288
+ },
289
+ };
290
+ return d;
291
+ }
292
+ const failing = (downs: string[], upError: unknown = new Error('boom')): Registry => {
293
+ const reg = new Registry();
294
+ reg.register({ schema: 'db', version: '1.1.0', up: () => {}, down: () => void downs.push('1.1.0') });
295
+ reg.register({ schema: 'db', version: '1.2.0', up: () => Promise.reject(upError), down: () => void downs.push('1.2.0') });
296
+ return reg;
297
+ };
298
+ const run = (m: Migrator) =>
299
+ m.run().then(
300
+ () => undefined,
301
+ (e: unknown) => e as Error,
302
+ );
303
+
304
+ it('restores the backup and calls no down, neither its own nor an earlier one', async () => {
305
+ const downs: string[] = [];
306
+ const d = recording();
307
+ const methods: string[] = [];
308
+ const m = new Migrator('t', '1.2.0', {
309
+ registry: failing(downs),
310
+ dataDir: dir,
311
+ publisher: { publish: (e) => e.topic.endsWith('.reverted') && methods.push((e.payload as { method: string }).method) },
312
+ });
313
+ m.addDriver(d.driver);
314
+ const err = await run(m);
315
+ expect(err?.message).toContain('up 1.2.0 failed: boom');
316
+ expect(isNotRestored(err)).toBe(false);
317
+ expect(downs).toEqual([]);
318
+ expect(d.restored).toBe(true);
319
+ expect(d.version).toBe('1.0.0');
320
+ expect(methods).toEqual(['restore']);
321
+ });
322
+
323
+ it('an up that fails with the abort error is a failed up: restore, no down', async () => {
324
+ const downs: string[] = [];
325
+ const ctl = new AbortController();
326
+ const d = recording();
327
+ const reg = new Registry();
328
+ reg.register({
329
+ schema: 'db',
330
+ version: '1.1.0',
331
+ up: () => {
332
+ ctl.abort();
333
+ throw abortError(ctl.signal);
334
+ },
335
+ down: () => void downs.push('1.1.0'),
336
+ });
337
+ const m = new Migrator('t', '1.1.0', { registry: reg, dataDir: dir });
338
+ m.addDriver(d.driver);
339
+ const err = await m.run(ctl.signal).then(
340
+ () => undefined,
341
+ (e: unknown) => e as Error,
342
+ );
343
+ expect(isCanceled(err)).toBe(true);
344
+ expect(isNotRestored(err)).toBe(false);
345
+ expect(downs).toEqual([]);
346
+ expect(d.restored).toBe(true);
347
+ expect(d.version).toBe('1.0.0');
348
+ });
349
+
350
+ it('with no backup it ends not restored at the step before, no down runs', async () => {
351
+ const downs: string[] = [];
352
+ const d = recording(true);
353
+ const methods: string[] = [];
354
+ const m = new Migrator('t', '1.2.0', {
355
+ registry: failing(downs),
356
+ dataDir: dir,
357
+ publisher: { publish: (e) => e.topic.endsWith('.reverted') && methods.push('reverted') },
358
+ });
359
+ m.addDriver(d.driver);
360
+ const err = await run(m);
361
+ expect(isNotRestored(err)).toBe(true);
362
+ expect(err?.message).toContain('up 1.2.0 failed: boom');
363
+ expect(err?.message).toContain('(rollback also failed: not restored: no backup was taken)');
364
+ expect(downs).toEqual([]);
365
+ expect(d.restored).toBe(false);
366
+ expect(d.version).toBe('1.1.0');
367
+ expect(methods).toEqual([]);
368
+ });
369
+
370
+ it('a failed final verify still rolls back by down, newest first', async () => {
371
+ const downs: string[] = [];
372
+ const reg = new Registry();
373
+ reg.register({ schema: 'db', version: '1.1.0', up: () => {}, down: () => void downs.push('1.1.0') });
374
+ reg.register({ schema: 'db', version: '1.2.0', up: () => {}, down: () => void downs.push('1.2.0') });
375
+ const d = recording();
376
+ const m = new Migrator('t', '1.2.0', {
377
+ registry: reg,
378
+ dataDir: dir,
379
+ verify: () => {
380
+ throw new Error('bad state');
381
+ },
382
+ });
383
+ m.addDriver(d.driver);
384
+ const err = await run(m);
385
+ expect(err?.message).toContain('final verify 1.2.0 failed: bad state');
386
+ expect(isNotRestored(err)).toBe(false);
387
+ expect(downs).toEqual(['1.2.0', '1.1.0']);
388
+ expect(d.restored).toBe(false);
389
+ expect(d.version).toBe('1.0.0');
390
+ });
391
+ });