@crombolo/server 0.21.0 → 0.23.0

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.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,18 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.21.0",
34
- "@crombolo/api-management": "0.21.0",
35
- "@crombolo/assistant": "0.21.0",
36
- "@crombolo/auth": "0.21.0",
37
- "@crombolo/backoffice-host": "0.21.0",
38
- "@crombolo/contracts": "0.21.0",
39
- "@crombolo/core": "0.21.0",
40
- "@crombolo/data": "0.21.0",
41
- "@crombolo/render": "0.21.0",
42
- "@crombolo/schema": "0.21.0",
43
- "@crombolo/transfer": "0.21.0",
33
+ "@crombolo/api-delivery": "0.23.0",
34
+ "@crombolo/api-management": "0.23.0",
35
+ "@crombolo/assistant": "0.23.0",
36
+ "@crombolo/auth": "0.23.0",
37
+ "@crombolo/backoffice-host": "0.23.0",
38
+ "@crombolo/content": "0.23.0",
39
+ "@crombolo/contracts": "0.23.0",
40
+ "@crombolo/core": "0.23.0",
41
+ "@crombolo/data": "0.23.0",
42
+ "@crombolo/render": "0.23.0",
43
+ "@crombolo/schema": "0.23.0",
44
+ "@crombolo/transfer": "0.23.0",
44
45
  "@logtape/logtape": "^2.3.8"
45
46
  }
46
47
  }
@@ -481,14 +481,19 @@ export function createDocumentPort(
481
481
  }
482
482
  }
483
483
 
484
+ /**
485
+ * What the published cache is built from. With `drafts`, every page as last
486
+ * saved instead of as published, for previewing in an app (story 053); the
487
+ * rest — media, languages, domains, elements — is the same either way.
488
+ */
484
489
  export function createPublishedContentSource(
485
490
  db: Db,
486
- options: DocumentRepositoryOptions = {},
491
+ options: DocumentRepositoryOptions & { drafts?: boolean } = {},
487
492
  ): PublishedContentSource {
488
493
  const repo = new DocumentRepository(db, options)
489
494
  return {
490
495
  async loadPublished(): Promise<PublishedNode[]> {
491
- const rows = await repo.loadPublished()
496
+ const rows = options.drafts ? await repo.loadDrafts() : await repo.loadPublished()
492
497
  return rows.map((row) => ({
493
498
  key: row.key,
494
499
  id: row.id,
@@ -12,7 +12,15 @@
12
12
  * themselves did.
13
13
  */
14
14
  import type { ElementPort, Principal } from '@crombolo/api-management'
15
- import { type ElementTreeItem, normaliseUuid, ObjectTypes, SystemNodes } from '@crombolo/core'
15
+ import {
16
+ type ElementTreeItem,
17
+ MENU_ALIAS_PROPERTY,
18
+ normaliseUuid,
19
+ ObjectTypes,
20
+ SYSTEM_CONTENT_TYPE_KEYS,
21
+ SystemNodes,
22
+ safeAlias,
23
+ } from '@crombolo/core'
16
24
  import {
17
25
  appendCacheInstruction,
18
26
  type Db,
@@ -77,6 +85,72 @@ export function createElementPort(
77
85
  /** An element has no template, whatever a save sends. */
78
86
  const saved = <T extends object>(input: T) => ({ ...input, componentKey: null })
79
87
 
88
+ /** Whether another menu, not in the bin, already answers to `alias`. */
89
+ const menuAliasTaken = async (alias: string, key: string | undefined): Promise<boolean> => {
90
+ const rows = await db.query<{ unique_id: string }>(
91
+ `SELECT n.unique_id FROM property_value pv
92
+ JOIN property_type p ON p.id = pv.property_type_id
93
+ JOIN node n ON n.id = pv.node_id
94
+ JOIN content c ON c.node_id = n.id
95
+ JOIN node ct ON ct.id = c.content_type_id
96
+ WHERE p.alias = ? AND pv.is_current = ? AND n.trashed = ? AND ct.unique_id = ?
97
+ AND LOWER(COALESCE(pv.varchar_value, pv.text_value)) = ?`,
98
+ [
99
+ MENU_ALIAS_PROPERTY,
100
+ db.dialect.boolValue(true),
101
+ db.dialect.boolValue(false),
102
+ SYSTEM_CONTENT_TYPE_KEYS.Menu,
103
+ alias.toLowerCase(),
104
+ ],
105
+ )
106
+ return rows.some((row) => normaliseUuid(String(row.unique_id)) !== key?.toLowerCase())
107
+ }
108
+
109
+ /**
110
+ * A menu's alias, filled from its name when left empty, as Umbraco makes a type's
111
+ * (story 141); refused when another menu has it, since a template could then get
112
+ * either. Anything that is not a menu is saved as sent.
113
+ */
114
+ const withMenuAlias = async <
115
+ T extends {
116
+ contentTypeKey?: string
117
+ values: Array<{
118
+ alias: string
119
+ culture: string | null
120
+ segment: string | null
121
+ value: unknown
122
+ }>
123
+ variants: Array<{ name: string }>
124
+ },
125
+ >(
126
+ input: T,
127
+ key?: string,
128
+ ): Promise<T | { ok: false; reason: string; status: number }> => {
129
+ const typeKey =
130
+ input.contentTypeKey ?? (key ? (await repo.byKey(key))?.contentTypeKey : undefined)
131
+ if (typeKey?.toLowerCase() !== SYSTEM_CONTENT_TYPE_KEYS.Menu) return input
132
+ const given = input.values.find((v) => v.alias === MENU_ALIAS_PROPERTY && v.culture === null)
133
+ const alias =
134
+ (typeof given?.value === 'string' ? given.value.trim() : '') ||
135
+ safeAlias(input.variants[0]?.name ?? '')
136
+ if (!alias) return input
137
+ if (await menuAliasTaken(alias, key))
138
+ return {
139
+ ok: false,
140
+ reason: `Another menu already uses the alias "${alias}". Choose another one.`,
141
+ status: 400,
142
+ }
143
+ return {
144
+ ...input,
145
+ values: [
146
+ ...input.values.filter((v) => !(v.alias === MENU_ALIAS_PROPERTY && v.culture === null)),
147
+ { alias: MENU_ALIAS_PROPERTY, culture: null, segment: null, value: alias },
148
+ ],
149
+ }
150
+ }
151
+ const refused = (value: object): value is { ok: false; reason: string; status: number } =>
152
+ 'ok' in value && value.ok === false
153
+
80
154
  return {
81
155
  folders: createFolderPort(folders, tree, changed),
82
156
 
@@ -118,7 +192,9 @@ export function createElementPort(
118
192
  byKeyPublished: (key) => repo.byKeyPublished(key),
119
193
  validate: (input, cultures) => repo.validate(input, cultures),
120
194
 
121
- async create(input, principal) {
195
+ async create(sent, principal) {
196
+ const input = await withMenuAlias(sent)
197
+ if (refused(input)) return input
122
198
  try {
123
199
  const created = await repo.create(saved({ ...input, userId: await userIdOf(principal) }))
124
200
  await changed()
@@ -128,7 +204,9 @@ export function createElementPort(
128
204
  }
129
205
  },
130
206
 
131
- async update(key, input, principal) {
207
+ async update(key, sent, principal) {
208
+ const input = await withMenuAlias(sent, key)
209
+ if (refused(input)) return input
132
210
  try {
133
211
  const updated = await repo.update(
134
212
  saved({ ...input, key, userId: await userIdOf(principal) }),
@@ -141,7 +219,9 @@ export function createElementPort(
141
219
  }
142
220
  },
143
221
 
144
- async createAndPublish(input, cultures, principal) {
222
+ async createAndPublish(sent, cultures, principal) {
223
+ const input = await withMenuAlias(sent)
224
+ if (refused(input)) return input
145
225
  try {
146
226
  const result = await repo.createAndPublish(
147
227
  saved({ ...input, userId: await userIdOf(principal) }),
@@ -161,7 +241,9 @@ export function createElementPort(
161
241
  }
162
242
  },
163
243
 
164
- async updateAndPublish(key, input, cultures, principal) {
244
+ async updateAndPublish(key, sent, cultures, principal) {
245
+ const input = await withMenuAlias(sent, key)
246
+ if (refused(input)) return input
165
247
  try {
166
248
  const result = await repo.updateAndPublish(
167
249
  saved({ ...input, key, userId: await userIdOf(principal) }),
package/src/approvals.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import type { Principal } from '@crombolo/api-management'
13
+ import { type Actor, systemActor } from '@crombolo/content'
13
14
  import {
14
15
  approvalsNeeded,
15
16
  DocumentPermissions,
@@ -45,13 +46,16 @@ import type { EmailPort } from './email.ts'
45
46
 
46
47
  /** What publishing and unpublishing go through when approval says yes. */
47
48
  export interface ApprovalPublisher {
49
+ /** As the site, on the approver's behalf: the gate has been passed by approving. */
48
50
  publish(
49
51
  key: string,
50
52
  cultures: string[] | null,
53
+ actor: Actor,
51
54
  ): Promise<{ ok: true } | { ok: false; reason: string }>
52
55
  unpublish(
53
56
  key: string,
54
57
  cultures: string[] | null,
58
+ actor: Actor,
55
59
  ): Promise<{ ok: true } | { ok: false; reason: string }>
56
60
  }
57
61
 
@@ -135,24 +139,24 @@ export interface Approvals {
135
139
  workflows(): Promise<StoredWorkflow[]>
136
140
  /** Undefined when the caller may go ahead; otherwise why not. */
137
141
  publishRefusal(
138
- principal: Principal,
142
+ principal: Principal | undefined,
139
143
  key: string,
140
144
  action: ApprovalAction,
141
145
  ): Promise<string | undefined>
142
146
  /** A branch publish: the root and every page below it. */
143
- branchRefusal(principal: Principal, key: string): Promise<string | undefined>
147
+ branchRefusal(principal: Principal | undefined, key: string): Promise<string | undefined>
144
148
  /** For a page being created and published at once: by its parent and type. */
145
149
  newPageRefusal(
146
- principal: Principal,
150
+ principal: Principal | undefined,
147
151
  parentKey: string | null,
148
152
  contentTypeKey: string,
149
153
  ): Promise<string | undefined>
150
154
  /** Undefined when the save may go ahead; otherwise why not. */
151
- beforeSave(principal: Principal, key: string): Promise<string | undefined>
155
+ beforeSave(principal: Principal | undefined, key: string): Promise<string | undefined>
152
156
  /** What the save does to a waiting request, once it has gone through. */
153
- afterSave(principal: Principal, key: string): Promise<void>
157
+ afterSave(principal: Principal | undefined, key: string): Promise<void>
154
158
  /** A direct publish, schedule or unpublish by someone allowed to: a scheduled request ends. */
155
- afterDirectPublish(principal: Principal, key: string, what: string): Promise<void>
159
+ afterDirectPublish(principal: Principal | undefined, key: string, what: string): Promise<void>
156
160
  /** The schedule job fired one of a page's schedules: a scheduled request goes on or ends. */
157
161
  scheduleFired(
158
162
  key: string,
@@ -292,11 +296,17 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
292
296
  const groupAliases = async (principal: Principal): Promise<Set<string>> =>
293
297
  new Set((await groups.byKeys(principal.groupKeys)).map((g) => g.alias))
294
298
 
295
- const mayPublish = (principal: Principal, facts: PageFacts, action: ApprovalAction): boolean =>
296
- principal.isAdmin ||
297
- permissionsForPath(principal.groups, facts.chain).has(
298
- action === 'publish' ? DocumentPermissions.Publish : DocumentPermissions.Unpublish,
299
- )
299
+ /** A local operator (no principal) holds no publishing rights of their own. */
300
+ const mayPublish = (
301
+ principal: Principal | undefined,
302
+ facts: PageFacts,
303
+ action: ApprovalAction,
304
+ ): boolean =>
305
+ principal !== undefined &&
306
+ (principal.isAdmin ||
307
+ permissionsForPath(principal.groups, facts.chain).has(
308
+ action === 'publish' ? DocumentPermissions.Publish : DocumentPermissions.Unpublish,
309
+ ))
300
310
 
301
311
  /**
302
312
  * Refuses, with a 403, a caller who cannot reach the page through their start
@@ -315,7 +325,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
315
325
  workflow !== undefined && (action === 'publish' || workflow.unpublish)
316
326
 
317
327
  const refusalFor = (
318
- principal: Principal,
328
+ principal: Principal | undefined,
319
329
  facts: PageFacts,
320
330
  workflow: SchemaWorkflow | undefined,
321
331
  action: ApprovalAction,
@@ -576,22 +586,22 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
576
586
  : undefined
577
587
  }
578
588
  if (cultures !== undefined) {
589
+ // As the site, on the approver's behalf; the publish raises the notification, with this note.
590
+ const actor = systemActor('Approval', {
591
+ source: principal ? 'request' : 'job',
592
+ user: principal ? { id: principal.id, name: principal.name } : undefined,
593
+ note: `approved through "${request.workflow.name}"`,
594
+ })
579
595
  const result =
580
596
  request.action === 'publish'
581
- ? await options.publisher.publish(request.nodeKey, cultures)
582
- : await options.publisher.unpublish(request.nodeKey, cultures)
597
+ ? await options.publisher.publish(request.nodeKey, cultures, actor)
598
+ : await options.publisher.unpublish(request.nodeKey, cultures, actor)
583
599
  if (!result.ok) return unpublishable(request, facts, result.reason)
584
600
  await repo.record(request.id, {
585
601
  kind: request.action === 'publish' ? 'published' : 'unpublished',
586
602
  userKey: principal?.id ?? null,
587
603
  comment: passed ? 'the requested time had passed when it was approved' : null,
588
604
  })
589
- if (request.action === 'publish')
590
- await options.notifier?.raise(
591
- { actions: ['Umb.Document.Publish'], key: request.nodeKey, keyKind: 'document' },
592
- principal ? { key: principal.id, name: principal.name } : null,
593
- `approved through "${request.workflow.name}"`,
594
- )
595
605
  }
596
606
  if (later.length + expires.length > 0)
597
607
  await documents().setSchedule(request.nodeKey, [...later, ...expires])
@@ -774,7 +784,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
774
784
 
775
785
  async beforeSave(principal, key) {
776
786
  const request = await requests().openFor(key)
777
- if (!request || principal.isAdmin) return undefined
787
+ if (!request || principal?.isAdmin) return undefined
778
788
  const edit = request.workflow.onEdit
779
789
  if (request.state === 'scheduled') {
780
790
  if (edit === 'lock' || edit === 'lock-after-first-approval')
@@ -800,18 +810,18 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
800
810
  ?.head ?? null
801
811
  if (head === request.eventId) return
802
812
  // Administrators may always edit; the request goes on, on what they saved.
803
- if (!principal.isAdmin && request.workflow.onEdit === 'withdraw') {
813
+ if (!principal?.isAdmin && request.workflow.onEdit === 'withdraw') {
804
814
  await repo.setState(request.id, 'withdrawn')
805
815
  await repo.record(request.id, {
806
816
  kind: 'withdrawn',
807
- userKey: principal.id,
817
+ userKey: principal?.id ?? null,
808
818
  comment: 'the page was changed after it was sent',
809
819
  })
810
820
  if (request.state === 'scheduled') await clearSchedule(request)
811
821
  return
812
822
  }
813
823
  await repo.setEvent(request.id, head)
814
- await repo.record(request.id, { kind: 'edited', userKey: principal.id })
824
+ await repo.record(request.id, { kind: 'edited', userKey: principal?.id ?? null })
815
825
  },
816
826
 
817
827
  async send(principal, key, action, cultures, comment, schedule) {
@@ -1010,8 +1020,8 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1010
1020
  await repo.setState(request.id, 'superseded')
1011
1021
  await repo.record(request.id, {
1012
1022
  kind: 'superseded',
1013
- userKey: principal.id,
1014
- comment: `${principal.name} ${what} directly`,
1023
+ userKey: principal?.id ?? null,
1024
+ comment: `${principal?.name ?? 'Someone at the command line'} ${what} directly`,
1015
1025
  })
1016
1026
  await auditStep(
1017
1027
  principal,
package/src/config.ts CHANGED
@@ -6,7 +6,12 @@ import {
6
6
  DEFAULT_PASSWORD_CONFIGURATION,
7
7
  isValidPassword,
8
8
  } from '@crombolo/core'
9
- import { DEFAULT_RENDER_TIMEOUT_MS, type RedirectRule, type SnapshotLimits } from '@crombolo/render'
9
+ import {
10
+ type CacheOptions,
11
+ DEFAULT_RENDER_TIMEOUT_MS,
12
+ type RedirectRule,
13
+ type SnapshotLimits,
14
+ } from '@crombolo/render'
10
15
  import type { AssistantConfig } from './assistant.ts'
11
16
  import type { ServerBundle } from './bundles.ts'
12
17
  import type { EmailPort } from './email.ts'
@@ -349,10 +354,19 @@ export interface CromboloConfig {
349
354
  /**
350
355
  * Umbraco's Delivery API (`docs/delivery-api.md`): off unless enabled.
351
356
  * `CROMBOLO_DELIVERY_API`, `CROMBOLO_DELIVERY_API_KEY`,
352
- * `CROMBOLO_DELIVERY_API_PUBLIC` and `CROMBOLO_DELIVERY_API_MEDIA`; member
357
+ * `CROMBOLO_DELIVERY_API_PUBLIC`, `CROMBOLO_DELIVERY_API_MEDIA`,
358
+ * `CROMBOLO_DELIVERY_API_CORS_ORIGINS`, `CROMBOLO_DELIVERY_API_PREVIEW_URL` and
359
+ * `CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES`; member
353
360
  * sign-in is configured here, since its clients and secrets are a list.
354
361
  */
355
362
  deliveryApi: DeliveryApiOptions
363
+ /**
364
+ * How long pages, Delivery API answers and media may be kept by browsers and a
365
+ * CDN (story 057; `docs/operations.md`, "Behind a CDN"). Nothing is kept unless
366
+ * set. `CROMBOLO_CACHE_MAX_AGE`, `CROMBOLO_CACHE_STALE_WHILE_REVALIDATE` and
367
+ * `CROMBOLO_CACHE_TAG_HEADER`; per type alias in code only.
368
+ */
369
+ cache: CacheOptions
356
370
  /**
357
371
  * Bundles whose server half this site runs, each the result of calling the
358
372
  * factory its package exports. Imported and listed here by hand on purpose:
@@ -485,6 +499,12 @@ export interface SeoConfig {
485
499
  defaultImage?: string
486
500
  /** A page key, or rules choosing one per hostname or language. */
487
501
  notFoundPage?: string | NotFoundRule[]
502
+ /**
503
+ * Where visitors see the site, when that is not here — an app on another host
504
+ * (story 055): used for preferred addresses, the sitemap and `robots.txt`.
505
+ * CROMBOLO_PUBLIC_URL.
506
+ */
507
+ publicUrl?: string
488
508
  }
489
509
 
490
510
  /** A site's config file exports `defineConfig({...})`; unset keys come from the environment. */
@@ -624,6 +644,7 @@ export function loadConfig(
624
644
  seo: stripUndefined({
625
645
  sitemap: envFlag(setting('CROMBOLO_SITEMAP')),
626
646
  indexable: envFlag(setting('CROMBOLO_INDEXABLE')),
647
+ publicUrl: setting('CROMBOLO_PUBLIC_URL') || undefined,
627
648
  }),
628
649
  deliveryApi: stripUndefined({
629
650
  enabled: envFlag(setting('CROMBOLO_DELIVERY_API')),
@@ -633,6 +654,27 @@ export function loadConfig(
633
654
  envFlag(setting('CROMBOLO_DELIVERY_API_MEDIA')) === undefined
634
655
  ? undefined
635
656
  : { enabled: envFlag(setting('CROMBOLO_DELIVERY_API_MEDIA')) },
657
+ cors:
658
+ setting('CROMBOLO_DELIVERY_API_CORS_ORIGINS') === undefined
659
+ ? undefined
660
+ : {
661
+ allowedOrigins: (setting('CROMBOLO_DELIVERY_API_CORS_ORIGINS') ?? '')
662
+ .split(',')
663
+ .map((origin) => origin.trim())
664
+ .filter(Boolean),
665
+ },
666
+ preview: stripUndefined({
667
+ url: setting('CROMBOLO_DELIVERY_API_PREVIEW_URL') || undefined,
668
+ tokenMinutes:
669
+ setting('CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES') === undefined
670
+ ? undefined
671
+ : Number(setting('CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES')),
672
+ }),
673
+ }),
674
+ cache: stripUndefined({
675
+ maxAge: numberSetting('CROMBOLO_CACHE_MAX_AGE'),
676
+ staleWhileRevalidate: numberSetting('CROMBOLO_CACHE_STALE_WHILE_REVALIDATE'),
677
+ tagHeader: setting('CROMBOLO_CACHE_TAG_HEADER') || undefined,
636
678
  }),
637
679
  // No environment variable: a bundle is an import, which is code.
638
680
  bundles: [],
@@ -653,10 +695,16 @@ export function loadConfig(
653
695
  throw new Error(
654
696
  `remote.environment "${merged.remote.environment}" must be lower case letters, digits and dashes.`,
655
697
  )
698
+ merged.cache = { ...fromEnv.cache, ...stripUndefined(overrides.cache ?? {}) }
656
699
  merged.deliveryApi = {
657
700
  ...fromEnv.deliveryApi,
658
701
  ...stripUndefined(overrides.deliveryApi ?? {}),
659
702
  media: { ...fromEnv.deliveryApi.media, ...(overrides.deliveryApi?.media ?? {}) },
703
+ cors: { ...fromEnv.deliveryApi.cors, ...stripUndefined(overrides.deliveryApi?.cors ?? {}) },
704
+ preview: {
705
+ ...fromEnv.deliveryApi.preview,
706
+ ...stripUndefined(overrides.deliveryApi?.preview ?? {}),
707
+ },
660
708
  }
661
709
  // A schema store makes backoffice writes durable, so it carries writability with
662
710
  // it — that is the point of configuring one. An explicit setting still wins.
@@ -740,4 +788,12 @@ export function describeDatabase(
740
788
  }
741
789
  }
742
790
 
743
- export const VERSION = '0.21.0'
791
+ export const VERSION = '0.23.0'
792
+
793
+ /** A whole number of seconds from the environment; undefined when unset or not one. */
794
+ function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
795
+ const raw = setting(name)
796
+ if (raw === undefined || raw.trim() === '') return undefined
797
+ const value = Number(raw)
798
+ return Number.isFinite(value) && value >= 0 ? value : undefined
799
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Where document operations announce what they did (story 170): the audit log,
3
+ * webhooks, the people subscribed to a page, and — on a server — the live
4
+ * backoffice. The command line wires the same sink without the live part, so a
5
+ * change records and raises the same things wherever it was started.
6
+ */
7
+ import {
8
+ actorName,
9
+ actorNote,
10
+ actorUserKey,
11
+ auditEntryFor,
12
+ type EventSink,
13
+ liveEventsFor,
14
+ notificationFor,
15
+ webhookFor,
16
+ } from '@crombolo/content'
17
+ import { AuditLog, type Db } from '@crombolo/data'
18
+ import { recordAudit } from './adapters/audit.ts'
19
+ import type { ContentNotifier } from './content-notifications.ts'
20
+ import { logger } from './logging.ts'
21
+ import type { WebhookService } from './webhooks.ts'
22
+
23
+ const log = logger('Content')
24
+
25
+ export interface ContentEventSinkOptions {
26
+ db: Db
27
+ webhooks?: Pick<WebhookService, 'raise'>
28
+ notifier?: Pick<ContentNotifier, 'raise'>
29
+ /** Tells an open backoffice what changed: a server's event hub; absent on the command line. */
30
+ live?(event: ReturnType<typeof liveEventsFor>[number]): void
31
+ }
32
+
33
+ export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
34
+ const audit = new AuditLog(options.db)
35
+ const nameOf = async (entityType: string, key: string) => {
36
+ try {
37
+ return await audit.describe(entityType, key)
38
+ } catch {
39
+ return { entityType, entityKey: key, entityName: null }
40
+ }
41
+ }
42
+ return {
43
+ async emit(event, actor) {
44
+ const entry = auditEntryFor(event, actor)
45
+ // A deleted page cannot be named after it went: the operation read its name first.
46
+ const subject =
47
+ event.type === 'deleted'
48
+ ? { entityType: entry.entityType, entityKey: event.key, entityName: event.name }
49
+ : entry.entityKey
50
+ ? await nameOf(entry.entityType, entry.entityKey)
51
+ : undefined
52
+ await recordAudit(options.db, {
53
+ ...entry,
54
+ entityType: subject?.entityType ?? entry.entityType,
55
+ entityKey: subject?.entityKey ?? entry.entityKey,
56
+ entityName: subject?.entityName ?? null,
57
+ })
58
+ // Queued and sent after: a slow receiver or an e-mail never holds the change up.
59
+ const hook = webhookFor(event)
60
+ if (hook)
61
+ void options.webhooks
62
+ ?.raise(hook)
63
+ .catch((error: unknown) =>
64
+ log.error('Could not queue the {alias} webhook: {error}', { alias: hook.alias, error }),
65
+ )
66
+ const change = notificationFor(event)
67
+ if (change)
68
+ void options.notifier
69
+ ?.raise(change, { key: actorUserKey(actor), name: actorName(actor) }, actorNote(actor))
70
+ .catch((error: unknown) =>
71
+ log.error('Could not queue change notifications: {error}', { error }),
72
+ )
73
+ for (const live of liveEventsFor(event)) options.live?.(live)
74
+ },
75
+ }
76
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Document operations for a process that is not serving requests — the command
3
+ * line (story 170). The same rules and the same announcements as the server's:
4
+ * approvals, redirect tracking, the audit log, webhooks and change notifications.
5
+ * What it cannot do is refresh an open backoffice; its cache instructions tell
6
+ * the running nodes instead.
7
+ */
8
+
9
+ import {
10
+ createDocumentOperations,
11
+ type DocumentOperations,
12
+ type EventSink,
13
+ } from '@crombolo/content'
14
+ import { currentSchemaState, type Db, RedirectRepository } from '@crombolo/data'
15
+ import { PublishedCache } from '@crombolo/render'
16
+ import { createPublishedContentSource } from './adapters/documents.ts'
17
+ import { createApprovals } from './approvals.ts'
18
+ import type { CromboloConfig } from './config.ts'
19
+ import { createContentEventSink } from './content-events.ts'
20
+ import { createContentNotifier } from './content-notifications.ts'
21
+ import { writeDomainsFor } from './domains.ts'
22
+ import { resolveEmailPort } from './email.ts'
23
+ import { TemporaryFileMissingError } from './file-intake.ts'
24
+ import { approvalsGate, backOfficeUrl } from './ports.ts'
25
+ import { createRedirectTracker } from './redirects.ts'
26
+ import { createWebhookService } from './webhooks.ts'
27
+
28
+ export interface SiteOperations {
29
+ operations: DocumentOperations
30
+ /** The sink they announce through, for a caller that adds its own steps. */
31
+ events: EventSink
32
+ }
33
+
34
+ export async function siteDocumentOperations(
35
+ db: Db,
36
+ config: CromboloConfig,
37
+ ): Promise<SiteOperations> {
38
+ const state = await currentSchemaState(db)
39
+ const nodeState = { version: state.version, revision: state.revision }
40
+ const email = resolveEmailPort(config)
41
+ const notifier = createContentNotifier(db, { canSend: Boolean(email) })
42
+ const webhooks = createWebhookService({
43
+ db,
44
+ schemaDir: config.schemaDir,
45
+ filesWritable: config.schemaWritable,
46
+ secretKey: config.secretKey,
47
+ bundles: config.bundles,
48
+ })
49
+ const events = createContentEventSink({ db, webhooks, notifier })
50
+ const cache = new PublishedCache(createPublishedContentSource(db, { nodeState }))
51
+ let operations: DocumentOperations | undefined
52
+ const approvals = createApprovals({
53
+ db,
54
+ nodeState,
55
+ email,
56
+ backOfficeUrl: backOfficeUrl(config),
57
+ notifier,
58
+ publisher: {
59
+ publish: (key, cultures, actor) =>
60
+ (operations as DocumentOperations).publish(actor, key, { cultures }),
61
+ unpublish: (key, cultures, actor) =>
62
+ (operations as DocumentOperations).unpublish(actor, key, cultures),
63
+ },
64
+ })
65
+ operations = createDocumentOperations({
66
+ db,
67
+ repository: { nodeState, nodeId: config.nodeId },
68
+ events,
69
+ approvals: approvalsGate(approvals),
70
+ redirects: createRedirectTracker({
71
+ cache,
72
+ redirects: new RedirectRepository(db),
73
+ enabled: config.trackRedirects,
74
+ }),
75
+ afterDomains: (node, assignment) => writeDomainsFor(db, config.siteDir, node, assignment),
76
+ refusalReason: (error) =>
77
+ error instanceof TemporaryFileMissingError ? error.message : undefined,
78
+ })
79
+ return { operations, events }
80
+ }