@crombolo/server 0.69.0 → 0.70.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.
Files changed (46) hide show
  1. package/package.json +15 -14
  2. package/src/adapters/blueprints.ts +51 -5
  3. package/src/adapters/change-recording.ts +140 -0
  4. package/src/adapters/content.ts +132 -21
  5. package/src/adapters/documents.ts +26 -5
  6. package/src/adapters/elements.ts +3 -0
  7. package/src/adapters/media.ts +7 -1
  8. package/src/adapters/schema-files.ts +89 -1
  9. package/src/adapters/workspace-dictionary.ts +287 -0
  10. package/src/adapters/workspace-file-port.ts +160 -0
  11. package/src/adapters/workspace-languages.ts +94 -0
  12. package/src/approvals-api.ts +16 -7
  13. package/src/bundle-api.ts +19 -16
  14. package/src/bundle-install.ts +4 -0
  15. package/src/change-transfer.ts +676 -0
  16. package/src/changes-api.ts +258 -0
  17. package/src/component-templates-api.ts +2 -2
  18. package/src/config.ts +162 -22
  19. package/src/content-events.ts +65 -1
  20. package/src/content-operations.ts +22 -3
  21. package/src/core.ts +2 -0
  22. package/src/environment-values-api.ts +161 -0
  23. package/src/host-token.ts +30 -1
  24. package/src/node-operations.ts +150 -2
  25. package/src/ports.ts +174 -52
  26. package/src/remote-changes.ts +279 -0
  27. package/src/remote-schema.ts +126 -0
  28. package/src/remote-workspaces.ts +82 -0
  29. package/src/remote.ts +289 -192
  30. package/src/schema-transfer.ts +240 -41
  31. package/src/schema.ts +7 -2
  32. package/src/seed/compile.ts +13 -1
  33. package/src/seed/values.ts +3 -0
  34. package/src/server.ts +971 -364
  35. package/src/settings.ts +123 -5
  36. package/src/site-sections.ts +1 -1
  37. package/src/workspace-access.ts +152 -0
  38. package/src/workspace-checks.ts +299 -0
  39. package/src/workspace-losses.ts +95 -0
  40. package/src/workspace-processes.ts +306 -0
  41. package/src/workspace-render-child.ts +168 -0
  42. package/src/workspace-schema-dir.ts +100 -0
  43. package/src/workspace-schema.ts +598 -0
  44. package/src/workspace-sites.ts +179 -0
  45. package/src/workspace-views.ts +121 -0
  46. package/src/workspaces.ts +1031 -0
@@ -0,0 +1,258 @@
1
+ /**
2
+ * The site's changes over HTTP (story 381), at `<plugin>/api/changes`: every
3
+ * merged workspace, direct edit, applied bundle and revert, newest first; one
4
+ * change with each file's text before and after and its pages; a file's
5
+ * versions, each a change that touched it, compared with the file now; and a
6
+ * revert, which is a change of its own, refused where something later touched
7
+ * the same file or page, and which can reopen the work as a workspace.
8
+ */
9
+ import type { Principal } from '@crombolo/api-management/domain'
10
+ import { normaliseUuid } from '@crombolo/core'
11
+ import {
12
+ ChangeRepository,
13
+ type Db,
14
+ DocumentRepository,
15
+ type NodeSchemaState,
16
+ TransferRunRepository,
17
+ WorkspaceFileRepository,
18
+ WorkspaceRepository,
19
+ } from '@crombolo/data'
20
+ import { revertRun } from '@crombolo/transfer'
21
+ import { recordAudit } from './adapters/audit.ts'
22
+ import type { WorkspaceSchema } from './workspace-schema.ts'
23
+
24
+ const json = (body: unknown, status = 200) => Response.json(body, { status })
25
+ const refused = (message: string, status: number, extra: Record<string, unknown> = {}) =>
26
+ json({ message, ...extra }, status)
27
+
28
+ type Client = { ipAddress: string | null; forwardedFor: string | null }
29
+
30
+ export function createChangesApi(
31
+ db: Db,
32
+ options: {
33
+ schema: () => WorkspaceSchema | undefined
34
+ nodeState?: NodeSchemaState
35
+ /** Told after a revert that changed what is served. */
36
+ onReverted?: () => void | Promise<void>
37
+ },
38
+ ) {
39
+ const changes = new ChangeRepository(db)
40
+
41
+ /** A change with what it holds: its files, and its pages with what each did. */
42
+ async function detail(id: string) {
43
+ const change = await changes.byId(id)
44
+ if (!change) return undefined
45
+ const items = await changes.itemsOf(id)
46
+ const pages = await new TransferRunRepository(db).changes(id)
47
+ return {
48
+ ...change,
49
+ pageEdits:
50
+ change.kind === 'edit' && change.madeBy
51
+ ? await changes.pageEditsBy(
52
+ change.madeBy,
53
+ change.startedAt,
54
+ // An open edit gathers the person's page saves up to now.
55
+ change.closedAt ?? new Date(),
56
+ )
57
+ : undefined,
58
+ files: items.map((i) => ({
59
+ path: i.path,
60
+ kind: i.kind,
61
+ class: i.class,
62
+ before: i.before,
63
+ after: i.after,
64
+ })),
65
+ pageChanges: pages.map((p) => ({ key: p.nodeKey, action: p.action })),
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Puts a change back, as a change of its own: its pages through a run's revert,
71
+ * its files as they were before it, all or nothing; then, when asked, its work
72
+ * reopened as a workspace to carry on with.
73
+ */
74
+ async function revert(id: string, principal: Principal, toWorkspace: boolean, client: Client) {
75
+ const change = await changes.byId(id)
76
+ if (!change) return refused('There is no such change.', 404)
77
+ if (change.kind === 'bundle')
78
+ return refused('An applied bundle is reverted with `crombolo content revert`.', 409)
79
+ if (change.status !== 'applied') return refused('This change was reverted already.', 409)
80
+ const later = await changes.laterTouching(id)
81
+ const laterPages = await new TransferRunRepository(db).laterRunsTouching(id)
82
+ if (later.length > 0 || laterPages.length > 0)
83
+ return refused('Something changed later touches the same things; revert that first.', 409, {
84
+ files: [...new Set(later.map((l) => l.path))],
85
+ changes: [...new Set([...later.map((l) => l.changeId), ...laterPages])],
86
+ })
87
+ const items = await changes.itemsOf(id)
88
+ const schema = options.schema()
89
+ const pages = await new TransferRunRepository(db).changes(id)
90
+
91
+ // Its pages first, through the revert a run has; it refuses where one was edited since.
92
+ let revertId: string | undefined
93
+ if (pages.length > 0) {
94
+ const result = await revertRun(db, id)
95
+ if (!result.runId)
96
+ return refused('A page it changed was edited since.', 409, {
97
+ findings: result.check.outstanding.map((f) => f.message),
98
+ })
99
+ revertId = result.runId
100
+ await db.q
101
+ .updateTable('content_transfer_run')
102
+ .set({
103
+ change_kind: 'revert',
104
+ name: `Revert of ${change.name ?? 'a change'}`,
105
+ made_by: principal.id,
106
+ change_key: revertId,
107
+ })
108
+ .where('id', '=', revertId)
109
+ .execute()
110
+ } else {
111
+ revertId = await changes.begin({
112
+ kind: 'revert',
113
+ name: `Revert of ${change.name ?? 'a change'}`,
114
+ madeBy: principal.id,
115
+ revertsId: id,
116
+ })
117
+ await changes.setStatus(id, 'reverted')
118
+ }
119
+
120
+ // Then its files, each as it was before the change.
121
+ if (items.length > 0 && schema) {
122
+ const writes: Record<string, string | null> = {}
123
+ const befores: Record<string, string | null> = {}
124
+ for (const item of items) {
125
+ writes[item.path] = item.before
126
+ befores[item.path] = item.after
127
+ }
128
+ const applied = await db.transaction((tx) =>
129
+ schema.apply(tx, {
130
+ writes,
131
+ befores,
132
+ conflicts: [],
133
+ problems: [],
134
+ change: 'breaking',
135
+ items: [],
136
+ }),
137
+ )
138
+ await applied.after()
139
+ const recorded = new ChangeRepository(db)
140
+ for (const item of items)
141
+ await recorded.item(revertId, {
142
+ path: item.path,
143
+ kind: item.kind,
144
+ class: item.class,
145
+ before: item.after,
146
+ after: item.before,
147
+ })
148
+ }
149
+
150
+ let reopened: string | undefined
151
+ if (toWorkspace) reopened = await reopen(change.name ?? 'A change', items, pages, principal)
152
+ await recordAudit(db, {
153
+ category: 'content',
154
+ action: 'Revert',
155
+ source: 'request',
156
+ userKey: principal.id,
157
+ userName: principal.name,
158
+ entityType: 'Change',
159
+ entityKey: id,
160
+ entityName: change.name,
161
+ detail: `Reverted "${change.name ?? id}"${reopened ? ', its work reopened as a workspace' : ''}`,
162
+ ipAddress: client.ipAddress,
163
+ forwardedFor: client.forwardedFor,
164
+ })
165
+ await options.onReverted?.()
166
+ return json({ revertId, ...(reopened ? { workspace: reopened } : {}) })
167
+ }
168
+
169
+ /** A workspace holding what a change held: its files as it left them, its pages likewise. */
170
+ async function reopen(
171
+ name: string,
172
+ items: Awaited<ReturnType<ChangeRepository['itemsOf']>>,
173
+ pages: Awaited<ReturnType<TransferRunRepository['changes']>>,
174
+ principal: Principal,
175
+ ): Promise<string> {
176
+ const workspaces = new WorkspaceRepository(db)
177
+ const opened = await workspaces.open({ name: `Reopened: ${name}`, ownerKey: principal.id })
178
+ await options.schema()?.snapshot(opened.id)
179
+ const store = new WorkspaceFileRepository(db)
180
+ for (const item of items) await store.write(opened.id, item.path, item.after, item.class)
181
+ const shared = new DocumentRepository(db, { nodeState: options.nodeState })
182
+ const own = shared.inWorkspace(opened.id)
183
+ for (const page of pages) {
184
+ if (page.eventId === null) continue
185
+ const held = await shared.atVersion(String(page.eventId))
186
+ if (!held) continue
187
+ const document = held.document
188
+ await own.update({
189
+ key: document.key,
190
+ contentTypeKey: document.contentTypeKey,
191
+ componentKey: document.componentKey,
192
+ parentKey: document.parentKey,
193
+ values: document.values,
194
+ variants: document.variants.map((v) => ({
195
+ culture: v.culture,
196
+ segment: v.segment,
197
+ name: v.name,
198
+ })),
199
+ })
200
+ }
201
+ return opened.key
202
+ }
203
+
204
+ return {
205
+ async handle(
206
+ request: Request,
207
+ principal: Principal,
208
+ rest: string,
209
+ client: Client,
210
+ ): Promise<Response> {
211
+ const url = new URL(request.url)
212
+ const parts = rest.split('/').filter(Boolean).map(decodeURIComponent)
213
+ if (parts.length === 0 && request.method === 'GET') {
214
+ const skip = Math.max(0, Number(url.searchParams.get('skip') ?? 0) || 0)
215
+ const take = Math.min(200, Math.max(1, Number(url.searchParams.get('take') ?? 50) || 50))
216
+ return json(await changes.list(skip, take))
217
+ }
218
+ if (parts[0] === 'versions' && parts.length === 1 && request.method === 'GET') {
219
+ const path = url.searchParams.get('path') ?? ''
220
+ if (!path) return refused('Name the file, by its path.', 400)
221
+ const versions = await changes.versions(path)
222
+ const out = []
223
+ for (const v of versions) {
224
+ const change = await changes.byId(v.changeId)
225
+ out.push({
226
+ changeId: v.changeId,
227
+ name: change?.name ?? null,
228
+ kind: change?.kind,
229
+ madeBy: change?.madeBy ?? null,
230
+ at: change?.startedAt,
231
+ class: v.class,
232
+ removed: v.after === null,
233
+ })
234
+ }
235
+ return json({ path, versions: out })
236
+ }
237
+ const id = parts[0] ? normaliseUuid(parts[0]) : ''
238
+ if (parts.length === 1 && request.method === 'GET') {
239
+ const found = await detail(id)
240
+ return found ? json(found) : refused('There is no such change.', 404)
241
+ }
242
+ // An earlier version of one file against the file now.
243
+ if (parts[1] === 'compare' && parts.length === 2 && request.method === 'GET') {
244
+ const path = url.searchParams.get('path') ?? ''
245
+ const item = (await changes.itemsOf(id)).find((i) => i.path === path)
246
+ if (!item) return refused('That change did not touch that file.', 404)
247
+ const now = (await options.schema()?.textNow(path)) ?? null
248
+ return json({ path, version: item.after, current: now, same: item.after === now })
249
+ }
250
+ if (parts[1] === 'revert' && parts.length === 2 && request.method === 'POST') {
251
+ if (!principal.isAdmin) return refused('Only an administrator reverts a change.', 403)
252
+ const asked = ((await request.json().catch(() => ({}))) ?? {}) as Record<string, unknown>
253
+ return revert(id, principal, asked.toWorkspace === true, client)
254
+ }
255
+ return refused('There is nothing here.', 404)
256
+ },
257
+ }
258
+ }
@@ -58,8 +58,8 @@ export async function handleComponentTemplates(
58
58
  return Response.json({ items: componentTemplates(onDisk, await repo.all(), extensions) })
59
59
 
60
60
  if (request.method === 'POST') {
61
- // As changing which templates a type allows: Settings.
62
- if (!hasSection(principal, 'settings'))
61
+ // As changing which templates a type allows: Structure (story 385).
62
+ if (!hasSection(principal, 'structure'))
63
63
  return Response.json(
64
64
  { message: 'Making a component a template needs access to Structure.' },
65
65
  { status: 403 },
package/src/config.ts CHANGED
@@ -112,18 +112,26 @@ export function agentsGuideProblem(guide: string): string | undefined {
112
112
  : `The remote's agentsGuide, ${guide}, is not https: a guide is fetched only over https.`
113
113
  }
114
114
 
115
- export type ContentMode = 'development' | 'production'
115
+ /** Whether the back office may change the site's code: its templates, stylesheets and scripts. */
116
+ export type CodeSetting = 'editable' | 'locked'
116
117
 
117
- /** `CROMBOLO_CONTENT_MODE`, refusing the switch it replaced so locked files never quietly unlock. */
118
- function contentModeSetting(): ContentMode {
119
- // Read directly: it is no longer a setting, only a name to refuse.
118
+ /** `CROMBOLO_CODE`, refusing the names it replaced so locked code never quietly unlocks. */
119
+ function codeSetting(): CodeSetting {
120
+ // Read directly: they are no longer settings, only names to refuse.
120
121
  if (Bun.env.CROMBOLO_CONTENT_FILES_READONLY !== undefined)
121
122
  throw new Error(
122
- 'CROMBOLO_CONTENT_FILES_READONLY has gone: set CROMBOLO_CONTENT_MODE to production to keep templates, stylesheets and scripts read-only, or to development (story 343).',
123
+ 'CROMBOLO_CONTENT_FILES_READONLY has gone: set CROMBOLO_CODE=locked to keep templates, stylesheets and scripts read-only, or CROMBOLO_CODE=editable (story 391).',
124
+ )
125
+ const old = Bun.env.CROMBOLO_CONTENT_MODE
126
+ if (old !== undefined) {
127
+ const now = old.trim().toLowerCase() === 'production' ? 'locked' : 'editable'
128
+ throw new Error(
129
+ `CROMBOLO_CONTENT_MODE has gone: set CROMBOLO_CODE=${now} instead of CROMBOLO_CONTENT_MODE=${old} (story 391).`,
123
130
  )
124
- const value = (setting('CROMBOLO_CONTENT_MODE') ?? 'development').trim().toLowerCase()
125
- if (value !== 'development' && value !== 'production')
126
- throw new Error(`CROMBOLO_CONTENT_MODE is "${value}": it is development or production.`)
131
+ }
132
+ const value = (setting('CROMBOLO_CODE') ?? 'editable').trim().toLowerCase()
133
+ if (value !== 'editable' && value !== 'locked')
134
+ throw new Error(`CROMBOLO_CODE is "${value}": it is editable or locked.`)
127
135
  return value
128
136
  }
129
137
 
@@ -154,9 +162,40 @@ function cliAccessSetting(): CliAccess | undefined {
154
162
  return value
155
163
  }
156
164
 
157
- /** Whether the back office must leave templates, stylesheets and scripts alone. */
158
- export const contentFilesLocked = (config: Pick<CromboloConfig, 'contentMode'>) =>
159
- config.contentMode === 'production'
165
+ /** `CROMBOLO_ENVIRONMENT`, or `local` in development and `production` otherwise (story 387). */
166
+ function environmentName(): string {
167
+ const value =
168
+ setting('CROMBOLO_ENVIRONMENT')?.trim().toLowerCase() ||
169
+ (setting('NODE_ENV') === 'production' ? 'production' : 'local')
170
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(value))
171
+ throw new Error(
172
+ `CROMBOLO_ENVIRONMENT is "${value}": an environment's name is lower-case letters, digits and hyphens.`,
173
+ )
174
+ return value
175
+ }
176
+
177
+ /** Whether pages, media, types and code arrive only by a change (story 388). */
178
+ export type ContentSetting = 'editable' | 'locked'
179
+
180
+ /** `CROMBOLO_CONTENT`: `editable` unless set. */
181
+ function contentSetting(): ContentSetting {
182
+ const value = (setting('CROMBOLO_CONTENT') ?? 'editable').trim().toLowerCase()
183
+ if (value !== 'editable' && value !== 'locked')
184
+ throw new Error(`CROMBOLO_CONTENT is "${value}": it is editable or locked.`)
185
+ return value
186
+ }
187
+
188
+ /** Whether the back office must leave templates, stylesheets and scripts alone: locked content locks them too. */
189
+ export const contentFilesLocked = (config: Pick<CromboloConfig, 'code' | 'contentEditing'>) =>
190
+ config.code === 'locked' || config.contentEditing === 'locked'
191
+
192
+ /** Whether workspaces are on: turned on, or a locked site's, for the changes staged on it (story 388). */
193
+ export const workspacesOn = (config: Pick<CromboloConfig, 'workspaces' | 'contentEditing'>) =>
194
+ config.workspaces || config.contentEditing === 'locked'
195
+
196
+ /** Whether the site takes its pages, media, types and code only by a change (story 388). */
197
+ export const contentLocked = (config: Pick<CromboloConfig, 'contentEditing'>) =>
198
+ config.contentEditing === 'locked'
160
199
 
161
200
  /** `CROMBOLO_REMOTE_ACCESS`, refusing the switch it replaced so a site does not quietly stop being a remote. */
162
201
  function remoteAccessSetting(): RemoteAccess {
@@ -241,6 +280,17 @@ export interface CromboloConfig {
241
280
  */
242
281
  signalRSkipNegotiation: boolean
243
282
  development: boolean
283
+ /**
284
+ * Which copy of the site this is (story 387): the environment whose own value a
285
+ * property varying by environment serves. `CROMBOLO_ENVIRONMENT`; `local` in
286
+ * development, `production` otherwise. The remote environment defaults to it.
287
+ */
288
+ environment: string
289
+ /**
290
+ * This environment's own values arrive only by a change (story 387): the editor and
291
+ * the API refuse to set them here. `CROMBOLO_ENVIRONMENT_VALUES_READONLY`, off.
292
+ */
293
+ environmentValuesReadOnly: boolean
244
294
  /**
245
295
  * Open pages reload when the views, the schema or the content change, and
246
296
  * show the background type check's findings (story 214). On in development,
@@ -415,11 +465,22 @@ export interface CromboloConfig {
415
465
  */
416
466
  schemaWritable: boolean
417
467
  /**
418
- * `production` keeps templates, stylesheets and scripts read-only in the back
419
- * office, for a site whose files come from its repository (stories 337, 343).
420
- * `development` unless set, in production too. `CROMBOLO_CONTENT_MODE`.
468
+ * `locked` keeps templates, stylesheets and scripts read-only in the back office,
469
+ * for a site whose files come from its repository (stories 337, 343, 391).
470
+ * `editable` unless set, in production too. `CROMBOLO_CODE`.
421
471
  */
422
- contentMode: ContentMode
472
+ code: CodeSetting
473
+ /**
474
+ * `locked` makes pages, media, the Library, types, data types and code read-only in
475
+ * the back office and the API: they arrive only by a change applied here (story
476
+ * 388). `editable` unless set. `CROMBOLO_CONTENT`.
477
+ */
478
+ contentEditing: ContentSetting
479
+ /**
480
+ * Where a locked site's content is edited: the other site's back office, for the
481
+ * line and link an item opened here shows. `CROMBOLO_CONTENT_EDITED_AT`.
482
+ */
483
+ contentEditedAt?: string
423
484
  /**
424
485
  * Whether a command that reads or changes the site needs a signed-in person
425
486
  * (story 350): `sign-in` unless `development`, where it is `open`.
@@ -433,6 +494,47 @@ export interface CromboloConfig {
433
494
  cliTokens: boolean
434
495
  /** The most days a command-line token may last. `CROMBOLO_CLI_TOKEN_MAX_DAYS`, 90. */
435
496
  cliTokenMaxDays: number
497
+ /**
498
+ * Whether people may open workspaces, to change pages apart from Shared
499
+ * (story 375). `CROMBOLO_WORKSPACES`, off unless set.
500
+ */
501
+ workspaces: boolean
502
+ /**
503
+ * Whether every change to a page is made in a workspace (story 380): Shared
504
+ * takes it only by a merge. `CROMBOLO_WORKSPACES_REQUIRED`, off unless set; it
505
+ * needs workspaces on.
506
+ */
507
+ workspacesRequired: boolean
508
+ /**
509
+ * How many workspaces with changed views render at once on a node, each in a
510
+ * process of its own (story 378); past it the least recently used is stopped.
511
+ * `CROMBOLO_WORKSPACE_PROCESSES`, 10.
512
+ */
513
+ workspaceProcesses: number
514
+ /** A workspace's process is stopped after this long unused. `CROMBOLO_WORKSPACE_PROCESS_IDLE_MINUTES`, 30. */
515
+ workspaceProcessIdleMinutes: number
516
+ /** A workspace's process is stopped past this much memory. `CROMBOLO_WORKSPACE_PROCESS_MEMORY_MB`, 1024. */
517
+ workspaceProcessMemoryMb: number
518
+ /** How long a page may take in a workspace's process. `CROMBOLO_WORKSPACE_RENDER_SECONDS`, 30. */
519
+ workspaceRenderSeconds: number
520
+ /**
521
+ * The fewest days between retiring a property and purging it, with its values
522
+ * (story 382). `CROMBOLO_PURGE_AFTER_DAYS`, 0.
523
+ */
524
+ purgeAfterDays: number
525
+ /**
526
+ * Where a workspace's site is served (story 379): a host pattern with
527
+ * `{workspace}` for its key's 32 hex digits, and `{host}` for one of the site's
528
+ * hosts, such as `{workspace}.preview.example.com`. Unset, a workspace is
529
+ * opened by a cookie on the site's own host. `CROMBOLO_WORKSPACES_HOST`.
530
+ */
531
+ workspacesHost: string | undefined
532
+ /** The longest a link to a workspace's site may last, in days; 0 turns links off. `CROMBOLO_WORKSPACE_LINK_MAX_DAYS`, 30. */
533
+ workspaceLinkMaxDays: number
534
+ /** How many workspaces' sites one node keeps ready. `CROMBOLO_WORKSPACE_SITES`, 3. */
535
+ workspaceSites: number
536
+ /** How long a workspace's site is kept without a visit. `CROMBOLO_WORKSPACE_SITE_IDLE_MINUTES`, 15. */
537
+ workspaceSiteIdleMinutes: number
436
538
  /** Sync `schema/` at boot; a pipeline that runs `crombolo types sync` turns this off. */
437
539
  syncSchemaAtBoot: boolean
438
540
  /** Which database engine; from CROMBOLO_DB. */
@@ -936,6 +1038,8 @@ export function loadConfig(
936
1038
  umbracoCssPath: DEFAULTS.umbracoCssPath,
937
1039
  signalRSkipNegotiation: DEFAULTS.signalRSkipNegotiation,
938
1040
  development: setting('NODE_ENV') !== 'production',
1041
+ environment: environmentName(),
1042
+ environmentValuesReadOnly: envFlag(setting('CROMBOLO_ENVIRONMENT_VALUES_READONLY')) === true,
939
1043
  sqliteFile: setting('CROMBOLO_SQLITE_FILE') ?? DEFAULTS.sqliteFile,
940
1044
  adminLogin: setting('CROMBOLO_ADMIN_LOGIN') ?? DEFAULTS.adminLogin,
941
1045
  adminPassword: setting('CROMBOLO_ADMIN_PASSWORD'),
@@ -990,11 +1094,29 @@ export function loadConfig(
990
1094
  ? setting('CROMBOLO_SCHEMA_WRITABLE') === 'true'
991
1095
  : setting('NODE_ENV') !== 'production',
992
1096
  syncSchemaAtBoot: setting('CROMBOLO_SYNC_SCHEMA_AT_BOOT') !== 'false',
993
- contentMode: contentModeSetting(),
1097
+ code: codeSetting(),
1098
+ contentEditing: contentSetting(),
1099
+ contentEditedAt: setting('CROMBOLO_CONTENT_EDITED_AT') || undefined,
994
1100
  // Resolved again below, once it is known whether this is development.
995
1101
  cliAccess: cliAccessSetting() as CliAccess,
996
1102
  cliTokens: setting('CROMBOLO_CLI_TOKENS') === 'true',
997
1103
  cliTokenMaxDays: Math.floor(positiveNumber(setting('CROMBOLO_CLI_TOKEN_MAX_DAYS'), 90)),
1104
+ workspaces: setting('CROMBOLO_WORKSPACES') === 'true',
1105
+ workspacesRequired: setting('CROMBOLO_WORKSPACES_REQUIRED') === 'true',
1106
+ purgeAfterDays: Math.floor(nonNegativeNumber(setting('CROMBOLO_PURGE_AFTER_DAYS'), 0)),
1107
+ workspacesHost: setting('CROMBOLO_WORKSPACES_HOST') || undefined,
1108
+ workspaceLinkMaxDays: Math.floor(
1109
+ nonNegativeNumber(setting('CROMBOLO_WORKSPACE_LINK_MAX_DAYS'), 30),
1110
+ ),
1111
+ workspaceSites: Math.floor(positiveNumber(setting('CROMBOLO_WORKSPACE_SITES'), 3)),
1112
+ workspaceSiteIdleMinutes: positiveNumber(setting('CROMBOLO_WORKSPACE_SITE_IDLE_MINUTES'), 15),
1113
+ workspaceProcesses: Math.floor(positiveNumber(setting('CROMBOLO_WORKSPACE_PROCESSES'), 10)),
1114
+ workspaceProcessIdleMinutes: positiveNumber(
1115
+ setting('CROMBOLO_WORKSPACE_PROCESS_IDLE_MINUTES'),
1116
+ 30,
1117
+ ),
1118
+ workspaceProcessMemoryMb: positiveNumber(setting('CROMBOLO_WORKSPACE_PROCESS_MEMORY_MB'), 1024),
1119
+ workspaceRenderSeconds: positiveNumber(setting('CROMBOLO_WORKSPACE_RENDER_SECONDS'), 30),
998
1120
  dialect: setting('CROMBOLO_DB') === 'postgres' ? 'postgres' : 'sqlite',
999
1121
  pgDump: setting('CROMBOLO_PG_DUMP'),
1000
1122
  upgradePolicy:
@@ -1064,7 +1186,7 @@ export function loadConfig(
1064
1186
  remote: {
1065
1187
  enabled: remoteAccessSetting() !== 'off',
1066
1188
  access: remoteAccessSetting(),
1067
- environment: setting('CROMBOLO_REMOTE_ENVIRONMENT') || 'production',
1189
+ environment: setting('CROMBOLO_REMOTE_ENVIRONMENT') || environmentName(),
1068
1190
  protected: setting('CROMBOLO_REMOTE_PROTECTED') !== 'false',
1069
1191
  approvals: setting('CROMBOLO_REMOTE_APPROVALS') === 'true',
1070
1192
  maxUploadBytes: Number(setting('CROMBOLO_REMOTE_MAX_UPLOAD_GB') ?? 50) * 1024 ** 3,
@@ -1152,16 +1274,28 @@ export function loadConfig(
1152
1274
  host: undefined,
1153
1275
  }
1154
1276
  const merged: CromboloConfig = { ...fromEnv, ...stripUndefined(overrides) }
1155
- // The file is checked as the environment is: an unknown mode must not fall back to editable.
1156
- if (merged.contentMode !== 'development' && merged.contentMode !== 'production')
1277
+ // The file is checked as the environment is: an unknown value must not fall back to editable.
1278
+ if ('contentMode' in overrides)
1279
+ throw new Error(
1280
+ `contentMode has gone from crombolo.config.ts: set code: '${(overrides as { contentMode?: string }).contentMode === 'production' ? 'locked' : 'editable'}' instead (story 391).`,
1281
+ )
1282
+ if (merged.contentEditing !== 'editable' && merged.contentEditing !== 'locked')
1283
+ throw new Error(
1284
+ `contentEditing is "${String(merged.contentEditing)}" in crombolo.config.ts: it is editable or locked.`,
1285
+ )
1286
+ if (merged.code !== 'editable' && merged.code !== 'locked')
1157
1287
  throw new Error(
1158
- `contentMode is "${String(merged.contentMode)}" in crombolo.config.ts: it is development or production.`,
1288
+ `code is "${String(merged.code)}" in crombolo.config.ts: it is editable or locked.`,
1159
1289
  )
1160
1290
  merged.cliAccess ??= merged.development ? 'open' : 'sign-in'
1161
1291
  if (merged.cliAccess !== 'open' && merged.cliAccess !== 'sign-in')
1162
1292
  throw new Error(
1163
1293
  `cliAccess is "${String(merged.cliAccess)}" in crombolo.config.ts: it is open or sign-in.`,
1164
1294
  )
1295
+ if (merged.workspacesRequired && !merged.workspaces)
1296
+ throw new Error(
1297
+ 'Workspaces are required (CROMBOLO_WORKSPACES_REQUIRED) but not turned on: set CROMBOLO_WORKSPACES=true as well.',
1298
+ )
1165
1299
  checkIdentityProviders(merged.memberIdentityProviders, 'member')
1166
1300
  checkIdentityProviders(merged.backofficeIdentityProviders, 'backoffice')
1167
1301
  for (const clash of exchangeAudienceClashes(
@@ -1200,7 +1334,7 @@ export function loadConfig(
1200
1334
  'webhooks.allowPrivateAddresses is now CROMBOLO_ALLOW_PRIVATE_ADDRESSES (allowPrivateAddresses in the config), which covers forms and identity providers too (story 304).',
1201
1335
  )
1202
1336
  checkApiClient(merged.apiClient)
1203
- checkHost(merged.host)
1337
+ checkHost(merged.host, merged.backofficeIdentityProviders, merged.lockedIdentityProviders)
1204
1338
  // The key itself is refused, so a config left over from before says so rather
1205
1339
  // than starting without the feature it asked for.
1206
1340
  if ('assistant' in overrides)
@@ -1314,7 +1448,7 @@ export function describeDatabase(
1314
1448
  }
1315
1449
  }
1316
1450
 
1317
- export const VERSION = '0.69.0'
1451
+ export const VERSION = '0.70.0'
1318
1452
 
1319
1453
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1320
1454
  /** A positive number from a setting, else the default. */
@@ -1323,6 +1457,12 @@ function positiveNumber(raw: string | undefined, fallback: number): number {
1323
1457
  return raw !== undefined && raw !== '' && Number.isFinite(value) && value > 0 ? value : fallback
1324
1458
  }
1325
1459
 
1460
+ /** Zero or more from a setting, else the default. */
1461
+ function nonNegativeNumber(raw: string | undefined, fallback: number): number {
1462
+ const value = Number(raw)
1463
+ return raw !== undefined && raw !== '' && Number.isFinite(value) && value >= 0 ? value : fallback
1464
+ }
1465
+
1326
1466
  function validatorSetting(name: Parameters<typeof setting>[0]): Validator | undefined {
1327
1467
  const raw = setting(name)?.trim()
1328
1468
  return raw === 'published' || raw === 'body' ? raw : undefined
@@ -5,7 +5,10 @@
5
5
  * live backoffice, and a nudge so the dispatcher sends it now rather than at
6
6
  * its next tick. The command line wires the same sink without the live part.
7
7
  */
8
+
9
+ import { CHANGE_PUBLISHED } from '@crombolo/api-management'
8
10
  import {
11
+ type Actor,
9
12
  actorMemberKey,
10
13
  actorName,
11
14
  actorNote,
@@ -23,7 +26,7 @@ import {
23
26
  notificationFor,
24
27
  webhookFor,
25
28
  } from '@crombolo/content'
26
- import { AuditLog, ContentEventRepository, type Db } from '@crombolo/data'
29
+ import { AuditLog, ChangeRepository, ContentEventRepository, type Db } from '@crombolo/data'
27
30
  import type { ContentNotifier } from './content-notifications.ts'
28
31
  import type { WebhookService } from './webhooks.ts'
29
32
 
@@ -34,8 +37,21 @@ export interface ContentEventSinkOptions {
34
37
  live?(event: ReturnType<typeof liveEventsFor>[number]): void
35
38
  /** Called after a commit that left work in the outbox. */
36
39
  nudge?(): void
40
+ /**
41
+ * Story 388: a person's own saves join their change, and a publish closes it and
42
+ * raises `Crombolo.ChangePublished` naming it, for a host to pass on.
43
+ */
44
+ changes?: boolean
37
45
  }
38
46
 
47
+ const SAVES = new Set(['created', 'saved', 'createdAndPublished', 'savedAndPublished'])
48
+ const PUBLISHES = new Set([
49
+ 'published',
50
+ 'createdAndPublished',
51
+ 'savedAndPublished',
52
+ 'branchPublished',
53
+ ])
54
+
39
55
  /** The page an event is about, for the outbox row. */
40
56
  const subjectOf = (event: DocumentEvent): string | null =>
41
57
  'key' in event ? event.key : 'parentKey' in event ? event.parentKey : null
@@ -60,8 +76,37 @@ export const outboxActor = (actor: MediaActor) => {
60
76
  }
61
77
 
62
78
  export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
79
+ /** A person's own write in the back office or the API, not a merge's nor the site's code. */
80
+ const ownEdit = (actor: Actor) => actor.kind === 'user' && !actor.origin.via
81
+
82
+ /** Story 388: the page in its writer's change, and on a publish the change closed and announced. */
83
+ async function recordInChange(tx: Db, event: DocumentEvent, actor: Actor) {
84
+ const key = subjectOf(event)
85
+ const userKey = actorUserKey(actor)
86
+ if (!key || !userKey || !ownEdit(actor)) return
87
+ const changes = new ChangeRepository(tx)
88
+ if (SAVES.has(event.type)) await changes.pageSavedBy(userKey, { key, kind: 'document' })
89
+ if (!PUBLISHES.has(event.type)) return
90
+ const change = await changes.publishedBy(userKey, { key, kind: 'document' })
91
+ if (!change) return
92
+ const hook = { alias: CHANGE_PUBLISHED, key }
93
+ await new ContentEventRepository(tx).record({
94
+ kind: 'change-published',
95
+ entityType: 'Document',
96
+ entityKey: key,
97
+ facts: {
98
+ v: 1,
99
+ ...(options.webhooks
100
+ ? { webhook: { ...(await options.webhooks.factsFor(tx, hook)), change } }
101
+ : {}),
102
+ },
103
+ actor: outboxActor(actor),
104
+ })
105
+ }
106
+
63
107
  return {
64
108
  async record(tx: Db, event, actor) {
109
+ if (options.changes) await recordInChange(tx, event, actor as Actor)
65
110
  const entry = auditEntryFor(event, actor)
66
111
  const audit = new AuditLog(tx)
67
112
  // A deleted page cannot be named after it went: the operation read its name first.
@@ -175,3 +220,22 @@ export function createElementEventSink(): ElementEventSink {
175
220
  },
176
221
  }
177
222
  }
223
+
224
+ /** A workspace's Library writes (story 390): audited, naming the workspace, and announced nowhere else. */
225
+ export function workspaceElementEventSink(name: string): ElementEventSink {
226
+ return {
227
+ async record(tx: Db, event, actor) {
228
+ const entry = elementAuditEntryFor(event, actor)
229
+ const audit = new AuditLog(tx)
230
+ const subject = await audit.describe(entry.entityType, entry.entityKey)
231
+ const where = `In the workspace "${name}"`
232
+ await audit.record({
233
+ ...entry,
234
+ entityType: subject.entityType,
235
+ entityKey: subject.entityKey,
236
+ entityName: subject.entityName,
237
+ detail: entry.detail ? `${where}. ${entry.detail}` : where,
238
+ })
239
+ },
240
+ }
241
+ }