@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
@@ -0,0 +1,156 @@
1
+ /**
2
+ * `stopped` is a service's Stop returning, so on a canceled run the
3
+ * events follow reverse start order however the cancellation and the
4
+ * Start returns interleave with the supervisor's wait.
5
+ */
6
+
7
+ import { describe, expect, it } from 'vitest';
8
+
9
+ import {
10
+ ServiceRegistry,
11
+ Supervisor,
12
+ type EventPayload,
13
+ type Publisher,
14
+ type Service,
15
+ type ServiceConfig,
16
+ } from './serve.js';
17
+
18
+ const enabled = (...names: string[]): Record<string, ServiceConfig> =>
19
+ Object.fromEntries(names.map((n) => [n, { enabled: true }]));
20
+
21
+ const sleep = (ms: number): Promise<void> =>
22
+ new Promise((r) => { const t = setTimeout(r, ms); t.unref?.(); });
23
+
24
+ const onAbort = (signal: AbortSignal): Promise<void> =>
25
+ new Promise((r) => {
26
+ if (signal.aborted) { r(); return; }
27
+ signal.addEventListener('abort', () => r(), { once: true });
28
+ });
29
+
30
+ /** Start returns as soon as the run is canceled. */
31
+ function onCancel(name: string, readyAfterMs = 0): Service {
32
+ return {
33
+ name,
34
+ async start(signal, ready) {
35
+ if (readyAfterMs > 0) await sleep(readyAfterMs);
36
+ ready();
37
+ await onAbort(signal);
38
+ },
39
+ ready: () => true,
40
+ async stop() { /* nothing to release */ },
41
+ };
42
+ }
43
+
44
+ /** Start returns only once its Stop was called: the listener shape. */
45
+ function untilStop(name: string, readyAfterMs = 0): Service {
46
+ let release!: () => void;
47
+ const released = new Promise<void>((r) => { release = r; });
48
+ return {
49
+ name,
50
+ async start(_signal, ready) {
51
+ if (readyAfterMs > 0) await sleep(readyAfterMs);
52
+ ready();
53
+ await released;
54
+ },
55
+ ready: () => true,
56
+ async stop() { release(); },
57
+ };
58
+ }
59
+
60
+ type Recorded = { topic: string; payload: EventPayload };
61
+
62
+ function recorder(
63
+ hook?: (e: Recorded) => void,
64
+ ): Publisher & { events: Recorded[]; stopped: () => string[] } {
65
+ const events: Recorded[] = [];
66
+ return {
67
+ events,
68
+ publish(e) {
69
+ const rec = { topic: e.topic, payload: e.payload };
70
+ events.push(rec);
71
+ hook?.(rec);
72
+ },
73
+ stopped: () => events
74
+ .filter((e) => e.topic === 'kit.serve.service.stopped')
75
+ .map((e) => e.payload.service as string),
76
+ };
77
+ }
78
+
79
+ const NAMES = ['alpha', 'beta', 'gamma', 'delta'];
80
+ const REVERSE = ['delta', 'gamma', 'beta', 'alpha'];
81
+
82
+ describe('serve stopped order on a canceled run', () => {
83
+ it('cancel at the aggregate-ready publish keeps reverse order', async () => {
84
+ for (let i = 0; i < 50; i++) {
85
+ const ac = new AbortController();
86
+ const pub = recorder((e) => {
87
+ if (e.topic === 'kit.serve.supervisor.ready_reported') ac.abort();
88
+ });
89
+ const sup = new Supervisor(
90
+ registryOf(onCancel('alpha'), untilStop('beta'), onCancel('gamma'), untilStop('delta')),
91
+ { publisher: pub },
92
+ );
93
+ const res = await sup.run(ac.signal, NAMES, enabled(...NAMES));
94
+ expect(res.error).toBeUndefined();
95
+ expect(pub.stopped()).toEqual(REVERSE);
96
+ }
97
+ });
98
+
99
+ it('cancel while the last service is still starting keeps reverse order', async () => {
100
+ for (let i = 0; i < 20; i++) {
101
+ const ac = new AbortController();
102
+ const pub = recorder((e) => {
103
+ if (e.topic === 'kit.serve.service.ready_reported' && e.payload.service === 'gamma') {
104
+ ac.abort();
105
+ }
106
+ });
107
+ const sup = new Supervisor(
108
+ registryOf(onCancel('alpha'), untilStop('beta'), onCancel('gamma'), untilStop('delta', 20)),
109
+ { publisher: pub },
110
+ );
111
+ const res = await sup.run(ac.signal, NAMES, enabled(...NAMES));
112
+ expect(res.error).toBeUndefined();
113
+ expect(pub.stopped()).toEqual(REVERSE);
114
+ }
115
+ });
116
+
117
+ it('cancel after steady state keeps reverse order', async () => {
118
+ for (let i = 0; i < 50; i++) {
119
+ const ac = new AbortController();
120
+ const pub = recorder();
121
+ const sup = new Supervisor(
122
+ registryOf(onCancel('alpha'), untilStop('beta'), onCancel('gamma'), untilStop('delta')),
123
+ { publisher: pub },
124
+ );
125
+ const run = sup.run(ac.signal, NAMES, enabled(...NAMES));
126
+ await sleep(5);
127
+ ac.abort();
128
+ await run;
129
+ expect(pub.stopped()).toEqual(REVERSE);
130
+ }
131
+ });
132
+
133
+ it('an early self-exit still reports stopped once, at exit time', async () => {
134
+ const quitter: Service = {
135
+ name: 'quitter',
136
+ async start(_signal, ready) { ready(); await sleep(10); },
137
+ ready: () => true,
138
+ async stop() { /* nothing to release */ },
139
+ };
140
+ const ac = new AbortController();
141
+ const pub = recorder();
142
+ const sup = new Supervisor(registryOf(onCancel('steady'), quitter), { publisher: pub });
143
+ const run = sup.run(ac.signal, ['steady', 'quitter'], enabled('steady', 'quitter'));
144
+ for (let i = 0; i < 200 && !pub.stopped().includes('quitter'); i++) await sleep(5);
145
+ expect(pub.stopped()).toEqual(['quitter']);
146
+ ac.abort();
147
+ await run;
148
+ expect(pub.stopped()).toEqual(['quitter', 'steady']);
149
+ });
150
+ });
151
+
152
+ function registryOf(...svcs: Service[]): ServiceRegistry {
153
+ const r = new ServiceRegistry();
154
+ for (const s of svcs) r.register(s);
155
+ return r;
156
+ }
@@ -0,0 +1,42 @@
1
+ # upgrade
2
+
3
+ ## What it answers
4
+
5
+ How a TypeScript tool checks for a newer release, orders migration versions leniently, registers versioned schema migrations and migrates one JSON document by its own version field, and runs migrations across schema drivers with backup, lock, baseline and rollback (`Migrator`). Same semantics as Go `core/upgrade`. Drivers for config files, directories, SQLite and Postgres live in [`drivers/`](drivers/README.md), one subpath import each; write others against `SchemaDriver`. Wrong module for self-update (download, replace): Go only.
6
+
7
+ ## Use it when
8
+
9
+ - announce a newer release: `createChecker({ name, currentVersion, owner, repo })`, then `notifyIfAvailable(process.stderr)`
10
+ - order or select migrations: `compareVersions('v1.9.0', '1.10.0')`, `new Registry().pending(schema, from, to)`
11
+ - migrate a JSON document: `migrateDocument(text, steps, { latest: 3 })`
12
+ - migrate stores: `new Migrator(tool, version, opts)`, `addDriver(d)`, `await run(signal?)`, `status()`, `rollbackLatest()`
13
+ - share one Postgres database across installs: `await openPostgresDriver({ db: pool, connect: () => pool.connect(), table, name })`
14
+
15
+ ## Quick start
16
+
17
+ ```ts
18
+ import { migrateDocument, type DocStep } from '@hop-top/kit/upgrade';
19
+
20
+ const steps: DocStep[] = [
21
+ { from: 1, to: 2, apply: (d) => ({ ...d, title: d.name }), note: 'add title' },
22
+ ];
23
+ const { doc, report } = migrateDocument('{"version":1,"name":"x"}', steps);
24
+ ```
25
+
26
+ ## Contract
27
+
28
+ - Versions: a leading `v` and `+build` are dropped; missing or non-numeric parts are 0; a release sorts above its pre-releases. Not the strict `semver` package.
29
+ - Documents: the chain follows versions, not step order; newer, versionless or gapped documents fail with a `DocError` whose `kind` says why; the input is never modified; a current document comes back byte for byte.
30
+ - Migrator: per schema, lock, read version, baseline, backup, each `up` then `verify` then the version record, rollback, prune, unlock. A failed `up` is an applied step that cannot be downed: with a backup the run restores it at once (no `down` runs, reverted `restore`); without one (server database, `SqliteDriver` with `db`) it ends not restored, so keep an `up` atomic there. `down` serves a failed `verify`, record or final verify. `run` and `status` return Promises; `signal` aborts between steps (`context canceled`).
31
+ - Drivers: `SchemaDriver` methods may be sync or async. Optional `lock(signal)` returns an unlock; `storesVersion: true` means the driver owns its version, else the Migrator writes `<data dir>/<schema>/version`. Backups: `<data dir>/backups/<schema>/pre-<v>/` plus `pre-<v>.version`.
32
+ - Errors: a driver throws `BackupUnsupportedError` when it cannot back up or restore; `isBackupUnsupported`, `isNotRestored`, `isVerifyError`, `isCanceled` walk the run error's `cause` chain. Events go to any `{ publish(event) }` (a kit `Bus`).
33
+ - Postgres: the table is `<table>(schema_name, version)`; the lock is a session advisory lock on `kit-upgrade:<table>:<name>` (same key as Go, so Go and TypeScript Migrators exclude each other) taken on a dedicated `connect()` client by polling `pg_try_advisory_lock` about every 50ms, so an aborted wait rejects with `abortError(signal)` and holds nothing. Unlock runs `pg_advisory_unlock` on that client, then releases it; if that fails the client is destroyed (`release(true)`). `db.options.max === 1` is refused at lock time: the lock holds one connection. No transaction-mode pooler. No backup: a failed run is `NotRestoredError`; keep an `up` atomic. `pg` is the caller's, kit imports none.
34
+ - Parity: [`contracts/upgrade-v1`](../../../../contracts/upgrade-v1/README.md) `versions.json`, `document.json` and `migrator.json`, replayed by [`conformance.test.ts`](conformance.test.ts).
35
+
36
+ ## Neighbours
37
+
38
+ - Go reference: [`go/core/upgrade`](../../../../go/core/upgrade/README.md); Rust port: [`sdk/rs/src/upgrade`](../../../rs/src/upgrade/README.md)
39
+
40
+ ## See also
41
+
42
+ - [`docs/adopters/reference/ts-api-reference.md`](../../../../docs/adopters/reference/ts-api-reference.md)
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Backup bookkeeping and the version file, ported from Go
3
+ * `core/upgrade/backup.go`. The layout is Go's, so two ports see the same
4
+ * directory under the same data dir:
5
+ *
6
+ * <data dir>/<schema>/version the version file
7
+ * <data dir>/backups/<schema>/pre-<v>/ a backup, filled by the driver
8
+ * <data dir>/backups/<schema>/pre-<v>.version the version the run started at
9
+ *
10
+ * The Migrator writes the version file (for drivers without
11
+ * `storesVersion`) and the `.version` sidecar; drivers fill the backup
12
+ * directory and read the version file back with {@link readVersionFile}.
13
+ */
14
+
15
+ import { promises as fs } from 'node:fs';
16
+ import * as path from 'node:path';
17
+
18
+ import { dataDir as xdgDataDir } from '../xdg';
19
+ import { NotRestoredError, BackupUnsupportedError } from './errors';
20
+ import { compareSemver, parseSemver, trimV } from './semver';
21
+
22
+ export const DEFAULT_RETENTION = 5;
23
+
24
+ /** Suffix of the file beside a backup directory: `pre-<v>.version`. */
25
+ const PRE_RUN_SUFFIX = '.version';
26
+
27
+ /** The default data dir of a tool: `<xdg data dir>/hop/<tool>`. */
28
+ export function defaultDataDir(tool: string): string {
29
+ return xdgDataDir(path.join('hop', tool));
30
+ }
31
+
32
+ /**
33
+ * Reads `<dataDir>/<schema>/version`, trimmed. Resolves `""` when the file
34
+ * does not exist. For drivers that read what the Migrator recorded.
35
+ */
36
+ export async function readVersionFile(dataDir: string, schema: string): Promise<string> {
37
+ try {
38
+ return (await fs.readFile(path.join(dataDir, schema, 'version'), 'utf8')).trim();
39
+ } catch (e) {
40
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return '';
41
+ throw e;
42
+ }
43
+ }
44
+
45
+ /** Writes `<dataDir>/<schema>/version`, creating the directory. */
46
+ export async function writeVersionFile(dataDir: string, schema: string, version: string): Promise<void> {
47
+ const dir = path.join(dataDir, schema);
48
+ try {
49
+ await fs.mkdir(dir, { recursive: true, mode: 0o750 });
50
+ } catch (e) {
51
+ throw new Error(`create version dir: ${(e as Error).message}`, { cause: e });
52
+ }
53
+ try {
54
+ await fs.writeFile(path.join(dir, 'version'), version, { mode: 0o600 });
55
+ } catch (e) {
56
+ throw new Error(`write version file: ${(e as Error).message}`, { cause: e });
57
+ }
58
+ }
59
+
60
+ /** The versioned `pre-` directories of a schema, newest semver first. */
61
+ async function backupDirs(schemaDir: string): Promise<{ name: string; v: ReturnType<typeof parseSemver> }[]> {
62
+ const entries = await fs.readdir(schemaDir, { withFileTypes: true });
63
+ const dirs: { name: string; v: ReturnType<typeof parseSemver> }[] = [];
64
+ for (const e of entries) {
65
+ if (!e.isDirectory() || !e.name.startsWith('pre-')) continue;
66
+ dirs.push({ name: e.name, v: parseSemver(trimV(e.name.slice('pre-'.length))) });
67
+ }
68
+ return dirs.sort((a, b) => compareSemver(b.v, a.v));
69
+ }
70
+
71
+ const isMissing = (e: unknown): boolean => (e as NodeJS.ErrnoException).code === 'ENOENT';
72
+
73
+ /** Backup lifecycle of one schema. */
74
+ export class BackupStore {
75
+ private readonly retention: number;
76
+
77
+ constructor(
78
+ private readonly schema: string,
79
+ private readonly base: string,
80
+ retention: number,
81
+ ) {
82
+ this.retention = retention <= 0 ? DEFAULT_RETENTION : retention;
83
+ }
84
+
85
+ private get schemaDir(): string {
86
+ return path.join(this.base, 'backups', this.schema);
87
+ }
88
+
89
+ /** Creates and returns the directory of the backup taken before `version`. */
90
+ async backupDir(version: string): Promise<string> {
91
+ const dir = path.join(this.schemaDir, 'pre-' + version);
92
+ try {
93
+ await fs.mkdir(dir, { recursive: true, mode: 0o750 });
94
+ } catch (e) {
95
+ throw new Error(`create backup dir: ${(e as Error).message}`, { cause: e });
96
+ }
97
+ return dir;
98
+ }
99
+
100
+ async hasBackup(version: string): Promise<boolean> {
101
+ try {
102
+ await fs.stat(path.join(this.schemaDir, 'pre-' + version));
103
+ return true;
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+
109
+ /** Removes a backup directory (after an unsupported backup). */
110
+ async discard(backupPath: string): Promise<void> {
111
+ await fs.rm(backupPath, { recursive: true, force: true });
112
+ }
113
+
114
+ /** Saves, beside the backup, the version the run started at ("" is an empty file). */
115
+ async savePreRun(backupPath: string, version: string): Promise<void> {
116
+ try {
117
+ await fs.writeFile(backupPath + PRE_RUN_SUFFIX, version, { mode: 0o600 });
118
+ } catch (e) {
119
+ throw new Error(`write pre-run version: ${(e as Error).message}`, { cause: e });
120
+ }
121
+ }
122
+
123
+ /** The version saved beside `backupPath`; `recorded` is false for a backup taken before it was saved. */
124
+ async readPreRun(backupPath: string): Promise<{ version: string; recorded: boolean }> {
125
+ try {
126
+ const data = await fs.readFile(backupPath + PRE_RUN_SUFFIX, 'utf8');
127
+ return { version: data.trim(), recorded: true };
128
+ } catch (e) {
129
+ if (isMissing(e)) return { version: '', recorded: false };
130
+ throw new Error(`read pre-run version: ${(e as Error).message}`, { cause: e });
131
+ }
132
+ }
133
+
134
+ /** The most recent backup directory by semver. */
135
+ async latestBackup(): Promise<string> {
136
+ let dirs: Awaited<ReturnType<typeof backupDirs>>;
137
+ try {
138
+ dirs = await backupDirs(this.schemaDir);
139
+ } catch (e) {
140
+ if (isMissing(e)) throw this.noBackups();
141
+ throw new Error(`read backup dir: ${(e as Error).message}`, { cause: e });
142
+ }
143
+ if (dirs.length === 0) throw this.noBackups();
144
+ return path.join(this.schemaDir, dirs[0].name);
145
+ }
146
+
147
+ /** No backup at all: not restored, with unsupported as its cause. */
148
+ private noBackups(): NotRestoredError {
149
+ return new NotRestoredError('no backups found for ' + this.schema, {
150
+ cause: new BackupUnsupportedError(),
151
+ });
152
+ }
153
+
154
+ /** Keeps the `retention` most recent backups by semver, removing the rest and their sidecars. */
155
+ async prune(): Promise<void> {
156
+ let dirs: Awaited<ReturnType<typeof backupDirs>>;
157
+ try {
158
+ dirs = await backupDirs(this.schemaDir);
159
+ } catch (e) {
160
+ if (isMissing(e)) return;
161
+ throw new Error(`read backup dir: ${(e as Error).message}`, { cause: e });
162
+ }
163
+ // Oldest first, like Go: the first failure stops the prune.
164
+ for (const d of dirs.slice(this.retention).reverse()) {
165
+ const p = path.join(this.schemaDir, d.name);
166
+ try {
167
+ await fs.rm(p, { recursive: true, force: true });
168
+ await fs.rm(p + PRE_RUN_SUFFIX, { force: true });
169
+ } catch (e) {
170
+ throw new Error(`prune backup ${d.name}: ${(e as Error).message}`, { cause: e });
171
+ }
172
+ }
173
+ }
174
+ }
@@ -0,0 +1,310 @@
1
+ // Runs the shared corpus in contracts/upgrade-v1. The vectors are the
2
+ // source of truth: a failure here means this implementation drifted from
3
+ // the contract, not that the vector should be edited to fit. The runner is
4
+ // strict like the Go and Rust ones: unknown fields, a `version` other than
5
+ // v1 and a corpus file nobody consumes all fail the run.
6
+
7
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+
10
+ import { describe, it, expect } from 'vitest';
11
+
12
+ import { DIR, strict, type Shape } from '../../test/upgrade/conformance-support';
13
+ import { MIGRATOR_SHAPE, runMigratorScenario, type MigratorFile } from '../../test/upgrade/conformance-migrator';
14
+
15
+ import {
16
+ DocError,
17
+ Registry,
18
+ compareVersions,
19
+ migrateDocument,
20
+ migrateDocumentValue,
21
+ type DocKind,
22
+ type DocReport,
23
+ type DocStep,
24
+ type JsonObject,
25
+ } from './index';
26
+
27
+ // Files this runner consumes.
28
+ const CONSUMED = new Set(['versions.json', 'document.json', 'migrator.json']);
29
+ // Files it knows about but does not consume yet: listed by name with the
30
+ // reason, never silently ignored. Nothing is pending for TypeScript.
31
+ const PENDING: Record<string, string> = {};
32
+
33
+ // ─── strict loading ───────────────────────────────────────────────────
34
+
35
+ const HEADER: Shape = { $schema: true, $id: true, version: true, description: true };
36
+
37
+ function load<T>(name: string, shape: Shape): T {
38
+ for (const f of readdirSync(DIR)) {
39
+ if (f.endsWith('.json') && !CONSUMED.has(f) && !(f in PENDING)) {
40
+ throw new Error(`${f} has no runner`);
41
+ }
42
+ }
43
+ const raw = JSON.parse(readFileSync(join(DIR, name), 'utf8')) as { version?: string };
44
+ strict(raw, { ...HEADER, ...shape }, name);
45
+ if (raw.version !== 'v1') throw new Error(`${name}: version = ${raw.version}, want v1`);
46
+ return raw as T;
47
+ }
48
+
49
+ // ─── corpus bookkeeping ───────────────────────────────────────────────
50
+
51
+ describe('upgrade-v1 corpus', () => {
52
+ it('every .json file is consumed or listed as pending', () => {
53
+ for (const f of readdirSync(DIR)) {
54
+ if (!f.endsWith('.json')) continue;
55
+ expect(CONSUMED.has(f) || f in PENDING, `${f} has no runner`).toBe(true);
56
+ }
57
+ });
58
+
59
+ it('every consumed and pending file exists', () => {
60
+ for (const f of [...CONSUMED, ...Object.keys(PENDING)]) {
61
+ expect(existsSync(join(DIR, f)), `${f} is gone: drop it from the runner`).toBe(true);
62
+ }
63
+ });
64
+
65
+ it('no file is both consumed and pending', () => {
66
+ for (const f of Object.keys(PENDING)) expect(CONSUMED.has(f)).toBe(false);
67
+ });
68
+ });
69
+
70
+ // ─── versions.json ────────────────────────────────────────────────────
71
+
72
+ interface VersionsFile {
73
+ compare: { name: string; a: string; b: string; cmp: number }[];
74
+ pending: {
75
+ name: string;
76
+ migrations: { schema: string; version: string }[];
77
+ schema: string;
78
+ from: string;
79
+ to: string;
80
+ pending: string[];
81
+ }[];
82
+ }
83
+
84
+ const VERSIONS_SHAPE: Shape = {
85
+ compare: [{ name: true, a: true, b: true, cmp: true }],
86
+ pending: [
87
+ {
88
+ name: true,
89
+ migrations: [{ schema: true, version: true }],
90
+ schema: true,
91
+ from: true,
92
+ to: true,
93
+ pending: [true],
94
+ },
95
+ ],
96
+ };
97
+
98
+ describe('upgrade-v1 versions.json', () => {
99
+ const f = load<VersionsFile>('versions.json', VERSIONS_SHAPE);
100
+
101
+ it('has vectors', () => {
102
+ expect(f.compare.length).toBeGreaterThan(0);
103
+ expect(f.pending.length).toBeGreaterThan(0);
104
+ });
105
+
106
+ describe('compare', () => {
107
+ for (const c of f.compare) {
108
+ it(c.name, () => {
109
+ expect(compareVersions(c.a, c.b)).toBe(c.cmp);
110
+ expect(compareVersions(c.b, c.a)).toBe(-c.cmp || 0);
111
+ });
112
+ }
113
+ });
114
+
115
+ describe('pending', () => {
116
+ for (const c of f.pending) {
117
+ it(c.name, () => {
118
+ const reg = new Registry();
119
+ for (const m of c.migrations) {
120
+ reg.register({ schema: m.schema, version: m.version, up: () => {} });
121
+ }
122
+ expect(reg.pending(c.schema, c.from, c.to).map((m) => m.version)).toEqual(c.pending);
123
+ });
124
+ }
125
+ });
126
+ });
127
+
128
+ // ─── document.json ────────────────────────────────────────────────────
129
+
130
+ interface ConfStep {
131
+ from: number;
132
+ to: number;
133
+ note?: string;
134
+ ops?: { set?: { path: string; value: unknown }; rename?: { from: string; to: string }; fail?: string }[];
135
+ verify?: { require: string };
136
+ }
137
+
138
+ interface DocScenario {
139
+ name: string;
140
+ doc?: unknown;
141
+ text?: string;
142
+ options?: { version_field?: string; latest?: number; missing_is_zero?: boolean };
143
+ steps: ConfStep[];
144
+ expect: { doc?: unknown; text?: string; report?: DocReport; error?: string; kind?: DocKind };
145
+ }
146
+
147
+ const DOCUMENT_SHAPE: Shape = {
148
+ scenarios: [
149
+ {
150
+ name: true,
151
+ doc: true,
152
+ text: true,
153
+ options: { version_field: true, latest: true, missing_is_zero: true },
154
+ steps: [
155
+ {
156
+ from: true,
157
+ to: true,
158
+ note: true,
159
+ ops: [{ set: { path: true, value: true }, rename: { from: true, to: true }, fail: true }],
160
+ verify: { require: true },
161
+ },
162
+ ],
163
+ expect: {
164
+ doc: true,
165
+ text: true,
166
+ report: { from: true, to: true, applied: [{ from: true, to: true, note: true }] },
167
+ error: true,
168
+ kind: true,
169
+ },
170
+ },
171
+ ],
172
+ };
173
+
174
+ function lookup(doc: JsonObject, path: string): boolean {
175
+ let cur: unknown = doc;
176
+ for (const seg of path.split('.')) {
177
+ if (cur === null || typeof cur !== 'object' || Array.isArray(cur)) return false;
178
+ if (!Object.prototype.hasOwnProperty.call(cur, seg)) return false;
179
+ cur = (cur as JsonObject)[seg];
180
+ }
181
+ return true;
182
+ }
183
+
184
+ function setPath(doc: JsonObject, path: string, v: unknown): void {
185
+ const segs = path.split('.');
186
+ let cur = doc;
187
+ for (const seg of segs.slice(0, -1)) {
188
+ let next = cur[seg];
189
+ if (next === null || typeof next !== 'object' || Array.isArray(next)) {
190
+ next = {};
191
+ cur[seg] = next;
192
+ }
193
+ cur = next as JsonObject;
194
+ }
195
+ cur[segs[segs.length - 1]] = v as never;
196
+ }
197
+
198
+ function docSteps(cases: ConfStep[]): DocStep[] {
199
+ return cases.map((c) => {
200
+ const step: DocStep = {
201
+ from: c.from,
202
+ to: c.to,
203
+ note: c.note,
204
+ // In place, on purpose: the migrator must hand steps a copy.
205
+ apply: (doc) => {
206
+ for (const op of c.ops ?? []) {
207
+ if (op.set) setPath(doc, op.set.path, op.set.value);
208
+ else if (op.rename) {
209
+ if (Object.prototype.hasOwnProperty.call(doc, op.rename.from)) {
210
+ doc[op.rename.to] = doc[op.rename.from];
211
+ delete doc[op.rename.from];
212
+ }
213
+ } else if (op.fail !== undefined && op.fail !== '') throw new Error(op.fail);
214
+ }
215
+ return doc;
216
+ },
217
+ };
218
+ if (c.verify) {
219
+ const req = c.verify.require;
220
+ step.verify = (doc) => {
221
+ if (!lookup(doc, req)) throw new Error('missing ' + req);
222
+ };
223
+ }
224
+ return step;
225
+ });
226
+ }
227
+
228
+ describe('upgrade-v1 document.json', () => {
229
+ const f = load<{ scenarios: DocScenario[] }>('document.json', DOCUMENT_SHAPE);
230
+
231
+ it('has scenarios', () => {
232
+ expect(f.scenarios.length).toBeGreaterThan(0);
233
+ });
234
+
235
+ for (const sc of f.scenarios) {
236
+ it(sc.name, () => {
237
+ const opts = {
238
+ versionField: sc.options?.version_field,
239
+ latest: sc.options?.latest,
240
+ missingIsZero: sc.options?.missing_is_zero,
241
+ };
242
+ const steps = docSteps(sc.steps);
243
+ const input = sc.text !== undefined ? sc.text : JSON.stringify(sc.doc);
244
+
245
+ const check = (via: string, run: () => { doc: unknown; report: DocReport }) => {
246
+ if (sc.expect.error !== undefined) {
247
+ let err: unknown;
248
+ try {
249
+ run();
250
+ } catch (e) {
251
+ err = e;
252
+ }
253
+ expect(err, `${via}: no error, want ${sc.expect.error}`).toBeDefined();
254
+ expect((err as Error).message, via).toBe(sc.expect.error);
255
+ expect(err, via).toBeInstanceOf(DocError);
256
+ expect((err as DocError).kind, via).toBe(sc.expect.kind);
257
+ return;
258
+ }
259
+ const got = run();
260
+ if (sc.expect.doc !== undefined) expect(got.doc, via).toEqual(sc.expect.doc);
261
+ if (sc.expect.report !== undefined) expect(got.report, via).toEqual(sc.expect.report);
262
+ };
263
+
264
+ // Bytes form, as text and as Uint8Array.
265
+ const bytes = new TextEncoder().encode(input);
266
+ const before = bytes.slice();
267
+ check('bytes', () => {
268
+ const r = migrateDocument(bytes, steps, opts);
269
+ const text = new TextDecoder().decode(r.doc);
270
+ if (sc.expect.text !== undefined) expect(text).toBe(sc.expect.text);
271
+ return { doc: JSON.parse(text), report: r.report };
272
+ });
273
+ expect(bytes, 'input bytes changed').toEqual(before);
274
+ check('text', () => {
275
+ const r = migrateDocument(input, steps, opts);
276
+ expect(typeof r.doc).toBe('string');
277
+ return { doc: JSON.parse(r.doc), report: r.report };
278
+ });
279
+
280
+ // The value form, when the input is an object: same result, and the
281
+ // caller's value is untouched however the steps mutate. Exact
282
+ // literals (text) only survive the bytes form.
283
+ if (sc.text === undefined && sc.doc !== null && typeof sc.doc === 'object' && !Array.isArray(sc.doc)) {
284
+ const doc = sc.doc as JsonObject;
285
+ const snapshot = JSON.stringify(doc);
286
+ check('value', () => {
287
+ const r = migrateDocumentValue(doc, steps, opts);
288
+ return { doc: r.doc, report: r.report };
289
+ });
290
+ expect(JSON.stringify(doc), "caller's document changed").toBe(snapshot);
291
+ }
292
+ });
293
+ }
294
+ });
295
+
296
+ // ─── migrator.json ────────────────────────────────────────────────────
297
+
298
+ describe('upgrade-v1 migrator.json', () => {
299
+ const f = load<MigratorFile>('migrator.json', MIGRATOR_SHAPE);
300
+
301
+ it('has scenarios', () => {
302
+ expect(f.scenarios.length).toBeGreaterThan(0);
303
+ });
304
+
305
+ for (const sc of f.scenarios) {
306
+ it(sc.name, async () => {
307
+ await runMigratorScenario(sc);
308
+ });
309
+ }
310
+ });