@crombolo/server 0.44.0 → 0.46.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": "@crombolo/server",
3
- "version": "0.44.0",
3
+ "version": "0.46.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,19 +31,25 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.44.0",
35
- "@crombolo/api-management": "0.44.0",
36
- "@crombolo/auth": "0.44.0",
37
- "@crombolo/backoffice-host": "0.44.0",
38
- "@crombolo/common": "0.44.0",
39
- "@crombolo/content": "0.44.0",
40
- "@crombolo/contracts": "0.44.0",
41
- "@crombolo/core": "0.44.0",
42
- "@crombolo/data": "0.44.0",
43
- "@crombolo/render": "0.44.0",
44
- "@crombolo/schema": "0.44.0",
45
- "@crombolo/transfer": "0.44.0",
34
+ "@crombolo/api-delivery": "0.46.1",
35
+ "@crombolo/api-management": "0.46.1",
36
+ "@crombolo/auth": "0.46.1",
37
+ "@crombolo/backoffice-host": "0.46.1",
38
+ "@crombolo/common": "0.46.1",
39
+ "@crombolo/content": "0.46.1",
40
+ "@crombolo/contracts": "0.46.1",
41
+ "@crombolo/core": "0.46.1",
42
+ "@crombolo/data": "0.46.1",
43
+ "@crombolo/render": "0.46.1",
44
+ "@crombolo/schema": "0.46.1",
45
+ "@crombolo/transfer": "0.46.1",
46
46
  "@logtape/logtape": "^2.3.8",
47
- "jose": "^6.2.12"
47
+ "@sigstore/bundle": "^3.1.0",
48
+ "@sigstore/core": "^2.0.0",
49
+ "@sigstore/protobuf-specs": "^0.4.3",
50
+ "@sigstore/tuf": "^3.1.1",
51
+ "@sigstore/verify": "^2.1.1",
52
+ "jose": "^6.2.12",
53
+ "sigstore": "^3.1.0"
48
54
  }
49
55
  }
@@ -7,6 +7,7 @@ import type {
7
7
  HealthCheckGroup,
8
8
  HealthCheckResult,
9
9
  } from '@crombolo/api-management/domain'
10
+ import { RemotePermissions } from '@crombolo/core'
10
11
  import {
11
12
  changedSince,
12
13
  compareStates,
@@ -20,12 +21,16 @@ import {
20
21
  pendingMigrations,
21
22
  type QueueCounts,
22
23
  queueCounts,
24
+ RemoteTrustRepository,
23
25
  sql,
26
+ UserGroupRepository,
27
+ UserRepository,
24
28
  } from '@crombolo/data'
25
29
  import { type CromboloConfig, describeDatabase, VERSION } from '../config.ts'
26
30
  import { BundleConfigurationError, pendingTablesSteps, tablesChainsFor } from '../custom-tables.ts'
27
31
  import { type EmailPort, emailAvailability } from '../email.ts'
28
32
  import type { MediaStore } from '../media-store.ts'
33
+ import { restartPending } from '../restart-pending.ts'
29
34
  import { backofficeVersion } from '../status.ts'
30
35
 
31
36
  export const UPGRADE_PACKAGE = '@crombolo/crombolo'
@@ -42,6 +47,7 @@ const CHECKS = {
42
47
  outgoing: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000006', name: 'Outgoing changes' },
43
48
  routes: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000007', name: 'Routes and pages' },
44
49
  settings: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000008', name: 'Site settings' },
50
+ code: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000009', name: 'Installing code' },
45
51
  } as const
46
52
 
47
53
  /** Waiting longer than this means nothing is sending: no server is running its jobs, or one is stuck. */
@@ -93,6 +99,11 @@ const GROUPS: HealthCheckGroup[] = [
93
99
  description:
94
100
  "Whether each site has at most one settings page, kept directly below the site's top page.",
95
101
  },
102
+ {
103
+ ...CHECKS.code,
104
+ description:
105
+ 'Who may install code on this site, and whether installed code is waiting for a restart.',
106
+ },
96
107
  ],
97
108
  },
98
109
  ]
@@ -374,6 +385,43 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
374
385
  ),
375
386
  )
376
387
  },
388
+ [CHECKS.code.id]: async () => {
389
+ const results: HealthCheckResult[] = []
390
+ const verb = RemotePermissions.InstallCode
391
+ const groups = (await new UserGroupRepository(db).all()).filter((group) =>
392
+ group.permissions.includes(verb),
393
+ )
394
+ const users = await new UserRepository(db).all()
395
+ for (const group of groups) {
396
+ const members = users.filter((user) => user.groupKeys.includes(group.key)).length
397
+ results.push(
398
+ result(
399
+ 'Info',
400
+ `The group "${group.name}" may install code on this site: ${members} user(s) in it.`,
401
+ ),
402
+ )
403
+ }
404
+ for (const rule of (await new RemoteTrustRepository(db).all()).filter(
405
+ (candidate) => !candidate.disabled && candidate.permissions.includes(verb),
406
+ ))
407
+ results.push(
408
+ result(
409
+ 'Info',
410
+ `The CI rule "${rule.name}" (${rule.repository}) may install code on this site.`,
411
+ ),
412
+ )
413
+ if (results.length === 0)
414
+ results.push(result('Success', 'Nobody may install code on this site.'))
415
+ const pending = restartPending(config.siteDir)
416
+ if (pending)
417
+ results.push(
418
+ result(
419
+ 'Warning',
420
+ `Code installed since ${new Date(pending.since).toLocaleString('en-GB')} runs once the site restarts: ${pending.reasons.join('; ')}.`,
421
+ ),
422
+ )
423
+ return results
424
+ },
377
425
  [CHECKS.outgoing.id]: async () =>
378
426
  outgoingResults(
379
427
  {
@@ -7,7 +7,6 @@ import type { MediaPort } from '@crombolo/api-management/domain'
7
7
  import {
8
8
  type ContentTypeAggregate,
9
9
  DEFAULT_UPLOAD_SETTINGS,
10
- type DocumentAggregate,
11
10
  IMAGE_CROPPER_EDITOR_ALIAS,
12
11
  mediaFileOf,
13
12
  normaliseUuid,
@@ -18,11 +17,21 @@ import {
18
17
  DataTypeRepository,
19
18
  type Db,
20
19
  DocumentRepository,
20
+ MediaListingRepository,
21
+ type MediaSortField,
21
22
  type NodeRow,
22
23
  type NodeSchemaState,
23
24
  type ValueIntake,
24
25
  } from '@crombolo/data'
25
26
 
27
+ /** The folder view's `orderBy`, as the listing sorts; anything else is sort order. */
28
+ const COLLECTION_SORTS: Record<string, MediaSortField> = {
29
+ name: 'name',
30
+ createDate: 'createDate',
31
+ updateDate: 'updateDate',
32
+ sortOrder: 'sortOrder',
33
+ }
34
+
26
35
  /** The Media section's reads; its writes go through the media operations (story 165). */
27
36
  export function createMediaPort(
28
37
  db: Db,
@@ -109,50 +118,35 @@ export function createMediaPort(
109
118
  return { total: page.total, items: await tree(page.items) }
110
119
  },
111
120
 
121
+ /**
122
+ * The folder view (story 246): counted, filtered, sorted and paged in the
123
+ * database, so a folder of a million files costs a page, not the folder.
124
+ * Only the page's items are loaded, and their creators in one query.
125
+ */
112
126
  async collection(parentKey, options) {
113
- const children = await repo.children(parentKey, 0, Number.MAX_SAFE_INTEGER)
114
- const filter = options.filter?.trim().toLowerCase()
115
- const loaded: Array<DocumentAggregate & { sortOrder: number; creator: string | null }> = []
116
- for (const node of children.items) {
117
- const media = await repo.load(node)
118
- if (!media) continue
119
- const name = media.variants[0]?.name ?? node.text ?? ''
120
- if (filter && !name.toLowerCase().includes(filter)) continue
121
- const latest = (await repo.versions(node.key))[0]
122
- const creator = latest?.userKey
123
- ? ((
124
- await db.q
125
- .selectFrom('user_account')
126
- .select('user_name')
127
- .where('key', '=', latest.userKey)
128
- .execute()
129
- )[0]?.user_name ?? null)
130
- : null
131
- loaded.push({ ...media, sortOrder: node.sortOrder, creator })
132
- }
133
- const keyOf = (m: (typeof loaded)[number]): string | number => {
134
- const variant = m.variants[0]
135
- switch (options.orderBy) {
136
- case 'name':
137
- return (variant?.name ?? '').toLowerCase()
138
- case 'createDate':
139
- return variant?.createDate.getTime() ?? 0
140
- case 'updateDate':
141
- return variant?.updateDate.getTime() ?? 0
142
- default:
143
- return m.sortOrder
144
- }
145
- }
146
- loaded.sort((a, b) => {
147
- const x = keyOf(a)
148
- const y = keyOf(b)
149
- const order = x < y ? -1 : x > y ? 1 : 0
150
- return options.orderDirection === 'Descending' ? -order : order
127
+ const listing = new MediaListingRepository(db)
128
+ const parent = parentKey ? await listing.byKey(parentKey) : { id: -1, path: '-1' }
129
+ if (!parent) return { total: 0, items: [] }
130
+ const filter = options.filter?.trim()
131
+ const page = await listing.children({
132
+ parentId: parent.id,
133
+ parentPath: parent.path,
134
+ names: filter ? [filter] : [],
135
+ sort: {
136
+ field: COLLECTION_SORTS[options.orderBy ?? ''] ?? 'sortOrder',
137
+ ascending: options.orderDirection !== 'Descending',
138
+ },
139
+ skip: options.skip,
140
+ take: options.take,
151
141
  })
152
- return {
153
- total: loaded.length,
154
- items: loaded.slice(options.skip, options.skip + options.take),
155
- }
142
+ const [loaded, creators] = await Promise.all([
143
+ Promise.all(page.keys.map((key) => repo.byKey(key))),
144
+ listing.creators(page.keys),
145
+ ])
146
+ const items = loaded.flatMap((media) =>
147
+ media ? [{ ...media, creator: creators.get(media.key) ?? null }] : [],
148
+ )
149
+ return { total: page.total, items }
156
150
  },
157
151
 
158
152
  async typesForExtension(raw) {
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Installed bundles, managed (stories 194, 222, 225, 241): the list, install,
3
+ * uninstall, disable and enable, each audited. One implementation behind
4
+ * Settings → Bundles, the remote protocol and the CLI on the site's own machine.
5
+ */
6
+ import type { ExtensionRegistry } from '@crombolo/backoffice-host'
7
+ import { createExtensionRegistry } from '@crombolo/backoffice-host/registry'
8
+ import { type Db, TransferRunRepository } from '@crombolo/data'
9
+ import { recordAudit } from './adapters/audit.ts'
10
+ import { type BundleGrants, createBundleGrants } from './bundle-grants.ts'
11
+ import { CommandError, installBundleContent } from './bundle-install.ts'
12
+ import type { CromboloConfig } from './config.ts'
13
+ import {
14
+ createMarketplace,
15
+ type InstalledListing,
16
+ type InstallOutcome,
17
+ type Marketplace,
18
+ type PackageInstaller,
19
+ } from './marketplace.ts'
20
+ import { describeProvenance, type ProvenancePolicy } from './provenance.ts'
21
+ import { markRestartPending, type RestartPending, restartPending } from './restart-pending.ts'
22
+
23
+ /** Who acted, and from where, for the audit log. */
24
+ export interface BundleActor {
25
+ id: string | null
26
+ name: string
27
+ email: string | null
28
+ source: 'request' | 'cli'
29
+ ipAddress?: string | null
30
+ forwardedFor?: string | null
31
+ }
32
+
33
+ export interface InstalledBundles {
34
+ installs: boolean
35
+ installsElsewhere: { message: string; url?: string } | null
36
+ /** Code installed here that runs once the site restarts. */
37
+ restartPending: RestartPending | null
38
+ /** What this site takes of a bundle's signature (story 060). */
39
+ policy: ProvenancePolicy
40
+ items: InstalledListing[]
41
+ }
42
+
43
+ export interface InstallRequest {
44
+ /** A package name, or with `file` a packed bundle on this machine. */
45
+ name: string
46
+ version?: string
47
+ file?: boolean
48
+ applyContent?: boolean
49
+ acceptServerCode?: boolean
50
+ grant?: readonly string[]
51
+ }
52
+
53
+ export interface SwitchOutcome {
54
+ status: number
55
+ ok: boolean
56
+ on?: boolean
57
+ message: string
58
+ }
59
+
60
+ export interface BundleAdmin {
61
+ installed(): Promise<InstalledBundles>
62
+ /** What installing a version would bring, with nothing installed. */
63
+ inspect: Marketplace['inspect']
64
+ install(actor: BundleActor, request: InstallRequest): Promise<InstallOutcome>
65
+ uninstall(actor: BundleActor, name: string): Promise<InstallOutcome>
66
+ /** Turns a bundle's server features off or on; `id` is its bundle id or its package name. */
67
+ setEnabled(actor: BundleActor, id: string, enabled: boolean): Promise<SwitchOutcome>
68
+ }
69
+
70
+ /** What restarting will make live, said after an install that changed code. */
71
+ export const RESTART_NOTICE = 'It takes effect when the site restarts: `crombolo restart`.'
72
+
73
+ export function createBundleAdmin(options: {
74
+ db: Db
75
+ config: CromboloConfig
76
+ marketplace: Marketplace
77
+ extensions: Pick<ExtensionRegistry, 'bundles'>
78
+ bundleGrants: Pick<BundleGrants, 'disable' | 'enable'>
79
+ }): BundleAdmin {
80
+ const { db, config, marketplace, extensions, bundleGrants } = options
81
+ const audit = (actor: BundleActor, action: string, entityName: string, detail: string | null) =>
82
+ recordAudit(db, {
83
+ category: 'system',
84
+ action,
85
+ entityType: 'Bundle',
86
+ entityName,
87
+ detail,
88
+ source: actor.source,
89
+ userKey: actor.id,
90
+ userName: actor.name,
91
+ ipAddress: actor.ipAddress ?? null,
92
+ forwardedFor: actor.forwardedFor ?? null,
93
+ })
94
+ const find = (name: string) =>
95
+ extensions.bundles().bundles.find((bundle) => bundle.packageName === name || bundle.id === name)
96
+
97
+ return {
98
+ inspect: (name, version) => marketplace.inspect(name, version),
99
+
100
+ async installed() {
101
+ return {
102
+ installs: config.runtimeInstalls,
103
+ installsElsewhere: config.runtimeInstalls ? null : (config.installsElsewhere ?? null),
104
+ restartPending: restartPending(config.siteDir) ?? null,
105
+ policy: config.bundlePolicy,
106
+ items: await marketplace.installed(),
107
+ }
108
+ },
109
+
110
+ async install(actor, request) {
111
+ const asked = {
112
+ applyContent: request.applyContent !== false,
113
+ acceptServerCode: request.acceptServerCode === true,
114
+ grant: request.grant ?? [],
115
+ by: actor.email ?? actor.name,
116
+ }
117
+ const outcome = request.file
118
+ ? await marketplace.installFile(request.name, asked)
119
+ : await marketplace.install(request.name, request.version, asked)
120
+ if (!outcome.ok) return outcome
121
+ const name = outcome.dependency?.name ?? request.name
122
+ const landed = find(name)
123
+ await audit(
124
+ actor,
125
+ 'Install',
126
+ outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
127
+ [
128
+ asked.acceptServerCode
129
+ ? `accepted server code; granted ${asked.grant.length > 0 ? asked.grant.join(', ') : 'nothing'}`
130
+ : undefined,
131
+ outcome.provenance ? describeProvenance(outcome.provenance) : undefined,
132
+ ]
133
+ .filter(Boolean)
134
+ .join('; ') || null,
135
+ )
136
+ if (!landed?.carries.server) return outcome
137
+ markRestartPending(config.siteDir, `${name}@${landed.version} installed`)
138
+ return { ...outcome, restartPending: true }
139
+ },
140
+
141
+ async uninstall(actor, name) {
142
+ const before = find(name)
143
+ const outcome = await marketplace.uninstall(name)
144
+ if (!outcome.ok) return outcome
145
+ await audit(actor, 'Uninstall', name, null)
146
+ if (!before?.carries.server) return outcome
147
+ markRestartPending(config.siteDir, `${name} removed`)
148
+ return { ...outcome, restartPending: true }
149
+ },
150
+
151
+ async setEnabled(actor, id, enabled) {
152
+ const pkg = find(id)
153
+ if (!pkg?.carries.server)
154
+ return {
155
+ status: 404,
156
+ ok: false,
157
+ message: `No installed bundle with a server half is called "${id}".`,
158
+ }
159
+ const state = enabled
160
+ ? await bundleGrants.enable(pkg)
161
+ : await bundleGrants.disable(pkg, actor.email ?? actor.name)
162
+ await audit(
163
+ actor,
164
+ enabled ? 'Enable' : 'Disable',
165
+ `${pkg.packageName}@${pkg.version}`,
166
+ enabled ? 'enabled; it runs again' : 'disabled; it is off',
167
+ )
168
+ return {
169
+ status: 200,
170
+ ok: true,
171
+ on: state.on,
172
+ message: enabled
173
+ ? `${pkg.name} is turned on.`
174
+ : `${pkg.name} is turned off until it is enabled again.`,
175
+ }
176
+ },
177
+ }
178
+ }
179
+
180
+ /**
181
+ * The same, for the CLI on the site's own machine, with no server running: the
182
+ * site directory's dependencies, its database's grants, and `bun add` here.
183
+ * Installing is always allowed, whatever the site says about installs while it
184
+ * runs: on its own machine the site is a working copy to commit from.
185
+ */
186
+ export async function localBundleAdmin(
187
+ db: Db,
188
+ config: CromboloConfig,
189
+ options: { install?: PackageInstaller; fetch?: typeof fetch } = {},
190
+ ): Promise<BundleAdmin> {
191
+ const extensions = createExtensionRegistry(config.siteDir, { cache: false })
192
+ const bundleGrants = createBundleGrants({
193
+ db,
194
+ packages: () => new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg])),
195
+ })
196
+ await bundleGrants.refresh()
197
+ const marketplace = createMarketplace({
198
+ registry: config.npmRegistry,
199
+ keyword: config.packageKeyword,
200
+ marketplaceUrl: config.marketplaceUrl,
201
+ extensions,
202
+ siteDir: config.siteDir,
203
+ grants: bundleGrants,
204
+ installs: true,
205
+ policy: config.bundlePolicy,
206
+ applyContentOnInstall: true,
207
+ contentApplied: async (packageName) =>
208
+ (await new TransferRunRepository(db).appliedForPackage(packageName))?.packageVersion ?? null,
209
+ applyContent: async (packageName) => {
210
+ const result = await installBundleContent(db, config, { bundle: packageName }).catch(
211
+ (error: unknown) => {
212
+ if (error instanceof CommandError) return error
213
+ throw error
214
+ },
215
+ )
216
+ if (result instanceof CommandError)
217
+ return { applied: false, message: `Its content was not applied: ${result.message}` }
218
+ if (!result.runId)
219
+ return {
220
+ applied: false,
221
+ message: `Its content was not applied: ${[...result.problems, ...result.check.outstanding.map((f) => f.message)].join('; ') || 'the check refused it'}. \`crombolo bundle apply ${packageName} --dry-run\` says what it needs.`,
222
+ }
223
+ return { applied: true, runId: result.runId, message: 'Its content was applied.' }
224
+ },
225
+ ...(options.install ? { install: options.install } : {}),
226
+ ...(options.fetch ? { fetch: options.fetch } : {}),
227
+ })
228
+ return createBundleAdmin({
229
+ db,
230
+ config: { ...config, runtimeInstalls: true },
231
+ marketplace,
232
+ extensions,
233
+ bundleGrants,
234
+ })
235
+ }
@@ -32,7 +32,8 @@ export interface BundleBuildOptions {
32
32
  label?: string
33
33
  /**
34
34
  * Globs naming the site's own code, in place of `crombolo.code` in its
35
- * `package.json` (story 192). Neither: the bundle carries no code.
35
+ * `package.json` (story 192). Neither: the bundle carries `package.json`,
36
+ * `bun.lock` and `crombolo.config.ts` alone, when the site has a lockfile.
36
37
  */
37
38
  code?: readonly string[]
38
39
  /**
@@ -81,7 +82,10 @@ export async function buildBundleFromDirectory(
81
82
  const name = options.name ?? identity.name
82
83
  if (!existsSync(join(dir, 'schema')))
83
84
  return { problems: [`${dir} has no schema/ directory, so it is not a site`], name }
84
- const patterns = options.code ?? codePatternsOf(dir)
85
+ // A site that names no code of its own still sends what installing and
86
+ // wiring a bundle changes (story 241), once it has the lockfile to install from.
87
+ const carriesInstall = existsSync(join(dir, 'package.json')) && existsSync(join(dir, 'bun.lock'))
88
+ const patterns = options.code ?? codePatternsOf(dir) ?? (carriesInstall ? [] : undefined)
85
89
  const code = patterns ? selectCodeFiles(dir, patterns) : undefined
86
90
  if (code && code.problems.length > 0)
87
91
  return { problems: code.problems.map((problem) => `its code: ${problem}`), name }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The code a bundle carries, installed into the site it is applied to (story
3
+ * 241), which story 192 left to a host. Each file under `code/` lands at its site
4
+ * path, what it replaces is kept under the run, and a changed `package.json` or
5
+ * `bun.lock` is installed from the lockfile with no install scripts. The server
6
+ * loads code at boot, so the change waits for `crombolo restart`.
7
+ * `docs/bundles.md`, "A site's bundle with code".
8
+ */
9
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { dirname, join } from 'node:path'
11
+ import { CODE_DIR } from '@crombolo/transfer'
12
+ import type { CarriedSections, FileAction, SectionFile } from './bundle-sections.ts'
13
+ import { RUN_BACKUP_DIR } from './bundle-sections.ts'
14
+ import type { CromboloConfig } from './config.ts'
15
+ import { markRestartPending } from './restart-pending.ts'
16
+
17
+ /** Where a run keeps the code it replaced, and what it did to each file. */
18
+ const CODE_RUN_DIR = 'code'
19
+ const CODE_RECORD = 'code.json'
20
+ const DEPENDENCY_FILES = new Set(['package.json', 'bun.lock'])
21
+
22
+ interface CodeRecord {
23
+ files: { path: string; action: FileAction }[]
24
+ /** Whether the dependencies were installed, and so are installed again on a revert. */
25
+ installed: boolean
26
+ }
27
+
28
+ export interface CodeInstall {
29
+ written: string[]
30
+ replaced: string[]
31
+ /** Whether `bun install` ran, because the dependencies changed. */
32
+ installed: boolean
33
+ problems: string[]
34
+ }
35
+
36
+ const sitePath = (path: string) => path.slice(`${CODE_DIR}/`.length)
37
+
38
+ function actionFor(target: string, bytes: Uint8Array): FileAction {
39
+ if (!existsSync(target)) return 'create'
40
+ return Buffer.from(readFileSync(target)).equals(Buffer.from(bytes)) ? 'unchanged' : 'overwrite'
41
+ }
42
+
43
+ const bytesOf = (carried: CarriedSections, path: string): Uint8Array => {
44
+ const file = carried.files.get(path)
45
+ if (!file) throw new Error(`${path} is declared but was not read`)
46
+ return new Uint8Array(readFileSync(file))
47
+ }
48
+
49
+ /** Read-only: what installing the bundle's code here would do, file by file. */
50
+ export function planCode(config: CromboloConfig, carried: CarriedSections): SectionFile[] {
51
+ return (carried.carries.code ?? []).map((path) => {
52
+ const target = join(config.siteDir, sitePath(path))
53
+ return { path, target, action: actionFor(target, bytesOf(carried, path)) }
54
+ })
55
+ }
56
+
57
+ /** The files installing it would change; none means the site already runs this code. */
58
+ export const codeChanges = (plan: readonly SectionFile[]): SectionFile[] =>
59
+ plan.filter((file) => file.action !== 'unchanged')
60
+
61
+ /** `bun install` from the site's lockfile, running no package's install scripts. */
62
+ async function installFromLockfile(dir: string): Promise<string | undefined> {
63
+ const run = Bun.spawn([process.execPath, 'install', '--frozen-lockfile', '--ignore-scripts'], {
64
+ cwd: dir,
65
+ stdout: 'pipe',
66
+ stderr: 'pipe',
67
+ })
68
+ const [out, err, code] = await Promise.all([
69
+ new Response(run.stdout).text(),
70
+ new Response(run.stderr).text(),
71
+ run.exited,
72
+ ])
73
+ if (code === 0) return undefined
74
+ const tail = `${err}\n${out}`.trim().split('\n').slice(-5).join(' / ')
75
+ return `the install from its bun.lock failed: ${tail}`
76
+ }
77
+
78
+ /**
79
+ * Writes the bundle's code into the site, keeping what it replaces under the
80
+ * run's directory, then installs the dependencies when they changed. Run after
81
+ * the content has committed, as the other sections' swap is.
82
+ */
83
+ export async function installCode(
84
+ config: CromboloConfig,
85
+ carried: CarriedSections,
86
+ runDir: string,
87
+ label: string,
88
+ ): Promise<CodeInstall> {
89
+ const plan = planCode(config, carried)
90
+ const changed = codeChanges(plan)
91
+ const result: CodeInstall = { written: [], replaced: [], installed: false, problems: [] }
92
+ if (changed.length === 0) return result
93
+ const keep = join(runDir, CODE_RUN_DIR)
94
+ for (const file of changed) {
95
+ if (file.action === 'overwrite') {
96
+ const kept = join(keep, sitePath(file.path))
97
+ mkdirSync(dirname(kept), { recursive: true })
98
+ copyFileSync(file.target, kept)
99
+ result.replaced.push(file.target)
100
+ }
101
+ mkdirSync(dirname(file.target), { recursive: true })
102
+ writeFileSync(file.target, bytesOf(carried, file.path))
103
+ result.written.push(file.target)
104
+ }
105
+ const dependencies = changed.some((file) => DEPENDENCY_FILES.has(sitePath(file.path)))
106
+ if (dependencies) {
107
+ const failed = await installFromLockfile(config.siteDir)
108
+ if (failed) result.problems.push(failed)
109
+ else result.installed = true
110
+ }
111
+ const record: CodeRecord = {
112
+ files: changed.map((file) => ({ path: sitePath(file.path), action: file.action })),
113
+ installed: dependencies,
114
+ }
115
+ mkdirSync(runDir, { recursive: true })
116
+ writeFileSync(join(runDir, CODE_RECORD), `${JSON.stringify(record, null, 2)}\n`)
117
+ markRestartPending(config.siteDir, `${label}: ${changed.length} code file(s) installed`)
118
+ return result
119
+ }
120
+
121
+ function codeRecord(config: CromboloConfig, runId: string): CodeRecord | undefined {
122
+ const file = join(config.siteDir, RUN_BACKUP_DIR, runId, CODE_RECORD)
123
+ if (!existsSync(file)) return undefined
124
+ try {
125
+ return JSON.parse(readFileSync(file, 'utf8')) as CodeRecord
126
+ } catch {
127
+ return undefined
128
+ }
129
+ }
130
+
131
+ /** Whether a run installed code, so that reverting it changes code too. */
132
+ export const installedCode = (config: CromboloConfig, runId: string): boolean =>
133
+ (codeRecord(config, runId)?.files.length ?? 0) > 0
134
+
135
+ export interface CodeRevert {
136
+ restored: string[]
137
+ removed: string[]
138
+ installed: boolean
139
+ problems: string[]
140
+ }
141
+
142
+ /** Puts back the code a run replaced, removes what it added, and installs again. */
143
+ export async function revertCode(config: CromboloConfig, runId: string): Promise<CodeRevert> {
144
+ const result: CodeRevert = { restored: [], removed: [], installed: false, problems: [] }
145
+ const record = codeRecord(config, runId)
146
+ if (!record || record.files.length === 0) return result
147
+ const keep = join(config.siteDir, RUN_BACKUP_DIR, runId, CODE_RUN_DIR)
148
+ for (const file of record.files) {
149
+ const target = join(config.siteDir, file.path)
150
+ if (file.action === 'overwrite') {
151
+ const kept = join(keep, file.path)
152
+ if (!existsSync(kept)) continue
153
+ mkdirSync(dirname(target), { recursive: true })
154
+ copyFileSync(kept, target)
155
+ result.restored.push(target)
156
+ } else if (file.action === 'create' && existsSync(target)) {
157
+ rmSync(target, { force: true })
158
+ result.removed.push(target)
159
+ }
160
+ }
161
+ if (record.installed) {
162
+ const failed = await installFromLockfile(config.siteDir)
163
+ if (failed) result.problems.push(failed)
164
+ else result.installed = true
165
+ }
166
+ markRestartPending(config.siteDir, `run ${runId} reverted: its code put back`)
167
+ return result
168
+ }