@otwdesign/cli 0.0.0-stage → 1.0.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.
package/src/update.ts ADDED
@@ -0,0 +1,485 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { access, readFile, writeFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { promisify } from 'node:util'
5
+ import type { Brand } from '@otwdesign/core'
6
+ import semver from 'semver'
7
+
8
+ const run = promisify(execFile)
9
+
10
+ /** The CMS's own packages, released together under one version. `@otwdesign/next` sets it. */
11
+ export const CORE_PACKAGES = [
12
+ '@otwdesign/next',
13
+ '@otwdesign/cli',
14
+ '@otwdesign/core',
15
+ '@otwdesign/sdk',
16
+ '@otwdesign/admin-ui',
17
+ '@otwdesign/testing',
18
+ ] as const
19
+ const CORE_VERSION_FROM = '@otwdesign/next'
20
+ /** Plugins declare the core they work with as a peer dependency on one of these. */
21
+ const COMPATIBILITY_PEERS = ['@otwdesign/sdk', '@otwdesign/next']
22
+
23
+ /** The parts of npm's package metadata this reads: each version's peer dependencies. */
24
+ export interface Packument {
25
+ name: string
26
+ versions: Record<string, { version: string; peerDependencies?: Record<string, string> }>
27
+ }
28
+
29
+ /** A package npm couldn't look up, with its reason (not found, no access, offline). */
30
+ export interface Unreachable {
31
+ name: string
32
+ error: string
33
+ }
34
+
35
+ export type FetchVersions = (name: string, installed: string) => Promise<Packument>
36
+
37
+ type Runner = (
38
+ file: string,
39
+ args: string[],
40
+ options: { cwd: string },
41
+ ) => Promise<{ stdout: string }>
42
+
43
+ type ViewEntry = Packument['versions'][string]
44
+
45
+ function npmError(error: unknown): string {
46
+ const stdout = (error as { stdout?: string }).stdout ?? ''
47
+ try {
48
+ const summary = (JSON.parse(stdout) as { error?: { summary?: string } }).error?.summary
49
+ if (summary) return summary
50
+ } catch {
51
+ // Not npm's JSON: fall back to the process error.
52
+ }
53
+ return error instanceof Error ? (error.message.split('\n')[0] ?? error.message) : String(error)
54
+ }
55
+
56
+ /**
57
+ * Asks npm from the site's directory, so `.npmrc` applies: the registry, scoped registries for
58
+ * private and paid plugins, and their tokens. npm ships with Node, and pnpm and Bun read the same
59
+ * file.
60
+ */
61
+ export function npmView(root: string, runner: Runner = run): FetchVersions {
62
+ return async (name, installed) => {
63
+ // Every stable version, or from a prerelease on, to include its later prereleases. Not `*`:
64
+ // npm resolves that to the latest version alone.
65
+ const range = semver.prerelease(installed) ? `>=${installed}` : '>=0.0.0'
66
+ let stdout: string
67
+ try {
68
+ ;({ stdout } = await runner(
69
+ 'npm',
70
+ ['view', `${name}@${range}`, 'version', 'peerDependencies', '--json'],
71
+ { cwd: root },
72
+ ))
73
+ } catch (error) {
74
+ throw new Error(npmError(error), { cause: error })
75
+ }
76
+ if (!stdout.trim()) return { name, versions: {} }
77
+ // One matching version comes back alone, several as a list; a version without peer
78
+ // dependencies comes back as just its version string.
79
+ const parsed = JSON.parse(stdout) as ViewEntry | string | (ViewEntry | string)[]
80
+ const entries = (Array.isArray(parsed) ? parsed : [parsed]).map((entry) =>
81
+ typeof entry === 'string' ? { version: entry } : entry,
82
+ )
83
+ return { name, versions: Object.fromEntries(entries.map((entry) => [entry.version, entry])) }
84
+ }
85
+ }
86
+
87
+ export interface SitePackages {
88
+ /** Name to the spec in package.json, such as `^0.1.0`. */
89
+ specs: Record<string, string>
90
+ /** Name to the version installed in node_modules. */
91
+ installed: Record<string, string>
92
+ /** Name to the installed version's peer dependencies, read from node_modules. */
93
+ peers: Record<string, Record<string, string>>
94
+ /** Plugin package names, from cms.config.json. */
95
+ plugins: readonly string[]
96
+ }
97
+
98
+ export interface PluginReport {
99
+ name: string
100
+ from: string
101
+ /** `null` when it stays on the installed version. */
102
+ to: string | null
103
+ /** The newest version published, whether or not it can be used. */
104
+ latest: string | null
105
+ /** Whether the version it ends on declares support for the target core. */
106
+ compatible: 'yes' | 'unknown' | 'no'
107
+ /** Why it isn't going to `latest`, when it isn't. */
108
+ note?: string
109
+ }
110
+
111
+ export interface UpdatePlan {
112
+ core: { from: string; to: string } | null
113
+ /** Every package.json change, core and plugins. */
114
+ changes: { name: string; from: string; to: string }[]
115
+ /** The plugins this update looked at. */
116
+ plugins: PluginReport[]
117
+ /** Reasons the update would leave the site worse off; `--force` ignores them. */
118
+ blockers: string[]
119
+ /** Worth knowing, but no reason to stop. */
120
+ warnings: string[]
121
+ /** Packages that can't be updated from a registry, such as `workspace:` links. */
122
+ linked: string[]
123
+ }
124
+
125
+ export interface UpdateScope {
126
+ /** Allow a new major version of core. */
127
+ major?: boolean
128
+ /** Only these packages (from `resolveTargets`). Core packages move together. */
129
+ only?: readonly string[]
130
+ /** Leave core where it is. */
131
+ pluginsOnly?: boolean
132
+ /** Patch releases only (`~` of what's installed), for automatic updates. */
133
+ patchOnly?: boolean
134
+ }
135
+
136
+ const INCLUDE_PRERELEASE = { includePrerelease: true }
137
+
138
+ /** Installed from a workspace, a folder or git: the registry has nothing to offer for it. */
139
+ export function isLinked(spec: string): boolean {
140
+ return /^(workspace|file|link|git\+|github):/.test(spec) || spec.includes('/')
141
+ }
142
+
143
+ export function isCore(name: string): boolean {
144
+ return (CORE_PACKAGES as readonly string[]).includes(name)
145
+ }
146
+
147
+ /** Stable releases, or prereleases too when the installed version is one. */
148
+ function candidates(packument: Packument, installed: string): string[] {
149
+ const allowPrerelease = semver.prerelease(installed) !== null
150
+ return Object.keys(packument.versions).filter(
151
+ (version) => semver.valid(version) && (allowPrerelease || !semver.prerelease(version)),
152
+ )
153
+ }
154
+
155
+ function coreSupport(
156
+ peers: Readonly<Record<string, string>>,
157
+ core: string,
158
+ ): PluginReport['compatible'] {
159
+ const range = COMPATIBILITY_PEERS.map((name) => peers[name]).find(Boolean)
160
+ if (!range) return 'unknown'
161
+ return semver.satisfies(core, range, INCLUDE_PRERELEASE) ? 'yes' : 'no'
162
+ }
163
+
164
+ /** `commerce` for `@otwdesign/plugin-commerce`, `forum` for `@acme/forum`, `core` for the CMS's own packages. */
165
+ export function resolveTargets(site: SitePackages, names: readonly string[]): string[] {
166
+ return names.map((name) => {
167
+ if (name === 'core') return CORE_VERSION_FROM
168
+ if (site.plugins.includes(name) || (isCore(name) && name in site.specs)) return name
169
+ const firstParty = `@otwdesign/plugin-${name}`
170
+ if (site.plugins.includes(firstParty)) return firstParty
171
+ // `forum` for `@acme/forum`, when only one installed plugin is called that.
172
+ const unscoped = site.plugins.filter((plugin) => plugin.split('/').at(-1) === name)
173
+ if (unscoped.length === 1) return unscoped[0]!
174
+ if (unscoped.length > 1) {
175
+ throw new Error(`${name} could be ${unscoped.join(' or ')}; use the full package name.`)
176
+ }
177
+ throw new Error(
178
+ `${name} is not an installed plugin or a CMS package. Installed plugins: ${site.plugins.join(', ') || 'none'}.`,
179
+ )
180
+ })
181
+ }
182
+
183
+ function planCore(
184
+ site: SitePackages,
185
+ packuments: Readonly<Record<string, Packument | Unreachable>>,
186
+ { major = false, patchOnly = false }: UpdateScope,
187
+ ): { core: UpdatePlan['core']; changes: UpdatePlan['changes']; blockers: string[] } {
188
+ const from = site.installed[CORE_VERSION_FROM]!
189
+ const doc = packuments[CORE_VERSION_FROM]
190
+ if (!doc || 'error' in doc) {
191
+ throw new Error(`Can't look up ${CORE_VERSION_FROM}: ${doc?.error ?? 'not fetched'}`)
192
+ }
193
+ const range = patchOnly ? `~${from}` : major ? '*' : `^${from}`
194
+ const target = semver.maxSatisfying(candidates(doc, from), range)
195
+ if (!target || !semver.gt(target, from)) return { core: null, changes: [], blockers: [] }
196
+ const changes: UpdatePlan['changes'] = []
197
+ const blockers: string[] = []
198
+ for (const name of CORE_PACKAGES.filter((n) => n in site.specs && !isLinked(site.specs[n]!))) {
199
+ const published = packuments[name]
200
+ if (!published || 'error' in published || !published.versions[target]) {
201
+ blockers.push(`${name} ${target} is not published, and core packages update together.`)
202
+ } else {
203
+ changes.push({ name, from: site.installed[name] ?? site.specs[name]!, to: target })
204
+ }
205
+ }
206
+ return { core: { from, to: target }, changes, blockers }
207
+ }
208
+
209
+ /**
210
+ * Picks core (the newest within the installed version's caret range, or any with `major`) and
211
+ * the newest version of each plugin that supports it. Plugins that say nothing about core stay
212
+ * within their own caret range, flagged unknown, as WordPress shows "Compatibility: Unknown".
213
+ *
214
+ * Then it settles what plugins need from each other: a plugin's peer dependency on another
215
+ * plugin must hold for the versions chosen. When it doesn't, the plugin required is held back if
216
+ * it can be, so the plugins that need it keep working; otherwise the one requiring it is. Versions
217
+ * only ever go down while settling, back to what is installed at worst, so it always ends.
218
+ */
219
+ export function planUpdate(
220
+ site: SitePackages,
221
+ packuments: Readonly<Record<string, Packument | Unreachable>>,
222
+ scope: UpdateScope = {},
223
+ ): UpdatePlan {
224
+ const linked = Object.keys(site.specs).filter(
225
+ (name) => isLinked(site.specs[name]!) && (isCore(name) || site.plugins.includes(name)),
226
+ )
227
+ const installed = (name: string) => {
228
+ const version = site.installed[name]
229
+ if (!version)
230
+ throw new Error(`${name} is not installed; run your package manager's install first`)
231
+ return version
232
+ }
233
+ const coreFrom = installed(CORE_VERSION_FROM)
234
+ const coreInScope = scope.only ? scope.only.some(isCore) : !scope.pluginsOnly
235
+ const pluginInScope = (name: string) => (scope.only ? scope.only.includes(name) : true)
236
+
237
+ const coreMove =
238
+ coreInScope && !linked.includes(CORE_VERSION_FROM)
239
+ ? planCore(site, packuments, scope)
240
+ : { core: null, changes: [], blockers: [] }
241
+ const coreTo = coreMove.core?.to ?? coreFrom
242
+ const blockers = [...coreMove.blockers]
243
+ const warnings: string[] = []
244
+
245
+ const peersOf = (name: string, version: string): Record<string, string> => {
246
+ if (version === site.installed[name]) return site.peers[name] ?? {}
247
+ const doc = packuments[name]
248
+ return (doc && !('error' in doc) && doc.versions[version]?.peerDependencies) || {}
249
+ }
250
+
251
+ // Each plugin's usable versions, newest first; the installed one is always the last resort.
252
+ const options = new Map<string, string[]>()
253
+ const latest = new Map<string, string | null>()
254
+ for (const name of site.plugins) {
255
+ const from = installed(name)
256
+ const doc = packuments[name]
257
+ if (doc && 'error' in doc)
258
+ warnings.push(`Couldn't check ${name}: ${doc.error}. It stays at ${from}.`)
259
+ if (linked.includes(name) || !pluginInScope(name) || !doc || 'error' in doc) {
260
+ options.set(name, [from])
261
+ continue
262
+ }
263
+ const newer = candidates(doc, from)
264
+ .filter(
265
+ (version) =>
266
+ semver.gt(version, from) && (!scope.patchOnly || semver.satisfies(version, `~${from}`)),
267
+ )
268
+ .sort(semver.rcompare)
269
+ latest.set(name, newer[0] ?? null)
270
+ const usable = newer.filter((version) => {
271
+ const support = coreSupport(peersOf(name, version), coreTo)
272
+ return support === 'yes' || (support === 'unknown' && semver.satisfies(version, `^${from}`))
273
+ })
274
+ options.set(name, [...usable, from])
275
+ }
276
+
277
+ const chosen = new Map([...options].map(([name, list]) => [name, list[0]!]))
278
+ const notes = new Map<string, string>()
279
+ const unresolved = new Set<string>()
280
+ for (let changed = true; changed;) {
281
+ changed = false
282
+ for (const a of site.plugins) {
283
+ const va = chosen.get(a)!
284
+ for (const [b, range] of Object.entries(peersOf(a, va))) {
285
+ const vb = chosen.get(b)
286
+ const pair = `${a} ${b}`
287
+ if (vb === undefined || unresolved.has(pair)) continue
288
+ if (semver.satisfies(vb, range, INCLUDE_PRERELEASE)) continue
289
+ const lowerB = options
290
+ .get(b)!
291
+ .find((v) => semver.lt(v, vb) && semver.satisfies(v, range, INCLUDE_PRERELEASE))
292
+ if (lowerB) {
293
+ chosen.set(b, lowerB)
294
+ notes.set(b, `${a} ${va} needs ${b} ${range}`)
295
+ changed = true
296
+ continue
297
+ }
298
+ const lowerA = options.get(a)!.find((v) => {
299
+ const needs = peersOf(a, v)[b]
300
+ return semver.lt(v, va) && (!needs || semver.satisfies(vb, needs, INCLUDE_PRERELEASE))
301
+ })
302
+ if (lowerA) {
303
+ chosen.set(a, lowerA)
304
+ notes.set(a, `${latest.get(a) ?? va} needs ${b} ${range}, and ${b} stays at ${vb}`)
305
+ changed = true
306
+ break
307
+ }
308
+ // Even the installed versions disagree: the site is already like this.
309
+ unresolved.add(pair)
310
+ warnings.push(`${a} ${va} needs ${b} ${range}, but ${b} is ${vb}.`)
311
+ }
312
+ }
313
+ }
314
+
315
+ const plugins: PluginReport[] = []
316
+ const changes = [...coreMove.changes]
317
+ for (const name of site.plugins.filter((n) => !linked.includes(n) && pluginInScope(n))) {
318
+ const from = installed(name)
319
+ const version = chosen.get(name)!
320
+ const newest = latest.get(name) ?? null
321
+ const compatible = coreSupport(peersOf(name, version), coreTo)
322
+ let note = notes.get(name)
323
+ if (!note && newest && version !== newest) {
324
+ note =
325
+ coreSupport(peersOf(name, newest), coreTo) === 'no'
326
+ ? `${newest} needs a different core than ${coreTo}`
327
+ : `${newest} is a new major version that doesn't say which core it supports`
328
+ }
329
+ plugins.push({
330
+ name,
331
+ from,
332
+ to: version === from ? null : version,
333
+ latest: newest,
334
+ compatible,
335
+ ...(note ? { note } : {}),
336
+ })
337
+ if (version !== from) changes.push({ name, from, to: version })
338
+ if (compatible === 'no' && coreMove.core) {
339
+ blockers.push(
340
+ `${name} ${version} doesn't support core ${coreTo}, and no newer version does yet; it would be switched off.`,
341
+ )
342
+ }
343
+ }
344
+ // Out of scope, but they must still work with the new core.
345
+ if (coreMove.core) {
346
+ for (const name of site.plugins.filter((n) => !pluginInScope(n) && !linked.includes(n))) {
347
+ if (coreSupport(peersOf(name, installed(name)), coreTo) === 'no') {
348
+ blockers.push(
349
+ `${name} ${installed(name)} doesn't support core ${coreTo}; update it too, or it would be switched off.`,
350
+ )
351
+ }
352
+ }
353
+ }
354
+ return { core: coreMove.core, changes, plugins, blockers, warnings, linked }
355
+ }
356
+
357
+ interface PackageJson {
358
+ dependencies?: Record<string, string>
359
+ devDependencies?: Record<string, string>
360
+ peerDependencies?: Record<string, string>
361
+ }
362
+
363
+ /** What `planUpdate` needs from the site: specs, installed versions and the plugin list. */
364
+ export async function readSitePackages(root: string): Promise<SitePackages> {
365
+ const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8')) as PackageJson
366
+ const specs = { ...manifest.devDependencies, ...manifest.dependencies }
367
+ const { plugins } = JSON.parse(await readFile(join(root, 'cms.config.json'), 'utf8')) as {
368
+ plugins: string[]
369
+ }
370
+ const installed: Record<string, string> = {}
371
+ const peers: Record<string, Record<string, string>> = {}
372
+ for (const name of Object.keys(specs).filter((n) => isCore(n) || plugins.includes(n))) {
373
+ const file = join(root, 'node_modules', ...name.split('/'), 'package.json')
374
+ const found = await readFile(file, 'utf8').catch(() => null)
375
+ if (!found) continue
376
+ const pkg = JSON.parse(found) as PackageJson & { version: string }
377
+ installed[name] = pkg.version
378
+ peers[name] = pkg.peerDependencies ?? {}
379
+ }
380
+ return { specs, installed, peers, plugins }
381
+ }
382
+
383
+ /**
384
+ * Plans an update for the site at `root`: reads what is installed, looks up what is published
385
+ * (through npm, so `.npmrc` applies), and plans. `packages` are names as typed, resolved with
386
+ * `resolveTargets`. What `cms update` and `cms serve` both run.
387
+ */
388
+ export async function planSite(
389
+ root: string,
390
+ { packages = [], ...scope }: Omit<UpdateScope, 'only'> & { packages?: readonly string[] } = {},
391
+ fetchVersions: FetchVersions = npmView(root),
392
+ ): Promise<UpdatePlan> {
393
+ const site = await readSitePackages(root)
394
+ const only = packages.length > 0 ? resolveTargets(site, packages) : undefined
395
+ const coreInScope = only ? only.some(isCore) : !scope.pluginsOnly
396
+ const lookups = [
397
+ ...(coreInScope ? CORE_PACKAGES.filter((name) => name in site.specs) : []),
398
+ ...site.plugins.filter((name) => !only || only.includes(name)),
399
+ ].filter((name) => site.specs[name] && !isLinked(site.specs[name]))
400
+ // One plugin npm can't reach (a private registry without a token, say) doesn't stop the rest.
401
+ const packuments: Record<string, Packument | Unreachable> = Object.fromEntries(
402
+ await Promise.all(
403
+ lookups.map(async (name) => {
404
+ const found = await fetchVersions(name, site.installed[name] ?? '0.0.0').catch(
405
+ (error: unknown): Unreachable => ({
406
+ name,
407
+ error: error instanceof Error ? error.message : String(error),
408
+ }),
409
+ )
410
+ return [name, found] as const
411
+ }),
412
+ ),
413
+ )
414
+ return planUpdate(site, packuments, { ...scope, only })
415
+ }
416
+
417
+ /** Keeps the spec's style: `^1.2.0` stays a caret range, `1.2.0` stays exact. */
418
+ export function nextSpec(current: string, version: string): string {
419
+ const prefix = /^[\^~]/.exec(current)?.[0] ?? ''
420
+ return `${prefix}${version}`
421
+ }
422
+
423
+ /** Rewrites package.json in place, leaving everything else in it as it was. */
424
+ export async function writeChanges(
425
+ root: string,
426
+ changes: readonly UpdatePlan['changes'][number][],
427
+ ): Promise<void> {
428
+ const file = join(root, 'package.json')
429
+ const raw = await readFile(file, 'utf8')
430
+ const manifest = JSON.parse(raw) as PackageJson
431
+ for (const { name, to } of changes) {
432
+ for (const deps of [manifest.dependencies, manifest.devDependencies]) {
433
+ if (deps?.[name]) deps[name] = nextSpec(deps[name], to)
434
+ }
435
+ }
436
+ const indent = /^(\s+)"/m.exec(raw)?.[1] ?? ' '
437
+ await writeFile(file, `${JSON.stringify(manifest, null, indent)}\n`)
438
+ }
439
+
440
+ export type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun'
441
+
442
+ const LOCKFILES: [string, PackageManager][] = [
443
+ ['pnpm-lock.yaml', 'pnpm'],
444
+ ['bun.lock', 'bun'],
445
+ ['bun.lockb', 'bun'],
446
+ ['yarn.lock', 'yarn'],
447
+ ['package-lock.json', 'npm'],
448
+ ]
449
+
450
+ /** From the lockfile next to package.json, or the nearest one above (workspaces). */
451
+ export async function detectPackageManager(root: string): Promise<PackageManager> {
452
+ for (let dir = root; ; dir = join(dir, '..')) {
453
+ for (const [file, manager] of LOCKFILES) {
454
+ if (
455
+ await access(join(dir, file)).then(
456
+ () => true,
457
+ () => false,
458
+ )
459
+ )
460
+ return manager
461
+ }
462
+ if (join(dir, '..') === dir) return 'npm'
463
+ }
464
+ }
465
+
466
+ export async function install(root: string, manager: PackageManager): Promise<void> {
467
+ await run(manager, ['install'], { cwd: root })
468
+ }
469
+
470
+ /** `--commit`'s message, which the GitHub workflow makes the pull request's title. */
471
+ export function updateCommitMessage(brand: Brand, coreTarget: string | undefined): string {
472
+ return coreTarget ? `Update ${brand.name} to ${coreTarget}` : `Update ${brand.name} plugins`
473
+ }
474
+
475
+ /** `--commit`: the change on its own branch, for hosts that build from git. */
476
+ export async function commitUpdate(root: string, branch: string, message: string): Promise<void> {
477
+ const git = (...args: string[]) => run('git', args, { cwd: root })
478
+ const status = await git('status', '--porcelain')
479
+ if (!status.stdout.trim()) throw new Error('Nothing changed, so there is nothing to commit')
480
+ await git('checkout', '-b', branch)
481
+ // The whole repository: the lockfile may sit above the site, in a workspace. The caller made
482
+ // sure the tree was clean, so this is only the update.
483
+ await git('add', '--all')
484
+ await git('commit', '--message', message)
485
+ }