@otwdesign/cli 1.4.0 → 1.7.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@otwdesign/cli",
3
- "version": "1.4.0",
3
+ "version": "1.7.1",
4
4
  "description": "The cms command for OTW CMS sites: generate, migrate, update and serve.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "OTW SRL",
@@ -41,9 +41,9 @@
41
41
  "@types/semver": "^7.7.0",
42
42
  "semver": "^7.8.0",
43
43
  "tsx": "^4.23.15",
44
- "@otwdesign/core": "1.4.0",
45
- "@otwdesign/next": "1.4.0",
46
- "@otwdesign/sdk": "1.4.0"
44
+ "@otwdesign/core": "1.7.1",
45
+ "@otwdesign/sdk": "1.7.1",
46
+ "@otwdesign/next": "1.7.1"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@opentelemetry/api": "~1.9.0",
package/src/generate.ts CHANGED
@@ -135,6 +135,8 @@ export interface SiteLayout {
135
135
  }
136
136
 
137
137
  const SITE_MODULE = 'cms/site.generated.ts'
138
+ /** Beside `app`, where Next.js looks for it. */
139
+ const PROXY_FILE = 'proxy.ts'
138
140
  const ADMIN_MODULE = 'cms/admin.generated.ts'
139
141
 
140
142
  /** Where the generated site module lives, relative to the site's root. */
@@ -190,6 +192,8 @@ export function managedFiles(
190
192
  admin: readonly string[] = [],
191
193
  /** Whether the site has its own templates, `cms/templates.tsx`, which only its pages need. */
192
194
  templates = false,
195
+ /** The plugins whose packages have a proxy entry (`./proxy`). */
196
+ proxy: readonly string[] = [],
193
197
  ): ManagedFile[] {
194
198
  const at = (path: string) => (srcDir ? `${srcDir}/${path}` : path)
195
199
  const site = siteModulePath({ srcDir })
@@ -252,6 +256,27 @@ export function managedFiles(
252
256
  // catch-all would claim / as well, and Next.js allows only one.
253
257
  route('app/(site)/page.tsx', storefront, true),
254
258
  route('app/(site)/[...slug]/page.tsx', storefront),
259
+ // Only for a site with a plugin that has one: without, the site has no proxy, and no request
260
+ // pays for one. A site with a proxy of its own keeps it, and calls createProxy() from there.
261
+ ...(proxy.length > 0
262
+ ? [
263
+ file(
264
+ at(PROXY_FILE),
265
+ [
266
+ "import { createProxy } from '@otwdesign/next/proxy'",
267
+ // Quoted as the lines around it and as Prettier would: this file is the site's own
268
+ // to format, unlike the `.generated.ts` ones a site's Prettier ignores.
269
+ ...proxy.map((name, i) => `import proxy${i} from '${name}/proxy'`),
270
+ '',
271
+ `export const proxy = createProxy([${proxy.map((_, i) => `proxy${i}`).join(', ')}])`,
272
+ '',
273
+ "// Next.js's own files never reach a plugin's proxy.",
274
+ "export const config = { matcher: ['/((?!_next/static|_next/image).*)'] }",
275
+ ],
276
+ true,
277
+ ),
278
+ ]
279
+ : []),
255
280
  ]
256
281
  }
257
282
 
@@ -304,7 +329,8 @@ export async function generate({
304
329
  }): Promise<GenerateResult> {
305
330
  const config = await readConfig(configPath)
306
331
  const layout: SiteLayout = { srcDir: (await exists(join(root, 'src', 'app'))) ? 'src' : '' }
307
- const admin = await pluginsWithAdmin(root, config.plugins)
332
+ const admin = await pluginsWith(root, config.plugins, './admin')
333
+ const proxy = await pluginsWith(root, config.plugins, './proxy')
308
334
  const cmsDir = join(root, layout.srcDir, 'cms')
309
335
  const templates =
310
336
  (await exists(join(cmsDir, 'templates.tsx'))) || (await exists(join(cmsDir, 'templates.ts')))
@@ -322,7 +348,16 @@ export async function generate({
322
348
  for (const path of retired.replacedBy) clashing.add(path)
323
349
  }
324
350
  }
325
- for (const managed of managedFiles(config, layout, admin, templates)) {
351
+ // The proxy this wrote for a plugin that has since gone: a site with no plugin proxy has none.
352
+ if (proxy.length === 0) {
353
+ const path = layout.srcDir ? `${layout.srcDir}/${PROXY_FILE}` : PROXY_FILE
354
+ const target = join(root, ...path.split('/'))
355
+ if ((await readIfExists(target))?.startsWith(MARKER)) {
356
+ await unlink(target)
357
+ files.push({ path, status: 'removed' })
358
+ }
359
+ }
360
+ for (const managed of managedFiles(config, layout, admin, templates, proxy)) {
326
361
  if (clashing.has(managed.path)) continue
327
362
  const target = join(root, ...managed.path.split('/'))
328
363
  const existing = await readIfExists(target)
@@ -340,15 +375,20 @@ export async function generate({
340
375
  }
341
376
 
342
377
  /**
343
- * The plugins whose package exports an admin entry (`./admin`), found as Node resolves packages:
344
- * in `node_modules` here or in a folder above, where workspaces install them.
378
+ * The plugins whose package exports an entry, such as the admin's (`./admin`) or a proxy
379
+ * (`./proxy`), found as Node resolves packages: in `node_modules` here or in a folder above,
380
+ * where workspaces install them.
345
381
  */
346
- async function pluginsWithAdmin(root: string, plugins: readonly string[]): Promise<string[]> {
382
+ async function pluginsWith(
383
+ root: string,
384
+ plugins: readonly string[],
385
+ entry: './admin' | './proxy',
386
+ ): Promise<string[]> {
347
387
  const found: string[] = []
348
388
  for (const name of plugins) {
349
389
  const manifest = await packageManifest(root, name)
350
390
  const exports = manifest?.exports
351
- if (exports && typeof exports === 'object' && './admin' in exports) found.push(name)
391
+ if (exports && typeof exports === 'object' && entry in exports) found.push(name)
352
392
  }
353
393
  return found
354
394
  }
package/src/main.ts CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  commitUpdate,
12
12
  detectPackageManager,
13
13
  install,
14
+ planInstall,
15
+ planRemove,
14
16
  planSite,
15
17
  updateCommitMessage,
16
18
  writeChanges,
@@ -36,6 +38,12 @@ Commands:
36
38
  --major allow a new major version of core
37
39
  --force update even if a plugin would be switched off
38
40
  --commit put the update on a new git branch, for hosts that build from git
41
+ plugin add <package>
42
+ Add a plugin from npm, in its newest version that works with the site's CMS: to
43
+ package.json and cms.config.json. It starts inactive
44
+ plugin remove <package>
45
+ Take a plugin's package off the site. Delete its data in the admin first
46
+ --commit put the change on a new git branch, for hosts that build from git
39
47
 
40
48
  Options:
41
49
  --root <dir> The site's directory (default: the current directory)`
@@ -185,6 +193,45 @@ async function runUpdate(root: string, names: readonly string[]): Promise<void>
185
193
  )
186
194
  }
187
195
 
196
+ /** `cms plugin add` and `cms plugin remove`: the site's files, the install, the route files. */
197
+ async function runPlugin(root: string, action: string | undefined, name: string | undefined) {
198
+ if ((action !== 'add' && action !== 'remove') || !name) {
199
+ throw new Error('Use `cms plugin add <package>` or `cms plugin remove <package>`.')
200
+ }
201
+ const plan = action === 'add' ? await planInstall(root, name) : await planRemove(root, name)
202
+ for (const warning of plan.warnings) console.warn(`cms: ${warning}`)
203
+ if (plan.blockers.length > 0) throw new Error(plan.blockers.join(' '))
204
+ const [change] = plan.changes
205
+ if (!change) throw new Error(`Nothing to ${action}.`)
206
+ if (values.commit) {
207
+ const { stdout } = await run('git', ['status', '--porcelain'], { cwd: root })
208
+ if (stdout.trim())
209
+ throw new Error('Commit or stash your changes first, so this is a commit of its own')
210
+ }
211
+
212
+ await writeChanges(root, plan.changes)
213
+ const manager = await detectPackageManager(root)
214
+ console.log(`cms: installing with ${manager}`)
215
+ await install(root, manager)
216
+ await runInstalledCli(root, ['generate'])
217
+
218
+ const did = action === 'add' ? `Add ${change.name} ${change.to}` : `Remove ${change.name}`
219
+ if (values.commit) {
220
+ const slug = change.name.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
221
+ const branch = `cms-plugin-${action}-${slug}-${Date.now().toString(36)}`
222
+ await commitUpdate(root, branch, did)
223
+ console.log(
224
+ `cms: committed on ${branch}. Push it and open a pull request; your host builds it.`,
225
+ )
226
+ return
227
+ }
228
+ console.log(
229
+ action === 'add'
230
+ ? `cms: added ${change.name} ${change.to}. Run \`${manager} run build\` and restart, then activate it on the Plugins screen.`
231
+ : `cms: removed ${change.name}. Run \`${manager} run build\` and restart.`,
232
+ )
233
+ }
234
+
188
235
  async function main(): Promise<void> {
189
236
  const [command] = positionals
190
237
  if (values.help || !command) {
@@ -197,6 +244,7 @@ async function main(): Promise<void> {
197
244
  if (command === 'generate') return runGenerate(root)
198
245
  if (command === 'migrate') return runMigrate(root)
199
246
  if (command === 'update') return runUpdate(root, positionals.slice(1))
247
+ if (command === 'plugin') return runPlugin(root, positionals[1], positionals[2])
200
248
  if (command === 'serve') {
201
249
  const port = Number(values.port ?? process.env.PORT ?? 3000)
202
250
  if (!Number.isInteger(port) || port < 0 || port > 65535)
@@ -5,7 +5,7 @@ import type { AddressInfo } from 'node:net'
5
5
  import { join, resolve } from 'node:path'
6
6
  import type { UpdateRequest } from '@otwdesign/core'
7
7
  import { loadEnv } from '../site.ts'
8
- import { detectPackageManager, planSite } from '../update.ts'
8
+ import { detectPackageManager, packageName, planInstall, planRemove, planSite } from '../update.ts'
9
9
  import { ControlError, createControlServer } from './control.ts'
10
10
  import { startRelease } from './processes.ts'
11
11
  import { createProxy } from './proxy.ts'
@@ -25,6 +25,17 @@ export interface ServeOptions {
25
25
  checkEveryMs?: number
26
26
  }
27
27
 
28
+ /** The package a request names, checked to be a package name and nothing else. */
29
+ function packageOf(body: unknown): string {
30
+ const name = (body as { package?: unknown } | null)?.package
31
+ if (typeof name !== 'string') throw new ControlError(400, '"package" is required')
32
+ try {
33
+ return packageName(name)
34
+ } catch (error) {
35
+ throw new ControlError(400, error instanceof Error ? error.message : String(error))
36
+ }
37
+ }
38
+
28
39
  function parseUpdateRequest(body: unknown): UpdateRequest {
29
40
  const { packages, pluginsOnly } = (body ?? {}) as { packages?: unknown; pluginsOnly?: unknown }
30
41
  if (
@@ -90,6 +101,8 @@ export async function serve(options: ServeOptions): Promise<void> {
90
101
  await loadState(stateFile),
91
102
  {
92
103
  plan: (release, scope) => planSite(release.dir, scope),
104
+ planInstall: (release, name) => planInstall(release.dir, name),
105
+ planRemove: (release, name) => planRemove(release.dir, name),
93
106
  build: (id, changes, log) => buildRelease(builder, id, changes, log),
94
107
  migrate: (release, log) =>
95
108
  migrateRelease(release, log, {
@@ -126,6 +139,8 @@ export async function serve(options: ServeOptions): Promise<void> {
126
139
  if (typeof release !== 'string') throw new ControlError(400, '"release" is required')
127
140
  return { notice: supervisor.rollback(release) }
128
141
  },
142
+ 'POST /install': (body: unknown) => ({ notice: supervisor.install(packageOf(body)) }),
143
+ 'POST /remove': (body: unknown) => ({ notice: supervisor.remove(packageOf(body)) }),
129
144
  'PUT /auto-update': async (body: unknown) => {
130
145
  const mode = (body as { mode?: unknown } | null)?.mode
131
146
  if (mode !== 'off' && mode !== 'patch') {
@@ -38,6 +38,10 @@ export type Log = (line: string) => void
38
38
  export interface SupervisorDeps {
39
39
  /** What an update would change, judged from what a release has installed. */
40
40
  plan(release: Release, scope: UpdateScope): Promise<UpdatePlan>
41
+ /** What adding a plugin's package to a release would change. */
42
+ planInstall(release: Release, packageName: string): Promise<UpdatePlan>
43
+ /** What taking a plugin's package off a release would change. */
44
+ planRemove(release: Release, packageName: string): Promise<UpdatePlan>
41
45
  /** Copies the site into a new release, applies `changes`, installs and builds it. */
42
46
  build(id: string, changes: readonly PackageChange[], log: Log): Promise<BuiltRelease>
43
47
  /** Runs the release's own `cms migrate`, so its migrations are the ones that run. */
@@ -117,7 +121,29 @@ const UPDATE_STEPS = [
117
121
  ] as const
118
122
 
119
123
  function describeChanges(changes: readonly PackageChange[]): string {
120
- return changes.map((change) => `${change.name} ${change.from} → ${change.to}`).join(', ')
124
+ return changes
125
+ .map((change) =>
126
+ change.from === ''
127
+ ? `${change.name} ${change.to} added`
128
+ : change.to === ''
129
+ ? `${change.name} removed`
130
+ : `${change.name} ${change.from} → ${change.to}`,
131
+ )
132
+ .join(', ')
133
+ }
134
+
135
+ /** What a job that builds and switches to a new release says, by what it's for. */
136
+ interface Wording {
137
+ /** The plan changes nothing. */
138
+ unchanged: string
139
+ refused(blockers: readonly string[]): string
140
+ done(changes: readonly PackageChange[]): string
141
+ }
142
+
143
+ const UPDATE_WORDING: Wording = {
144
+ unchanged: 'Already up to date.',
145
+ refused: (blockers) => `Not updated: ${blockers.join(' ')}`,
146
+ done: (changes) => `Updated: ${describeChanges(changes)}.`,
121
147
  }
122
148
 
123
149
  function toCheck(plan: UpdatePlan, at: Date): UpdateCheck {
@@ -247,24 +273,60 @@ export class Supervisor {
247
273
  pluginsOnly: request.pluginsOnly,
248
274
  patchOnly: request.patchOnly,
249
275
  }
250
- this.#running = this.#update(run, current, scope).finally(() => {
276
+ this.#running = this.#apply(run, current, () => this.#deps.plan(current, scope)).finally(() => {
251
277
  this.#running = null
252
278
  })
253
279
  return 'Updating. This page shows the progress.'
254
280
  }
255
281
 
256
- async #update(run: JobRun, current: Release, scope: UpdateScope): Promise<void> {
282
+ /** Adds a plugin's package in a new release, like WordPress's Install Now. It arrives inactive. */
283
+ install(packageName: string): string {
284
+ const current = this.#current()
285
+ if (!current) throw new ControlError(409, 'The site has no release yet.')
286
+ const run = this.#begin('install', UPDATE_STEPS)
287
+ this.#running = this.#apply(run, current, () => this.#deps.planInstall(current, packageName), {
288
+ unchanged: `${packageName} was not installed.`,
289
+ refused: (blockers) => `Not installed: ${blockers.join(' ')}`,
290
+ done: (changes) =>
291
+ `Installed ${changes.map((change) => `${change.name} ${change.to}`).join(', ')}. Activate it on the Plugins screen.`,
292
+ }).finally(() => {
293
+ this.#running = null
294
+ })
295
+ return `Installing ${packageName}. Dashboard › Updates shows the progress.`
296
+ }
297
+
298
+ /** Takes a plugin's package off the site in a new release, like WordPress's Delete. */
299
+ remove(packageName: string): string {
300
+ const current = this.#current()
301
+ if (!current) throw new ControlError(409, 'The site has no release yet.')
302
+ const run = this.#begin('remove', UPDATE_STEPS)
303
+ this.#running = this.#apply(run, current, () => this.#deps.planRemove(current, packageName), {
304
+ unchanged: `${packageName} was not removed.`,
305
+ refused: (blockers) => `Not removed: ${blockers.join(' ')}`,
306
+ done: (changes) => `Removed ${changes.map((change) => change.name).join(', ')}.`,
307
+ }).finally(() => {
308
+ this.#running = null
309
+ })
310
+ return `Removing ${packageName}. Dashboard › Updates shows the progress.`
311
+ }
312
+
313
+ /** Builds the release a plan describes, and switches to it: an update, an install, a removal. */
314
+ async #apply(
315
+ run: JobRun,
316
+ current: Release,
317
+ planner: () => Promise<UpdatePlan>,
318
+ wording: Wording = UPDATE_WORDING,
319
+ ): Promise<void> {
257
320
  const { now } = this.#deps
258
321
  let plan: UpdatePlan
259
322
  try {
260
- plan = await run.step('Check versions', () => this.#deps.plan(current, scope))
323
+ plan = await run.step('Check versions', planner)
261
324
  } catch (error) {
262
325
  return run.finish('failed', `Couldn't check versions: ${message(error)}`, now())
263
326
  }
264
- if (plan.changes.length === 0) return run.finish('succeeded', 'Already up to date.', now())
265
- if (plan.blockers.length > 0) {
266
- return run.finish('failed', `Not updated: ${plan.blockers.join(' ')}`, now())
267
- }
327
+ // Why not comes before "nothing to do": a refused install changes nothing either.
328
+ if (plan.blockers.length > 0) return run.finish('failed', wording.refused(plan.blockers), now())
329
+ if (plan.changes.length === 0) return run.finish('succeeded', wording.unchanged, now())
268
330
 
269
331
  let release: BuiltRelease
270
332
  try {
@@ -319,7 +381,7 @@ export class Supervisor {
319
381
  await this.#prune()
320
382
  await this.#deps.save(this.#state)
321
383
  })
322
- run.finish('succeeded', `Updated: ${describeChanges(plan.changes)}.`, now())
384
+ run.finish('succeeded', wording.done(plan.changes), now())
323
385
  }
324
386
 
325
387
  /** After a failed update: the old release serves again, on its own database. */
@@ -390,9 +452,16 @@ export class Supervisor {
390
452
  )
391
453
  }
392
454
  await run.step('Finish', async () => {
393
- const changes = Object.entries(target.versions)
394
- .filter(([name, version]) => current.versions[name] !== version)
395
- .map(([name, version]) => ({ name, from: current.versions[name] ?? version, to: version }))
455
+ // What the release going live has that the one leaving doesn't, and the other way round:
456
+ // a plugin added since goes from the site's files, one removed since comes back.
457
+ const changes = [
458
+ ...Object.entries(target.versions)
459
+ .filter(([name, version]) => current.versions[name] !== version)
460
+ .map(([name, version]) => ({ name, from: current.versions[name] ?? '', to: version })),
461
+ ...Object.entries(current.versions)
462
+ .filter(([name]) => !(name in target.versions))
463
+ .map(([name, version]) => ({ name, from: version, to: '' })),
464
+ ]
396
465
  await this.#deps.writeBack(target, changes)
397
466
  current.status = 'previous'
398
467
  target.status = 'live'
package/src/update.ts CHANGED
@@ -2,7 +2,7 @@ import { execFile } from 'node:child_process'
2
2
  import { access, readFile, writeFile } from 'node:fs/promises'
3
3
  import { join } from 'node:path'
4
4
  import { promisify } from 'node:util'
5
- import type { Brand } from '@otwdesign/core'
5
+ import { isPackageName, type Brand } from '@otwdesign/core'
6
6
  import semver from 'semver'
7
7
 
8
8
  const run = promisify(execFile)
@@ -110,7 +110,10 @@ export interface PluginReport {
110
110
 
111
111
  export interface UpdatePlan {
112
112
  core: { from: string; to: string } | null
113
- /** Every package.json change, core and plugins. */
113
+ /**
114
+ * Every package.json change, core and plugins. An empty `from` adds a plugin to the site (and
115
+ * to cms.config.json), an empty `to` removes one.
116
+ */
114
117
  changes: { name: string; from: string; to: string }[]
115
118
  /** The plugins this update looked at. */
116
119
  plugins: PluginReport[]
@@ -414,27 +417,171 @@ export async function planSite(
414
417
  return planUpdate(site, packuments, { ...scope, only })
415
418
  }
416
419
 
420
+ /** The name as npm knows it, or an error for the person who typed it. */
421
+ export function packageName(name: string): string {
422
+ const trimmed = name.trim()
423
+ if (!isPackageName(trimmed)) {
424
+ throw new Error(
425
+ `"${trimmed}" isn't a package name. Use the plugin's name on npm, such as @acme/forum.`,
426
+ )
427
+ }
428
+ return trimmed
429
+ }
430
+
431
+ const emptyPlan = (): UpdatePlan => ({
432
+ core: null,
433
+ changes: [],
434
+ plugins: [],
435
+ blockers: [],
436
+ warnings: [],
437
+ linked: [],
438
+ })
439
+
440
+ /**
441
+ * Plans adding a plugin to the site at `root`: the newest version on npm that says it works with
442
+ * the CMS the site runs. Through npm, so `.npmrc` applies and private plugins can be added. A
443
+ * package that says nothing about the CMS isn't one of its plugins, and is refused.
444
+ */
445
+ export async function planInstall(
446
+ root: string,
447
+ name: string,
448
+ fetchVersions: FetchVersions = npmView(root),
449
+ ): Promise<UpdatePlan> {
450
+ const plan = emptyPlan()
451
+ const wanted = packageName(name)
452
+ const site = await readSitePackages(root)
453
+ if (isCore(wanted)) {
454
+ plan.blockers.push(`${wanted} is part of the CMS, not a plugin.`)
455
+ return plan
456
+ }
457
+ if (site.plugins.includes(wanted)) {
458
+ plan.blockers.push(`${wanted} is already installed.`)
459
+ return plan
460
+ }
461
+ const core = site.installed[CORE_VERSION_FROM]
462
+ if (!core) throw new Error(`${CORE_VERSION_FROM} is not installed in ${root}`)
463
+ let packument: Packument
464
+ try {
465
+ packument = await fetchVersions(wanted, '0.0.0')
466
+ } catch (error) {
467
+ plan.blockers.push(
468
+ `npm has no package ${wanted} that this site can read: ${error instanceof Error ? error.message : String(error)}`,
469
+ )
470
+ return plan
471
+ }
472
+ const versions = semver.rsort(candidates(packument, '0.0.0'))
473
+ const peersOf = (version: string) => packument.versions[version]?.peerDependencies ?? {}
474
+ const latest = versions[0] ?? null
475
+ if (!latest) {
476
+ plan.blockers.push(`${wanted} has no released version.`)
477
+ return plan
478
+ }
479
+ const supported = versions.find((version) => coreSupport(peersOf(version), core) === 'yes')
480
+ if (!supported) {
481
+ plan.blockers.push(
482
+ versions.every((version) => coreSupport(peersOf(version), core) === 'unknown')
483
+ ? `${wanted} isn't a plugin for this CMS: it doesn't say which version of ${COMPATIBILITY_PEERS[0]} it works with.`
484
+ : `No version of ${wanted} supports core ${core}. The newest is ${latest}.`,
485
+ )
486
+ return plan
487
+ }
488
+ // What it needs of plugins already on the site must hold for the versions they're at. A
489
+ // plugin it needs that isn't installed shows when it's activated: "Stripe requires Commerce".
490
+ for (const [peer, range] of Object.entries(peersOf(supported))) {
491
+ const installed = site.plugins.includes(peer) ? site.installed[peer] : undefined
492
+ if (installed && !semver.satisfies(installed, range, INCLUDE_PRERELEASE)) {
493
+ plan.blockers.push(
494
+ `${wanted} ${supported} needs ${peer} ${range}; ${installed} is installed.`,
495
+ )
496
+ }
497
+ }
498
+ plan.changes.push({ name: wanted, from: '', to: supported })
499
+ plan.plugins.push({
500
+ name: wanted,
501
+ from: '',
502
+ to: supported,
503
+ latest,
504
+ compatible: 'yes',
505
+ ...(supported === latest ? {} : { note: `${latest} doesn't support core ${core}` }),
506
+ })
507
+ return plan
508
+ }
509
+
510
+ /** Plans taking a plugin's package off the site at `root`. Other plugins mustn't need it. */
511
+ export async function planRemove(root: string, name: string): Promise<UpdatePlan> {
512
+ const plan = emptyPlan()
513
+ const site = await readSitePackages(root)
514
+ const [wanted] = resolveTargets(site, [name])
515
+ if (!wanted || !site.plugins.includes(wanted)) {
516
+ plan.blockers.push(`${name} is not an installed plugin.`)
517
+ return plan
518
+ }
519
+ for (const other of site.plugins.filter((plugin) => plugin !== wanted)) {
520
+ if (site.peers[other]?.[wanted])
521
+ plan.blockers.push(`${other} needs ${wanted}: remove that first.`)
522
+ }
523
+ plan.changes.push({
524
+ name: wanted,
525
+ from: site.installed[wanted] ?? site.specs[wanted] ?? '',
526
+ to: '',
527
+ })
528
+ return plan
529
+ }
530
+
417
531
  /** Keeps the spec's style: `^1.2.0` stays a caret range, `1.2.0` stays exact. */
418
532
  export function nextSpec(current: string, version: string): string {
419
533
  const prefix = /^[\^~]/.exec(current)?.[0] ?? ''
420
534
  return `${prefix}${version}`
421
535
  }
422
536
 
423
- /** Rewrites package.json in place, leaving everything else in it as it was. */
537
+ async function rewriteJson<T>(file: string, change: (json: T) => void): Promise<void> {
538
+ const raw = await readFile(file, 'utf8')
539
+ const json = JSON.parse(raw) as T
540
+ change(json)
541
+ const indent = /^(\s+)"/m.exec(raw)?.[1] ?? ' '
542
+ await writeFile(file, `${JSON.stringify(json, null, indent)}\n`)
543
+ }
544
+
545
+ /**
546
+ * Rewrites package.json in place, leaving everything else in it as it was. A plugin that is
547
+ * added or removed is also added to or removed from cms.config.json's `plugins`.
548
+ */
424
549
  export async function writeChanges(
425
550
  root: string,
426
551
  changes: readonly UpdatePlan['changes'][number][],
427
552
  ): 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)
553
+ const added = changes.filter((change) => change.from === '' && change.to !== '')
554
+ const removed = changes.filter((change) => change.to === '')
555
+ await rewriteJson<PackageJson>(join(root, 'package.json'), (manifest) => {
556
+ for (const { name, from, to } of changes) {
557
+ if (to === '') {
558
+ for (const deps of [manifest.dependencies, manifest.devDependencies]) delete deps?.[name]
559
+ } else if (
560
+ from === '' &&
561
+ !manifest.dependencies?.[name] &&
562
+ !manifest.devDependencies?.[name]
563
+ ) {
564
+ manifest.dependencies = { ...manifest.dependencies, [name]: `^${to}` }
565
+ } else {
566
+ for (const deps of [manifest.dependencies, manifest.devDependencies]) {
567
+ if (deps?.[name]) deps[name] = nextSpec(deps[name], to)
568
+ }
569
+ }
434
570
  }
435
- }
436
- const indent = /^(\s+)"/m.exec(raw)?.[1] ?? ' '
437
- await writeFile(file, `${JSON.stringify(manifest, null, indent)}\n`)
571
+ // npm keeps dependencies in order; one added by hand goes where npm would have put it.
572
+ if (added.length > 0 && manifest.dependencies) {
573
+ manifest.dependencies = Object.fromEntries(
574
+ Object.entries(manifest.dependencies).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
575
+ )
576
+ }
577
+ })
578
+ if (added.length === 0 && removed.length === 0) return
579
+ await rewriteJson<{ plugins?: string[] }>(join(root, 'cms.config.json'), (config) => {
580
+ const gone = new Set(removed.map((change) => change.name))
581
+ const plugins = (config.plugins ?? []).filter((name) => !gone.has(name))
582
+ for (const { name } of added) if (!plugins.includes(name)) plugins.push(name)
583
+ config.plugins = plugins
584
+ })
438
585
  }
439
586
 
440
587
  export type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun'