@crombolo/server 0.36.2 → 0.38.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.
Files changed (83) hide show
  1. package/package.json +15 -13
  2. package/src/access.ts +29 -27
  3. package/src/adapters/audit.ts +1 -1
  4. package/src/adapters/blueprints.ts +22 -13
  5. package/src/adapters/content.ts +1 -1
  6. package/src/adapters/dictionary.ts +1 -1
  7. package/src/adapters/documents.ts +17 -10
  8. package/src/adapters/elements.ts +47 -37
  9. package/src/adapters/file-system.ts +1 -1
  10. package/src/adapters/health.ts +33 -5
  11. package/src/adapters/media.ts +12 -8
  12. package/src/adapters/member-groups.ts +8 -6
  13. package/src/adapters/members.ts +6 -4
  14. package/src/adapters/public-access.ts +7 -5
  15. package/src/adapters/redirects.ts +1 -1
  16. package/src/adapters/references.ts +1 -1
  17. package/src/adapters/relations.ts +1 -1
  18. package/src/adapters/schema-files.ts +33 -1
  19. package/src/adapters/search-index.ts +1 -1
  20. package/src/adapters/template-files.ts +6 -1
  21. package/src/adapters/template-query.ts +1 -1
  22. package/src/adapters/users.ts +13 -13
  23. package/src/adapters/webhooks.ts +1 -1
  24. package/src/anonymise-rules.ts +83 -0
  25. package/src/approvals-api.ts +1 -1
  26. package/src/approvals.ts +75 -38
  27. package/src/back-office-url.ts +20 -0
  28. package/src/backup.ts +26 -2
  29. package/src/bundle-code.ts +1 -1
  30. package/src/bundle-grants.ts +265 -0
  31. package/src/bundle-install.ts +13 -2
  32. package/src/bundle-media.ts +12 -11
  33. package/src/bundles.ts +258 -444
  34. package/src/component-snippets.ts +1 -1
  35. package/src/components.ts +48 -7
  36. package/src/config.ts +141 -4
  37. package/src/content-notifications.ts +13 -9
  38. package/src/content-operations.ts +23 -65
  39. package/src/content-query.ts +1 -1
  40. package/src/core.ts +663 -0
  41. package/src/cron.ts +139 -0
  42. package/src/custom-tables.ts +274 -0
  43. package/src/database.ts +22 -14
  44. package/src/dictionary-transfer.ts +1 -1
  45. package/src/git-routes.ts +1 -1
  46. package/src/identity-provider-overrides.ts +18 -16
  47. package/src/imaging.ts +65 -15
  48. package/src/index.ts +14 -1
  49. package/src/islands.ts +197 -0
  50. package/src/job-wake.ts +23 -0
  51. package/src/live-reload.ts +195 -0
  52. package/src/log-viewer.ts +6 -1
  53. package/src/marketplace.ts +82 -10
  54. package/src/media-access.ts +12 -9
  55. package/src/member-auth.ts +6 -4
  56. package/src/middleware.ts +236 -0
  57. package/src/models-builder.ts +1 -1
  58. package/src/node-operations.ts +122 -0
  59. package/src/owner-jobs.ts +428 -0
  60. package/src/ports.ts +39 -154
  61. package/src/preview-tokens.ts +6 -12
  62. package/src/remote.ts +3 -1
  63. package/src/routes.ts +420 -0
  64. package/src/schema.ts +8 -3
  65. package/src/seed/compile.ts +7 -5
  66. package/src/seed/export.ts +6 -4
  67. package/src/seo.ts +2 -2
  68. package/src/server.ts +866 -483
  69. package/src/settings.ts +49 -2
  70. package/src/site-data.ts +195 -0
  71. package/src/site-file.ts +30 -4
  72. package/src/site-queries.ts +140 -0
  73. package/src/site-replace.ts +25 -19
  74. package/src/site-sections.ts +1 -1
  75. package/src/site-services.ts +116 -0
  76. package/src/status-pages.ts +142 -0
  77. package/src/status.ts +11 -9
  78. package/src/url-settings.ts +1 -2
  79. package/src/webhook-files.ts +18 -1
  80. package/src/webhooks.ts +83 -15
  81. package/src/worker-watch.ts +73 -0
  82. package/src/worker.ts +138 -0
  83. package/src/bundle-tables.ts +0 -161
@@ -21,11 +21,13 @@ import { readFileSync } from 'node:fs'
21
21
  import { join } from 'node:path'
22
22
  import {
23
23
  type BundlePackage,
24
+ describePermissions,
24
25
  EXTENSION_KEYWORD,
25
26
  type ExtensionRegistry,
26
27
  type PackageJson,
27
28
  validateBundlePackage,
28
29
  } from '@crombolo/backoffice-host'
30
+ import { type BundleGrants, declaredPermissions } from './bundle-grants.ts'
29
31
  import { logger } from './logging.ts'
30
32
 
31
33
  const log = logger('packages')
@@ -62,6 +64,14 @@ export interface InstalledListing {
62
64
  description: string
63
65
  /** The crombolo releases it is written for. */
64
66
  peerRange: string
67
+ /** What its server half may do with the site, each with what it allows (story 222). */
68
+ permissions: { permission: string; allows: string }[]
69
+ /** Whether it is turned on: nothing is declared, or an administrator granted all of it. */
70
+ on: boolean
71
+ /** What it declares and has not been granted. */
72
+ missing: string[]
73
+ /** Who granted it, and when; absent when nobody has. */
74
+ granted?: { by: string | null; at: string; version: string }
65
75
  }
66
76
 
67
77
  /** What became of the content half of an install. */
@@ -84,6 +94,8 @@ export interface MarketplaceOptions {
84
94
  install?: PackageInstaller
85
95
  /** The ids of the bundles whose server half this node has mounted. */
86
96
  wired?: () => readonly string[]
97
+ /** Where an install's grant is recorded, and where the listing reads it (story 222). */
98
+ grants?: Pick<BundleGrants, 'state' | 'grant'>
87
99
  /** The version of a package whose content has been applied here. */
88
100
  contentApplied?: (packageName: string) => Promise<string | null>
89
101
  /**
@@ -118,6 +130,8 @@ export interface InstallOutcome {
118
130
  * accept that (story 194): the screen asks, and sends the install again.
119
131
  */
120
132
  needsServerConsent?: boolean
133
+ /** With `needsServerConsent`: what it asks to do with the site, to grant as a whole (story 222). */
134
+ permissions?: { permission: string; allows: string }[]
121
135
  }
122
136
 
123
137
  export type PackageInstaller = (
@@ -160,7 +174,14 @@ export interface Marketplace {
160
174
  install(
161
175
  name: string,
162
176
  version: string | undefined,
163
- options?: { applyContent?: boolean; acceptServerCode?: boolean },
177
+ options?: {
178
+ applyContent?: boolean
179
+ acceptServerCode?: boolean
180
+ /** The permissions the administrator granted: the bundle's whole list (story 222). */
181
+ grant?: readonly string[]
182
+ /** Who is installing, recorded on the grant. */
183
+ by?: string | null
184
+ },
164
185
  ): Promise<InstallOutcome>
165
186
  uninstall(name: string): Promise<InstallOutcome>
166
187
  }
@@ -236,7 +257,9 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
236
257
  const declaresAt = async (
237
258
  name: string,
238
259
  wanted?: string,
239
- ): Promise<BundlePackage['carries'] | 'not-a-bundle' | 'unreachable'> => {
260
+ ): Promise<
261
+ (BundlePackage['carries'] & { permissions: string[] }) | 'not-a-bundle' | 'unreachable'
262
+ > => {
240
263
  try {
241
264
  const response = await call(`${options.registry}/${encodeURIComponent(name)}`, {
242
265
  headers: { accept: 'application/json' },
@@ -263,11 +286,13 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
263
286
  extensions?: unknown[]
264
287
  content?: boolean
265
288
  server?: string
289
+ permissions?: string[]
266
290
  }
267
291
  return {
268
292
  extensions: Array.isArray(field.extensions) && field.extensions.length > 0,
269
293
  content: field.content === true,
270
294
  server: field.server !== undefined,
295
+ permissions: Array.isArray(field.permissions) ? field.permissions : [],
271
296
  }
272
297
  } catch {
273
298
  return 'unreachable'
@@ -276,8 +301,32 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
276
301
 
277
302
  /** What the registry says this package's latest version carries, when it is a valid bundle. */
278
303
  const declares = async (name: string): Promise<BundlePackage['carries'] | undefined> => {
279
- const carries = await declaresAt(name)
280
- return typeof carries === 'string' ? undefined : carries
304
+ const declared = await declaresAt(name)
305
+ if (typeof declared === 'string') return undefined
306
+ const { permissions: _, ...carries } = declared
307
+ return carries
308
+ }
309
+
310
+ /** A bundle's permissions and where its grant stands, for the listing. */
311
+ const grantOf = (bundle: BundlePackage) => {
312
+ const declared = describePermissions(declaredPermissions(bundle))
313
+ if (!bundle.carries.server || !options.grants)
314
+ return { permissions: declared, on: true, missing: [] as string[] }
315
+ const state = options.grants.state(bundle)
316
+ return {
317
+ permissions: state.declared,
318
+ on: state.on,
319
+ missing: state.missing,
320
+ ...(state.grant
321
+ ? {
322
+ granted: {
323
+ by: state.grant.grantedBy,
324
+ at: state.grant.grantedAt.toISOString(),
325
+ version: state.grant.version,
326
+ },
327
+ }
328
+ : {}),
329
+ }
281
330
  }
282
331
 
283
332
  return {
@@ -356,6 +405,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
356
405
  contentApplied: (await options.contentApplied?.(bundle.packageName)) ?? null,
357
406
  description: descriptionOf(bundle.directory),
358
407
  peerRange: bundle.peerRange,
408
+ ...grantOf(bundle),
359
409
  })),
360
410
  )
361
411
  },
@@ -381,7 +431,8 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
381
431
  ok: false,
382
432
  message: `${name} is not a bundle for this site, so it was not installed.`,
383
433
  }
384
- if (declared.server && request.acceptServerCode !== true) return serverConsentNeeded(name)
434
+ if (declared.server && !consented(request, declared.permissions))
435
+ return serverConsentNeeded(name, declared.permissions)
385
436
 
386
437
  const specifier = version ? `${name}@${version}` : name
387
438
  const result = await install('add', specifier, options.siteDir)
@@ -404,14 +455,17 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
404
455
  }
405
456
  // The version that landed is what counts: a release published between
406
457
  // reading the registry and installing may have brought server code.
407
- if (found.carries.server && request.acceptServerCode !== true) {
458
+ if (found.carries.server && !consented(request, declaredPermissions(found))) {
408
459
  await install('remove', name, options.siteDir)
409
460
  options.extensions.invalidate()
410
461
  return serverConsentNeeded(
411
462
  name,
412
- `${name}@${found.version} turned out to run code on the server, so it was removed again.`,
463
+ declaredPermissions(found),
464
+ `${name}@${found.version} turned out to run code on the server, or to ask for more than was granted, so it was removed again.`,
413
465
  )
414
466
  }
467
+ // What was granted is recorded against the version that landed.
468
+ if (found.carries.server) await options.grants?.grant(found, request.by ?? null)
415
469
 
416
470
  // The content half lands after the dependency, so a refused check leaves
417
471
  // the package installed and says why, rather than undoing an install that
@@ -475,12 +529,30 @@ function descriptionOf(directory: string): string {
475
529
  /** Said of every bundle installed here: its screens are someone else's code in our browsers. */
476
530
  export const SCREENS_NOTICE = 'Its screens run in the browser of everyone who uses the back office.'
477
531
 
478
- /** A refusal the screen answers by asking for an explicit yes (story 194). */
479
- function serverConsentNeeded(name: string, before = ''): InstallOutcome {
532
+ /**
533
+ * Whether an install request said yes to server code and granted exactly what
534
+ * the bundle asks for (stories 194, 222): all of it, and nothing it did not ask.
535
+ */
536
+ function consented(
537
+ request: { acceptServerCode?: boolean; grant?: readonly string[] },
538
+ permissions: readonly string[],
539
+ ): boolean {
540
+ if (request.acceptServerCode !== true) return false
541
+ const granted = new Set(request.grant ?? [])
542
+ return granted.size === new Set(permissions).size && permissions.every((p) => granted.has(p))
543
+ }
544
+
545
+ /** A refusal the screen answers by asking for an explicit yes, and the grant (stories 194, 222). */
546
+ function serverConsentNeeded(
547
+ name: string,
548
+ permissions: readonly string[],
549
+ before = '',
550
+ ): InstallOutcome {
480
551
  return {
481
552
  ok: false,
482
553
  needsServerConsent: true,
483
- message: `${before ? `${before} ` : ''}${name} runs code on the server, with access to the site's data, files and settings. Confirm that you trust its publisher to install it.`,
554
+ permissions: describePermissions(permissions),
555
+ message: `${before ? `${before} ` : ''}${name} runs code on the server, with access to the site's data, files and settings. Confirm that you trust its publisher, and approve what it asks to do, to install it.`,
484
556
  }
485
557
  }
486
558
 
@@ -8,7 +8,7 @@
8
8
  * reads and sets rules through `handle`, under
9
9
  * `<backoffice>/crombolo/api/media-access/{key}`, which is not in the contract.
10
10
  */
11
- import { hasSection, type Principal } from '@crombolo/api-management'
11
+ import { hasSection, type Principal } from '@crombolo/api-management/domain'
12
12
  import {
13
13
  fallbackPermissions,
14
14
  hasPathAccess,
@@ -180,10 +180,12 @@ export function createMediaAccess(deps: MediaAccessDeps) {
180
180
  const isProtected = (item: MediaByUrl) => item.trashed || isProtectedMedia(item.access, item.rule)
181
181
 
182
182
  const memberGroups = async (): Promise<string[]> => {
183
- const rows = await db.query<{ text: string | null }>(
184
- 'SELECT text FROM node WHERE node_object_type = ? ORDER BY text',
185
- [ObjectTypes.MemberGroup],
186
- )
183
+ const rows = await db.q
184
+ .selectFrom('node')
185
+ .select('text')
186
+ .where('node_object_type', '=', ObjectTypes.MemberGroup)
187
+ .orderBy('text')
188
+ .execute()
187
189
  return rows.flatMap((row) => (row.text ? [String(row.text)] : []))
188
190
  }
189
191
 
@@ -222,10 +224,11 @@ export function createMediaAccess(deps: MediaAccessDeps) {
222
224
  writePolicy: 'inherit' as const,
223
225
  creatorMemberKey: null,
224
226
  }
225
- const fileRows = await db.query<{ file_url: string | null }>(
226
- 'SELECT file_url FROM content WHERE node_id = ?',
227
- [node.id],
228
- )
227
+ const fileRows = await db.q
228
+ .selectFrom('content')
229
+ .select('file_url')
230
+ .where('node_id', '=', node.id)
231
+ .execute()
229
232
  const from = inherited ? await nodes.byKey(inherited.nodeKey) : undefined
230
233
  const creator = item.creatorMemberKey
231
234
  ? await new MemberRepository(db).byKey(item.creatorMemberKey)
@@ -199,10 +199,12 @@ export function createMemberAuth(
199
199
  const groupKeysFor = async (names: readonly string[]): Promise<string[]> => {
200
200
  const keys: string[] = []
201
201
  for (const groupName of names) {
202
- const rows = await db.query<{ unique_id: string }>(
203
- 'SELECT unique_id FROM node WHERE text = ? AND node_object_type = ?',
204
- [groupName, ObjectTypes.MemberGroup],
205
- )
202
+ const rows = await db.q
203
+ .selectFrom('node')
204
+ .select('unique_id')
205
+ .where('text', '=', groupName)
206
+ .where('node_object_type', '=', ObjectTypes.MemberGroup)
207
+ .execute()
206
208
  if (rows[0]) keys.push(String(rows[0].unique_id))
207
209
  }
208
210
  return keys
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Running a site's middleware chain (story 210): each stage an onion, its
3
+ * middleware matched by path, under one time budget for the whole chain that
4
+ * stops while a middleware waits on `next()`, so crombolo's own work never
5
+ * counts against it. docs/rendering.md, "Middleware".
6
+ */
7
+ import type {
8
+ Matcher,
9
+ MatcherCondition,
10
+ Middleware,
11
+ MiddlewareContext,
12
+ MiddlewareHandler,
13
+ MiddlewareStage,
14
+ } from '@crombolo/common'
15
+
16
+ /** A middleware that threw, overran, or tried what its stage refuses, by name. */
17
+ export class MiddlewareError extends Error {
18
+ constructor(
19
+ readonly middleware: string,
20
+ message: string,
21
+ override readonly cause?: unknown,
22
+ ) {
23
+ super(message)
24
+ }
25
+ }
26
+
27
+ /** Any middleware, whatever its context is bound to: the runner hands each the context it gets. */
28
+ type AnyMiddleware = Middleware<never, never, never>
29
+
30
+ /** The chain's time, shared by every middleware in a request. */
31
+ export interface MiddlewareBudget {
32
+ remainingMs: number
33
+ }
34
+
35
+ const nameOf = (middleware: AnyMiddleware, index: number, stage: MiddlewareStage) =>
36
+ typeof middleware === 'function'
37
+ ? middleware.name || `${stage} middleware ${index + 1}`
38
+ : middleware.name
39
+
40
+ const handlerOf = (middleware: AnyMiddleware): MiddlewareHandler =>
41
+ (typeof middleware === 'function' ? middleware : middleware.handle) as MiddlewareHandler
42
+
43
+ function cookieValue(request: Request, name: string): string | undefined {
44
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
45
+ const at = part.indexOf('=')
46
+ if (at > 0 && part.slice(0, at).trim() === name)
47
+ return decodeURIComponent(part.slice(at + 1).trim())
48
+ }
49
+ return undefined
50
+ }
51
+
52
+ function conditionHolds(condition: MatcherCondition, request: Request, url: URL): boolean {
53
+ const value =
54
+ condition.type === 'header'
55
+ ? request.headers.get(condition.key)
56
+ : condition.type === 'cookie'
57
+ ? cookieValue(request, condition.key)
58
+ : url.searchParams.get(condition.key)
59
+ if (value === null || value === undefined) return false
60
+ return condition.value === undefined || new RegExp(`^(?:${condition.value})$`).test(value)
61
+ }
62
+
63
+ const patterns = new Map<string, URLPattern>()
64
+
65
+ /** Whether a matcher, in Next.js's syntax, selects this request. Pure but for a pattern cache. */
66
+ export function matches(
67
+ matcher: Matcher | Matcher[] | undefined,
68
+ request: Request,
69
+ url: URL,
70
+ ): boolean {
71
+ if (matcher === undefined) return true
72
+ const list = Array.isArray(matcher) ? matcher : [matcher]
73
+ return list.some((entry) => {
74
+ const { source, has = [], missing = [] } = typeof entry === 'string' ? { source: entry } : entry
75
+ let pattern = patterns.get(source)
76
+ if (!pattern) {
77
+ pattern = new URLPattern({ pathname: source })
78
+ patterns.set(source, pattern)
79
+ }
80
+ return (
81
+ pattern.test({ pathname: url.pathname }) &&
82
+ has.every((c) => conditionHolds(c, request, url)) &&
83
+ !missing.some((c) => conditionHolds(c, request, url))
84
+ )
85
+ })
86
+ }
87
+
88
+ /** Runs one handler, its clock stopped while it waits on `next()`. */
89
+ function timed(
90
+ name: string,
91
+ budget: MiddlewareBudget,
92
+ run: (next: (request?: Request) => Promise<Response>) => Response | Promise<Response>,
93
+ next: (request?: Request) => Promise<Response>,
94
+ ): Promise<Response> {
95
+ return new Promise((resolve, reject) => {
96
+ let settled = false
97
+ let timer: ReturnType<typeof setTimeout> | undefined
98
+ let armedAt = 0
99
+ const arm = () => {
100
+ armedAt = Date.now()
101
+ if (!Number.isFinite(budget.remainingMs)) return
102
+ timer = setTimeout(
103
+ () => {
104
+ if (settled) return
105
+ settled = true
106
+ budget.remainingMs = 0
107
+ reject(
108
+ new MiddlewareError(
109
+ name,
110
+ `${name} took longer than the middleware chain's time limit.`,
111
+ ),
112
+ )
113
+ },
114
+ Math.max(0, budget.remainingMs),
115
+ )
116
+ }
117
+ const pause = () => {
118
+ clearTimeout(timer)
119
+ if (Number.isFinite(budget.remainingMs)) budget.remainingMs -= Date.now() - armedAt
120
+ }
121
+ arm()
122
+ const waiting = async (request?: Request) => {
123
+ pause()
124
+ try {
125
+ return await next(request)
126
+ } finally {
127
+ if (!settled) arm()
128
+ }
129
+ }
130
+ Promise.resolve()
131
+ .then(() => run(waiting))
132
+ .then(
133
+ (response) => {
134
+ if (settled) return
135
+ settled = true
136
+ pause()
137
+ if (!(response instanceof Response))
138
+ reject(new MiddlewareError(name, `${name} did not answer with a Response.`))
139
+ else resolve(response)
140
+ },
141
+ (error: unknown) => {
142
+ if (settled) return
143
+ settled = true
144
+ clearTimeout(timer)
145
+ reject(
146
+ error instanceof MiddlewareError
147
+ ? error
148
+ : new MiddlewareError(
149
+ name,
150
+ `${name} failed: ${error instanceof Error ? error.message : String(error)}`,
151
+ error,
152
+ ),
153
+ )
154
+ },
155
+ )
156
+ })
157
+ }
158
+
159
+ export interface StageOptions {
160
+ stage: MiddlewareStage
161
+ chain: readonly AnyMiddleware[] | undefined
162
+ request: Request
163
+ /** What follows the stage: the next stage, or crombolo itself. */
164
+ inner: (request: Request) => Promise<Response>
165
+ /** The context each middleware is given, less what the runner fills in. */
166
+ context: (request: Request) => Omit<MiddlewareContext, 'stage'>
167
+ budget: MiddlewareBudget
168
+ }
169
+
170
+ /** One stage of the chain as an onion, outermost first; the matching middleware only. */
171
+ export function runStage(options: StageOptions): Promise<Response> {
172
+ const chain = options.chain ?? []
173
+ const step = (index: number, request: Request): Promise<Response> => {
174
+ if (index >= chain.length) return options.inner(request)
175
+ const middleware = chain[index] as AnyMiddleware
176
+ const url = new URL(request.url)
177
+ if (typeof middleware !== 'function' && !matches(middleware.matcher, request, url))
178
+ return step(index + 1, request)
179
+ const name = nameOf(middleware, index, options.stage)
180
+ return timed(
181
+ name,
182
+ options.budget,
183
+ // Assigned, not spread: spreading would read `cookies`, which marks the answer personal.
184
+ (next) =>
185
+ handlerOf(middleware)(
186
+ request,
187
+ next,
188
+ Object.assign(options.context(request), { stage: options.stage }) as MiddlewareContext,
189
+ ),
190
+ (changed) => step(index + 1, changed ?? request),
191
+ )
192
+ }
193
+ return step(0, options.request)
194
+ }
195
+
196
+ /** Whether a chain has anything in it. */
197
+ export const hasMiddleware = (chain: readonly AnyMiddleware[] | undefined): boolean =>
198
+ (chain?.length ?? 0) > 0
199
+
200
+ /** The request's cookies, read-only, as 206's `cookies()` gives them. */
201
+ export function requestCookies(request: Request) {
202
+ const all: Array<{ name: string; value: string }> = []
203
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
204
+ const at = part.indexOf('=')
205
+ if (at <= 0) continue
206
+ let value = part.slice(at + 1).trim()
207
+ try {
208
+ value = decodeURIComponent(value)
209
+ } catch {}
210
+ all.push({ name: part.slice(0, at).trim(), value })
211
+ }
212
+ const first = new Map<string, { name: string; value: string }>()
213
+ for (const cookie of all) if (!first.has(cookie.name)) first.set(cookie.name, cookie)
214
+ return Object.freeze({
215
+ get: (name: string) => first.get(name),
216
+ getAll: (name?: string) => (name === undefined ? [...all] : all.filter((c) => c.name === name)),
217
+ has: (name: string) => first.has(name),
218
+ size: first.size,
219
+ [Symbol.iterator]: () => first.entries(),
220
+ })
221
+ }
222
+
223
+ /**
224
+ * Whether a path is one of the site's own, which a rewrite may go to: never the
225
+ * back office, the APIs, crombolo's endpoints or `/media/`. Pure.
226
+ */
227
+ export function isSitePath(pathname: string, backOfficePath: string): boolean {
228
+ const lower = pathname.toLowerCase()
229
+ if (['/sitemap.xml', '/robots.txt', '/health'].includes(lower)) return false
230
+ return ![
231
+ '/umbraco',
232
+ '/crombolo',
233
+ '/media',
234
+ backOfficePath.toLowerCase().replace(/\/+$/, ''),
235
+ ].some((prefix) => lower === prefix || lower.startsWith(`${prefix}/`))
236
+ }
@@ -15,7 +15,7 @@ import type {
15
15
  ModelsBuilderInfo,
16
16
  ModelsBuilderPort,
17
17
  OutOfDateStatus,
18
- } from '@crombolo/api-management'
18
+ } from '@crombolo/api-management/domain'
19
19
  import type { FormTypes } from '@crombolo/core'
20
20
  import { generateTypes, loadSchemaDirectory, validateSchemaSet } from '@crombolo/schema'
21
21
  import type { CromboloConfig } from './config.ts'
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Every document and media write, whoever starts it (stories 165 and 170): the
3
+ * operations with their approvals and redirect tracking. Built once per node
4
+ * and shared by the Management API, the jobs and the command line, so a worker
5
+ * (story 223) publishes a schedule exactly as an editor's node does.
6
+ */
7
+ import {
8
+ createDocumentOperations,
9
+ createMediaOperations,
10
+ type DocumentOperations,
11
+ type EventSink,
12
+ type MediaOperations,
13
+ SILENT,
14
+ } from '@crombolo/content'
15
+ import {
16
+ appendCacheInstruction,
17
+ type Db,
18
+ type NodeSchemaState,
19
+ RedirectRepository,
20
+ } from '@crombolo/data'
21
+ import type { PublishedCache } from '@crombolo/render'
22
+ import { type Approvals, approvalsGate, createApprovals } from './approvals.ts'
23
+ import type { CromboloConfig } from './config.ts'
24
+ import { createMediaEventSink } from './content-events.ts'
25
+ import type { ContentNotifier } from './content-notifications.ts'
26
+ import { writeDomainsFor } from './domains.ts'
27
+ import type { EmailPort } from './email.ts'
28
+ import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
29
+ import type { MediaFileStore } from './media-files.ts'
30
+ import { createRedirectTracker, NO_REDIRECT_TRACKING, type RedirectTracker } from './redirects.ts'
31
+ import type { WebhookService } from './webhooks.ts'
32
+
33
+ export interface NodeOperations {
34
+ valueIntake: ReturnType<typeof createFileIntake>
35
+ tracker: RedirectTracker
36
+ approvals: Approvals
37
+ documents: DocumentOperations
38
+ media: MediaOperations
39
+ }
40
+
41
+ export interface NodeOperationsOptions {
42
+ db: Db
43
+ config: CromboloConfig
44
+ /** Absent only in tests of the API's contract: nothing is cached, so nothing is tracked. */
45
+ cache?: PublishedCache
46
+ nodeState?: NodeSchemaState
47
+ nodeId?: string
48
+ /** Who a redirect's cache instruction says it is from; the node, unless said otherwise. */
49
+ instructedBy?: string
50
+ mediaFiles: MediaFileStore
51
+ email?: EmailPort
52
+ notifier?: ContentNotifier
53
+ /** Where document operations announce what they did; nothing hears them when absent. */
54
+ contentEvents?: EventSink
55
+ webhooks?: WebhookService
56
+ nudgeEvents?: () => void
57
+ backOfficeUrl?: string
58
+ }
59
+
60
+ export function createNodeOperations(options: NodeOperationsOptions): NodeOperations {
61
+ const { db, cache } = options
62
+ const repository = {
63
+ nodeState: options.nodeState,
64
+ nodeId: options.nodeId,
65
+ valueIntake: createFileIntake(options.mediaFiles),
66
+ }
67
+ const refusalReason = (error: unknown) =>
68
+ error instanceof TemporaryFileMissingError ? error.message : undefined
69
+ const tracker = cache
70
+ ? createRedirectTracker({
71
+ cache,
72
+ redirects: new RedirectRepository(db),
73
+ enabled: options.config.trackRedirects,
74
+ instruct: () =>
75
+ appendCacheInstruction(db, {
76
+ kind: 'content',
77
+ payload: { redirects: true },
78
+ by: options.instructedBy ?? options.nodeId,
79
+ }),
80
+ })
81
+ : NO_REDIRECT_TRACKING
82
+ // Approvals publish through the operations too, so what an approval publishes
83
+ // is cached, tracked and announced as any publish is.
84
+ let documents: DocumentOperations | undefined
85
+ const approvals = createApprovals({
86
+ db,
87
+ nodeState: options.nodeState,
88
+ email: options.email,
89
+ backOfficeUrl: options.backOfficeUrl,
90
+ notifier: options.notifier,
91
+ publisher: {
92
+ publish: (key, cultures, actor, approvedHead) =>
93
+ (documents as DocumentOperations).publish(actor, key, {
94
+ cultures,
95
+ expectedHead: approvedHead,
96
+ }),
97
+ unpublish: (key, cultures, actor) =>
98
+ (documents as DocumentOperations).unpublish(actor, key, cultures),
99
+ },
100
+ })
101
+ documents = createDocumentOperations({
102
+ db,
103
+ repository,
104
+ events: options.contentEvents ?? SILENT,
105
+ approvals: approvalsGate(approvals),
106
+ redirects: tracker,
107
+ onChange: () => cache?.invalidate(),
108
+ afterDomains: (node, assignment) =>
109
+ writeDomainsFor(db, options.config.siteDir, node, assignment),
110
+ refusalReason,
111
+ })
112
+ const media = createMediaOperations({
113
+ db,
114
+ repository,
115
+ events: createMediaEventSink({ webhooks: options.webhooks, nudge: options.nudgeEvents }),
116
+ files: options.mediaFiles,
117
+ // Only the items it touched: a media change leaves the pages alone (story 197).
118
+ onChange: (change) => cache?.media?.apply(change),
119
+ refusalReason,
120
+ })
121
+ return { valueIntake: repository.valueIntake, tracker, approvals, documents, media }
122
+ }