@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,61 @@
1
+ import { D as DriverOptions } from '../../version-DEJ3pbiO.js';
2
+
3
+ /**
4
+ * A {@link SchemaDriver} for a filesystem directory, ported from Go
5
+ * `core/upgrade/driver/fsdir`: backup writes `<name>.tar.gz` into the
6
+ * backup directory, restore replaces the directory with its contents.
7
+ * The archive layout is Go's (entries relative to the directory, `.` for
8
+ * the directory itself, gzip), so either port restores the other's.
9
+ *
10
+ * Imports the `tar` package: import this module only where it is used
11
+ * (`@hop-top/kit/upgrade/drivers/fsdir`); the main entry never loads it.
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+
16
+ /** Options of an {@link FsDirDriver}. */
17
+ type FsDirOptions = DriverOptions;
18
+ /**
19
+ * Why a member name must not be extracted under the target directory, or
20
+ * `undefined` when it is a plain relative path inside it. Rejects absolute
21
+ * names (POSIX, backslash and drive-letter forms), any `..` segment and
22
+ * NUL bytes, on top of what the `tar` package does by default (it strips
23
+ * a leading `/` and skips `..` members with a warning instead of failing).
24
+ */
25
+ declare function unsafeName(name: string): string | undefined;
26
+ /**
27
+ * Backs up and restores one directory as a tar.gz archive.
28
+ *
29
+ * A `SchemaDriver`; not declared with `implements` so the bundled declarations
30
+ * keep `SchemaDriver` out of a chunk shared with the root barrel (the tests
31
+ * check the fit).
32
+ */
33
+ declare class FsDirDriver {
34
+ private readonly schema;
35
+ private readonly dirPath;
36
+ private readonly opts;
37
+ constructor(schema: string, dirPath: string, options?: FsDirOptions);
38
+ name(): string;
39
+ version(): Promise<string>;
40
+ /** The Migrator writes the version file; nothing to do here. */
41
+ setVersion(): void;
42
+ private archiveName;
43
+ /**
44
+ * Writes `<dest>/<name>.tar.gz` of the directory; a missing directory is
45
+ * "nothing to back up" (no archive, no error). Symbolic links and special
46
+ * files are not archived: they make the backup fail rather than be lost.
47
+ */
48
+ backup(dest: string): Promise<void>;
49
+ /**
50
+ * Replaces the directory with the archive in `src`. Every member is
51
+ * checked first (see {@link unsafeName}; links, devices and other
52
+ * special members are refused: `path traversal blocked: <name>`,
53
+ * `special member blocked: <name>`); the
54
+ * archive is then extracted into a temporary directory beside the target
55
+ * and swapped in, so a refused or failed restore leaves the directory
56
+ * as it was.
57
+ */
58
+ restore(src: string): Promise<void>;
59
+ }
60
+
61
+ export { FsDirDriver, type FsDirOptions, unsafeName };
@@ -0,0 +1,170 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }
2
+
3
+ var _chunkB7XTFDBBjs = require('../../chunk-B7XTFDBB.js');
4
+ require('../../chunk-IDM6YZXN.js');
5
+ require('../../chunk-I6XDPSXQ.js');
6
+ require('../../chunk-4UE5TCMQ.js');
7
+ require('../../chunk-R5U7XKVJ.js');
8
+
9
+ // src/upgrade/drivers/fsdir.ts
10
+ var _fs = require('fs');
11
+ var _path = require('path'); var path = _interopRequireWildcard(_path);
12
+ var _crypto = require('crypto');
13
+ var _tar = require('tar'); var tar = _interopRequireWildcard(_tar);
14
+ var isMissing = (e) => e.code === "ENOENT";
15
+ var msg = (e) => e instanceof Error ? e.message : String(e);
16
+ var PLAIN = /* @__PURE__ */ new Set(["File", "OldFile", "ContiguousFile", "Directory"]);
17
+ function unsafeName(name) {
18
+ if (name.includes("\0")) return "NUL in name";
19
+ if (name.startsWith("/") || name.startsWith("\\") || /^[A-Za-z]:/.test(name)) return "absolute path";
20
+ if (name.split(/[\\/]/).includes("..")) return "parent directory reference";
21
+ return void 0;
22
+ }
23
+ var FsDirDriver = class {
24
+ constructor(schema, dirPath, options = {}) {
25
+ this.schema = schema;
26
+ this.dirPath = dirPath;
27
+ this.opts = { dataDir: options.dataDir, tool: options.tool };
28
+ }
29
+ name() {
30
+ return this.schema;
31
+ }
32
+ version() {
33
+ return _chunkB7XTFDBBjs.versionOf.call(void 0, this.opts, this.schema);
34
+ }
35
+ /** The Migrator writes the version file; nothing to do here. */
36
+ setVersion() {
37
+ }
38
+ archiveName() {
39
+ return this.schema + ".tar.gz";
40
+ }
41
+ /**
42
+ * Writes `<dest>/<name>.tar.gz` of the directory; a missing directory is
43
+ * "nothing to back up" (no archive, no error). Symbolic links and special
44
+ * files are not archived: they make the backup fail rather than be lost.
45
+ */
46
+ async backup(dest) {
47
+ try {
48
+ await _fs.promises.mkdir(dest, { recursive: true, mode: 488 });
49
+ } catch (e) {
50
+ throw new Error(`create backup dir: ${msg(e)}`, { cause: e });
51
+ }
52
+ try {
53
+ await _fs.promises.stat(this.dirPath);
54
+ } catch (e) {
55
+ if (isMissing(e)) return;
56
+ throw new Error(`stat dir: ${msg(e)}`, { cause: e });
57
+ }
58
+ await requirePlain(this.dirPath);
59
+ const archive = path.join(dest, this.archiveName());
60
+ const tmp = archive + ".tmp";
61
+ try {
62
+ await tar.c(
63
+ {
64
+ file: tmp,
65
+ cwd: this.dirPath,
66
+ gzip: true,
67
+ // Go's names: relative to the directory, `.` for the directory.
68
+ onWriteEntry: (entry) => {
69
+ entry.path = entry.path.replace(/^\.\//, "") || ".";
70
+ }
71
+ },
72
+ ["."]
73
+ );
74
+ await _fs.promises.rename(tmp, archive);
75
+ } catch (e) {
76
+ await _fs.promises.rm(tmp, { force: true });
77
+ throw new Error(`create archive: ${msg(e)}`, { cause: e });
78
+ }
79
+ }
80
+ /**
81
+ * Replaces the directory with the archive in `src`. Every member is
82
+ * checked first (see {@link unsafeName}; links, devices and other
83
+ * special members are refused: `path traversal blocked: <name>`,
84
+ * `special member blocked: <name>`); the
85
+ * archive is then extracted into a temporary directory beside the target
86
+ * and swapped in, so a refused or failed restore leaves the directory
87
+ * as it was.
88
+ */
89
+ async restore(src) {
90
+ const archive = path.join(src, this.archiveName());
91
+ try {
92
+ await _fs.promises.stat(archive);
93
+ } catch (e) {
94
+ if (isMissing(e)) throw new Error(`backup archive not found: ${archive}`, { cause: e });
95
+ throw new Error(`open archive: ${msg(e)}`, { cause: e });
96
+ }
97
+ const hasRoot = await checkMembers(archive);
98
+ const target = path.resolve(this.dirPath);
99
+ const parent = path.dirname(target);
100
+ const base = path.basename(target);
101
+ await _fs.promises.mkdir(parent, { recursive: true, mode: 488 });
102
+ const tmp = await _fs.promises.mkdtemp(path.join(parent, `.${base}.restore-`));
103
+ let old;
104
+ try {
105
+ try {
106
+ await tar.x({
107
+ file: archive,
108
+ cwd: tmp,
109
+ strict: true,
110
+ preservePaths: false,
111
+ preserveOwner: false,
112
+ filter: (_p, entry) => PLAIN.has(entry.type)
113
+ });
114
+ } catch (e) {
115
+ throw new Error(`tar read: ${msg(e)}`, { cause: e });
116
+ }
117
+ if (!hasRoot) await _fs.promises.chmod(tmp, 488);
118
+ try {
119
+ old = path.join(parent, `.${base}.old-${_crypto.randomBytes.call(void 0, 6).toString("hex")}`);
120
+ await _fs.promises.rename(target, old);
121
+ } catch (e) {
122
+ if (!isMissing(e)) throw new Error(`remove dir: ${msg(e)}`, { cause: e });
123
+ old = void 0;
124
+ }
125
+ try {
126
+ await _fs.promises.rename(tmp, target);
127
+ } catch (e) {
128
+ if (old !== void 0) await _fs.promises.rename(old, target).catch(() => void 0);
129
+ throw new Error(`recreate dir: ${msg(e)}`, { cause: e });
130
+ }
131
+ } finally {
132
+ await _fs.promises.rm(tmp, { recursive: true, force: true });
133
+ }
134
+ if (old !== void 0) await _fs.promises.rm(old, { recursive: true, force: true });
135
+ }
136
+ };
137
+ async function requirePlain(dir) {
138
+ const entries = await _fs.promises.readdir(dir, { withFileTypes: true, recursive: true });
139
+ for (const e of entries) {
140
+ if (e.isFile() || e.isDirectory()) continue;
141
+ const rel = path.relative(dir, path.join(e.parentPath, e.name));
142
+ throw new Error(`create archive: ${rel}: only files and directories can be backed up`);
143
+ }
144
+ }
145
+ async function checkMembers(archive) {
146
+ let problem;
147
+ let hasRoot = false;
148
+ try {
149
+ await tar.t({
150
+ file: archive,
151
+ strict: true,
152
+ onReadEntry: (entry) => {
153
+ entry.resume();
154
+ if (problem !== void 0) return;
155
+ const bad = unsafeName(entry.path);
156
+ if (bad !== void 0) problem = `path traversal blocked: ${entry.path}`;
157
+ else if (!PLAIN.has(entry.type)) problem = `special member blocked: ${entry.path} (${entry.type})`;
158
+ else if (path.posix.normalize(entry.path) === "./" || path.posix.normalize(entry.path) === ".") hasRoot = true;
159
+ }
160
+ });
161
+ } catch (e) {
162
+ throw new Error(`tar read: ${msg(e)}`, { cause: e });
163
+ }
164
+ if (problem !== void 0) throw new Error(problem);
165
+ return hasRoot;
166
+ }
167
+
168
+
169
+
170
+ exports.FsDirDriver = FsDirDriver; exports.unsafeName = unsafeName;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * A {@link SchemaDriver} for PostgreSQL over a caller-provided
3
+ * node-postgres style handle, ported from Go
4
+ * `core/upgrade/driver/postgres`. Kit has no runtime Postgres dependency:
5
+ * the caller opens the `pg` Pool (or any object with the same `query`
6
+ * shape) and passes it in, plus a function that returns a dedicated client
7
+ * for the lock.
8
+ *
9
+ * SQL, the table-name rule and the lock key text are the Go driver's,
10
+ * character for character, so a Go and a TypeScript Migrator on one table
11
+ * and schema name exclude each other.
12
+ *
13
+ * Import from `@hop-top/kit/upgrade/drivers/postgres`. The class is a
14
+ * structural `SchemaDriver` (checked in `postgres.test.ts`); it imports no
15
+ * type from `../driver` so the published declarations stay one chunk per
16
+ * entry.
17
+ */
18
+ /** What a query resolves with: the rows, as objects keyed by column. */
19
+ interface PgResult {
20
+ rows: Array<Record<string, any>>;
21
+ }
22
+ /** The node-postgres `query(text, params)` shape (a `Pool` or `Client`). */
23
+ interface PgQueryable {
24
+ query(text: string, params?: any[]): Promise<PgResult>;
25
+ /** A node-postgres `Pool` carries its options; `max: 1` is refused at lock time. */
26
+ readonly options?: {
27
+ max?: number;
28
+ };
29
+ }
30
+ /**
31
+ * A dedicated connection for the lock: a client from `pool.connect()` (has
32
+ * `release`) or a standalone connected `Client` (has `end`). The driver
33
+ * ends the physical connection through whichever exists.
34
+ */
35
+ interface PgLockClient {
36
+ query(text: string, params?: any[]): Promise<PgResult>;
37
+ /** Pooled client: `release()` returns it, `release(true)` destroys it. */
38
+ release?(destroy?: boolean | Error): void;
39
+ /** Standalone client: closes the connection. */
40
+ end?(): void | Promise<void>;
41
+ }
42
+ interface PostgresDriverOptions {
43
+ /** Runs the version queries. Never closed by the driver. */
44
+ db: PgQueryable;
45
+ /**
46
+ * Returns a dedicated connected client, e.g. `() => pool.connect()`.
47
+ * It carries the lock for the whole run, so it must not be `db` itself
48
+ * and a pool needs at least two connections.
49
+ */
50
+ connect: () => Promise<PgLockClient>;
51
+ /** Version table, `^[a-zA-Z_][a-zA-Z0-9_]{0,63}$`, interpolated unquoted. */
52
+ table: string;
53
+ /** Schema name, matched against `Migration.schema`. Default `postgres`. */
54
+ name?: string;
55
+ }
56
+ /** SQL shared verbatim by every port (the server hashes the key text). */
57
+ declare const SQL_LOCK = "SELECT pg_advisory_lock(hashtextextended($1, 0))";
58
+ declare const SQL_UNLOCK = "SELECT pg_advisory_unlock(hashtextextended($1, 0))";
59
+ declare const SQL_XACT_LOCK = "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))";
60
+ /**
61
+ * The non-blocking form of {@link SQL_LOCK}: same key, same session-level
62
+ * lock, so it excludes (and is excluded by) a blocking `pg_advisory_lock`
63
+ * on the key. Polled so an aborted wait holds nothing.
64
+ */
65
+ declare const SQL_TRY_LOCK = "SELECT pg_try_advisory_lock(hashtextextended($1, 0))";
66
+ /** Text hashed into the advisory lock key for a run. */
67
+ declare const lockKey: (table: string, name: string) => string;
68
+ /** Text hashed into the key that serialises table creation. */
69
+ declare const ddlKey: (table: string) => string;
70
+ /** The DDL for the version table. */
71
+ declare const createTableSql: (table: string) => string;
72
+ declare const versionSql: (table: string) => string;
73
+ declare const upsertSql: (table: string) => string;
74
+ /** Throws `invalid table name: "<name>"` unless `name` is a legal table name. */
75
+ declare function validateTable(name: string): void;
76
+ /**
77
+ * Tracks a schema version in a PostgreSQL table and serialises concurrent
78
+ * migrators with a session-level advisory lock. Create it with
79
+ * {@link openPostgresDriver}.
80
+ */
81
+ declare class PostgresDriver {
82
+ private readonly o;
83
+ readonly storesVersion = true;
84
+ /** @internal use {@link openPostgresDriver}. */
85
+ constructor(o: Required<PostgresDriverOptions>);
86
+ name(): string;
87
+ /** The stored version; no row means `""`. */
88
+ version(): Promise<string>;
89
+ /** Upserts the version row for this schema. */
90
+ setVersion(version: string): Promise<void>;
91
+ /** Kit does not back up a server database: the run goes on without one. */
92
+ backup(_dest: string): Promise<void>;
93
+ /** Nothing is restored: a rollback that needs it ends "not restored". */
94
+ restore(_src: string): Promise<void>;
95
+ /**
96
+ * Takes the session-level advisory lock on one dedicated connection and
97
+ * holds that connection until the returned unlock runs. Waits by polling
98
+ * `pg_try_advisory_lock` (about every 50 ms) until acquired or `signal`
99
+ * aborts; an aborted wait rejects with `abortError(signal)` and the
100
+ * connection is destroyed, so nothing is held. Unlock runs
101
+ * `pg_advisory_unlock` on that same connection regardless of `signal`;
102
+ * when it fails or answers `false` the connection is destroyed, which
103
+ * ends the session and the lock.
104
+ *
105
+ * A pool with `options.max === 1` is refused (the lock holds its only
106
+ * connection and the run's queries would wait for ever).
107
+ */
108
+ lock(signal?: AbortSignal): Promise<() => Promise<void>>;
109
+ private unlocker;
110
+ private release;
111
+ }
112
+ /**
113
+ * Ensures the version table exists, then returns a driver for it. The
114
+ * table is created in a transaction on a dedicated client that first takes
115
+ * `pg_advisory_xact_lock`: two sessions running `CREATE TABLE IF NOT
116
+ * EXISTS` at once can still fail with a catalog unique violation. The
117
+ * driver never closes `db`.
118
+ */
119
+ declare function openPostgresDriver(opts: PostgresDriverOptions): Promise<PostgresDriver>;
120
+
121
+ export { type PgLockClient, type PgQueryable, type PgResult, PostgresDriver, type PostgresDriverOptions, SQL_LOCK, SQL_TRY_LOCK, SQL_UNLOCK, SQL_XACT_LOCK, createTableSql, ddlKey, lockKey, openPostgresDriver, upsertSql, validateTable, versionSql };
@@ -0,0 +1,195 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+ var _chunkI6XDPSXQjs = require('../../chunk-I6XDPSXQ.js');
6
+ require('../../chunk-R5U7XKVJ.js');
7
+
8
+ // src/upgrade/drivers/postgres.ts
9
+ var TABLE_RE = /^[a-zA-Z_][a-zA-Z0-9_]{0,63}$/;
10
+ var SQL_LOCK = "SELECT pg_advisory_lock(hashtextextended($1, 0))";
11
+ var SQL_UNLOCK = "SELECT pg_advisory_unlock(hashtextextended($1, 0))";
12
+ var SQL_XACT_LOCK = "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))";
13
+ var SQL_TRY_LOCK = "SELECT pg_try_advisory_lock(hashtextextended($1, 0))";
14
+ var lockKey = (table, name) => `kit-upgrade:${table}:${name}`;
15
+ var ddlKey = (table) => `kit-upgrade:${table}:ddl`;
16
+ var createTableSql = (table) => `CREATE TABLE IF NOT EXISTS ${table} (schema_name TEXT PRIMARY KEY, version TEXT NOT NULL DEFAULT '')`;
17
+ var versionSql = (table) => `SELECT version FROM ${table} WHERE schema_name = $1`;
18
+ var upsertSql = (table) => `INSERT INTO ${table} (schema_name, version) VALUES ($1, $2) ON CONFLICT (schema_name) DO UPDATE SET version = EXCLUDED.version`;
19
+ var POLL_MS = 50;
20
+ function validateTable(name) {
21
+ if (typeof name !== "string" || !TABLE_RE.test(name)) {
22
+ throw new Error(`invalid table name: ${JSON.stringify(name)}`);
23
+ }
24
+ }
25
+ var firstValue = (r) => {
26
+ const row = r.rows[0];
27
+ return row === void 0 ? void 0 : Object.values(row)[0];
28
+ };
29
+ async function discard(c) {
30
+ try {
31
+ if (typeof c.release === "function") c.release(true);
32
+ else if (typeof c.end === "function") await c.end();
33
+ } catch (e2) {
34
+ }
35
+ }
36
+ async function finish(c) {
37
+ if (typeof c.release === "function") c.release();
38
+ else if (typeof c.end === "function") await c.end();
39
+ }
40
+ function pause(ms, signal) {
41
+ return new Promise((resolve) => {
42
+ const done = () => {
43
+ clearTimeout(t);
44
+ _optionalChain([signal, 'optionalAccess', _ => _.removeEventListener, 'call', _2 => _2("abort", done)]);
45
+ resolve();
46
+ };
47
+ const t = setTimeout(done, ms);
48
+ _optionalChain([signal, 'optionalAccess', _3 => _3.addEventListener, 'call', _4 => _4("abort", done, { once: true })]);
49
+ });
50
+ }
51
+ var PostgresDriver = class {
52
+ /** @internal use {@link openPostgresDriver}. */
53
+ constructor(o) {
54
+ this.o = o;
55
+ this.storesVersion = true;
56
+ }
57
+ name() {
58
+ return this.o.name;
59
+ }
60
+ /** The stored version; no row means `""`. */
61
+ async version() {
62
+ try {
63
+ const r = await this.o.db.query(versionSql(this.o.table), [this.o.name]);
64
+ const v = _optionalChain([r, 'access', _5 => _5.rows, 'access', _6 => _6[0], 'optionalAccess', _7 => _7["version"]]);
65
+ return typeof v === "string" ? v : "";
66
+ } catch (e) {
67
+ throw new Error(`postgres upgrade: version: ${_chunkI6XDPSXQjs.errorText.call(void 0, e)}`, { cause: e });
68
+ }
69
+ }
70
+ /** Upserts the version row for this schema. */
71
+ async setVersion(version) {
72
+ try {
73
+ await this.o.db.query(upsertSql(this.o.table), [this.o.name, version]);
74
+ } catch (e) {
75
+ throw new Error(`postgres upgrade: set version: ${_chunkI6XDPSXQjs.errorText.call(void 0, e)}`, { cause: e });
76
+ }
77
+ }
78
+ /** Kit does not back up a server database: the run goes on without one. */
79
+ async backup(_dest) {
80
+ throw new (0, _chunkI6XDPSXQjs.BackupUnsupportedError)("postgres upgrade: backup unsupported");
81
+ }
82
+ /** Nothing is restored: a rollback that needs it ends "not restored". */
83
+ async restore(_src) {
84
+ throw new (0, _chunkI6XDPSXQjs.BackupUnsupportedError)("postgres upgrade: restore unsupported");
85
+ }
86
+ /**
87
+ * Takes the session-level advisory lock on one dedicated connection and
88
+ * holds that connection until the returned unlock runs. Waits by polling
89
+ * `pg_try_advisory_lock` (about every 50 ms) until acquired or `signal`
90
+ * aborts; an aborted wait rejects with `abortError(signal)` and the
91
+ * connection is destroyed, so nothing is held. Unlock runs
92
+ * `pg_advisory_unlock` on that same connection regardless of `signal`;
93
+ * when it fails or answers `false` the connection is destroyed, which
94
+ * ends the session and the lock.
95
+ *
96
+ * A pool with `options.max === 1` is refused (the lock holds its only
97
+ * connection and the run's queries would wait for ever).
98
+ */
99
+ async lock(signal) {
100
+ if (_optionalChain([this, 'access', _8 => _8.o, 'access', _9 => _9.db, 'access', _10 => _10.options, 'optionalAccess', _11 => _11.max]) === 1) {
101
+ throw new Error(
102
+ "postgres upgrade: lock needs a pool of at least two connections: the lock holds one for the whole run (a pool with max 1 would deadlock)"
103
+ );
104
+ }
105
+ if (_optionalChain([signal, 'optionalAccess', _12 => _12.aborted])) throw _chunkI6XDPSXQjs.abortError.call(void 0, signal);
106
+ let client;
107
+ try {
108
+ client = await this.o.connect();
109
+ } catch (e) {
110
+ throw new Error(`postgres upgrade: lock: ${_chunkI6XDPSXQjs.errorText.call(void 0, e)}`, { cause: e });
111
+ }
112
+ const key = lockKey(this.o.table, this.o.name);
113
+ try {
114
+ for (; ; ) {
115
+ if (_optionalChain([signal, 'optionalAccess', _13 => _13.aborted])) throw _chunkI6XDPSXQjs.abortError.call(void 0, signal);
116
+ const r = await client.query(SQL_TRY_LOCK, [key]);
117
+ if (firstValue(r) === true) break;
118
+ await pause(POLL_MS, signal);
119
+ }
120
+ if (_optionalChain([signal, 'optionalAccess', _14 => _14.aborted])) throw _chunkI6XDPSXQjs.abortError.call(void 0, signal);
121
+ } catch (e) {
122
+ await discard(client);
123
+ if (_optionalChain([signal, 'optionalAccess', _15 => _15.aborted])) throw _chunkI6XDPSXQjs.abortError.call(void 0, signal);
124
+ throw new Error(`postgres upgrade: lock: ${_chunkI6XDPSXQjs.errorText.call(void 0, e)}`, { cause: e });
125
+ }
126
+ return this.unlocker(client, key);
127
+ }
128
+ unlocker(client, key) {
129
+ let result;
130
+ return () => _nullishCoalesce(result, () => ( (result = this.release(client, key))));
131
+ }
132
+ async release(client, key) {
133
+ let err;
134
+ try {
135
+ const r = await client.query(SQL_UNLOCK, [key]);
136
+ if (firstValue(r) !== true) err = new Error("lock was not held by this session");
137
+ } catch (e) {
138
+ err = e;
139
+ }
140
+ if (err !== void 0) {
141
+ await discard(client);
142
+ throw new Error(`postgres upgrade: unlock: ${_chunkI6XDPSXQjs.errorText.call(void 0, err)}`, { cause: err });
143
+ }
144
+ await finish(client);
145
+ }
146
+ };
147
+ async function openPostgresDriver(opts) {
148
+ validateTable(opts.table);
149
+ if (!opts.db || typeof opts.db.query !== "function") {
150
+ throw new Error("postgres upgrade: db must have query(text, params)");
151
+ }
152
+ if (typeof opts.connect !== "function") {
153
+ throw new Error("postgres upgrade: connect must return a dedicated client");
154
+ }
155
+ const o = { ...opts, name: _nullishCoalesce(opts.name, () => ( "postgres")) };
156
+ try {
157
+ await ensureTable(o);
158
+ } catch (e) {
159
+ throw new Error(`postgres upgrade: migrate: ${_chunkI6XDPSXQjs.errorText.call(void 0, e)}`, { cause: e });
160
+ }
161
+ return new PostgresDriver(o);
162
+ }
163
+ async function ensureTable(o) {
164
+ const client = await o.connect();
165
+ try {
166
+ await client.query("BEGIN");
167
+ await client.query(SQL_XACT_LOCK, [ddlKey(o.table)]);
168
+ await client.query(createTableSql(o.table));
169
+ await client.query("COMMIT");
170
+ } catch (e) {
171
+ try {
172
+ await client.query("ROLLBACK");
173
+ } catch (e3) {
174
+ await discard(client);
175
+ throw e;
176
+ }
177
+ await finish(client);
178
+ throw e;
179
+ }
180
+ await finish(client);
181
+ }
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+ exports.PostgresDriver = PostgresDriver; exports.SQL_LOCK = SQL_LOCK; exports.SQL_TRY_LOCK = SQL_TRY_LOCK; exports.SQL_UNLOCK = SQL_UNLOCK; exports.SQL_XACT_LOCK = SQL_XACT_LOCK; exports.createTableSql = createTableSql; exports.ddlKey = ddlKey; exports.lockKey = lockKey; exports.openPostgresDriver = openPostgresDriver; exports.upsertSql = upsertSql; exports.validateTable = validateTable; exports.versionSql = versionSql;
@@ -0,0 +1,101 @@
1
+ import Database from 'better-sqlite3';
2
+ import { D as DriverOptions } from '../../version-DEJ3pbiO.js';
3
+
4
+ /**
5
+ * A {@link SchemaDriver} for a SQLite database file, ported from Go
6
+ * `core/upgrade/driver/sqlite`, over `better-sqlite3`.
7
+ *
8
+ * Two modes. Path only: `new SqliteDriver(dbPath)` opens its own
9
+ * short-lived connection for `backup` and swaps the file on `restore`.
10
+ * Handle: `new SqliteDriver(dbPath, { db })` backs up through the caller's
11
+ * `Database`, never closes it, and cannot restore (the file cannot be
12
+ * replaced under a live connection): `restore` throws
13
+ * {@link BackupUnsupportedError} and the backup stays for manual recovery.
14
+ *
15
+ * The lock is `BEGIN EXCLUSIVE` on a separate database `.lock.db` beside
16
+ * the version file, because Node has no `flock`. It excludes other
17
+ * connections and processes using this driver, but does NOT interoperate
18
+ * with the `flock` on `.lock` that the Go, Python and Rust drivers take: a
19
+ * TypeScript and a non-TypeScript process migrating one file do not
20
+ * exclude each other.
21
+ *
22
+ * Imports `better-sqlite3`: import this module only where it is used
23
+ * (`@hop-top/kit/upgrade/drivers/sqlite`); the main entry never loads it.
24
+ *
25
+ * @packageDocumentation
26
+ */
27
+
28
+ /** Options of a {@link SqliteDriver}. */
29
+ interface SqliteOptions extends DriverOptions {
30
+ /** The schema name (default `"sqlite"`). */
31
+ name?: string;
32
+ /**
33
+ * The caller's open connection. `backup` runs on it and leaves it open;
34
+ * `restore` throws {@link BackupUnsupportedError}. `dbPath` then only
35
+ * names the backup file (and may be empty).
36
+ */
37
+ db?: Database.Database;
38
+ }
39
+ /** The lock database, in the version file's directory. */
40
+ declare const LOCK_FILE = ".lock.db";
41
+ /**
42
+ * Backs up, restores and locks one SQLite database file.
43
+ *
44
+ * A `SchemaDriver`; not declared with `implements` so the bundled declarations
45
+ * keep `SchemaDriver` out of a chunk shared with the root barrel (the tests
46
+ * check the fit).
47
+ */
48
+ declare class SqliteDriver {
49
+ private readonly dbPath;
50
+ private readonly schema;
51
+ private readonly db?;
52
+ private readonly opts;
53
+ constructor(dbPath: string, options?: SqliteOptions);
54
+ name(): string;
55
+ version(): Promise<string>;
56
+ /** The Migrator writes the version file; nothing to do here. */
57
+ setVersion(): void;
58
+ /** The backup file's name: the database file's base name, or `<schema>.db` without a path. */
59
+ private backupName;
60
+ /**
61
+ * Writes a consistent snapshot to `<dest>/<database file name>` with
62
+ * `VACUUM INTO`, which reads through the WAL: rows committed but not yet
63
+ * checkpointed are in it. Path only: a missing database file is
64
+ * "nothing to back up" (no file, no error); the driver opens a
65
+ * connection of its own and closes it. With a caller handle the snapshot
66
+ * runs on it, left open; it must not be inside a transaction.
67
+ */
68
+ backup(dest: string): Promise<void>;
69
+ /** Snapshots the database to `file`, bound as a parameter so no path needs quoting. */
70
+ private vacuumInto;
71
+ /**
72
+ * Replaces the database file with the backup in `src`, then removes the
73
+ * replaced database's `-wal`, `-shm` and `-journal` files.
74
+ *
75
+ * Precondition: no open handle on the file, in this process or another;
76
+ * a connection left open keeps using the replaced file and may recreate
77
+ * its -wal beside the restored one. With a caller handle it restores
78
+ * nothing and throws {@link BackupUnsupportedError}; the backup stays.
79
+ *
80
+ * The backup is copied to a temporary file beside the database, synced
81
+ * and renamed over it, so a failure before the rename leaves the
82
+ * database and its sidecars untouched. An error after the rename means
83
+ * the database already holds the backup; a sidecar named in the error
84
+ * must be removed before the database is opened.
85
+ */
86
+ restore(src: string): Promise<void>;
87
+ /** `<data dir>/<schema>`: where the version file and the lock database live. */
88
+ private stateDir;
89
+ /**
90
+ * Holds `BEGIN EXCLUSIVE` on `<version dir>/.lock.db` (the directory is
91
+ * created if needed) until the returned function runs, retrying about
92
+ * every 50 ms while another connection holds it. When `signal` aborts
93
+ * while waiting it rejects with `abortError(signal)` and holds nothing.
94
+ * The retry loop is asynchronous (the busy timeout is 0), so a wait
95
+ * never blocks the event loop. The file is never deleted. Does not
96
+ * interoperate with the other ports' `flock` on `.lock`.
97
+ */
98
+ lock(signal?: AbortSignal): Promise<() => void>;
99
+ }
100
+
101
+ export { LOCK_FILE, SqliteDriver, type SqliteOptions };