@acryldev/manifest 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,184 @@
1
+ import assert from 'node:assert/strict'
2
+ import {
3
+ cpSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ mkdtempSync,
7
+ readFileSync,
8
+ rmSync,
9
+ writeFileSync,
10
+ } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+ import { afterEach, test } from 'node:test'
14
+ import { LOCK_FILE } from '../lock.ts'
15
+ import { applySnapshot, captureApp, verifyApp } from '../snapshot.ts'
16
+
17
+ const dirs: string[] = []
18
+ afterEach(() => {
19
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
20
+ })
21
+
22
+ const BLEND = `# What this app is.
23
+ apiVersion: blends.acryl.dev/v1alpha1
24
+ kind: Blueprint
25
+ metadata: { id: acme.board, name: board, version: 0.1.0 }
26
+ spec:
27
+ runtime: cordis
28
+ rows:
29
+ - id: router # the routes every plugin mounts on
30
+ name: 'acryl-router'
31
+ - id: extensions
32
+ name: extensions
33
+ - id: server
34
+ name: 'acryl-node-server'
35
+ `
36
+
37
+ function plugin(app: string, name: string, body = '', exportName = name) {
38
+ mkdirSync(join(app, 'plugins', name), { recursive: true })
39
+ writeFileSync(
40
+ join(app, 'plugins', name, 'index.ts'),
41
+ `export const name = '${exportName}'\nexport function apply() {}\n${body}`,
42
+ )
43
+ }
44
+
45
+ function app(id = 'board'): string {
46
+ const dir = mkdtempSync(join(tmpdir(), 'snapshot-test-'))
47
+ dirs.push(dir)
48
+ writeFileSync(
49
+ join(dir, 'blend.yaml'),
50
+ BLEND.replace('id: acme.board, name: board', `id: acme.${id}, name: ${id}`),
51
+ )
52
+ plugin(dir, 'router', '', 'acryl-router')
53
+ writeFileSync(join(dir, 'plugins', 'library.json'), JSON.stringify({ plugins: ['router'] }))
54
+ return dir
55
+ }
56
+
57
+ test('capture gives every plugin folder of the app a row, keeps the comments, locks it, and changes nothing the second time', () => {
58
+ const dir = app()
59
+ plugin(dir, 'notes')
60
+ const capture = captureApp(dir)
61
+ assert.deepEqual(capture.addedRows, ['notes'])
62
+ const yaml = readFileSync(join(dir, 'blend.yaml'), 'utf8')
63
+ assert.match(yaml, /# What this app is\./)
64
+ assert.match(yaml, /# the routes every plugin mounts on/)
65
+ // The new row sits before the extensions row, so the extensions row never starts it a second time.
66
+ assert.ok(yaml.indexOf('id: notes') < yaml.indexOf('id: extensions'), yaml)
67
+ const lock = JSON.parse(readFileSync(join(dir, LOCK_FILE), 'utf8'))
68
+ assert.deepEqual(
69
+ lock.modules.map((module: { name: string; source: string }) => [module.name, module.source]),
70
+ [
71
+ ['acryl-router', 'plugins/router'],
72
+ ['notes', 'plugins/notes'],
73
+ ],
74
+ )
75
+ assert.deepEqual(verifyApp(dir), { ok: true, problems: [], checked: 3 })
76
+ assert.deepEqual(captureApp(dir).addedRows, [])
77
+ assert.equal(readFileSync(join(dir, 'blend.yaml'), 'utf8'), yaml)
78
+ })
79
+
80
+ test('verify names the manifest and each plugin folder changed after the capture', () => {
81
+ const dir = app()
82
+ plugin(dir, 'notes')
83
+ captureApp(dir)
84
+ writeFileSync(
85
+ join(dir, 'blend.yaml'),
86
+ `${readFileSync(join(dir, 'blend.yaml'), 'utf8')}# edited\n`,
87
+ )
88
+ writeFileSync(
89
+ join(dir, 'plugins', 'notes', 'index.ts'),
90
+ 'export const name = "notes"\n// edited\n',
91
+ )
92
+ const result = verifyApp(dir)
93
+ assert.equal(result.ok, false)
94
+ assert.match(result.problems.join('\n'), /blend\.yaml changed since the lock/)
95
+ assert.match(result.problems.join('\n'), /notes: plugins\/notes differs from the locked digest/)
96
+ })
97
+
98
+ test('verify refuses a lock that places a plugin outside the app', () => {
99
+ const dir = app()
100
+ captureApp(dir)
101
+ const lock = JSON.parse(readFileSync(join(dir, LOCK_FILE), 'utf8'))
102
+ lock.modules[0].source = '../elsewhere'
103
+ writeFileSync(join(dir, LOCK_FILE), JSON.stringify(lock))
104
+ assert.match(verifyApp(dir).problems.join('\n'), /not a plugin folder of the app/)
105
+ })
106
+
107
+ test('apply brings a snapshot into an app: its rows and folders come in, and applying an older one leaves the newer folder in place but off', () => {
108
+ // An older version (no notes) and a newer one (notes, with its row).
109
+ const older = app()
110
+ captureApp(older)
111
+ const newer = app()
112
+ plugin(newer, 'notes', '// the newer one\n')
113
+ captureApp(newer)
114
+
115
+ const target = app('shop')
116
+ captureApp(target)
117
+ const forward = applySnapshot(newer, target)
118
+ assert.equal(forward.ok, true, forward.problems.join('\n'))
119
+ assert.deepEqual(
120
+ forward.modules.map((module) => [module.name, module.status]),
121
+ [
122
+ ['acryl-router', 'unchanged'],
123
+ ['notes', 'added'],
124
+ ],
125
+ )
126
+ assert.equal(forward.manifestChanged, true)
127
+ assert.match(readFileSync(join(target, 'blend.yaml'), 'utf8'), /id: notes/)
128
+ // The rows come in; the app stays the app it is.
129
+ assert.match(readFileSync(join(target, 'blend.yaml'), 'utf8'), /id: acme\.shop, name: shop/)
130
+ assert.match(readFileSync(join(target, 'plugins', 'notes', 'index.ts'), 'utf8'), /the newer one/)
131
+ assert.equal(verifyApp(target).ok, true)
132
+
133
+ const back = applySnapshot(older, target)
134
+ assert.equal(back.ok, true, back.problems.join('\n'))
135
+ const restored = readFileSync(join(target, 'blend.yaml'), 'utf8')
136
+ assert.doesNotMatch(restored, /id: notes/)
137
+ // The folder is somebody's work: kept and reported, and switched off, because the extensions row starts every folder without a row.
138
+ assert.deepEqual(back.extra, ['notes'])
139
+ assert.match(restored, /off:\n\s+- notes/)
140
+ assert.equal(existsSync(join(target, 'plugins', 'notes', 'index.ts')), true)
141
+
142
+ // Applying the same snapshot twice is harmless.
143
+ const again = applySnapshot(newer, target)
144
+ assert.equal(again.ok, true)
145
+ assert.deepEqual(
146
+ again.modules.map((module) => module.status),
147
+ ['unchanged', 'unchanged'],
148
+ )
149
+ })
150
+
151
+ test('apply refuses the whole snapshot when a folder in the app differs from the locked one, and writes nothing', () => {
152
+ const snapshot = app()
153
+ plugin(snapshot, 'notes', '// theirs\n')
154
+ captureApp(snapshot)
155
+ const target = app()
156
+ plugin(target, 'notes', '// mine\n')
157
+ const before = readFileSync(join(target, 'blend.yaml'), 'utf8')
158
+ const result = applySnapshot(snapshot, target)
159
+ assert.equal(result.ok, false)
160
+ assert.match(
161
+ result.problems.join('\n'),
162
+ /notes: plugins\/notes in the app differs from the snapshot's/,
163
+ )
164
+ assert.equal(readFileSync(join(target, 'blend.yaml'), 'utf8'), before)
165
+ assert.match(readFileSync(join(target, 'plugins', 'notes', 'index.ts'), 'utf8'), /mine/)
166
+ })
167
+
168
+ test('apply refuses a snapshot that no longer matches its own lock', () => {
169
+ const snapshot = app()
170
+ plugin(snapshot, 'notes')
171
+ captureApp(snapshot)
172
+ const copy = mkdtempSync(join(tmpdir(), 'snapshot-copy-'))
173
+ dirs.push(copy)
174
+ cpSync(snapshot, copy, { recursive: true })
175
+ writeFileSync(
176
+ join(copy, 'plugins', 'notes', 'index.ts'),
177
+ 'export const name = "notes"\n// tampered\n',
178
+ )
179
+ const target = app()
180
+ const result = applySnapshot(copy, target)
181
+ assert.equal(result.ok, false)
182
+ assert.match(result.problems.join('\n'), /differs from the locked digest/)
183
+ assert.equal(existsSync(join(target, 'plugins', 'notes')), false)
184
+ })
@@ -0,0 +1,123 @@
1
+ import assert from 'node:assert/strict'
2
+ import {
3
+ cpSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ mkdtempSync,
7
+ readFileSync,
8
+ rmSync,
9
+ writeFileSync,
10
+ } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+ import { afterEach, test } from 'node:test'
14
+ import { blueprintsIn, loadManifest } from '../index.ts'
15
+ import { runUpgrade } from '../upgrade-cli.ts'
16
+
17
+ const dirs: string[] = []
18
+ afterEach(() => {
19
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
20
+ })
21
+
22
+ const blueprint = (version: string, extra: string) => `apiVersion: blends.acryl.dev/v1alpha1
23
+ kind: Blueprint
24
+ metadata: { id: acme.shop, name: Shop, version: ${version} }
25
+ spec:
26
+ runtime: cordis
27
+ rows:
28
+ - id: http
29
+ name: http
30
+ ${extra}`
31
+
32
+ test('npm run upgrade plans, refuses an unsafe plan, and with --apply moves the lineage and installs the new Blueprint', () => {
33
+ const app = mkdtempSync(join(tmpdir(), 'upgrade-cli-'))
34
+ dirs.push(app)
35
+ mkdirSync(join(app, 'blueprints'))
36
+ writeFileSync(join(app, 'blueprints', 'acme.shop.yaml'), blueprint('1.0.0', ''))
37
+ writeFileSync(
38
+ join(app, 'blend.yaml'),
39
+ `apiVersion: blends.acryl.dev/v1alpha1
40
+ kind: Blend
41
+ metadata: { id: me.shop, name: shop, version: 0.1.0 }
42
+ spec:
43
+ runtime: cordis
44
+ lineage: { blueprint: acme.shop, blueprintVersion: 1.0.0 }
45
+ overrides:
46
+ - id: http
47
+ disabled: true
48
+ `,
49
+ )
50
+ writeFileSync(
51
+ join(app, 'v1.1.yaml'),
52
+ blueprint('1.1.0', ' - id: metrics\n name: metrics\n'),
53
+ )
54
+ writeFileSync(
55
+ join(app, 'v2.yaml'),
56
+ blueprint('2.0.0', '').replace(
57
+ ' - id: http\n name: http\n',
58
+ ' - id: other\n name: other\n',
59
+ ),
60
+ )
61
+ const output: string[] = []
62
+ const say = (text: string) => void output.push(text)
63
+
64
+ assert.equal(runUpgrade([], app, say), 2)
65
+ assert.equal(
66
+ runUpgrade(
67
+ [
68
+ '--from',
69
+ join(app, 'blueprints', 'acme.shop.yaml'),
70
+ '--to',
71
+ join(app, 'v2.yaml'),
72
+ '--apply',
73
+ ],
74
+ app,
75
+ say,
76
+ ),
77
+ 1,
78
+ )
79
+ assert.match(
80
+ output.join('\n'),
81
+ /this Blend would break:[\s\S]*override-unknown-id|spec\.overrides\[0\]\.id/,
82
+ )
83
+ assert.match(readFileSync(join(app, 'blend.yaml'), 'utf8'), /blueprintVersion: 1\.0\.0/)
84
+
85
+ output.length = 0
86
+ assert.equal(
87
+ runUpgrade(
88
+ ['--from', join(app, 'blueprints', 'acme.shop.yaml'), '--to', join(app, 'v1.1.yaml')],
89
+ app,
90
+ say,
91
+ ),
92
+ 0,
93
+ )
94
+ assert.match(readFileSync(join(app, 'blend.yaml'), 'utf8'), /blueprintVersion: 1\.0\.0/)
95
+
96
+ assert.equal(
97
+ runUpgrade(
98
+ [
99
+ '--from',
100
+ join(app, 'blueprints', 'acme.shop.yaml'),
101
+ '--to',
102
+ join(app, 'v1.1.yaml'),
103
+ '--apply',
104
+ ],
105
+ app,
106
+ say,
107
+ ),
108
+ 0,
109
+ )
110
+ assert.match(readFileSync(join(app, 'blend.yaml'), 'utf8'), /blueprintVersion: 1\.1\.0/)
111
+ assert.ok(existsSync(join(app, 'blueprints', 'acme.shop.yaml')))
112
+ const resolved = loadManifest(join(app, 'blend.yaml'), {
113
+ getBlueprint: blueprintsIn(join(app, 'blueprints')),
114
+ })
115
+ assert.deepEqual(
116
+ resolved.plugins.map((row) => [row.id, row.disabled ?? false]),
117
+ [
118
+ ['http', true],
119
+ ['metrics', false],
120
+ ],
121
+ )
122
+ cpSync(join(app, 'blend.yaml'), join(app, 'copy.yaml'))
123
+ })
@@ -0,0 +1,158 @@
1
+ import assert from 'node:assert/strict'
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { afterEach, test } from 'node:test'
6
+ import { blueprintsIn, loadManifest } from '../index.ts'
7
+ import { applyUpgrade, describePlan, planUpgrade } from '../upgrade.ts'
8
+
9
+ const dirs: string[] = []
10
+ afterEach(() => {
11
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
12
+ })
13
+
14
+ const blueprint = (version: string, rows: string) => `apiVersion: blends.acryl.dev/v1alpha1
15
+ kind: Blueprint
16
+ metadata: { id: acme.shop, name: Shop, version: ${version} }
17
+ spec:
18
+ runtime: cordis
19
+ rows:
20
+ ${rows}`
21
+
22
+ const V1_ROWS = ` - id: http
23
+ name: http
24
+ - id: routes
25
+ name: routes
26
+ config: { title: base }
27
+ - id: server
28
+ name: server
29
+ config: { port: 3000 }
30
+ `
31
+
32
+ const BLEND = `# my shop: a Blend of acme.shop
33
+ apiVersion: blends.acryl.dev/v1alpha1
34
+ kind: Blend
35
+ metadata: { id: me.my-shop, name: my-shop, version: 0.1.0 }
36
+ spec:
37
+ runtime: cordis
38
+ lineage: { blueprint: acme.shop, blueprintVersion: 1.0.0 } # moves on upgrade
39
+ overrides:
40
+ - id: server
41
+ config: { port: 8080 }
42
+ - id: routes
43
+ disabled: true
44
+ rows:
45
+ - id: cache
46
+ name: cache
47
+ `
48
+
49
+ function setup(newVersion: string, newRows: string) {
50
+ const dir = mkdtempSync(join(tmpdir(), 'upgrade-test-'))
51
+ dirs.push(dir)
52
+ writeFileSync(join(dir, 'v1.yaml'), blueprint('1.0.0', V1_ROWS))
53
+ writeFileSync(join(dir, 'v2.yaml'), blueprint(newVersion, newRows))
54
+ writeFileSync(join(dir, 'blend.yaml'), BLEND)
55
+ return {
56
+ blendFile: join(dir, 'blend.yaml'),
57
+ oldBlueprint: join(dir, 'v1.yaml'),
58
+ newBlueprint: join(dir, 'v2.yaml'),
59
+ dir,
60
+ }
61
+ }
62
+
63
+ test('a safe upgrade: the plan says what the Blueprint changed, what the app would do differently, and what the overrides hide', () => {
64
+ const files = setup(
65
+ '1.1.0',
66
+ ` - id: http
67
+ name: http
68
+ - id: metrics
69
+ name: metrics
70
+ - id: routes
71
+ name: routes
72
+ config: { title: updated }
73
+ - id: server
74
+ name: server
75
+ config: { port: 4000 }
76
+ `,
77
+ )
78
+ const plan = planUpgrade(files)
79
+ assert.deepEqual(plan.blueprintChanges, [
80
+ { id: 'metrics', change: 'added' },
81
+ { id: 'routes', change: 'changed', fields: ['config'] },
82
+ { id: 'server', change: 'changed', fields: ['config'] },
83
+ ])
84
+ // The Blend sets port itself, so the Blueprint's new port changes nothing here.
85
+ assert.deepEqual(plan.shadowed, [{ id: 'server', keys: ['port'] }])
86
+ assert.deepEqual(plan.appChanges, [
87
+ { id: 'metrics', change: 'added' },
88
+ { id: 'routes', change: 'changed', fields: ['config'] },
89
+ ])
90
+ assert.deepEqual([plan.safe, plan.conflicts, plan.from, plan.to], [true, [], '1.0.0', '1.1.0'])
91
+ assert.match(
92
+ describePlan(plan),
93
+ /acme\.shop: 1\.0\.0 -> 1\.1\.0[\s\S]*your app would change:[\s\S]*safe to apply/,
94
+ )
95
+ })
96
+
97
+ test('an upgrade that removes a row the Blend overrides, or adds one the Blend already has, is not safe and changes nothing', () => {
98
+ const removed = planUpgrade(
99
+ setup(
100
+ '2.0.0',
101
+ V1_ROWS.replace(/ {4}- id: routes\n {6}name: routes\n {6}config: \{ title: base \}\n/, ''),
102
+ ),
103
+ )
104
+ assert.equal(removed.safe, false)
105
+ assert.deepEqual(
106
+ removed.conflicts.map((c) => `${c.code} ${c.path}`),
107
+ ['override-unknown-id spec.overrides[1].id'],
108
+ )
109
+ assert.deepEqual(removed.appChanges, [])
110
+ assert.match(describePlan(removed), /this Blend would break:[\s\S]*NOT safe/)
111
+
112
+ const collides = planUpgrade(setup('1.2.0', `${V1_ROWS} - id: cache\n name: cache\n`))
113
+ assert.deepEqual(
114
+ collides.conflicts.map((c) => `${c.code} ${c.path}`),
115
+ ['insert-id-collision spec.rows[0].id'],
116
+ )
117
+ const files = setup('1.2.0', `${V1_ROWS} - id: cache\n name: cache\n`)
118
+ assert.throws(() => applyUpgrade(files.blendFile, planUpgrade(files)), /conflict/)
119
+ assert.equal(readFileSync(files.blendFile, 'utf8'), BLEND)
120
+ })
121
+
122
+ test('applying a safe plan moves only the lineage version, keeps the comments, and the Blend resolves over the new Blueprint', () => {
123
+ const files = setup('1.1.0', `${V1_ROWS} - id: metrics\n name: metrics\n`)
124
+ const plan = planUpgrade(files)
125
+ applyUpgrade(files.blendFile, plan)
126
+ const after = readFileSync(files.blendFile, 'utf8')
127
+ assert.equal(after, BLEND.replace('blueprintVersion: 1.0.0', 'blueprintVersion: 1.1.0'))
128
+ assert.match(after, /# my shop: a Blend of acme\.shop/)
129
+ assert.throws(
130
+ () => applyUpgrade(files.blendFile, plan),
131
+ /the Blend says 1\.1\.0 but the plan was made from 1\.0\.0/,
132
+ )
133
+ // The Blend now resolves over the new Blueprint, found by id.
134
+ writeFileSync(join(files.dir, 'acme.shop.yaml'), readFileSync(files.newBlueprint, 'utf8'))
135
+ const resolved = loadManifest(files.blendFile, { getBlueprint: blueprintsIn(files.dir) })
136
+ assert.deepEqual(
137
+ resolved.plugins.map((row) => row.id),
138
+ ['http', 'routes', 'server', 'metrics', 'cache'],
139
+ )
140
+ })
141
+
142
+ test('input that is not an upgrade is refused with a reason: a Blueprint, the wrong Blueprint, the wrong old version', () => {
143
+ const files = setup('1.1.0', V1_ROWS)
144
+ assert.throws(
145
+ () => planUpgrade({ ...files, blendFile: files.oldBlueprint }),
146
+ /is a Blueprint; an upgrade applies to a Blend/,
147
+ )
148
+ writeFileSync(files.newBlueprint, blueprint('1.1.0', V1_ROWS).replace('acme.shop', 'acme.other'))
149
+ assert.throws(
150
+ () => planUpgrade(files),
151
+ /newBlueprint is 'acme\.other' but the Blend is made from 'acme\.shop'/,
152
+ )
153
+ writeFileSync(files.oldBlueprint, blueprint('0.9.0', V1_ROWS))
154
+ assert.throws(
155
+ () => planUpgrade({ ...files, newBlueprint: files.oldBlueprint }),
156
+ /oldBlueprint is version 0\.9\.0 but the Blend's lineage says 1\.0\.0/,
157
+ )
158
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
5
+ "module": "NodeNext",
6
+ "moduleResolution": "NodeNext",
7
+ "allowImportingTsExtensions": true,
8
+ "erasableSyntaxOnly": true,
9
+ "rootDir": ".",
10
+ "outDir": "lib",
11
+ "declaration": true,
12
+ "declarationDir": "lib/types",
13
+ "esModuleInterop": true,
14
+ "strict": true,
15
+ "noImplicitOverride": true,
16
+ "verbatimModuleSyntax": true,
17
+ "skipLibCheck": true,
18
+ "types": ["node"]
19
+ },
20
+ "include": ["*.ts"]
21
+ }
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { defineConfig } from 'tsdown'
3
+
4
+ /** The package's importable files, exactly as `plugin.json`'s `entries` names them (the copy path uses the same table). */
5
+ const { entries } = JSON.parse(readFileSync(new URL('./plugin.json', import.meta.url), 'utf8')) as {
6
+ entries: Record<string, string>
7
+ }
8
+ const entry = Object.fromEntries(
9
+ Object.entries(entries).map(([, file]) => [file.replace(/.ts$/, ''), file]),
10
+ )
11
+
12
+ export default defineConfig({
13
+ name: '@acryldev/manifest',
14
+ entry,
15
+ outDir: 'lib',
16
+ format: 'esm',
17
+ platform: 'node',
18
+ target: 'es2024',
19
+ fixedExtension: false,
20
+ dts: false,
21
+ clean: true,
22
+ sourcemap: true,
23
+ })
package/upgrade-cli.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `npm run upgrade -- --from <old blueprint file> --to <new blueprint file> [--apply]`
3
+ *
4
+ * Plans the upgrade of this app's Blend to a newer version of its Blueprint and prints the plan (exit 1 when it is not safe). With
5
+ * `--apply` and a safe plan, it moves `spec.lineage.blueprintVersion` and puts the new Blueprint in `blueprints/<id>.yaml`, where the
6
+ * app finds it. Nothing else is changed; run `npm run lock` afterwards to record the new Blueprint's digest.
7
+ */
8
+ import { copyFileSync, mkdirSync } from 'node:fs'
9
+ import { join, resolve } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { parseArgs } from 'node:util'
12
+ import { blueprintsIn, ManifestError } from './index.ts'
13
+ import { applyUpgrade, describePlan, planUpgrade } from './upgrade.ts'
14
+
15
+ export function runUpgrade(
16
+ argv: readonly string[],
17
+ appRoot: string,
18
+ out: (text: string) => void = console.log,
19
+ ): number {
20
+ let args: ReturnType<typeof parse>
21
+ try {
22
+ args = parse(argv)
23
+ } catch (error) {
24
+ out(`error: ${(error as Error).message}`)
25
+ return 2
26
+ }
27
+ const { from, to, apply } = args.values
28
+ if (!from || !to) {
29
+ out('usage: npm run upgrade -- --from <old blueprint file> --to <new blueprint file> [--apply]')
30
+ return 2
31
+ }
32
+ const blueprints = join(appRoot, 'blueprints')
33
+ try {
34
+ const blendFile = join(appRoot, 'blend.yaml')
35
+ const plan = planUpgrade({
36
+ blendFile,
37
+ oldBlueprint: resolve(from),
38
+ newBlueprint: resolve(to),
39
+ getBlueprint: blueprintsIn(blueprints),
40
+ })
41
+ out(describePlan(plan))
42
+ if (!plan.safe) return 1
43
+ if (apply) {
44
+ applyUpgrade(blendFile, plan)
45
+ mkdirSync(blueprints, { recursive: true })
46
+ copyFileSync(resolve(to), join(blueprints, `${plan.blueprint}.yaml`))
47
+ out(`applied: lineage is now ${plan.blueprint} ${plan.to}; run npm run lock to record it`)
48
+ }
49
+ return 0
50
+ } catch (error) {
51
+ out(
52
+ `error: ${error instanceof ManifestError ? error.message : error instanceof Error ? error.message : String(error)}`,
53
+ )
54
+ return 1
55
+ }
56
+ }
57
+
58
+ const parse = (argv: readonly string[]) =>
59
+ parseArgs({
60
+ args: [...argv],
61
+ strict: true,
62
+ options: { from: { type: 'string' }, to: { type: 'string' }, apply: { type: 'boolean' } },
63
+ })
64
+
65
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
66
+ process.exitCode = runUpgrade(
67
+ process.argv.slice(2),
68
+ resolve(fileURLToPath(new URL('../..', import.meta.url))),
69
+ )
70
+ }
package/upgrade.ts ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Upgrading a Blend: what happens when its Blueprint moves to a new version. The plan and its application are ACRYL's own
3
+ * (`@acryldev/blends-core`); this file only reads the Blend and the two Blueprint files and keeps the terminal output.
4
+ *
5
+ * An upgrade is a *plan* before it is an action: what the Blueprint changed, what the Blend can no longer do on it (conflicts),
6
+ * which changes its overrides hide, and how the rows the app mounts would differ. Only a plan with no conflicts is `safe`.
7
+ * Applying it moves `spec.lineage.blueprintVersion` and nothing else, keeping the file's comments.
8
+ */
9
+ import { readFileSync, writeFileSync } from 'node:fs'
10
+ import {
11
+ applyUpgrade as applyToSource,
12
+ type BlendDocument,
13
+ type Diagnostic,
14
+ parseDefinition,
15
+ planUpgrade as planFromDocuments,
16
+ type RowChange,
17
+ type UpgradePlan,
18
+ } from '@acryldev/blends-core'
19
+ import type { LoadOptions } from './index.ts'
20
+
21
+ export type { RowChange, UpgradePlan }
22
+
23
+ const refusal = (diagnostics: readonly Diagnostic[], file?: string) =>
24
+ new Error(
25
+ `${file ? `${file}:\n` : ''}${diagnostics.map((d) => `${d.path}: ${d.message}`).join('\n')}`,
26
+ )
27
+
28
+ function read(file: string): BlendDocument {
29
+ const { document, diagnostics } = parseDefinition(readFileSync(file, 'utf8'))
30
+ if (diagnostics.length > 0) throw refusal(diagnostics, file)
31
+ return document as BlendDocument
32
+ }
33
+
34
+ /**
35
+ * Plan the upgrade of the Blend in `blendFile` from the Blueprint file it was made from (`oldBlueprint`) to a newer one
36
+ * (`newBlueprint`). `getBlueprint` finds the parents of either Blueprint, if they have any. Throws for input that cannot be read
37
+ * as a plan: a Blueprint file with the wrong id, an old Blueprint whose version is not the Blend's lineage version, or a document
38
+ * that is not a Blend. Everything the upgrade would break is in the plan.
39
+ */
40
+ export function planUpgrade(options: {
41
+ blendFile: string
42
+ oldBlueprint: string
43
+ newBlueprint: string
44
+ getBlueprint?: LoadOptions['getBlueprint']
45
+ values?: LoadOptions['values']
46
+ }): UpgradePlan {
47
+ const getDefinition = options.getBlueprint
48
+ ? (id: string) => {
49
+ const file = options.getBlueprint?.(id)
50
+ return file === undefined ? undefined : read(file)
51
+ }
52
+ : undefined
53
+ const { plan, diagnostics } = planFromDocuments({
54
+ blend: read(options.blendFile),
55
+ oldBlueprint: read(options.oldBlueprint),
56
+ newBlueprint: read(options.newBlueprint),
57
+ ...(getDefinition ? { getDefinition } : {}),
58
+ ...(options.values ? { parameters: options.values } : {}),
59
+ })
60
+ if (plan === null) throw refusal(diagnostics)
61
+ return plan
62
+ }
63
+
64
+ /** Move the Blend's lineage to the plan's new version, keeping the file's comments and layout. Refuses an unsafe plan. */
65
+ export function applyUpgrade(blendFile: string, plan: UpgradePlan): void {
66
+ const { source, diagnostics } = applyToSource(readFileSync(blendFile, 'utf8'), plan)
67
+ if (source === null) throw refusal(diagnostics)
68
+ writeFileSync(blendFile, source)
69
+ }
70
+
71
+ /** A short, readable account of a plan, for a terminal. */
72
+ export function describePlan(plan: UpgradePlan): string {
73
+ const line = (change: RowChange) =>
74
+ ` ${change.change.padEnd(7)} ${change.id}${change.fields ? ` (${change.fields.join(', ')})` : ''}`
75
+ const lines = [`${plan.blueprint}: ${plan.from} -> ${plan.to}`]
76
+ lines.push(
77
+ plan.blueprintChanges.length ? 'the Blueprint changed:' : 'the Blueprint has no row changes',
78
+ ...plan.blueprintChanges.map(line),
79
+ )
80
+ if (plan.shadowed.length)
81
+ lines.push(
82
+ 'your overrides hide some of that:',
83
+ ...plan.shadowed.map((entry) => ` ${entry.id}: ${entry.keys.join(', ')}`),
84
+ )
85
+ if (plan.conflicts.length)
86
+ lines.push(
87
+ 'this Blend would break:',
88
+ ...plan.conflicts.map((conflict) => ` ${conflict.path}: ${conflict.message}`),
89
+ )
90
+ else
91
+ lines.push(
92
+ plan.appChanges.length ? 'your app would change:' : 'your app would not change',
93
+ ...plan.appChanges.map(line),
94
+ )
95
+ lines.push(plan.safe ? 'safe to apply' : 'NOT safe: resolve the conflicts first')
96
+ return lines.join('\n')
97
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.