@hop-top/kit 0.5.0-alpha.12 → 0.5.0-alpha.14

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 (125) hide show
  1. package/CHANGELOG.md +51 -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-BXJ2J27B.js → chunk-IGKBRNEW.js} +10 -10
  13. package/dist/{chunk-VWGP4NVJ.js → chunk-MDVGMOZO.js} +45 -39
  14. package/dist/{chunk-4FMALWYB.js → chunk-MEF7W3MG.js} +45 -45
  15. package/dist/{chunk-VGOA5Y7S.js → chunk-Q547MHNB.js} +11 -11
  16. package/dist/{chunk-K7E34Q3A.js → chunk-TUU2BY5I.js} +136 -47
  17. package/dist/chunk-VKQCOVKI.js +880 -0
  18. package/dist/cli.js +3 -3
  19. package/dist/index-BqZ7WGQf.d.ts +731 -0
  20. package/dist/index.d.ts +8 -5
  21. package/dist/index.js +32 -18
  22. package/dist/{llm-DYuR7_uX.d.ts → llm-BazFKc_2.d.ts} +95 -9
  23. package/dist/{llm-anthropic-Cd_I2xXB.d.ts → llm-anthropic-BcAitoDV.d.ts} +1 -1
  24. package/dist/llm-anthropic.d.ts +2 -2
  25. package/dist/llm-anthropic.js +4 -4
  26. package/dist/{llm-openai-DyFrucmV.d.ts → llm-openai-CSDvuRH6.d.ts} +1 -1
  27. package/dist/llm-openai.d.ts +2 -2
  28. package/dist/llm-openai.js +4 -4
  29. package/dist/llm.d.ts +1 -1
  30. package/dist/llm.js +8 -2
  31. package/dist/{routellm-B0nv59mH.d.ts → routellm-B9UrONPr.d.ts} +1 -1
  32. package/dist/routellm.d.ts +2 -2
  33. package/dist/routellm.js +5 -5
  34. package/dist/upgrade/drivers/configfile.d.ts +45 -0
  35. package/dist/upgrade/drivers/configfile.js +78 -0
  36. package/dist/upgrade/drivers/fsdir.d.ts +61 -0
  37. package/dist/upgrade/drivers/fsdir.js +170 -0
  38. package/dist/upgrade/drivers/postgres.d.ts +121 -0
  39. package/dist/upgrade/drivers/postgres.js +195 -0
  40. package/dist/upgrade/drivers/sqlite.d.ts +101 -0
  41. package/dist/upgrade/drivers/sqlite.js +241 -0
  42. package/dist/upgrade/index.d.ts +2 -0
  43. package/dist/upgrade/index.js +73 -0
  44. package/dist/uri-IJ_AoY3d.d.ts +144 -0
  45. package/dist/uri.d.ts +1 -0
  46. package/dist/uri.js +37 -0
  47. package/dist/version-DEJ3pbiO.d.ts +10 -0
  48. package/dist/wizard-Bf_qHc31.d.ts +159 -0
  49. package/dist/wizard.d.ts +1 -0
  50. package/dist/wizard.js +39 -0
  51. package/package.json +76 -17
  52. package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +19 -0
  53. package/skills/hop-top-kit-ts/SKILL.md +117 -0
  54. package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.expected +2 -0
  55. package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.ts +20 -0
  56. package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.expected +13 -0
  57. package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.ts +26 -0
  58. package/skills/hop-top-kit-ts/gym.json +5 -0
  59. package/skills/hop-top-kit-ts/references/ai-and-agents.md +45 -0
  60. package/skills/hop-top-kit-ts/references/cli-and-console.md +63 -0
  61. package/skills/hop-top-kit-ts/references/coverage.md +56 -0
  62. package/skills/hop-top-kit-ts/references/guardrails-and-trust.md +60 -0
  63. package/skills/hop-top-kit-ts/references/other-ports.md +31 -0
  64. package/skills/hop-top-kit-ts/references/serving-and-transports.md +49 -0
  65. package/skills/hop-top-kit-ts/scripts/detect-port.sh +168 -0
  66. package/src/index.test.ts +48 -2
  67. package/src/index.ts +6 -1
  68. package/src/llm-anthropic.conformance.test.ts +7 -0
  69. package/src/llm-boundkey.test.ts +260 -0
  70. package/src/llm-choice-hermetic.test.ts +1 -1
  71. package/src/llm-config.test.ts +2 -4
  72. package/src/llm-config.ts +5 -1
  73. package/src/llm-endpoint.ts +25 -5
  74. package/src/llm-keys.ts +47 -15
  75. package/src/llm-openai.test.ts +10 -4
  76. package/src/llm-openai.ts +7 -1
  77. package/src/llm-spec.test.ts +347 -0
  78. package/src/llm-spec.ts +80 -0
  79. package/src/llm-uri.ts +96 -12
  80. package/src/llm.test.ts +2 -2
  81. package/src/llm.ts +10 -0
  82. package/src/published-types.test.ts +8 -0
  83. package/src/serve.stopped-order.test.ts +156 -0
  84. package/src/upgrade/README.md +42 -0
  85. package/src/upgrade/backup.ts +174 -0
  86. package/src/upgrade/conformance.test.ts +310 -0
  87. package/src/upgrade/document.ts +229 -0
  88. package/src/upgrade/driver.ts +66 -0
  89. package/src/upgrade/drivers/README.md +47 -0
  90. package/src/upgrade/drivers/configfile.test.ts +112 -0
  91. package/src/upgrade/drivers/configfile.ts +107 -0
  92. package/src/upgrade/drivers/fsdir.test.ts +188 -0
  93. package/src/upgrade/drivers/fsdir.ts +216 -0
  94. package/src/upgrade/drivers/isolation.test.ts +18 -0
  95. package/src/upgrade/drivers/postgres.integration.test.ts +395 -0
  96. package/src/upgrade/drivers/postgres.test.ts +272 -0
  97. package/src/upgrade/drivers/postgres.ts +284 -0
  98. package/src/upgrade/drivers/sqlite.integration.test.ts +492 -0
  99. package/src/upgrade/drivers/sqlite.ts +300 -0
  100. package/src/upgrade/drivers/version.ts +21 -0
  101. package/src/upgrade/errors.ts +117 -0
  102. package/src/upgrade/events.ts +117 -0
  103. package/src/{upgrade.test.ts → upgrade/index.test.ts} +1 -1
  104. package/src/{upgrade.ts → upgrade/index.ts} +20 -0
  105. package/src/upgrade/migration.ts +89 -0
  106. package/src/upgrade/migrator.test.ts +391 -0
  107. package/src/upgrade/migrator.ts +527 -0
  108. package/src/upgrade/options.ts +59 -0
  109. package/src/upgrade/semver.ts +90 -0
  110. package/test/llm/conformance-helpers.ts +3 -0
  111. package/test/skill-snippets.test.ts +60 -0
  112. package/test/upgrade/conformance-migrator.ts +439 -0
  113. package/test/upgrade/conformance-support.ts +44 -0
  114. package/test/upgrade/driver-support.ts +44 -0
  115. package/test/upgrade/pg-container.ts +64 -0
  116. package/test/upgrade/pg-race-worker.ts +48 -0
  117. package/test/upgrade/race-helper.ts +36 -0
  118. package/test/upgrade/sqlite-support.ts +41 -0
  119. package/test/upgrade/testdata/go-fsdir-mydata.tar.gz +0 -0
  120. package/vitest.config.ts +26 -0
  121. package/dist/chunk-X4E5QGEB.js +0 -171
  122. package/dist/upgrade-BJ2z6Oqf.d.ts +0 -156
  123. package/dist/upgrade.d.ts +0 -1
  124. package/dist/upgrade.js +0 -9
  125. package/dist/{chunk-MFVUENZR.js → chunk-KV7FYEAF.js} +2 -2
@@ -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
+ });
@@ -0,0 +1,229 @@
1
+ /**
2
+ * In-memory JSON document migrator, ported from Go `upgrade.MigrateDocument`.
3
+ * A document is a JSON object with an integer version at `versionField`
4
+ * (dotted path). Steps move it `from -> to`; the chain follows versions, not
5
+ * the order of steps. No I/O; the caller's input is never modified.
6
+ *
7
+ * Same shape as Go with two TypeScript differences: JSON numbers are JS
8
+ * numbers (integers past 2^53 lose exactness), and the re-encoded document
9
+ * keeps key insertion order where Go sorts keys.
10
+ */
11
+
12
+ /** A decoded JSON object. */
13
+ export type JsonObject = { [key: string]: unknown };
14
+
15
+ /**
16
+ * Moves a document from version `from` to `to` (to > from). `apply` gets a
17
+ * private copy and may mutate it in place; it returns the migrated document.
18
+ * The version field is set to `to` after `apply`, so `apply` need not touch it.
19
+ */
20
+ export interface DocStep {
21
+ from: number;
22
+ to: number;
23
+ apply(doc: JsonObject): JsonObject;
24
+ /** Optional; runs on `apply`'s result. Throw to fail the step. */
25
+ verify?(doc: JsonObject): void;
26
+ note?: string;
27
+ }
28
+
29
+ export interface DocOptions {
30
+ /** Dotted path of the integer version; `version` when empty. */
31
+ versionField?: string;
32
+ /** The version this build writes; 0 or absent means the highest `to`. */
33
+ latest?: number;
34
+ /** Read a missing or non-integer version as 0 instead of failing. */
35
+ missingIsZero?: boolean;
36
+ }
37
+
38
+ export interface DocApplied {
39
+ from: number;
40
+ to: number;
41
+ note: string;
42
+ }
43
+
44
+ /** Says what the migration did. */
45
+ export interface DocReport {
46
+ from: number;
47
+ to: number;
48
+ applied: DocApplied[];
49
+ }
50
+
51
+ /** Why a document migration failed. */
52
+ export type DocKind = 'newer' | 'version' | 'gap' | 'step' | 'verify' | 'invalid';
53
+
54
+ /** Every failure of the document migrator; `kind` says which. `cause` is the step's own error, when there is one. */
55
+ export class DocError extends Error {
56
+ readonly kind: DocKind;
57
+ constructor(kind: DocKind, message: string, cause?: unknown) {
58
+ super(message, cause === undefined ? undefined : { cause });
59
+ this.name = 'DocError';
60
+ this.kind = kind;
61
+ }
62
+ }
63
+
64
+ const isObject = (v: unknown): v is JsonObject =>
65
+ v !== null && typeof v === 'object' && !Array.isArray(v);
66
+
67
+ const own = (o: object, k: string): boolean => Object.prototype.hasOwnProperty.call(o, k);
68
+
69
+ const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));
70
+
71
+ /** An integer literal fits Go's int: no fraction, no exponent. */
72
+ function isIntegerLiteral(src: string): boolean {
73
+ return /^-?\d+$/.test(src) && Number.isSafeInteger(Number(src));
74
+ }
75
+
76
+ interface Parsed {
77
+ doc: JsonObject;
78
+ /** Source text of each number, by holder object and key. */
79
+ literals: Map<object, Map<string, string>>;
80
+ }
81
+
82
+ type Reviver = (this: unknown, key: string, value: unknown, ctx?: { source?: string }) => unknown;
83
+
84
+ function decode(text: string): Parsed {
85
+ const literals = new Map<object, Map<string, string>>();
86
+ const reviver: Reviver = function (key, value, ctx) {
87
+ if (typeof value === 'number' && ctx?.source !== undefined && this !== null && typeof this === 'object') {
88
+ let m = literals.get(this);
89
+ if (!m) literals.set(this, (m = new Map()));
90
+ m.set(key, ctx.source);
91
+ }
92
+ return value;
93
+ };
94
+ let v: unknown;
95
+ try {
96
+ v = JSON.parse(text, reviver as Parameters<typeof JSON.parse>[1]);
97
+ } catch (e) {
98
+ throw new DocError('invalid', `parse document: ${errText(e)}`, e);
99
+ }
100
+ if (!isObject(v)) throw new DocError('invalid', 'document is not a JSON object');
101
+ return { doc: v, literals };
102
+ }
103
+
104
+ /** The integer literal at `path`, if there is one. */
105
+ function docVersion(doc: JsonObject, path: string, literals?: Parsed['literals']): number | undefined {
106
+ let holder: unknown = undefined;
107
+ let cur: unknown = doc;
108
+ let key = '';
109
+ for (const seg of path.split('.')) {
110
+ if (!isObject(cur) || !own(cur, seg)) return undefined;
111
+ holder = cur;
112
+ key = seg;
113
+ cur = cur[seg];
114
+ }
115
+ if (typeof cur !== 'number') return undefined;
116
+ const src = literals?.get(holder as object)?.get(key) ?? String(cur);
117
+ return isIntegerLiteral(src) ? cur : undefined;
118
+ }
119
+
120
+ function setDocVersion(doc: JsonObject, path: string, v: number): void {
121
+ const segs = path.split('.');
122
+ let cur = doc;
123
+ for (const seg of segs.slice(0, -1)) {
124
+ let next = cur[seg];
125
+ if (!isObject(next)) {
126
+ next = {};
127
+ cur[seg] = next;
128
+ }
129
+ cur = next as JsonObject;
130
+ }
131
+ cur[segs[segs.length - 1]] = v;
132
+ }
133
+
134
+ /** Runs the chain on `doc`, which it owns. */
135
+ function run(doc: JsonObject, steps: DocStep[], opts: DocOptions, literals?: Parsed['literals']): { doc: JsonObject; report: DocReport } {
136
+ const field = opts.versionField || 'version';
137
+ let cur = docVersion(doc, field, literals);
138
+ if (cur === undefined) {
139
+ if (!opts.missingIsZero) {
140
+ throw new DocError('version', `document has no integer version at "${field}"`);
141
+ }
142
+ cur = 0;
143
+ }
144
+ let latest = opts.latest ?? 0;
145
+ if (latest === 0) for (const s of steps) latest = Math.max(latest, s.to);
146
+ const report: DocReport = { from: cur, to: cur, applied: [] };
147
+ for (const s of steps) {
148
+ if (s.to <= s.from) {
149
+ throw new DocError('invalid', `migration ${s.from} -> ${s.to} does not move forward`);
150
+ }
151
+ if (s.to > latest) {
152
+ throw new DocError('invalid', `migration ${s.from} -> ${s.to} goes past the latest known ${latest}`);
153
+ }
154
+ }
155
+ if (cur > latest) {
156
+ throw new DocError('newer', `document version ${cur} is newer than the latest known ${latest}`);
157
+ }
158
+ while (cur < latest) {
159
+ const step = steps.find((s) => s.from === cur);
160
+ if (!step) {
161
+ throw new DocError('gap', `no migration from version ${cur} (highest target is ${latest}); chain has a gap`);
162
+ }
163
+ let out: JsonObject | null | undefined;
164
+ try {
165
+ out = step.apply(doc);
166
+ } catch (e) {
167
+ throw new DocError('step', `migration ${step.from} -> ${step.to}: ${errText(e)}`, e);
168
+ }
169
+ if (!isObject(out)) {
170
+ throw new DocError('step', `migration ${step.from} -> ${step.to} returned nil map`);
171
+ }
172
+ if (step.verify) {
173
+ try {
174
+ step.verify(out);
175
+ } catch (e) {
176
+ throw new DocError('verify', `migration ${step.from} -> ${step.to}: verify: ${errText(e)}`, e);
177
+ }
178
+ }
179
+ doc = out;
180
+ setDocVersion(doc, field, step.to);
181
+ cur = step.to;
182
+ report.to = cur;
183
+ report.applied.push({ from: step.from, to: step.to, note: step.note ?? '' });
184
+ }
185
+ return { doc, report };
186
+ }
187
+
188
+ /**
189
+ * Migrates one JSON document given as text or UTF-8 bytes. When it is
190
+ * already at the latest version the input is returned as it is, byte for
191
+ * byte; otherwise the result is re-encoded. The result has the type of the
192
+ * input. Throws {@link DocError}; the input is untouched either way.
193
+ */
194
+ export function migrateDocument<T extends string | Uint8Array>(
195
+ doc: T,
196
+ steps: DocStep[],
197
+ opts: DocOptions = {},
198
+ ): { doc: T; report: DocReport } {
199
+ let text: string;
200
+ try {
201
+ text = typeof doc === 'string' ? doc : new TextDecoder('utf-8', { fatal: true }).decode(doc);
202
+ } catch (e) {
203
+ throw new DocError('invalid', `parse document: ${errText(e)}`, e);
204
+ }
205
+ const parsed = decode(text);
206
+ const { doc: out, report } = run(parsed.doc, steps, opts, parsed.literals);
207
+ if (report.applied.length === 0) return { doc, report };
208
+ const encoded = JSON.stringify(out);
209
+ return { doc: (typeof doc === 'string' ? encoded : new TextEncoder().encode(encoded)) as T, report };
210
+ }
211
+
212
+ /**
213
+ * {@link migrateDocument} on a decoded document. The caller's object is
214
+ * never modified; steps work on a deep copy. Throws {@link DocError}.
215
+ */
216
+ export function migrateDocumentValue(
217
+ doc: JsonObject,
218
+ steps: DocStep[],
219
+ opts: DocOptions = {},
220
+ ): { doc: JsonObject; report: DocReport } {
221
+ let copy: JsonObject;
222
+ try {
223
+ copy = structuredClone(doc);
224
+ } catch (e) {
225
+ throw new DocError('invalid', `copy document: ${errText(e)}`, e);
226
+ }
227
+ if (!isObject(copy)) throw new DocError('invalid', 'document is not a JSON object');
228
+ return run(copy, steps, opts);
229
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The seam between the Migrator and a data store, ported from Go
3
+ * `core/upgrade` `SchemaDriver`.
4
+ *
5
+ * Every method may return a value or a Promise: a driver for a server
6
+ * database is async, one over `better-sqlite3` or a file is sync, and the
7
+ * Migrator awaits either. Capabilities are optional members the Migrator
8
+ * detects by shape, so a later driver adds one without any change to the
9
+ * Migrator: `lock` (a method) and `storesVersion` (a flag).
10
+ */
11
+
12
+ type MaybePromise<T> = T | Promise<T>;
13
+
14
+ /** Releases a lock taken by {@link SchemaDriver.lock}. */
15
+ export type Unlock = () => MaybePromise<void>;
16
+
17
+ export interface SchemaDriver {
18
+ /** The schema identifier, matched against `Migration.schema`. */
19
+ name(): string;
20
+
21
+ /** The applied version, or `""` when none is stored. */
22
+ version(): MaybePromise<string>;
23
+
24
+ /**
25
+ * Records a version: after each applied migration, and the earlier one
26
+ * again after a rollback or restore. For a driver without
27
+ * `storesVersion`, called after the Migrator wrote the version file.
28
+ */
29
+ setVersion(version: string): MaybePromise<void>;
30
+
31
+ /**
32
+ * Copies the current state into the existing directory `dest`. Resolve
33
+ * only when it really did; throw {@link BackupUnsupportedError} (or an
34
+ * error whose cause chain has one) when it cannot; any other throw is a
35
+ * failure that stops the run.
36
+ */
37
+ backup(dest: string): MaybePromise<void>;
38
+
39
+ /**
40
+ * Replaces the current state from the backup directory `src`. Same
41
+ * contract as `backup`: resolve only when it really restored.
42
+ */
43
+ restore(src: string): MaybePromise<void>;
44
+
45
+ /**
46
+ * Optional, for a store several processes can migrate at once. The
47
+ * Migrator calls it before it reads the version and holds the lock for
48
+ * the whole run of that schema (version read, baseline, backup, every
49
+ * `up`, every version record, rollback, prune), then calls the returned
50
+ * unlock, on every path.
51
+ *
52
+ * Wait until the lock is acquired or `signal` aborts; in the second
53
+ * case reject with `abortError(signal)` and hold nothing. A rejection
54
+ * fails the schema before anything else (`lock: <message>`, no unlock).
55
+ * An unlock failure is only a warning. `RollbackLatest` locks too;
56
+ * `status` never does.
57
+ */
58
+ lock?(signal?: AbortSignal): MaybePromise<Unlock>;
59
+
60
+ /**
61
+ * Optional: `true` when the driver keeps its version itself (a database
62
+ * table). The Migrator then calls only `setVersion` to record a version
63
+ * and writes no version file; `version()` is the one authority.
64
+ */
65
+ readonly storesVersion?: boolean;
66
+ }
@@ -0,0 +1,47 @@
1
+ # drivers
2
+
3
+ ## What it answers
4
+
5
+ Where a schema's data and version live, and how it is backed up, restored and locked, for the `Migrator`. Each driver is a `SchemaDriver`; migration logic stays in `../`. Ported from Go `go/core/upgrade/driver`. Every driver is its own subpath import, so importing `@hop-top/kit/upgrade` never loads a database client, `tar` or `better-sqlite3`.
6
+
7
+ ## Use it when
8
+
9
+ | Backend | Import | Constructor | Version lives in | Backup / restore |
10
+ |---------|--------|-------------|------------------|------------------|
11
+ | config files | `@hop-top/kit/upgrade/drivers/configfile` | `new ConfigFileDriver(paths, { name?, dataDir?, tool? })` | version file | copies each file to and from `dest` |
12
+ | a directory | `@hop-top/kit/upgrade/drivers/fsdir` | `new FsDirDriver(name, dirPath, { dataDir?, tool? })` | version file | `<name>.tar.gz`; restore extracts to a temp dir, then swaps (loads `tar`) |
13
+ | a SQLite file | `@hop-top/kit/upgrade/drivers/sqlite` | `new SqliteDriver(dbPath, { name?, db?, dataDir?, tool? })` | version file | `VACUUM INTO` (WAL-safe); restore swaps the file and drops `-wal`, `-shm`, `-journal` (loads `better-sqlite3`) |
14
+ | Postgres | `@hop-top/kit/upgrade/drivers/postgres` | `await openPostgresDriver({ db, connect, table, name? })` over your `pg` Pool | table row (`storesVersion`); advisory `lock` | both throw `BackupUnsupportedError`; back up outside kit |
15
+
16
+ - file-backed drivers read the Migrator's version file: give them the Migrator's `dataDir`
17
+ - `SqliteDriver` with `db`: backup runs on your `Database` and never closes it; `restore` throws `BackupUnsupportedError`, so a failed `up`, or a failure with a missing `down`, ends not restored; path-only mode restores the file
18
+ - pick Postgres when the schema lives in a shared database that several installs or a Go and a TypeScript tool migrate
19
+
20
+ ## Quick start
21
+
22
+ ```ts
23
+ import { Migrator } from '@hop-top/kit/upgrade';
24
+ import { SqliteDriver } from '@hop-top/kit/upgrade/drivers/sqlite';
25
+
26
+ const m = new Migrator('mytool', '1.2.0', { dataDir });
27
+ m.addDriver(new SqliteDriver('/data/app.db', { name: 'app', dataDir, db }));
28
+ await m.run();
29
+ ```
30
+
31
+ ## Contract
32
+
33
+ - `name()` must equal `Migration.schema`. Postgres defaults to `postgres`; its table matches `^[a-zA-Z_][a-zA-Z0-9_]{0,63}$`.
34
+ - Archive layout of `fsdir` is Go's: members relative to the directory, `.` for the directory itself. Either port restores the other's. A restore refuses absolute names, `..`, links, devices and other special members (`path traversal blocked`); a backup refuses a symbolic link.
35
+ - `SqliteDriver.lock` holds `BEGIN EXCLUSIVE` on `.lock.db` in `<data dir>/<schema>/`, retrying every 50 ms without blocking the event loop until acquired or `signal` aborts. Node has no `flock`: this does NOT exclude the Go, Python or Rust drivers, which flock `.lock`.
36
+ - `VACUUM INTO` cannot run in a transaction: a backup on a handle with one open fails with a clear error. Path-only restore needs no open handle on the file.
37
+ - Postgres: kit imports no Postgres client. `db` needs `query(text, params)`; `connect` returns a dedicated client (`pool.connect()`, or a connected `Client`) that holds the lock for the whole run. The pool needs at least two connections: `options.max === 1` is refused at lock time. No transaction-mode pooler in front.
38
+ - Tests: `*.integration.test.ts` need `better-sqlite3` or Postgres 16 in Docker and run under `make test-ts-upgrade-integration`; the rest run under `make test-ts-sdk`.
39
+
40
+ ## Neighbours
41
+
42
+ - [`../README.md`](../README.md): `Migrator`, `SchemaDriver`; Go reference: [`go/core/upgrade/driver`](../../../../../go/core/upgrade/driver/README.md)
43
+ - [`go/core/upgrade/driver/postgres`](../../../../../go/core/upgrade/driver/postgres/README.md): the driver the Postgres one interoperates with.
44
+
45
+ ## See also
46
+
47
+ - [`docs/adopters/reference/ts-api-reference.md`](../../../../../docs/adopters/reference/ts-api-reference.md)