@hop-top/kit 0.5.0-alpha.12 → 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.
- package/CHANGELOG.md +29 -0
- package/README.md +5 -5
- package/dist/bus-D2bAOPYz.d.ts +55 -0
- package/dist/bus.d.ts +1 -0
- package/dist/bus.js +13 -0
- package/dist/chunk-74E6RNOI.js +82 -0
- package/dist/chunk-B7XTFDBB.js +17 -0
- package/dist/chunk-CAONBSPO.js +497 -0
- package/dist/chunk-F7RSL4N4.js +88 -0
- package/dist/chunk-I6XDPSXQ.js +75 -0
- package/dist/chunk-IDM6YZXN.js +204 -0
- package/dist/chunk-VKQCOVKI.js +880 -0
- package/dist/cli.js +3 -3
- package/dist/index-BqZ7WGQf.d.ts +731 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +27 -13
- package/dist/upgrade/drivers/configfile.d.ts +45 -0
- package/dist/upgrade/drivers/configfile.js +78 -0
- package/dist/upgrade/drivers/fsdir.d.ts +61 -0
- package/dist/upgrade/drivers/fsdir.js +170 -0
- package/dist/upgrade/drivers/postgres.d.ts +121 -0
- package/dist/upgrade/drivers/postgres.js +195 -0
- package/dist/upgrade/drivers/sqlite.d.ts +101 -0
- package/dist/upgrade/drivers/sqlite.js +241 -0
- package/dist/upgrade/index.d.ts +2 -0
- package/dist/upgrade/index.js +73 -0
- package/dist/uri-IJ_AoY3d.d.ts +144 -0
- package/dist/uri.d.ts +1 -0
- package/dist/uri.js +37 -0
- package/dist/version-DEJ3pbiO.d.ts +10 -0
- package/dist/wizard-Bf_qHc31.d.ts +159 -0
- package/dist/wizard.d.ts +1 -0
- package/dist/wizard.js +39 -0
- package/package.json +74 -15
- package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +19 -0
- package/skills/hop-top-kit-ts/SKILL.md +117 -0
- package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.expected +2 -0
- package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.ts +20 -0
- package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.expected +13 -0
- package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.ts +26 -0
- package/skills/hop-top-kit-ts/gym.json +5 -0
- package/skills/hop-top-kit-ts/references/ai-and-agents.md +45 -0
- package/skills/hop-top-kit-ts/references/cli-and-console.md +63 -0
- package/skills/hop-top-kit-ts/references/coverage.md +56 -0
- package/skills/hop-top-kit-ts/references/guardrails-and-trust.md +60 -0
- package/skills/hop-top-kit-ts/references/other-ports.md +31 -0
- package/skills/hop-top-kit-ts/references/serving-and-transports.md +49 -0
- package/skills/hop-top-kit-ts/scripts/detect-port.sh +168 -0
- package/src/index.test.ts +48 -2
- package/src/index.ts +6 -1
- package/src/published-types.test.ts +8 -0
- package/src/serve.stopped-order.test.ts +156 -0
- package/src/upgrade/README.md +42 -0
- package/src/upgrade/backup.ts +174 -0
- package/src/upgrade/conformance.test.ts +310 -0
- package/src/upgrade/document.ts +229 -0
- package/src/upgrade/driver.ts +66 -0
- package/src/upgrade/drivers/README.md +47 -0
- package/src/upgrade/drivers/configfile.test.ts +112 -0
- package/src/upgrade/drivers/configfile.ts +107 -0
- package/src/upgrade/drivers/fsdir.test.ts +188 -0
- package/src/upgrade/drivers/fsdir.ts +216 -0
- package/src/upgrade/drivers/isolation.test.ts +18 -0
- package/src/upgrade/drivers/postgres.integration.test.ts +395 -0
- package/src/upgrade/drivers/postgres.test.ts +272 -0
- package/src/upgrade/drivers/postgres.ts +284 -0
- package/src/upgrade/drivers/sqlite.integration.test.ts +492 -0
- package/src/upgrade/drivers/sqlite.ts +300 -0
- package/src/upgrade/drivers/version.ts +21 -0
- package/src/upgrade/errors.ts +117 -0
- package/src/upgrade/events.ts +117 -0
- package/src/{upgrade.test.ts → upgrade/index.test.ts} +1 -1
- package/src/{upgrade.ts → upgrade/index.ts} +20 -0
- package/src/upgrade/migration.ts +89 -0
- package/src/upgrade/migrator.test.ts +391 -0
- package/src/upgrade/migrator.ts +527 -0
- package/src/upgrade/options.ts +59 -0
- package/src/upgrade/semver.ts +90 -0
- package/test/skill-snippets.test.ts +60 -0
- package/test/upgrade/conformance-migrator.ts +439 -0
- package/test/upgrade/conformance-support.ts +44 -0
- package/test/upgrade/driver-support.ts +44 -0
- package/test/upgrade/pg-container.ts +64 -0
- package/test/upgrade/pg-race-worker.ts +48 -0
- package/test/upgrade/race-helper.ts +36 -0
- package/test/upgrade/sqlite-support.ts +41 -0
- package/test/upgrade/testdata/go-fsdir-mydata.tar.gz +0 -0
- package/vitest.config.ts +26 -0
- package/dist/chunk-X4E5QGEB.js +0 -171
- package/dist/upgrade-BJ2z6Oqf.d.ts +0 -156
- package/dist/upgrade.d.ts +0 -1
- package/dist/upgrade.js +0 -9
- package/dist/{chunk-MFVUENZR.js → chunk-KV7FYEAF.js} +2 -2
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# detect-port.sh - report which kit port(s) a project directory already uses.
|
|
3
|
+
#
|
|
4
|
+
# Usage: detect-port.sh [dir] dir defaults to the current directory.
|
|
5
|
+
#
|
|
6
|
+
# Reads manifest files directly inside dir (no recursion). Writes nothing,
|
|
7
|
+
# touches no network, runs no package manager.
|
|
8
|
+
#
|
|
9
|
+
# Manifests, in the order they are reported:
|
|
10
|
+
# go.mod module hop.top/kit
|
|
11
|
+
# package.json @hop-top/kit
|
|
12
|
+
# pyproject.toml hop-top-kit
|
|
13
|
+
# requirements*.txt hop-top-kit
|
|
14
|
+
# uv.lock hop-top-kit
|
|
15
|
+
# Cargo.toml hop-top-kit
|
|
16
|
+
# composer.json hop-top/kit
|
|
17
|
+
#
|
|
18
|
+
# Output: one line per manifest found, fields separated by single spaces,
|
|
19
|
+
# key=value, no value contains a space:
|
|
20
|
+
# port=<go|ts|py|rs|php> manifest=<file> kit=<spec> skill=<name> url=<url>
|
|
21
|
+
# kit=<spec> is the version or range as the manifest writes it (spaces
|
|
22
|
+
# removed), "unpinned" when kit is listed without one, "absent" when the
|
|
23
|
+
# manifest does not list kit, "unreadable" when the file cannot be read.
|
|
24
|
+
# url is the port skill's SKILL.md. A directory with no manifest prints
|
|
25
|
+
# nothing on stdout and one note on stderr.
|
|
26
|
+
#
|
|
27
|
+
# Exit codes:
|
|
28
|
+
# 0 dir is readable (whether or not any manifest was found)
|
|
29
|
+
# 2 usage error, or dir is not a readable directory
|
|
30
|
+
|
|
31
|
+
LC_ALL=C
|
|
32
|
+
export LC_ALL
|
|
33
|
+
|
|
34
|
+
usage() {
|
|
35
|
+
echo "usage: detect-port.sh [dir]" >&2
|
|
36
|
+
exit 2
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
case ${1-} in
|
|
40
|
+
-h | --help)
|
|
41
|
+
echo "usage: detect-port.sh [dir]"
|
|
42
|
+
exit 0
|
|
43
|
+
;;
|
|
44
|
+
-*) usage ;;
|
|
45
|
+
esac
|
|
46
|
+
[ $# -le 1 ] || usage
|
|
47
|
+
dir=${1:-.}
|
|
48
|
+
if [ ! -d "$dir" ] || [ ! -r "$dir" ] || [ ! -x "$dir" ]; then
|
|
49
|
+
echo "detect-port: not a readable directory: $dir" >&2
|
|
50
|
+
exit 2
|
|
51
|
+
fi
|
|
52
|
+
|
|
53
|
+
found=0
|
|
54
|
+
|
|
55
|
+
# report <port> <file> <spec>
|
|
56
|
+
report() {
|
|
57
|
+
case $1 in
|
|
58
|
+
go) skill=hop-top-kit-go mirror=kit ;;
|
|
59
|
+
ts) skill=hop-top-kit-ts mirror=kit-ts ;;
|
|
60
|
+
py) skill=hop-top-kit-py mirror=kit-py ;;
|
|
61
|
+
rs) skill=hop-top-kit-rs mirror=kit-rs ;;
|
|
62
|
+
php) skill=hop-top-kit-php mirror=kit-php ;;
|
|
63
|
+
esac
|
|
64
|
+
printf 'port=%s manifest=%s kit=%s skill=%s url=https://github.com/hop-top/%s/blob/main/skills/%s/SKILL.md\n' \
|
|
65
|
+
"$1" "$2" "$3" "$skill" "$mirror" "$skill"
|
|
66
|
+
found=1
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
# check <port> <name> <extractor> [path]: report when the manifest exists.
|
|
70
|
+
check() {
|
|
71
|
+
path=${4:-$dir/$2}
|
|
72
|
+
[ -f "$path" ] || return 0
|
|
73
|
+
if [ -r "$path" ]; then
|
|
74
|
+
spec=$(extract "$3" "$path" | tr -d ' \t')
|
|
75
|
+
else
|
|
76
|
+
spec=unreadable
|
|
77
|
+
fi
|
|
78
|
+
report "$1" "$2" "${spec:-unpinned}"
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
# Extractors print the spec, "absent", or nothing for an unpinned entry.
|
|
82
|
+
|
|
83
|
+
extract() {
|
|
84
|
+
case $1 in
|
|
85
|
+
gomod) ex_gomod "$2" ;;
|
|
86
|
+
package) ex_package "$2" ;;
|
|
87
|
+
python) ex_python "$2" ;;
|
|
88
|
+
uvlock) ex_uvlock "$2" ;;
|
|
89
|
+
cargo) ex_cargo "$2" ;;
|
|
90
|
+
composer) ex_composer "$2" ;;
|
|
91
|
+
esac
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
# json_dep <key> <file>: the value of "<key>": "<value>".
|
|
95
|
+
json_dep() {
|
|
96
|
+
v=$(sed -n 's|.*"'"$1"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*|\1|p' "$2" | head -n 1)
|
|
97
|
+
[ -n "$v" ] && echo "$v" || echo absent
|
|
98
|
+
}
|
|
99
|
+
ex_package() { json_dep '@hop-top/kit' "$1"; }
|
|
100
|
+
ex_composer() { json_dep 'hop-top/kit' "$1"; }
|
|
101
|
+
|
|
102
|
+
ex_gomod() {
|
|
103
|
+
awk '
|
|
104
|
+
$1 == "require" && $2 == "hop.top/kit" && $3 ~ /^v[0-9]/ { print $3; f = 1; exit }
|
|
105
|
+
$1 == "hop.top/kit" && $2 ~ /^v[0-9]/ { print $2; f = 1; exit }
|
|
106
|
+
END { if (!f) print "absent" }' "$1"
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
# Python: requirement lines and TOML dependency entries, name normalised.
|
|
110
|
+
ex_python() {
|
|
111
|
+
awk '
|
|
112
|
+
/^[ \t]*#/ || /^[ \t]*name[ \t]*=/ { next }
|
|
113
|
+
{
|
|
114
|
+
low = tolower($0); gsub(/[_.]/, "-", low)
|
|
115
|
+
for (off = 0; (i = index(substr(low, off + 1), "hop-top-kit")) > 0; off += i) {
|
|
116
|
+
p = off + i
|
|
117
|
+
if (p > 1 && substr(low, p - 1, 1) ~ /[a-z0-9-]/) continue
|
|
118
|
+
if (substr(low, p + 11, 1) ~ /[a-z0-9-]/) continue
|
|
119
|
+
f = 1; rest = substr($0, p + 11)
|
|
120
|
+
sub(/^\[[^]]*\]/, "", rest)
|
|
121
|
+
if (match(rest, /^[ \t]*=[ \t]*["'"'"'][^"'"'"']*["'"'"']/)) {
|
|
122
|
+
v = substr(rest, RSTART, RLENGTH); sub(/^[ \t]*=[ \t]*["'"'"']/, "", v); sub(/["'"'"']$/, "", v)
|
|
123
|
+
} else if (match(rest, /^[ \t]*[<>=!~]+[ \t]*[^"'"'"';# \t,]*([ \t]*,[ \t]*[<>=!~]+[ \t]*[^"'"'"';# \t,]*)*/)) {
|
|
124
|
+
v = substr(rest, RSTART, RLENGTH); sub(/^[ \t]+/, "", v)
|
|
125
|
+
}
|
|
126
|
+
print v; exit
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
END { if (!f) print "absent" }' "$1"
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
ex_uvlock() {
|
|
133
|
+
awk '
|
|
134
|
+
tolower($0) ~ /^name[ \t]*=[ \t]*"hop[-_.]top[-_.]kit"/ { hit = 1; next }
|
|
135
|
+
hit && /^version[ \t]*=/ { v = $0; sub(/^[^"]*"/, "", v); sub(/".*/, "", v); print v; f = 1; exit }
|
|
136
|
+
/^\[\[package\]\]/ { hit = 0 }
|
|
137
|
+
END { if (!f) print (hit ? "" : "absent") }' "$1"
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
ex_cargo() {
|
|
141
|
+
awk '
|
|
142
|
+
/^[ \t]*#/ { next }
|
|
143
|
+
/^\[/ { tbl = ($0 ~ /dependencies\.hop-top-kit[ \t]*\]/); if (tbl) f = 1; next }
|
|
144
|
+
tbl && /^version[ \t]*=/ { v = $0; sub(/^[^"]*"/, "", v); sub(/".*/, "", v); print v; exit }
|
|
145
|
+
/^hop-top-kit[ \t]*=/ {
|
|
146
|
+
f = 1; v = $0; sub(/^[^=]*=[ \t]*/, "", v)
|
|
147
|
+
if (v ~ /^"/) { sub(/^"/, "", v); sub(/".*/, "", v) }
|
|
148
|
+
else if (match(v, /version[ \t]*=[ \t]*"[^"]*"/)) {
|
|
149
|
+
v = substr(v, RSTART, RLENGTH); sub(/^[^"]*"/, "", v); sub(/"$/, "", v)
|
|
150
|
+
} else v = ""
|
|
151
|
+
print v; exit
|
|
152
|
+
}
|
|
153
|
+
END { if (!f) print "absent" }' "$1"
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
check go go.mod gomod
|
|
157
|
+
check ts package.json package
|
|
158
|
+
check py pyproject.toml python
|
|
159
|
+
for req in "$dir"/requirements*.txt; do
|
|
160
|
+
[ -f "$req" ] || continue
|
|
161
|
+
check py "${req##*/}" python "$req"
|
|
162
|
+
done
|
|
163
|
+
check py uv.lock uvlock
|
|
164
|
+
check rs Cargo.toml cargo
|
|
165
|
+
check php composer.json composer
|
|
166
|
+
|
|
167
|
+
[ "$found" -eq 1 ] || echo "detect-port: no kit-relevant manifest in $dir" >&2
|
|
168
|
+
exit 0
|
package/src/index.test.ts
CHANGED
|
@@ -53,11 +53,51 @@ describe('exports map contract', () => {
|
|
|
53
53
|
});
|
|
54
54
|
});
|
|
55
55
|
|
|
56
|
+
describe('documented subpaths', () => {
|
|
57
|
+
const docs = ['README.md', '../../docs/adopters/reference/ts-api-reference.md'];
|
|
58
|
+
|
|
59
|
+
it.each(docs)('%s names only subpaths the exports map declares', (doc) => {
|
|
60
|
+
const text = readFileSync(join(pkgDir, doc), 'utf8');
|
|
61
|
+
const named = new Set(
|
|
62
|
+
[...text.matchAll(/@hop-top\/kit\/([a-z][a-z0-9/-]*[a-z0-9])/g)]
|
|
63
|
+
// `upgrade/drivers/{a,b}` is brace shorthand, not a subpath.
|
|
64
|
+
.filter((m) => !text.startsWith('/{', m.index + m[0].length))
|
|
65
|
+
.map((m) => `./${m[1]}`),
|
|
66
|
+
);
|
|
67
|
+
expect(named.size).toBeGreaterThan(0);
|
|
68
|
+
for (const sub of named) {
|
|
69
|
+
expect(pkg.exports, `${doc}: ${sub}`).toHaveProperty([sub]);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// Adopter-facing modules (README, API reference, capability parity page).
|
|
74
|
+
it.each(['uri', 'wizard', 'bus'])('%s is importable as a subpath', (name) => {
|
|
75
|
+
expect(pkg.exports).toHaveProperty([`./${name}`]);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// Documented as internal: router would load hono from the root import; triton is only router's transport.
|
|
79
|
+
it.each(['router', 'triton'])('%s is intentionally not exported', (name) => {
|
|
80
|
+
expect(pkg.exports).not.toHaveProperty([`./${name}`]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it.each(docs)('%s never presents router or triton as importable', (doc) => {
|
|
84
|
+
const text = readFileSync(join(pkgDir, doc), 'utf8');
|
|
85
|
+
expect(text).not.toMatch(/@hop-top\/kit\/(router|triton)\b/);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
// Plumbing behind the cli factory: its public names are re-exported from `./cli`.
|
|
89
|
+
it.each(['delegation', 'sideeffect', 'policy'])('%s stays internal (reached through ./cli)', (name) => {
|
|
90
|
+
expect(pkg.exports).not.toHaveProperty([`./${name}`]);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
56
94
|
describe('root barrel', () => {
|
|
57
|
-
it('re-exports every public subpath except sqlstore as a namespace', () => {
|
|
95
|
+
it('re-exports every public subpath except sqlstore and the upgrade drivers as a namespace', () => {
|
|
58
96
|
// Kebab-case subpaths become camelCase namespaces (completion-values -> completionValues).
|
|
59
97
|
const expected = Object.keys(pkg.exports)
|
|
60
|
-
|
|
98
|
+
// Driver subpaths (`upgrade/drivers/<name>`) are opt-in entries (a caller-provided
|
|
99
|
+
// client, or a native or heavy module); they are nested, so they have no namespace.
|
|
100
|
+
.filter((p) => p !== '.' && p !== './sqlstore' && !p.startsWith('./upgrade/drivers/'))
|
|
61
101
|
.map((p) => p.replace(/^\.\//, '').replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()));
|
|
62
102
|
for (const name of expected) {
|
|
63
103
|
expect(kit, name).toHaveProperty(name);
|
|
@@ -68,4 +108,10 @@ describe('root barrel', () => {
|
|
|
68
108
|
it('does not eagerly expose sqlstore (native deps stay behind the subpath)', () => {
|
|
69
109
|
expect(kit).not.toHaveProperty('sqlstore');
|
|
70
110
|
});
|
|
111
|
+
|
|
112
|
+
it('does not expose the upgrade drivers (better-sqlite3 and tar stay behind their subpaths)', () => {
|
|
113
|
+
expect(kit.upgrade).not.toHaveProperty('SqliteDriver');
|
|
114
|
+
expect(kit.upgrade).not.toHaveProperty('FsDirDriver');
|
|
115
|
+
expect(kit.upgrade).not.toHaveProperty('ConfigFileDriver');
|
|
116
|
+
});
|
|
71
117
|
});
|
package/src/index.ts
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
* `sqlstore` is intentionally NOT re-exported here: an eager re-export
|
|
12
12
|
* would load better-sqlite3 native bindings on every bare import of the
|
|
13
13
|
* package. Use the dedicated subpath instead: `@hop-top/kit/sqlstore`.
|
|
14
|
+
* The upgrade drivers (`@hop-top/kit/upgrade/drivers/{configfile,fsdir,sqlite}`)
|
|
15
|
+
* stay out for the same reason: `sqlite` loads better-sqlite3, `fsdir` loads `tar`.
|
|
14
16
|
*/
|
|
15
17
|
|
|
16
18
|
export * as aim from './aim.js';
|
|
@@ -18,6 +20,7 @@ export * as alias from './alias.js';
|
|
|
18
20
|
export * as anthropic from './llm-anthropic.js';
|
|
19
21
|
export * as api from './api.js';
|
|
20
22
|
export * as auth from './auth.js';
|
|
23
|
+
export * as bus from './bus.js';
|
|
21
24
|
export * as cli from './cli.js';
|
|
22
25
|
export * as completion from './completion.js';
|
|
23
26
|
export * as completionValues from './completion-values.js';
|
|
@@ -42,5 +45,7 @@ export * as stream from './stream.js';
|
|
|
42
45
|
export * as telemetry from './telemetry/index.js';
|
|
43
46
|
export * as toolspec from './toolspec.js';
|
|
44
47
|
export * as tui from './tui/index.js';
|
|
45
|
-
export * as upgrade from './upgrade.js';
|
|
48
|
+
export * as upgrade from './upgrade/index.js';
|
|
49
|
+
export * as uri from './uri.js';
|
|
50
|
+
export * as wizard from './wizard.js';
|
|
46
51
|
export * as xdg from './xdg.js';
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
17
17
|
import { execFileSync } from 'node:child_process';
|
|
18
|
+
import { createRequire } from 'node:module';
|
|
18
19
|
import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
19
20
|
import * as path from 'node:path';
|
|
20
21
|
import * as ts from 'typescript';
|
|
@@ -109,6 +110,13 @@ describe('published declarations', () => {
|
|
|
109
110
|
|
|
110
111
|
afterAll(() => { rmSync(stageDir, { recursive: true, force: true }); });
|
|
111
112
|
|
|
113
|
+
// Runtime resolution through the package `exports` map, outside any test alias.
|
|
114
|
+
it.each(Object.keys(pkg.exports))('%s resolves and loads from the built package', (key) => {
|
|
115
|
+
const req = createRequire(files[1]);
|
|
116
|
+
const spec = key === '.' ? pkg.name : `${pkg.name}/${key.slice(2)}`;
|
|
117
|
+
expect(typeof req(spec)).toBe('object');
|
|
118
|
+
});
|
|
119
|
+
|
|
112
120
|
it.each(Object.entries(modes).map(([name, m]) => [name, m.skipLibCheck] as const))(
|
|
113
121
|
'type-check clean (moduleResolution %s, skipLibCheck %s)', (mode) => {
|
|
114
122
|
const program = ts.createProgram(files, {
|
|
@@ -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
|
+
}
|