@crombolo/server 0.28.0 → 0.29.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.
@@ -1,22 +1,28 @@
1
1
  /**
2
- * Content already in a site, written out as seed files (story 163), so an
3
- * existing site can move to seeds. Text and toggles are written as themselves,
4
- * a content picker as the page's path where the export carries it, and every
5
- * other value in its editor's stored shape, which `seed apply` takes back
6
- * as given. A node keeps its key in the file wherever it is not the one its
7
- * path would derive, so a round trip names the same nodes.
2
+ * Content already in a site, written out as seed files (stories 163, 164), so
3
+ * an existing site can move to seeds. Pages go to `seed/content/`, Library
4
+ * elements to `seed/library/`, and media, files and all, to `seed/media/`.
5
+ *
6
+ * Values are written in the shorthand `seed apply` reads back — rich text as
7
+ * `{ html }`, pickers and links as paths to what the export carries, blocks as
8
+ * `{ type, key, values }` — and in their editor's stored shape where there is
9
+ * none. A node keeps its key in its file wherever it is not the one its path
10
+ * would derive, so a round trip names the same nodes.
8
11
  */
9
12
  import { mkdirSync, writeFileSync } from 'node:fs'
10
13
  import { join } from 'node:path'
11
- import { normaliseUuid, ObjectTypes } from '@crombolo/core'
14
+ import { mediaFileOf, normaliseUuid, ObjectTypes } from '@crombolo/core'
12
15
  import {
16
+ ContentTypeRepository,
13
17
  currentSchemaState,
18
+ DataTypeRepository,
14
19
  type Db,
15
20
  DocumentRepository,
16
21
  NodeRepository,
17
22
  type NodeRow,
18
23
  } from '@crombolo/data'
19
- import { seedKey } from './keys.ts'
24
+ import type { MediaFileStore } from '../media-files.ts'
25
+ import { pickKey, seedKey } from './keys.ts'
20
26
 
21
27
  /** A URL segment from a name: `About us` → `about-us`. */
22
28
  export const segmentOf = (name: string) =>
@@ -27,6 +33,9 @@ export const segmentOf = (name: string) =>
27
33
  .replace(/[^a-z0-9]+/g, '-')
28
34
  .replace(/^-+|-+$/g, '') || 'item'
29
35
 
36
+ /** A media file or folder name as it can sit on disk. */
37
+ const fileName = (name: string) => name.replace(/[/\\:*?"<>|]+/g, '-').trim() || 'item'
38
+
30
39
  const bareKey = (key: string) => (/^[A-Za-z0-9_-]+$/.test(key) ? key : JSON.stringify(key))
31
40
 
32
41
  /** A value as TOML, inline. Nulls are left out: TOML has none. */
@@ -50,64 +59,347 @@ export function tomlValue(value: unknown): string | undefined {
50
59
  return JSON.stringify(String(value))
51
60
  }
52
61
 
62
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
63
+ typeof value === 'object' && value !== null && !Array.isArray(value)
64
+
53
65
  const PICKER = /^umb:\/\/document\/([0-9a-f]{32})$/i
54
66
  const dashed = (hex: string) =>
55
67
  `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
56
68
 
69
+ /** What a media item's own properties are, which its file stands for in a seed. */
70
+ const FILE_PROPERTIES = new Set([
71
+ 'umbracoFile',
72
+ 'umbracoWidth',
73
+ 'umbracoHeight',
74
+ 'umbracoBytes',
75
+ 'umbracoExtension',
76
+ ])
77
+
78
+ export interface SeedExportOptions {
79
+ /** The pages to export, each with every page below it. */
80
+ pages: readonly NodeRow[]
81
+ /** Every Library element too. */
82
+ library?: boolean
83
+ /** Every media item too, with its file. */
84
+ media?: boolean
85
+ /** Where media files are read from; media is exported without files when absent. */
86
+ files?: MediaFileStore
87
+ }
88
+
57
89
  export interface SeedExportResult {
58
90
  written: string[]
59
91
  }
60
92
 
61
- /** Writes the branches under `roots` as `seed/content/…` files in `siteDir`. */
62
93
  export async function exportSeed(
63
94
  db: Db,
64
95
  siteDir: string,
65
- roots: readonly NodeRow[],
96
+ options: SeedExportOptions,
66
97
  ): Promise<SeedExportResult> {
67
98
  const state = await currentSchemaState(db)
68
- const docs = new DocumentRepository(db, {
69
- nodeState: { version: state.version, revision: state.revision },
70
- })
99
+ const nodeState = { version: state.version, revision: state.revision }
100
+ const repos = {
101
+ content: new DocumentRepository(db, { nodeState }),
102
+ library: new DocumentRepository(db, { nodeState, kind: 'element' }),
103
+ media: new DocumentRepository(db, { nodeState, kind: 'media' }),
104
+ }
71
105
  const nodes = new NodeRepository(db)
106
+ const documentTypes = new ContentTypeRepository(db)
107
+ const mediaTypes = new ContentTypeRepository(db, { kind: 'media' })
108
+ const dataTypes = new DataTypeRepository(db)
109
+
72
110
  const typeAliases = new Map<string, string>()
73
111
  const aliasOf = async (typeKey: string) => {
74
- if (!typeAliases.has(typeKey)) {
112
+ const key = normaliseUuid(typeKey)
113
+ if (!typeAliases.has(key)) {
75
114
  const rows = await db.query<{ alias: string }>(
76
- `SELECT ct.alias FROM node n JOIN content_type ct ON ct.node_id = n.id WHERE n.unique_id = ?`,
77
- [normaliseUuid(typeKey)],
115
+ 'SELECT ct.alias FROM node n JOIN content_type ct ON ct.node_id = n.id WHERE n.unique_id = ?',
116
+ [key],
78
117
  )
79
- typeAliases.set(typeKey, rows[0] ? String(rows[0].alias) : typeKey)
118
+ typeAliases.set(key, rows[0] ? String(rows[0].alias) : typeKey)
80
119
  }
81
- return typeAliases.get(typeKey) as string
120
+ return typeAliases.get(key) as string
82
121
  }
83
-
84
- // Every node's seed path first, so a picker can name a page by where it lands.
85
- const pathOf = new Map<string, string>()
86
- const branch: Array<{ node: NodeRow; path: string; order: number }> = []
87
- const walk = async (node: NodeRow, parentPath: string | null, order: number) => {
88
- const taken = new Set(
89
- branch
90
- .filter((b) => b.path.startsWith(parentPath ? `${parentPath}/` : ''))
91
- .map((b) => b.path),
122
+ const editorCache = new Map<string, Map<string, string>>()
123
+ const editorsOf = async (typeKey: string, media = false) => {
124
+ const key = normaliseUuid(typeKey)
125
+ const cached = editorCache.get(key)
126
+ if (cached) return cached
127
+ const properties = await (media ? mediaTypes : documentTypes).resolveProperties(key)
128
+ const byType = new Map(
129
+ (await dataTypes.byKeys(properties.map((p) => p.dataTypeKey))).map((d) => [
130
+ d.key,
131
+ d.editorAlias,
132
+ ]),
92
133
  )
93
- let segment = segmentOf(node.text ?? node.key)
94
- for (let n = 2; taken.has(parentPath ? `${parentPath}/${segment}` : segment); n++)
95
- segment = `${segmentOf(node.text ?? node.key)}-${n}`
96
- const path = parentPath ? `${parentPath}/${segment}` : segment
97
- pathOf.set(node.key, path)
98
- branch.push({ node, path, order })
134
+ const out = new Map<string, string>()
135
+ for (const property of properties) {
136
+ const editor = byType.get(property.dataTypeKey)
137
+ if (editor) out.set(property.alias, editor)
138
+ }
139
+ editorCache.set(key, out)
140
+ return out
141
+ }
142
+
143
+ // --------------------------------------------------- every node's place
144
+ type Kind = 'content' | 'library' | 'media'
145
+ type Entry = { kind: Kind; node: NodeRow; path: string; order: number }
146
+ const entries: Entry[] = []
147
+ const pathOf = new Map<string, { kind: Kind; path: string }>()
148
+ const taken = new Set<string>()
149
+ const place = (kind: Kind, node: NodeRow, parent: string | null, order: number, base: string) => {
150
+ const dot = kind === 'media' ? base.lastIndexOf('.') : -1
151
+ let name = base
152
+ for (let n = 2; taken.has(`${kind}/${parent ? `${parent}/` : ''}${name}`); n++)
153
+ name = dot > 0 ? `${base.slice(0, dot)}-${n}${base.slice(dot)}` : `${base}-${n}`
154
+ const path = parent ? `${parent}/${name}` : name
155
+ taken.add(`${kind}/${path}`)
156
+ pathOf.set(normaliseUuid(node.key), { kind, path })
157
+ entries.push({ kind, node, path, order })
158
+ return path
159
+ }
160
+ const walkPages = async (node: NodeRow, parent: string | null, order: number) => {
161
+ const path = place('content', node, parent, order, segmentOf(node.text ?? node.key))
99
162
  const children = await nodes.children(node.id, ObjectTypes.Document, 0, Number.MAX_SAFE_INTEGER)
100
- for (const [index, child] of children.items.entries()) await walk(child, path, index)
163
+ for (const [index, child] of children.items.entries()) await walkPages(child, path, index)
164
+ }
165
+ for (const [index, root] of options.pages.entries()) await walkPages(root, null, index)
166
+
167
+ if (options.library) {
168
+ const roots = await nodes.children(-1, ObjectTypes.Element, 0, Number.MAX_SAFE_INTEGER)
169
+ for (const [index, element] of roots.items.entries())
170
+ place('library', element, null, index, segmentOf(element.text ?? element.key))
101
171
  }
102
- for (const [index, root] of roots.entries()) await walk(root, null, index)
103
172
 
173
+ const mediaFile = new Map<string, string>()
174
+ if (options.media) {
175
+ const walkMedia = async (parentId: number, parent: string | null) => {
176
+ const children = await nodes.children(parentId, ObjectTypes.Media, 0, Number.MAX_SAFE_INTEGER)
177
+ for (const [index, child] of children.items.entries()) {
178
+ const item = await repos.media.byKey(child.key)
179
+ const src = item ? mediaFileOf(item) : null
180
+ if (src) mediaFile.set(child.key, src)
181
+ const base = src
182
+ ? fileName(src.split('/').at(-1) as string)
183
+ : fileName(child.text ?? child.key)
184
+ const path = place('media', child, parent, index, base)
185
+ if (!src) await walkMedia(child.id, path)
186
+ }
187
+ }
188
+ await walkMedia(-1, null)
189
+ }
190
+
191
+ const where = (key: string, kind: Kind) => {
192
+ const found = pathOf.get(normaliseUuid(key))
193
+ return found && found.kind === kind ? found.path : undefined
194
+ }
195
+
196
+ // -------------------------------------------------- values, as shorthand
197
+ const shorthand = async (editor: string, value: unknown): Promise<unknown> => {
198
+ switch (editor) {
199
+ case 'Umbraco.RichText':
200
+ case 'Umbraco.TinyMCE':
201
+ return isRecord(value) && typeof value.markup === 'string' && value.blocks == null
202
+ ? { html: value.markup }
203
+ : value
204
+ case 'Umbraco.ContentPicker': {
205
+ const picked = typeof value === 'string' ? PICKER.exec(value) : null
206
+ if (!picked) return value
207
+ const key = dashed((picked[1] as string).toLowerCase())
208
+ const path = where(key, 'content')
209
+ return path ? `/${path}` : key
210
+ }
211
+ case 'Umbraco.MediaPicker3': {
212
+ if (!Array.isArray(value)) return value
213
+ const paths = value.map((pick) =>
214
+ isRecord(pick) &&
215
+ typeof pick.mediaKey === 'string' &&
216
+ pick.key === pickKey(pick.mediaKey) &&
217
+ Array.isArray(pick.crops) &&
218
+ pick.crops.length === 0 &&
219
+ pick.focalPoint == null
220
+ ? where(pick.mediaKey, 'media')
221
+ : undefined,
222
+ )
223
+ if (paths.length === 0 || paths.some((p) => p === undefined)) return value
224
+ const full = paths.map((p) => `/${p}`)
225
+ return full.length === 1 ? full[0] : full
226
+ }
227
+ case 'Umbraco.ElementPicker': {
228
+ if (!Array.isArray(value)) return value
229
+ const paths = value.map((key) =>
230
+ typeof key === 'string' ? where(key, 'library') : undefined,
231
+ )
232
+ if (paths.length === 0 || paths.some((p) => p === undefined)) return value
233
+ return paths.length === 1 ? paths[0] : paths
234
+ }
235
+ case 'Umbraco.MultiUrlPicker': {
236
+ if (!Array.isArray(value)) return value
237
+ return value.map((link) => {
238
+ if (!isRecord(link)) return link
239
+ const target = link.target ?? null
240
+ if (
241
+ link.type === 'document' &&
242
+ typeof link.unique === 'string' &&
243
+ target === null &&
244
+ !link.url &&
245
+ !link.queryString
246
+ ) {
247
+ const path = where(link.unique, 'content')
248
+ if (path && (link.name === '' || link.name == null)) return `/${path}`
249
+ if (path && typeof link.name === 'string') return { path: `/${path}`, name: link.name }
250
+ }
251
+ if (link.type === 'external' && typeof link.url === 'string' && target === null)
252
+ return { url: link.url, name: link.name ?? link.url }
253
+ return link
254
+ })
255
+ }
256
+ case 'Umbraco.BlockList':
257
+ case 'Umbraco.BlockGrid':
258
+ return blocks(editor, value)
259
+ default:
260
+ return value
261
+ }
262
+ }
263
+
264
+ /** Blocks as `{ type, key, values, settings }`, when their layout is plain enough to say so. */
265
+ const blocks = async (editor: string, value: unknown): Promise<unknown> => {
266
+ if (!isRecord(value) || !isRecord(value.layout) || !Array.isArray(value.contentData))
267
+ return value
268
+ const layout = value.layout[editor]
269
+ if (!Array.isArray(layout)) return value
270
+ const content = new Map(
271
+ (value.contentData as unknown[]).filter(isRecord).map((d) => [String(d.key), d]),
272
+ )
273
+ const settings = new Map(
274
+ ((value.settingsData as unknown[] | undefined) ?? [])
275
+ .filter(isRecord)
276
+ .map((d) => [String(d.key), d]),
277
+ )
278
+ const out: unknown[] = []
279
+ for (const item of layout) {
280
+ if (!isRecord(item)) return value
281
+ const data = content.get(String(item.contentKey))
282
+ if (!data || typeof data.contentTypeKey !== 'string') return value
283
+ if (editor === 'Umbraco.BlockGrid' && Array.isArray(item.areas) && item.areas.length > 0)
284
+ return value
285
+ const entry: Record<string, unknown> = {
286
+ type: await aliasOf(data.contentTypeKey),
287
+ key: item.contentKey,
288
+ values: await elementValues(data),
289
+ }
290
+ if (typeof item.settingsKey === 'string') {
291
+ const setting = settings.get(item.settingsKey)
292
+ if (!setting || typeof setting.contentTypeKey !== 'string') return value
293
+ entry.settings = {
294
+ type: await aliasOf(setting.contentTypeKey),
295
+ key: item.settingsKey,
296
+ values: await elementValues(setting),
297
+ }
298
+ }
299
+ if (editor === 'Umbraco.BlockGrid') {
300
+ entry.columns = item.columnSpan
301
+ entry.rows = item.rowSpan
302
+ }
303
+ out.push(entry)
304
+ }
305
+ return out
306
+ }
307
+
308
+ const elementValues = async (data: Record<string, unknown>) => {
309
+ const editors = await editorsOf(String(data.contentTypeKey))
310
+ const out: Record<string, unknown> = {}
311
+ for (const v of (data.values as unknown[] | undefined) ?? []) {
312
+ if (!isRecord(v) || typeof v.alias !== 'string') continue
313
+ const editor = editors.get(v.alias)
314
+ out[v.alias] = editor ? await shorthand(editor, v.value) : v.value
315
+ }
316
+ return out
317
+ }
318
+
319
+ // --------------------------------------------------------- the files
104
320
  const written: string[] = []
105
- for (const { node, path, order } of branch) {
106
- const doc = await docs.byKey(node.key)
321
+ const write = (relative: string, text: string) => {
322
+ const file = join(siteDir, 'seed', relative)
323
+ mkdirSync(join(file, '..'), { recursive: true })
324
+ writeFileSync(file, text)
325
+ written.push(`seed/${relative}`)
326
+ }
327
+ const valueLines = async (
328
+ values: ReadonlyArray<{
329
+ alias: string
330
+ culture: string | null
331
+ segment: string | null
332
+ value: unknown
333
+ }>,
334
+ editors: ReadonlyMap<string, string>,
335
+ ) => {
336
+ const byCulture = new Map<string | null, string[]>()
337
+ for (const v of values) {
338
+ if (v.segment !== null) continue
339
+ const value = await shorthand(editors.get(v.alias) ?? '', v.value)
340
+ const text = tomlValue(value)
341
+ if (text === undefined) continue
342
+ const list = byCulture.get(v.culture) ?? []
343
+ // A long list reads better an item to a line; TOML allows that for arrays.
344
+ list.push(
345
+ Array.isArray(value) && text.length > 100
346
+ ? `${bareKey(v.alias)} = [\n${value
347
+ .map(tomlValue)
348
+ .filter((item) => item !== undefined)
349
+ .map((item) => ` ${item},`)
350
+ .join('\n')}\n]`
351
+ : `${bareKey(v.alias)} = ${text}`,
352
+ )
353
+ byCulture.set(v.culture, list)
354
+ }
355
+ const lines: string[] = []
356
+ for (const [culture, list] of byCulture)
357
+ lines.push('', culture ? `[values.${bareKey(culture)}]` : '[values]', ...list)
358
+ return lines
359
+ }
360
+
361
+ for (const { kind, node, path, order } of entries) {
362
+ const doc = await repos[kind].byKey(node.key)
363
+ const derived = seedKey(`${kind}/${path}`)
364
+ const lines: string[] = []
365
+ if (kind === 'media') {
366
+ const src = mediaFile.get(node.key)
367
+ if (!src) {
368
+ // A folder: its directory says it, unless it has a name or key of its own.
369
+ mkdirSync(join(siteDir, 'seed', 'media', path), { recursive: true })
370
+ continue
371
+ }
372
+ const stored = options.files ? await options.files.open(src) : undefined
373
+ if (stored) {
374
+ const file = join(siteDir, 'seed', 'media', path)
375
+ mkdirSync(join(file, '..'), { recursive: true })
376
+ writeFileSync(file, await stored.bytes())
377
+ written.push(`seed/media/${path}`)
378
+ }
379
+ // A sidecar only for what the file cannot say.
380
+ if (normaliseUuid(node.key) !== derived) lines.push(`key = ${JSON.stringify(node.key)}`)
381
+ lines.push(`order = ${order}`)
382
+ const name = doc?.variants[0]?.name
383
+ if (name && name !== path.split('/').at(-1)) lines.push(`name = ${JSON.stringify(name)}`)
384
+ const file = doc?.values.find((v) => v.alias === 'umbracoFile')?.value
385
+ if (isRecord(file) && isRecord(file.focalPoint))
386
+ lines.push(`focalPoint = ${tomlValue(file.focalPoint)}`)
387
+ if (doc) {
388
+ const editors = await editorsOf(doc.contentTypeKey, true)
389
+ lines.push(
390
+ ...(await valueLines(
391
+ doc.values.filter((v) => !FILE_PROPERTIES.has(v.alias)),
392
+ editors,
393
+ )),
394
+ )
395
+ }
396
+ if (lines.length > 0) write(`media/${path}.toml`, `${lines.join('\n')}\n`)
397
+ continue
398
+ }
399
+
107
400
  if (!doc) continue
108
- const lines: string[] = [`type = ${JSON.stringify(await aliasOf(doc.contentTypeKey))}`]
109
- if (normaliseUuid(node.key) !== seedKey(`content/${path}`))
110
- lines.push(`key = ${JSON.stringify(node.key)}`)
401
+ lines.push(`type = ${JSON.stringify(await aliasOf(doc.contentTypeKey))}`)
402
+ if (normaliseUuid(node.key) !== derived) lines.push(`key = ${JSON.stringify(node.key)}`)
111
403
  const invariant = doc.variants.find((v) => v.culture === null)
112
404
  if (invariant) lines.push(`name = ${JSON.stringify(invariant.name)}`)
113
405
  else
@@ -117,33 +409,8 @@ export async function exportSeed(
117
409
  lines.push(`order = ${order}`)
118
410
  if (!doc.variants.some((v) => v.state === 'Published' || v.state === 'PublishedPendingChanges'))
119
411
  lines.push('published = false')
120
-
121
- const value = (raw: unknown) => {
122
- if (typeof raw === 'string') {
123
- const picked = PICKER.exec(raw)
124
- if (picked) {
125
- const key = dashed((picked[1] as string).toLowerCase())
126
- return pathOf.has(key) ? `/${pathOf.get(key)}` : key
127
- }
128
- }
129
- return raw
130
- }
131
- const byCulture = new Map<string | null, string[]>()
132
- for (const v of doc.values) {
133
- if (v.segment !== null) continue
134
- const written = tomlValue(value(v.value))
135
- if (written === undefined) continue
136
- const list = byCulture.get(v.culture) ?? []
137
- list.push(`${bareKey(v.alias)} = ${written}`)
138
- byCulture.set(v.culture, list)
139
- }
140
- for (const [culture, entries] of byCulture) {
141
- lines.push('', culture ? `[values.${bareKey(culture)}]` : '[values]', ...entries)
142
- }
143
- const file = join(siteDir, 'seed', 'content', `${path}.toml`)
144
- mkdirSync(join(file, '..'), { recursive: true })
145
- writeFileSync(file, `${lines.join('\n')}\n`)
146
- written.push(`seed/content/${path}.toml`)
412
+ lines.push(...(await valueLines(doc.values, await editorsOf(doc.contentTypeKey))))
413
+ write(`${kind}/${path}.toml`, `${lines.join('\n')}\n`)
147
414
  }
148
415
  return { written }
149
416
  }
package/src/seed/keys.ts CHANGED
@@ -4,24 +4,32 @@
4
4
  * sites built from the same seed share keys.
5
5
  */
6
6
  import { createHash } from 'node:crypto'
7
+ import { SEED_NAMESPACE, uuidV5 } from '@crombolo/core'
7
8
 
8
- /** Crombolo's seed namespace. Fixed for ever: changing it re-keys every seeded node. */
9
- export const SEED_NAMESPACE = '6f1d3c0e-7a52-4b8e-9c41-2e5f8a1b7d63'
10
-
11
- const bytesOf = (uuid: string) => Buffer.from(uuid.replaceAll('-', ''), 'hex')
12
-
13
- /** A version 5 uuid for `name` in `namespace`. Pure. */
14
- export function uuidV5(name: string, namespace = SEED_NAMESPACE): string {
15
- const hash = createHash('sha1').update(bytesOf(namespace)).update(name, 'utf8').digest()
16
- const bytes = hash.subarray(0, 16)
17
- bytes[6] = ((bytes[6] as number) & 0x0f) | 0x50
18
- bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80
19
- const hex = bytes.toString('hex')
20
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
21
- }
9
+ export { SEED_NAMESPACE, uuidV5 }
22
10
 
23
11
  /** The key a seed item has when its file gives none: `content/about/team`, `media/logos/mark.png`. */
24
- export const seedKey = (path: string) => uuidV5(path)
12
+ export const seedKey = (path: string) => uuidV5(path, SEED_NAMESPACE)
25
13
 
26
14
  /** The key of a block inside an item's value: stable for the item, the property and the position. */
27
- export const blockKey = (owner: string, where: string) => uuidV5(`${owner}#${where}`)
15
+ export const blockKey = (owner: string, where: string) =>
16
+ uuidV5(`${owner}#${where}`, SEED_NAMESPACE)
17
+
18
+ /**
19
+ * A media picker item's own key: a uuid-shaped sha256 of the media key, the
20
+ * formula the demo sites' pickers have always used, so a seed reproduces them.
21
+ */
22
+ export function pickKey(mediaKey: string): string {
23
+ const hex = createHash('sha256')
24
+ .update(`pick:${normaliseKey(mediaKey)}`)
25
+ .digest('hex')
26
+ return [
27
+ hex.slice(0, 8),
28
+ hex.slice(8, 12),
29
+ `4${hex.slice(13, 16)}`,
30
+ `8${hex.slice(17, 20)}`,
31
+ hex.slice(20, 32),
32
+ ].join('-')
33
+ }
34
+
35
+ const normaliseKey = (key: string) => key.toLowerCase()
package/src/server.ts CHANGED
@@ -122,6 +122,7 @@ import { createPublishedContentSource, loadDraftNode } from './adapters/document
122
122
  import type { Approvals } from './approvals.ts'
123
123
  import { handleApprovalsApi } from './approvals-api.ts'
124
124
  import { CommandError, installBundleContent } from './bundle-install.ts'
125
+ import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
125
126
  import { bundleChains, bundleTablesReport } from './bundle-tables.ts'
126
127
  import { createBundleRedirects, createServerBundles, validateServerBundles } from './bundles.ts'
127
128
  import { busyResponse } from './busy.ts'
@@ -270,6 +271,12 @@ export interface ServerHandle {
270
271
  }
271
272
  /** Scheduled publishing and version cleanup; each run can be called directly. */
272
273
  jobs: BackgroundJobs
274
+ /**
275
+ * Reads the site's `package.json` and `node_modules` again, after a host has
276
+ * changed them (story 181), and says what changed. Back-office halves only:
277
+ * nothing is mounted, and a `web` node, which serves no back office, does nothing.
278
+ */
279
+ reloadBundles(): Promise<BundleReload>
273
280
  /** Stops the watcher and the poll, then closes the database. */
274
281
  close(): Promise<void>
275
282
  }
@@ -301,17 +308,26 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
301
308
  // Extensions are the site's own npm dependencies (`docs/bundles.md`).
302
309
  // Uncached in development so an author editing one sees a reload pick it up.
303
310
  const extensions = createExtensionRegistry(config.siteDir, { cache: !config.development })
311
+ // A host that installs packages itself calls `reloadBundles()` (story 181); the
312
+ // Marketplace's own install goes through it too, so either way open back
313
+ // offices hear about it. `events` is created further down, before any reload.
314
+ const bundleReloader = createBundleReloader({
315
+ extensions,
316
+ wired: () => bundles?.mounted.map((bundle) => bundle.id) ?? [],
317
+ changed: () => events.broadcast('notify', [BUNDLES_CHANGED_EVENT]),
318
+ })
304
319
  const marketplace = createMarketplace({
305
320
  registry: config.npmRegistry,
306
321
  keyword: config.packageKeyword,
307
322
  marketplaceUrl: config.marketplaceUrl,
308
- extensions,
323
+ extensions: { ...extensions, invalidate: () => void bundleReloader.reload() },
309
324
  siteDir: config.siteDir,
310
325
  wired: () => bundles?.mounted.map((bundle) => bundle.id) ?? [],
311
326
  contentApplied: async (packageName) =>
312
327
  (await new TransferRunRepository(db).appliedForPackage(packageName))?.packageVersion ?? null,
313
328
  applyContentOnInstall: config.applyBundleContentOnInstall,
314
329
  installs: config.runtimeInstalls,
330
+ installsElsewhere: config.installsElsewhere,
315
331
  applyContent: async (packageName) => {
316
332
  // A package from the marketplace is for anyone, so nothing in it can be
317
333
  // sealed; one that is is refused rather than half applied.
@@ -1438,6 +1454,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1438
1454
  keyword: config.packageKeyword,
1439
1455
  appliesContent: config.applyBundleContentOnInstall,
1440
1456
  installs: config.runtimeInstalls,
1457
+ installsElsewhere: config.runtimeInstalls ? null : (config.installsElsewhere ?? null),
1441
1458
  items: await marketplace.search(url.searchParams.get('q') ?? undefined),
1442
1459
  })
1443
1460
  }
@@ -1461,6 +1478,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1461
1478
  if (action === 'installed' && request.method === 'GET') {
1462
1479
  return Response.json({
1463
1480
  installs: config.runtimeInstalls,
1481
+ installsElsewhere: config.runtimeInstalls ? null : (config.installsElsewhere ?? null),
1464
1482
  items: await marketplace.installed(),
1465
1483
  })
1466
1484
  }
@@ -2492,6 +2510,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2492
2510
  health,
2493
2511
  events,
2494
2512
  jobs,
2513
+ reloadBundles: async () =>
2514
+ servesBackOffice
2515
+ ? bundleReloader.reload()
2516
+ : { added: [], removed: [], changed: [], problems: [] },
2495
2517
  serveOptions: {
2496
2518
  port: config.port,
2497
2519
  maxRequestBodySize: listeningBodyLimit(config),
package/src/settings.ts CHANGED
@@ -306,6 +306,19 @@ const DECLARED = [
306
306
  description:
307
307
  'The Packages section installs and removes packages on the running site. Off, they are added to `package.json` and deployed.',
308
308
  },
309
+ {
310
+ env: 'CROMBOLO_INSTALLS_ELSEWHERE_MESSAGE',
311
+ kind: 'string',
312
+ section: 'Back office and bundles',
313
+ description:
314
+ 'With runtime installs off, what the Marketplace says about where bundles are added, in place of "add it to package.json and deploy". For a host that installs them itself.',
315
+ },
316
+ {
317
+ env: 'CROMBOLO_INSTALLS_ELSEWHERE_URL',
318
+ kind: 'string',
319
+ section: 'Back office and bundles',
320
+ description: 'A link shown with that message: the host’s own place for installing bundles.',
321
+ },
309
322
  {
310
323
  env: 'CROMBOLO_MARKETPLACE_URL',
311
324
  kind: 'string',