@crombolo/server 0.45.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.
@@ -0,0 +1,509 @@
1
+ /**
2
+ * Values in the shorthand a person writes, both ways (stories 163, 253):
3
+ * Markdown, paths and `{ type, alias, values }` blocks into each property
4
+ * editor's stored shape, as `bundle apply` reads content files and the
5
+ * `content` commands read `--set`; and stored values back into that shorthand,
6
+ * as `bundle export --source` and `content show` write them.
7
+ */
8
+ import { type ContentTypeAggregate, normaliseUuid } from '@crombolo/core'
9
+ import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
10
+ import { blockKey, pickKey } from './keys.ts'
11
+
12
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
13
+ typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
14
+
15
+ const BLOCK_LAYOUT = {
16
+ 'Umbraco.BlockList': 'Umbraco.BlockList',
17
+ 'Umbraco.BlockGrid': 'Umbraco.BlockGrid',
18
+ } as const
19
+
20
+ /** A block's alias: a name a view or a command picks it out by (story 253). */
21
+ export const BLOCK_ALIAS = /^[A-Za-z][A-Za-z0-9_-]*$/
22
+
23
+ export type Converted = { ok: true; value: unknown } | { ok: false; message: string }
24
+ const fail = (message: string): Converted => ({ ok: false, message })
25
+
26
+ export interface PropertyEditor {
27
+ editor: string
28
+ variesByCulture: boolean
29
+ /** The data type's settings, by alias: a block list's `blocks`, say. */
30
+ config: Record<string, unknown>
31
+ }
32
+
33
+ /** The site's types and their properties' editors, looked up once each. */
34
+ export function schemaLookup(db: Db) {
35
+ const repos = {
36
+ document: new ContentTypeRepository(db),
37
+ media: new ContentTypeRepository(db, { kind: 'media' }),
38
+ }
39
+ const dataTypes = new DataTypeRepository(db)
40
+ const types = new Map<string, ContentTypeAggregate | undefined>()
41
+ const editors = new Map<string, Map<string, PropertyEditor>>()
42
+ return {
43
+ repos,
44
+ async typeOf(kind: 'document' | 'media', alias: string) {
45
+ const key = `${kind}:${alias.toLowerCase()}`
46
+ if (!types.has(key)) types.set(key, await repos[kind].byAlias(alias))
47
+ return types.get(key)
48
+ },
49
+ async typeByKey(kind: 'document' | 'media', typeKey: string) {
50
+ return repos[kind].byKey(normaliseUuid(typeKey))
51
+ },
52
+ async editorsOf(
53
+ kind: 'document' | 'media',
54
+ type: Pick<ContentTypeAggregate, 'key'>,
55
+ ): Promise<Map<string, PropertyEditor>> {
56
+ const cached = editors.get(type.key)
57
+ if (cached) return cached
58
+ const properties = await repos[kind].resolveProperties(type.key)
59
+ const byKey = new Map(
60
+ (await dataTypes.byKeys(properties.map((p) => p.dataTypeKey))).map((d) => [d.key, d]),
61
+ )
62
+ const out = new Map<string, PropertyEditor>()
63
+ for (const property of properties) {
64
+ const dataType = byKey.get(property.dataTypeKey)
65
+ if (dataType)
66
+ out.set(property.alias, {
67
+ editor: dataType.editorAlias,
68
+ variesByCulture: property.variesByCulture,
69
+ config: Object.fromEntries(dataType.values.map((v) => [v.alias, v.value])),
70
+ })
71
+ }
72
+ editors.set(type.key, out)
73
+ return out
74
+ },
75
+ }
76
+ }
77
+
78
+ export type SchemaLookup = ReturnType<typeof schemaLookup>
79
+
80
+ /** What a value's paths name: pages, media and Library elements. */
81
+ export interface ValueRefs {
82
+ content(ref: string, why: string): Promise<string | undefined>
83
+ media(ref: string, why: string): Promise<{ key: string; typeAlias: string } | undefined>
84
+ library(ref: string, why: string): Promise<string | undefined>
85
+ /** A link's path as media, before it is tried as a page. */
86
+ linkedMedia(ref: string): Promise<string | undefined>
87
+ }
88
+
89
+ /** The shorthand into each editor's stored shape. */
90
+ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
91
+ const trimPath = (ref: string) => ref.replace(/^\/+|\/+$/g, '')
92
+
93
+ /** Rich text: Markdown by default, `{ html = … }` as written; links to content paths become local links. */
94
+ const richText = async (raw: unknown, why: string): Promise<Converted> => {
95
+ let html: string
96
+ // HTML is taken exactly as written; only Markdown's links are made local.
97
+ if (isRecord(raw) && typeof raw.html === 'string')
98
+ return { ok: true, value: { markup: raw.html, blocks: null } }
99
+ if (typeof raw === 'string') html = Bun.markdown.html(raw)
100
+ else if (isRecord(raw) && typeof raw.markdown === 'string')
101
+ html = Bun.markdown.html(raw.markdown)
102
+ else if (isRecord(raw) && 'markup' in raw) return { ok: true, value: raw }
103
+ else return fail('rich text is Markdown, or { html = "…" }')
104
+ const links = [...html.matchAll(/href="(\/[^"#?]*)"/g)]
105
+ for (const [whole, path] of links) {
106
+ const key = await refs.content(path as string, why)
107
+ if (key) html = html.replace(whole, `href="/{localLink:${key}}"`)
108
+ }
109
+ return { ok: true, value: { markup: html, blocks: null } }
110
+ }
111
+
112
+ const element = async (
113
+ entry: Record<string, unknown>,
114
+ owner: string,
115
+ where: string,
116
+ what: string,
117
+ ): Promise<{ ok: true; data: Record<string, unknown> } | { ok: false; message: string }> => {
118
+ const type =
119
+ typeof entry.type === 'string' ? await lookup.typeOf('document', entry.type) : undefined
120
+ if (!type?.isElement)
121
+ return {
122
+ ok: false,
123
+ message:
124
+ typeof entry.type === 'string'
125
+ ? `${what}: there is no element type "${entry.type}"`
126
+ : `${what} has no type`,
127
+ }
128
+ const key =
129
+ typeof entry.key === 'string' && looksLikeKey(entry.key)
130
+ ? normaliseUuid(entry.key)
131
+ : blockKey(owner, where)
132
+ const values = await elementValues(type, entry.values, owner, where)
133
+ if (!values.ok) return { ok: false, message: `${what}: ${values.message}` }
134
+ return { ok: true, data: { key, contentTypeKey: type.key, values: values.value } }
135
+ }
136
+
137
+ const blocks = async (
138
+ editor: keyof typeof BLOCK_LAYOUT,
139
+ raw: unknown,
140
+ owner: string,
141
+ where: string,
142
+ ): Promise<Converted> => {
143
+ if (!Array.isArray(raw)) {
144
+ if (isRecord(raw) && 'layout' in raw) return { ok: true, value: raw }
145
+ return fail('blocks are a list of { type = "<element alias>", values = { … } }')
146
+ }
147
+ const layout: Record<string, unknown>[] = []
148
+ const contentData: unknown[] = []
149
+ const settingsData: unknown[] = []
150
+ const aliases = new Set<string>()
151
+ for (const [index, entry] of raw.entries()) {
152
+ if (!isRecord(entry)) return fail(`block ${index + 1} has no type`)
153
+ const content = await element(entry, owner, `${where}/${index}`, `block ${index + 1}`)
154
+ if (!content.ok) return fail(content.message)
155
+ contentData.push(content.data)
156
+ const item: Record<string, unknown> = { contentKey: content.data.key }
157
+ if (entry.alias !== undefined) {
158
+ if (typeof entry.alias !== 'string' || !BLOCK_ALIAS.test(entry.alias))
159
+ return fail(
160
+ `block ${index + 1}: an alias is letters, digits, - and _, starting with a letter`,
161
+ )
162
+ if (aliases.has(entry.alias.toLowerCase()))
163
+ return fail(`two blocks are called "${entry.alias}"`)
164
+ aliases.add(entry.alias.toLowerCase())
165
+ item.alias = entry.alias
166
+ }
167
+ if (isRecord(entry.settings)) {
168
+ const settings = await element(
169
+ entry.settings,
170
+ owner,
171
+ `${where}/${index}/settings`,
172
+ `block ${index + 1} settings`,
173
+ )
174
+ if (!settings.ok) return fail(settings.message)
175
+ settingsData.push(settings.data)
176
+ item.settingsKey = settings.data.key
177
+ }
178
+ if (editor === 'Umbraco.BlockGrid') {
179
+ item.columnSpan = typeof entry.columns === 'number' ? entry.columns : 12
180
+ item.rowSpan = typeof entry.rows === 'number' ? entry.rows : 1
181
+ item.areas = Array.isArray(entry.areas) ? entry.areas : []
182
+ }
183
+ layout.push(item)
184
+ }
185
+ return {
186
+ ok: true,
187
+ value: { layout: { [BLOCK_LAYOUT[editor]]: layout }, contentData, settingsData },
188
+ }
189
+ }
190
+
191
+ const elementValues = async (
192
+ type: ContentTypeAggregate,
193
+ raw: unknown,
194
+ owner: string,
195
+ where: string,
196
+ ): Promise<Converted> => {
197
+ if (raw === undefined) return { ok: true, value: [] }
198
+ if (!isRecord(raw)) return fail('values is a table')
199
+ const editors = await lookup.editorsOf('document', type)
200
+ const out: Array<{ alias: string; editorAlias: string; value: unknown }> = []
201
+ for (const [alias, value] of Object.entries(raw)) {
202
+ const property = editors.get(alias)
203
+ if (!property) return fail(`"${type.alias}" has no property "${alias}"`)
204
+ const converted = await convert(property.editor, value, owner, `${where}/${alias}`)
205
+ if (!converted.ok) return fail(`${alias}: ${converted.message}`)
206
+ out.push({ alias, editorAlias: property.editor, value: converted.value })
207
+ }
208
+ return { ok: true, value: out }
209
+ }
210
+
211
+ const list = (raw: unknown) => (Array.isArray(raw) ? raw : [raw])
212
+
213
+ const convert = async (
214
+ editor: string,
215
+ raw: unknown,
216
+ owner: string,
217
+ where: string,
218
+ ): Promise<Converted> => {
219
+ const why = `named by a value in ${where}`
220
+ switch (editor) {
221
+ case 'Umbraco.TextBox':
222
+ case 'Umbraco.TextArea':
223
+ return typeof raw === 'string' || typeof raw === 'number'
224
+ ? { ok: true, value: String(raw) }
225
+ : fail('a text value is a string')
226
+ case 'Umbraco.RichText':
227
+ case 'Umbraco.TinyMCE':
228
+ return richText(raw, why)
229
+ case 'Umbraco.TrueFalse':
230
+ return typeof raw === 'boolean'
231
+ ? { ok: true, value: raw }
232
+ : fail('a toggle is true or false')
233
+ case 'Umbraco.Integer':
234
+ case 'Umbraco.Decimal':
235
+ case 'Umbraco.Slider':
236
+ return typeof raw === 'number' ? { ok: true, value: raw } : fail('a number is a number')
237
+ case 'Umbraco.DateTime':
238
+ case 'Umbraco.DateTimeWithTimeZone': {
239
+ // Bun's TOML gives a Temporal value (a PlainDate, an Instant) for a TOML
240
+ // date, which writes itself as ISO 8601.
241
+ const text =
242
+ raw instanceof Date
243
+ ? raw.toISOString()
244
+ : isTemporalDate(raw)
245
+ ? String(raw)
246
+ : typeof raw === 'string'
247
+ ? raw
248
+ : undefined
249
+ const at = text === undefined ? Number.NaN : new Date(text).getTime()
250
+ if (text === undefined || Number.isNaN(at))
251
+ return fail('a date is a TOML date or an ISO 8601 string')
252
+ // A date picker stores Umbraco's wall clock, as a save does, so a seed
253
+ // exported and applied again is unchanged; one with a zone keeps ISO.
254
+ return {
255
+ ok: true,
256
+ value:
257
+ editor === 'Umbraco.DateTime'
258
+ ? new Date(at).toISOString().slice(0, 19).replace('T', ' ')
259
+ : text,
260
+ }
261
+ }
262
+ case 'Umbraco.Tags':
263
+ return list(raw).every((tag) => typeof tag === 'string')
264
+ ? { ok: true, value: list(raw) }
265
+ : fail('tags are a list of strings')
266
+ case 'Umbraco.ContentPicker': {
267
+ if (typeof raw !== 'string') return fail('a content picker takes a content path')
268
+ const key = await refs.content(raw, why)
269
+ return key
270
+ ? { ok: true, value: `umb://document/${key.replaceAll('-', '')}` }
271
+ : fail(`"${raw}" is not a page in the content files or on the site`)
272
+ }
273
+ case 'Umbraco.MediaPicker3': {
274
+ if (isRecord(raw) || (Array.isArray(raw) && raw.some(isRecord)))
275
+ return { ok: true, value: raw }
276
+ const picks: unknown[] = []
277
+ for (const ref of list(raw)) {
278
+ if (typeof ref !== 'string') return fail('a media picker takes media paths')
279
+ const media = await refs.media(ref, why)
280
+ if (!media) return fail(`"${ref}" is not media in the content files or on the site`)
281
+ picks.push({
282
+ key: pickKey(media.key),
283
+ mediaKey: media.key,
284
+ mediaTypeAlias: media.typeAlias,
285
+ crops: [],
286
+ focalPoint: null,
287
+ })
288
+ }
289
+ return { ok: true, value: picks }
290
+ }
291
+ case 'Umbraco.ElementPicker': {
292
+ const keys: string[] = []
293
+ for (const ref of list(raw)) {
294
+ if (typeof ref !== 'string') return fail('an element picker takes Library paths')
295
+ const key = await refs.library(ref, why)
296
+ if (!key)
297
+ return fail(`"${ref}" is not a Library element in the content files or on the site`)
298
+ keys.push(key)
299
+ }
300
+ return { ok: true, value: keys }
301
+ }
302
+ case 'Umbraco.MultiUrlPicker': {
303
+ const links: unknown[] = []
304
+ for (const entry of list(raw)) {
305
+ const link = typeof entry === 'string' ? { path: entry } : entry
306
+ if (!isRecord(link))
307
+ return fail('a link is a path, a URL, or { path | url, name, target }')
308
+ // A link as the editor stores it, as `bundle export --source` writes one.
309
+ if ('unique' in link || 'type' in link) {
310
+ links.push(link)
311
+ continue
312
+ }
313
+ const target = typeof link.target === 'string' ? link.target : null
314
+ const url = typeof link.url === 'string' ? link.url : undefined
315
+ const path = typeof link.path === 'string' ? link.path : undefined
316
+ if (path && /^[a-z]+:\/\//i.test(path)) {
317
+ links.push({
318
+ unique: null,
319
+ type: 'external',
320
+ name: link.name ?? path,
321
+ target,
322
+ url: path,
323
+ })
324
+ continue
325
+ }
326
+ if (url) {
327
+ links.push({ unique: null, type: 'external', name: link.name ?? url, target, url })
328
+ continue
329
+ }
330
+ if (!path) return fail('a link needs a path or a url')
331
+ const media = await refs.linkedMedia(trimPath(path))
332
+ const key = media ?? (await refs.content(path, why))
333
+ if (!key)
334
+ return fail(`"${path}" is not a page or media in the content files or on the site`)
335
+ links.push({
336
+ unique: key,
337
+ type: media ? 'media' : 'document',
338
+ name: typeof link.name === 'string' ? link.name : '',
339
+ target,
340
+ })
341
+ }
342
+ return { ok: true, value: links }
343
+ }
344
+ case 'Umbraco.BlockList':
345
+ case 'Umbraco.BlockGrid':
346
+ return blocks(editor, raw, owner, where)
347
+ default:
348
+ return { ok: true, value: raw }
349
+ }
350
+ }
351
+
352
+ return { convert, elementValues }
353
+ }
354
+
355
+ const PICKER = /^umb:\/\/document\/([0-9a-f]{32})$/i
356
+ const dashed = (hex: string) =>
357
+ `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
358
+
359
+ export type PathKind = 'content' | 'library' | 'media'
360
+
361
+ /**
362
+ * Each editor's stored shape back into the shorthand, where `where` names the
363
+ * path a key has; a value with no plain shorthand stays as it is stored.
364
+ */
365
+ export function shorthandReader(
366
+ lookup: SchemaLookup,
367
+ aliasOf: (typeKey: string) => Promise<string>,
368
+ where: (key: string, kind: PathKind) => string | undefined | Promise<string | undefined>,
369
+ ) {
370
+ const shorthand = async (editor: string, value: unknown): Promise<unknown> => {
371
+ switch (editor) {
372
+ case 'Umbraco.RichText':
373
+ case 'Umbraco.TinyMCE':
374
+ return isRecord(value) && typeof value.markup === 'string' && value.blocks == null
375
+ ? { html: value.markup }
376
+ : value
377
+ case 'Umbraco.ContentPicker': {
378
+ const picked = typeof value === 'string' ? PICKER.exec(value) : null
379
+ if (!picked) return value
380
+ const key = dashed((picked[1] as string).toLowerCase())
381
+ const path = await where(key, 'content')
382
+ return path ? `/${path}` : key
383
+ }
384
+ case 'Umbraco.MediaPicker3': {
385
+ if (!Array.isArray(value)) return value
386
+ const paths = await Promise.all(
387
+ value.map((pick) =>
388
+ isRecord(pick) &&
389
+ typeof pick.mediaKey === 'string' &&
390
+ pick.key === pickKey(pick.mediaKey) &&
391
+ Array.isArray(pick.crops) &&
392
+ pick.crops.length === 0 &&
393
+ pick.focalPoint == null
394
+ ? where(pick.mediaKey, 'media')
395
+ : undefined,
396
+ ),
397
+ )
398
+ if (paths.length === 0 || paths.some((p) => p === undefined)) return value
399
+ const full = paths.map((p) => `/${p}`)
400
+ return full.length === 1 ? full[0] : full
401
+ }
402
+ case 'Umbraco.ElementPicker': {
403
+ if (!Array.isArray(value)) return value
404
+ const paths = await Promise.all(
405
+ value.map((key) => (typeof key === 'string' ? where(key, 'library') : undefined)),
406
+ )
407
+ if (paths.length === 0 || paths.some((p) => p === undefined)) return value
408
+ return paths.length === 1 ? paths[0] : paths
409
+ }
410
+ case 'Umbraco.MultiUrlPicker': {
411
+ if (!Array.isArray(value)) return value
412
+ const out: unknown[] = []
413
+ for (const link of value) out.push(await linkShorthand(link))
414
+ return out
415
+ }
416
+ case 'Umbraco.BlockList':
417
+ case 'Umbraco.BlockGrid':
418
+ return blocks(editor, value)
419
+ default:
420
+ return value
421
+ }
422
+ }
423
+
424
+ const linkShorthand = async (link: unknown): Promise<unknown> => {
425
+ if (!isRecord(link)) return link
426
+ const target = link.target ?? null
427
+ if (
428
+ link.type === 'document' &&
429
+ typeof link.unique === 'string' &&
430
+ target === null &&
431
+ !link.url &&
432
+ !link.queryString
433
+ ) {
434
+ const path = await where(link.unique, 'content')
435
+ if (path && (link.name === '' || link.name == null)) return `/${path}`
436
+ if (path && typeof link.name === 'string') return { path: `/${path}`, name: link.name }
437
+ }
438
+ if (link.type === 'external' && typeof link.url === 'string' && target === null)
439
+ return { url: link.url, name: link.name ?? link.url }
440
+ return link
441
+ }
442
+
443
+ /** Blocks as `{ type, alias, key, values, settings }`, when their layout is plain enough to say so. */
444
+ const blocks = async (editor: string, value: unknown): Promise<unknown> => {
445
+ if (!isRecord(value) || !isRecord(value.layout) || !Array.isArray(value.contentData))
446
+ return value
447
+ const layout = value.layout[editor]
448
+ if (!Array.isArray(layout)) return value
449
+ const content = new Map(
450
+ (value.contentData as unknown[]).filter(isRecord).map((d) => [String(d.key), d]),
451
+ )
452
+ const settings = new Map(
453
+ ((value.settingsData as unknown[] | undefined) ?? [])
454
+ .filter(isRecord)
455
+ .map((d) => [String(d.key), d]),
456
+ )
457
+ const out: unknown[] = []
458
+ for (const item of layout) {
459
+ if (!isRecord(item)) return value
460
+ const data = content.get(String(item.contentKey))
461
+ if (!data || typeof data.contentTypeKey !== 'string') return value
462
+ if (editor === 'Umbraco.BlockGrid' && Array.isArray(item.areas) && item.areas.length > 0)
463
+ return value
464
+ const entry: Record<string, unknown> = {
465
+ type: await aliasOf(data.contentTypeKey),
466
+ ...(typeof item.alias === 'string' ? { alias: item.alias } : {}),
467
+ key: item.contentKey,
468
+ values: await elementValues(data),
469
+ }
470
+ if (typeof item.settingsKey === 'string') {
471
+ const setting = settings.get(item.settingsKey)
472
+ if (!setting || typeof setting.contentTypeKey !== 'string') return value
473
+ entry.settings = {
474
+ type: await aliasOf(setting.contentTypeKey),
475
+ key: item.settingsKey,
476
+ values: await elementValues(setting),
477
+ }
478
+ }
479
+ if (editor === 'Umbraco.BlockGrid') {
480
+ entry.columns = item.columnSpan
481
+ entry.rows = item.rowSpan
482
+ }
483
+ out.push(entry)
484
+ }
485
+ return out
486
+ }
487
+
488
+ const elementValues = async (data: Record<string, unknown>) => {
489
+ const editors = await lookup.editorsOf('document', {
490
+ key: normaliseUuid(String(data.contentTypeKey)),
491
+ })
492
+ const out: Record<string, unknown> = {}
493
+ for (const v of (data.values as unknown[] | undefined) ?? []) {
494
+ if (!isRecord(v) || typeof v.alias !== 'string') continue
495
+ const editor = editors.get(v.alias)?.editor
496
+ out[v.alias] = editor ? await shorthand(editor, v.value) : v.value
497
+ }
498
+ return out
499
+ }
500
+
501
+ return { shorthand, elementValues }
502
+ }
503
+
504
+ /** A TOML date as Bun's parser gives it: a Temporal value whose ISO form is a date. */
505
+ function isTemporalDate(raw: unknown): boolean {
506
+ if (typeof raw !== 'object' || raw === null || raw instanceof Date) return false
507
+ const text = String(raw)
508
+ return /^\d{4}-\d{2}-\d{2}/.test(text) && !Number.isNaN(new Date(text).getTime())
509
+ }
package/src/server.ts CHANGED
@@ -234,7 +234,7 @@ import {
234
234
  requestCookies,
235
235
  runStage,
236
236
  } from './middleware.ts'
237
- import type { JobRunner } from './owner-jobs.ts'
237
+ import { CORE_JOB_OWNER, type JobRunner } from './owner-jobs.ts'
238
238
  import { callerAddress } from './rate-limit.ts'
239
239
  import { syncConfiguredRedirects } from './redirects.ts'
240
240
  import { createRoutes, type DeclaredRoute, siteRouteProblems } from './routes.ts'
@@ -1208,6 +1208,9 @@ export async function createServer(
1208
1208
  // credentials anywhere near it.
1209
1209
  const auditPath = `${paths.pluginPath}/api/audit`
1210
1210
  const jobsPath = `${paths.pluginPath}/api/jobs`
1211
+ const mediaJobsPath = `${paths.pluginPath}/api/media-jobs`
1212
+ /** What an open back office hears when a media change is queued (story 246); its key is the job's id. */
1213
+ const MEDIA_JOB_QUEUED_EVENT = { eventSource: 'Crombolo:MediaJob', eventType: 'Queued' } as const
1211
1214
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1212
1215
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1213
1216
  const bundleInstallPaths = new Set(
@@ -1307,6 +1310,10 @@ export async function createServer(
1307
1310
  const response = await serveBackOffice(request, url)
1308
1311
  if (response) {
1309
1312
  if (response.ok) await auditPluginWrite(request, pathname)
1313
+ // A media change too large for the request is queued (story 246): open back
1314
+ // offices hear its id from the node that took it, wherever the job runs.
1315
+ const job = response.headers.get('crombolo-job')
1316
+ if (job) events.broadcast('notify', [{ ...MEDIA_JOB_QUEUED_EVENT, key: job }])
1310
1317
  return response
1311
1318
  }
1312
1319
  }
@@ -1325,25 +1332,13 @@ export async function createServer(
1325
1332
  }
1326
1333
 
1327
1334
  // Islands (story 209): the loader, and each generation's browser code.
1328
- if (pathname === ISLAND_LOADER_PATH)
1329
- return new Response(ISLAND_LOADER_SCRIPT, {
1330
- headers: {
1331
- 'content-type': 'text/javascript; charset=utf-8',
1332
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1333
- },
1334
- })
1335
+ if (pathname === ISLAND_LOADER_PATH) return siteScript(ISLAND_LOADER_SCRIPT)
1335
1336
  if (pathname.startsWith(`${ISLANDS_PATH}/`))
1336
1337
  return islandFile(pathname.slice(ISLANDS_PATH.length + 1))
1337
1338
 
1338
1339
  // The progressive-enhancement script. A site adds it to a layout; a form
1339
1340
  // works without it, so nothing emits it automatically.
1340
- if (pathname === FORM_SCRIPT_PATH)
1341
- return new Response(FORM_SCRIPT, {
1342
- headers: {
1343
- 'content-type': 'text/javascript; charset=utf-8',
1344
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1345
- },
1346
- })
1341
+ if (pathname === FORM_SCRIPT_PATH) return siteScript(FORM_SCRIPT)
1347
1342
 
1348
1343
  // A visitor posting a form. Before the renderer, which would otherwise try
1349
1344
  // to resolve `/crombolo/forms/...` as a page.
@@ -1356,16 +1351,10 @@ export async function createServer(
1356
1351
  : new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } })
1357
1352
  }
1358
1353
 
1359
- // The script that calls the site's routes as a member, wherever the site is served.
1360
- if (config.role !== 'api') {
1361
- if (pathname === BUNDLE_SCRIPT_PATH)
1362
- return new Response(BUNDLE_SCRIPT, {
1363
- headers: {
1364
- 'content-type': 'text/javascript; charset=utf-8',
1365
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1366
- },
1367
- })
1368
- }
1354
+ // The script that calls the site's routes as a member: on every node, as the
1355
+ // other site scripts are, so a proxy that sends `/crombolo/*` to the api node
1356
+ // still serves it (story 220).
1357
+ if (pathname === BUNDLE_SCRIPT_PATH) return siteScript(BUNDLE_SCRIPT)
1369
1358
 
1370
1359
  // Not on an `api` node, which serves no public site to describe.
1371
1360
  if ((pathname === '/sitemap.xml' || pathname === '/robots.txt') && config.role !== 'api')
@@ -1450,6 +1439,16 @@ export async function createServer(
1450
1439
  }
1451
1440
  }
1452
1441
 
1442
+ /** One of the scripts a site's pages load, answered alike on every node. */
1443
+ function siteScript(body: string): Response {
1444
+ return new Response(body, {
1445
+ headers: {
1446
+ 'content-type': 'text/javascript; charset=utf-8',
1447
+ 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1448
+ },
1449
+ })
1450
+ }
1451
+
1453
1452
  /** The site's stylesheets and scripts, or its pages. */
1454
1453
  async function siteFiles(request: Request, run?: ChainRun): Promise<Response> {
1455
1454
  const url = new URL(request.url)
@@ -2240,6 +2239,27 @@ export async function createServer(
2240
2239
  if (response) return response
2241
2240
  }
2242
2241
 
2242
+ // Non-contract, Media: how a large branch's queued trash, move or delete is
2243
+ // getting on (story 246), for anyone with the Media section, media jobs only.
2244
+ const mediaJob = /^\/([0-9a-f-]{36})$/i.exec(
2245
+ pathname.startsWith(mediaJobsPath) ? pathname.slice(mediaJobsPath.length) : '',
2246
+ )
2247
+ if (mediaJob && request.method === 'GET') {
2248
+ const principal = await authenticate(request)
2249
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2250
+ if (!hasSection(principal, 'media')) return new Response('Forbidden', { status: 403 })
2251
+ const job = await new JobRepository(db).get(mediaJob[1] as string)
2252
+ if (!job || job.owner !== CORE_JOB_OWNER || !job.name.startsWith('media.'))
2253
+ return new Response('Not Found', { status: 404 })
2254
+ return Response.json({
2255
+ id: job.id,
2256
+ state: job.state,
2257
+ progress: job.progress,
2258
+ error: job.lastError,
2259
+ finishedAt: job.finishedAt?.toISOString() ?? null,
2260
+ })
2261
+ }
2262
+
2243
2263
  // Non-contract, Settings: every owner's background jobs, and retrying a
2244
2264
  // failed one by hand (story 187).
2245
2265
  if (pathname === jobsPath || pathname.startsWith(`${jobsPath}/`)) {