@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
package/src/server.ts CHANGED
@@ -46,8 +46,7 @@ import {
46
46
  } from '@crombolo/auth'
47
47
  import {
48
48
  collectManifests,
49
- createBackOfficePaths,
50
- createExtensionRegistry,
49
+ type createBackOfficePaths,
51
50
  isSpaRoute,
52
51
  renderBackOfficeShell,
53
52
  renderDeviceShell,
@@ -58,9 +57,9 @@ import {
58
57
  resolveStaticFile,
59
58
  serveStaticFile,
60
59
  } from '@crombolo/backoffice-host'
61
- import type { DocumentOperations, MediaOperations } from '@crombolo/content'
62
60
  import { servedContract } from '@crombolo/contracts'
63
61
  import {
62
+ CACHE_KEEP_FOR_ALIAS,
64
63
  CHOICE_SOURCE_KINDS,
65
64
  type ChoiceSourceKind,
66
65
  contractPathFor,
@@ -77,11 +76,12 @@ import {
77
76
  } from '@crombolo/core'
78
77
  import {
79
78
  appendCacheInstruction,
80
- createTablesCapability,
81
79
  type Db,
82
80
  ensureKeyValue,
83
81
  FormEntryRepository,
84
82
  FormWorkflowRepository,
83
+ JobRepository,
84
+ type JobState,
85
85
  latestContentVersionId,
86
86
  MediaAccessRepository,
87
87
  MemberRepository,
@@ -92,33 +92,37 @@ import {
92
92
  readUrlOptions,
93
93
  SiteSearch,
94
94
  TransferRunRepository,
95
- UserGroupRepository,
96
95
  type WritesPaused,
97
96
  } from '@crombolo/data'
98
97
  import {
99
98
  BUNDLE_SCRIPT,
100
99
  BUNDLE_SCRIPT_PATH,
101
- BUNDLE_SITE_PATH,
102
100
  cacheable,
103
101
  cacheControl,
102
+ chosenLifetime,
104
103
  contentForNode,
105
- DEFAULT_MEDIA_CACHE_MEGABYTES,
106
- DEVELOPMENT_LIMITS,
107
104
  FORM_SCRIPT,
108
105
  FORM_SCRIPT_PATH,
109
106
  FORM_SUBMIT_PATH,
110
107
  formAction,
108
+ ISLAND_LOADER_PATH,
109
+ ISLAND_LOADER_SCRIPT,
110
+ ISLANDS_PATH,
111
+ LIVE_EVENTS_PATH,
112
+ LIVE_RELOAD_SCRIPT,
113
+ LIVE_RELOAD_SCRIPT_PATH,
114
+ type Lifetime,
111
115
  lifetimeFor,
112
- MEMBER_EXTERNAL_SIGN_IN_PATH,
113
- MediaCache,
116
+ type PageOutcome,
114
117
  PRIVATE_NO_STORE,
115
118
  PublishedCache,
116
- Renderer,
119
+ type PublishedContent,
120
+ type Renderer,
121
+ type RequestMember,
117
122
  resolveCacheSettings,
118
123
  type SnapshotStatus,
119
- setFormFieldTypes,
120
- setFormTokenSigner,
121
- ViewSnapshots,
124
+ type ViewSnapshots,
125
+ withLiveReload,
122
126
  } from '@crombolo/render'
123
127
  import type { SyncReport } from '@crombolo/schema'
124
128
  import { choicesFor } from '@crombolo/transfer'
@@ -126,31 +130,15 @@ import type { Server } from 'bun'
126
130
  import { createNodeLookup, loadAccess } from './access.ts'
127
131
  import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
128
132
  import { readCreatedBundlePackage, writeCreatedBundlePackage } from './adapters/bundles.ts'
129
- import {
130
- createMediaSource,
131
- createPublishedContentSource,
132
- loadDraftNode,
133
- } from './adapters/documents.ts'
133
+ import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
134
134
  import type { Approvals } from './approvals.ts'
135
135
  import { handleApprovalsApi } from './approvals-api.ts'
136
+ import type { BundleGrants } from './bundle-grants.ts'
136
137
  import { CommandError, installBundleContent } from './bundle-install.ts'
137
- import {
138
- type BundleMediaFactory,
139
- createBundleMedia,
140
- type ResolvedMediaFolder,
141
- resolveBundleMediaFolders,
142
- } from './bundle-media.ts'
143
138
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
144
- import { bundleChains, bundleTablesReport } from './bundle-tables.ts'
145
- import {
146
- type BundleMember,
147
- bundleRouteGroups,
148
- createBundleRedirects,
149
- createServerBundles,
150
- validateServerBundles,
151
- } from './bundles.ts'
139
+ import { bundleRouteGroups } from './bundles.ts'
152
140
  import { busyResponse } from './busy.ts'
153
- import { listEmailTemplates } from './components.ts'
141
+ import { checkTypes, listEmailTemplates } from './components.ts'
154
142
  import {
155
143
  type CromboloConfig,
156
144
  listeningBodyLimit,
@@ -158,32 +146,26 @@ import {
158
146
  type ServerRole,
159
147
  VERSION,
160
148
  } from './config.ts'
161
- import { createContentDispatcher } from './content-dispatch.ts'
162
- import { createContentEventSink } from './content-events.ts'
163
- import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
164
149
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
165
- import { attachDatabase, bootstrapDatabase } from './database.ts'
150
+ import { createCore } from './core.ts'
151
+ import { closeTables, tablesReport } from './custom-tables.ts'
166
152
  import { createDeliveryMediaPort } from './delivery-media.ts'
167
153
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
168
- import { createDiagnostics } from './diagnostics.ts'
169
154
  import { syncDomainsFile } from './domains.ts'
170
155
  import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
171
- import { emailAvailability, resolveEmailPort } from './email.ts'
156
+ import { emailAvailability } from './email.ts'
172
157
  import { noticeAboutEmail } from './email-notice.ts'
173
158
  import { warnAboutAppPlugins } from './extensions-notice.ts'
174
159
  import { coerceForm, deleteForm, saveForm } from './form-files.ts'
175
160
  import {
176
- createFormRegistry,
177
161
  FORM_FLASH_COOKIE,
178
- formSigningSecret,
179
162
  readFlash,
180
163
  signFormToken,
181
164
  submitForm,
182
165
  wantsJson,
183
166
  writeFlash,
184
167
  } from './form-submit.ts'
185
- import { describeFormTypes, formTypesFor, formTypesOf } from './form-types.ts'
186
- import { createWorkflowRunner } from './form-workflows.ts'
168
+ import { describeFormTypes, formTypesFor } from './form-types.ts'
187
169
  import {
188
170
  entriesCsv,
189
171
  formDetail,
@@ -193,54 +175,54 @@ import {
193
175
  redactSensitive,
194
176
  } from './forms.ts'
195
177
  import { HOST_TOKEN_SECONDS, issueHostToken } from './host-token.ts'
196
- import { ImageProcessor, parseImagingQuery } from './imaging.ts'
197
- import { type BackgroundJobs, createBackgroundJobs } from './jobs.ts'
178
+ import { canEncodeAvif, ImageProcessor, parseImagingQuery } from './imaging.ts'
179
+ import type { BackgroundJobs } from './jobs.ts'
180
+ import { createLiveReload, createTypeWatch, watchDirectory } from './live-reload.ts'
198
181
  import { configureLogging, logger } from './logging.ts'
199
182
  import { createMarketplace } from './marketplace.ts'
200
183
  import { createMediaAccess } from './media-access.ts'
201
- import { MediaFileStore } from './media-files.ts'
202
- import { mediaStoreFromEnvironment } from './media-store.ts'
203
184
  import { createMemberAuth, MEMBER_ROUTE_PREFIX } from './member-auth.ts'
204
185
  import { noNodesPage } from './no-nodes.ts'
205
186
  import { NotImplementedLog } from './not-implemented.ts'
206
- import { createDeps, documentEditUrl, PREVIEW_COOKIE, resolveUserLinkSender } from './ports.ts'
187
+ import { createDeps, PREVIEW_COOKIE, resolveUserLinkSender } from './ports.ts'
207
188
  import {
208
189
  previewSigningSecret,
209
190
  previewUser,
210
191
  readPreviewToken,
211
192
  signPreviewToken,
212
193
  } from './preview-tokens.ts'
213
- import { createRedirectTracker } from './redirects.ts'
214
194
  import { createRemote } from './remote.ts'
215
- import { withRemoteMedia } from './remote-media.ts'
216
195
  import { unknownHostProvided } from './site-file.ts'
217
196
  import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
218
- import {
219
- changeUrlOptions,
220
- redirectAfterUrlChange,
221
- type UrlChangeContext,
222
- urlSettingEditable,
223
- } from './url-settings.ts'
197
+ import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
198
+ import type { JobsStatus } from './worker-watch.ts'
224
199
 
225
200
  export { PREVIEW_COOKIE }
226
201
 
227
- import { BACKOFFICE_EXTERNAL_PATH, backofficeAudience } from './backoffice-external.ts'
202
+ import type { SiteRoute } from '@crombolo/common'
203
+ import { backofficeAudience } from './backoffice-external.ts'
228
204
  import { createExternalSignIn } from './external-sign-in.ts'
205
+ import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
206
+ import {
207
+ builtIslandFile,
208
+ devServerIslandManifest,
209
+ viteIslandManifest,
210
+ viteOutDir,
211
+ } from './islands.ts'
229
212
  import {
230
- createBundleIdentityProviders,
231
- IdentityProviderOverrides,
232
- } from './identity-provider-overrides.ts'
213
+ hasMiddleware,
214
+ isSitePath,
215
+ type MiddlewareBudget,
216
+ MiddlewareError,
217
+ requestCookies,
218
+ runStage,
219
+ } from './middleware.ts'
220
+ import type { JobRunner } from './owner-jobs.ts'
233
221
  import { callerAddress } from './rate-limit.ts'
234
222
  import { syncConfiguredRedirects } from './redirects.ts'
235
- import {
236
- bootSchema,
237
- CacheInstructionPoller,
238
- componentAliasesIn,
239
- importSchema,
240
- type SchemaBoot,
241
- watchSchema,
242
- } from './schema.ts'
243
- import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
223
+ import { createRoutes, type DeclaredRoute, siteRouteProblems } from './routes.ts'
224
+ import { componentAliasesIn, importSchema, type SchemaBoot, watchSchema } from './schema.ts'
225
+ import { publishSchema, type SchemaStore } from './schema-store.ts'
244
226
  import { createSeoHost, originOf, publicOrigin } from './seo.ts'
245
227
  import {
246
228
  combineHubs,
@@ -250,10 +232,16 @@ import {
250
232
  } from './server-events.ts'
251
233
  import { AttemptLimiter, createSetupRoutes } from './setup.ts'
252
234
  import { siteSearchFor } from './site-search.ts'
235
+ import {
236
+ genericStatusPage,
237
+ previewRedirectNotice,
238
+ resolveStatusPage,
239
+ statusPageKind,
240
+ unresolvedStatusPages,
241
+ } from './status-pages.ts'
253
242
  import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
254
243
  import { summariseUpgrades } from './upgrade-summary.ts'
255
- import { assertViewRuntime } from './view-runtime.ts'
256
- import { bundleEventProblems, createWebhookService, webhookStoreView } from './webhooks.ts'
244
+ import { webhookStoreView } from './webhooks.ts'
257
245
 
258
246
  export interface ServerHandle {
259
247
  config: CromboloConfig
@@ -275,6 +263,12 @@ export interface ServerHandle {
275
263
  /** The views generations this node has taken; `status()` is what /health reports. */
276
264
  snapshots: ViewSnapshots
277
265
  seededAdminPassword: string | undefined
266
+ /** What each bundle may do, and whether it is on (story 222). */
267
+ bundleGrants: BundleGrants
268
+ /** The site's and bundles' background jobs (story 187); started on a node that owns writes. */
269
+ backgroundJobs: JobRunner
270
+ /** The wired bundles that are off, waiting for an administrator to approve these permissions. */
271
+ waitingBundles(): { id: string; missing: string[] }[]
278
272
  schema: SchemaBoot
279
273
  /** Applies cache instructions other nodes appended; the interval calls this too. */
280
274
  poll(): Promise<number>
@@ -296,6 +290,8 @@ export interface ServerHandle {
296
290
  role: ServerRole
297
291
  /** The views generation in use, and whether newer ones are being refused. */
298
292
  components: SnapshotStatus
293
+ /** Where jobs run, and whether a worker is running them; not on a `web` node. */
294
+ jobs?: JobsStatus
299
295
  }
300
296
  /** Scheduled publishing and version cleanup; each run can be called directly. */
301
297
  jobs: BackgroundJobs
@@ -310,32 +306,82 @@ export interface ServerHandle {
310
306
  }
311
307
 
312
308
  export async function createServer(config: CromboloConfig = loadConfig()): Promise<ServerHandle> {
309
+ if (config.role === 'worker')
310
+ throw new Error('A worker serves no site: start it with createWorker (story 223).')
313
311
  configureLogging({
314
312
  logsDir: config.logsDir,
315
313
  level: config.logLevel,
316
314
  console: config.logToConsole,
317
315
  })
318
- const diagnostics = createDiagnostics(config.diagnostics)
319
316
  const log = logger('server')
320
317
  const schemaLog = logger('schema')
321
318
  const renderLog = logger('render')
322
319
  const redirectLog = logger('redirects')
323
- const bundleLog = (id: string) => {
324
- const named = logger('bundle', id)
325
- return {
326
- info: (message: string, properties?: Record<string, unknown>) =>
327
- named.info(message, properties),
328
- warn: (message: string, properties?: Record<string, unknown>) =>
329
- named.warn(message, properties),
330
- error: (message: string, properties?: Record<string, unknown>) =>
331
- named.error(message, properties),
332
- }
333
- }
334
320
  const domainLog = logger('domains')
335
321
  const apiLog = logger('management-api')
336
- // Extensions are the site's own npm dependencies (`docs/bundles.md`).
337
- // Uncached in development so an author editing one sees a reload pick it up.
338
- const extensions = createExtensionRegistry(config.siteDir, { cache: !config.development })
322
+ // Story 214: in development, open pages reload when what they show changes,
323
+ // and a template error says which components were rendering.
324
+ const live = config.liveReload ? createLiveReload() : undefined
325
+ let drafts: { cache: PublishedCache; version: number } | undefined
326
+ const core = await createCore(config, {
327
+ onCacheInvalidate: () => {
328
+ drafts = undefined
329
+ live?.changed('content')
330
+ },
331
+ onViewsSwap: () => {
332
+ live?.changed('views')
333
+ void typeWatch
334
+ ?.schedule()
335
+ .catch((error: unknown) =>
336
+ renderLog.error('The type check failed to run: {error}', { error: String(error) }),
337
+ )
338
+ },
339
+ buildIslands: true,
340
+ announce: (event) => announce(event),
341
+ onDocumentChanged: (key) =>
342
+ events.broadcast('notify', [
343
+ { eventSource: 'Umbraco:CMS:Document', eventType: 'Updated', key },
344
+ ]),
345
+ streamMemberFile: (src, search) => streamMemberFile(src, search),
346
+ siteName: async () => (await seo.siteDefaults()).siteName,
347
+ })
348
+ const {
349
+ diagnostics,
350
+ extensions,
351
+ paths,
352
+ owns,
353
+ bundlePackages,
354
+ formTypes,
355
+ chains,
356
+ db,
357
+ seededAdminPassword,
358
+ bundleGrants,
359
+ jobRunner,
360
+ schema,
361
+ forms,
362
+ formSecret,
363
+ cacheOptions,
364
+ mediaCache,
365
+ cache,
366
+ afterSync,
367
+ snapshots,
368
+ renderer,
369
+ mediaStore,
370
+ email,
371
+ notifier,
372
+ mediaFiles,
373
+ webhooks,
374
+ dispatcher,
375
+ contentEvents,
376
+ bundles,
377
+ poller,
378
+ siteServicesFor,
379
+ jobs,
380
+ wake,
381
+ urlChange,
382
+ } = core
383
+ // What this process answers: only `web` serves no back office.
384
+ const servesBackOffice = config.role !== 'web'
339
385
  // A host that installs packages itself calls `reloadBundles()` (story 181); the
340
386
  // Marketplace's own install goes through it too, so either way open back
341
387
  // offices hear about it. `events` is created further down, before any reload.
@@ -351,6 +397,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
351
397
  extensions: { ...extensions, invalidate: () => void bundleReloader.reload() },
352
398
  siteDir: config.siteDir,
353
399
  wired: () => bundles?.mounted.map((bundle) => bundle.id) ?? [],
400
+ grants: {
401
+ state: (pkg) => bundleGrants.state(pkg),
402
+ grant: (pkg, by) => bundleGrants.grant(pkg, by),
403
+ },
354
404
  contentApplied: async (packageName) =>
355
405
  (await new TransferRunRepository(db).appliedForPackage(packageName))?.packageVersion ?? null,
356
406
  applyContentOnInstall: config.applyBundleContentOnInstall,
@@ -383,46 +433,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
383
433
  return { applied: true, runId: result.runId, message: 'Its content was applied.' }
384
434
  },
385
435
  })
386
- const paths = createBackOfficePaths({ backOfficePath: config.backOfficePath })
387
- // Two questions, not one: what this process answers, and what it is
388
- // responsible for converging at boot. `all` and `api` are both owners; only
389
- // `all` and `web` serve the public site.
390
- const servesBackOffice = config.role !== 'web'
391
- const owns = config.role !== 'web'
392
- // Bundles are checked before the database is touched, because a bundle that
393
- // owns tables is migrated at boot, and a bad declaration must not get that far.
394
- // On every role: a bundle's form types are needed wherever forms render and
395
- // submit, and its member and public routes wherever the site is served. Its
396
- // tables are migrated only by the nodes that own the database.
397
- const bundlePackages = extensions.bundles().bundles
398
- const formTypes = formTypesOf(config)
399
- {
400
- const problems = [
401
- ...validateServerBundles(config.bundles, bundlePackages, VERSION),
402
- ...formTypes.problems,
403
- ...bundleEventProblems(config.bundles),
404
- ]
405
- if (problems.length > 0)
406
- throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
407
- }
408
- setFormFieldTypes(formTypes.types, formTypes.renderers)
409
- const chains = bundleChains(config.bundles, bundlePackages)
410
- const { db, seededAdminPassword } = owns
411
- ? await bootstrapDatabase(config, chains)
412
- : await attachDatabase(config)
413
- // A configured schema store is copied down before anything reads `schema/`, and
414
- // becomes the schema directory for this boot. Everything after here — loading,
415
- // validation, hashing, sync, the writer — works on files exactly as it always has.
416
- const copied = await useSchemaStore(config)
417
- if (config.schemaStore)
418
- schemaLog.info('Schema read from {store}: {count} files in {dir}', {
419
- store: config.schemaStore.description,
420
- count: copied,
421
- dir: config.schemaCacheDir,
422
- })
423
- // A node that does not own the schema still loads it — the renderer needs the
424
- // property definitions — but writes none of it.
425
- const schema = await bootSchema(db, owns ? config : { ...config, syncSchemaAtBoot: false })
426
436
 
427
437
  const auth = new AuthService(new AuthStore(db))
428
438
  const cookies = { siteName: config.siteName, securePrefix: config.secureCookies }
@@ -574,24 +584,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
574
584
  }
575
585
  }
576
586
 
577
- // Form definitions are files, so they are re-read rather than cached with the
578
- // content: nothing about a publish tells this node that a form changed.
579
- const forms = createFormRegistry(config.schemaDir, { formTypes: formTypes.types })
580
- // Every form this node renders carries a token signed with the site's key, so
581
- // the timing guard cannot be bypassed by posting a made-up render time.
582
- const formSecret = await formSigningSecret(db)
583
- setFormTokenSigner((formKey, renderedAt) => signFormToken(formSecret, formKey, renderedAt))
584
- const publishedSource = createPublishedContentSource(db, {
585
- nodeState: schema.nodeState,
586
- nodeId: schema.nodeId,
587
- })
588
- // Media is cached apart from the pages (story 197), item by item within a
589
- // budget, and shared by the published and draft caches: media has no drafts.
590
- const mediaCache = new MediaCache(
591
- createMediaSource(db, { nodeState: schema.nodeState, nodeId: schema.nodeId }),
592
- { budgetBytes: (config.mediaCacheMegabytes ?? DEFAULT_MEDIA_CACHE_MEGABYTES) * 1024 * 1024 },
593
- )
594
- const cacheOptions = { form: (key: string) => forms.byKey(key), media: mediaCache }
595
587
  // Every page as last saved, for previewing in an app (story 053). Built on the
596
588
  // first preview after a change and dropped with the published cache, so a site
597
589
  // nobody previews never holds it. A save on another node announces nothing,
@@ -601,77 +593,40 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
601
593
  nodeId: schema.nodeId,
602
594
  drafts: true,
603
595
  })
604
- let drafts: { cache: PublishedCache; version: number } | undefined
605
596
  const draftCache = async (): Promise<PublishedCache> => {
606
597
  const version = await latestContentVersionId(db)
607
598
  if (drafts?.version !== version)
608
599
  drafts = { cache: new PublishedCache(draftSource, cacheOptions), version }
609
600
  return drafts.cache
610
601
  }
611
- const cache = new PublishedCache(publishedSource, {
612
- ...cacheOptions,
613
- onInvalidate: () => {
614
- drafts = undefined
615
- },
616
- })
617
- // A sync or a Settings change that alters how URLs are built moves every URL:
618
- // the old ones redirect, as a rename's do.
619
- const urlChange: UrlChangeContext = {
620
- db,
621
- config,
622
- source: publishedSource,
623
- cacheOptions,
624
- cache,
625
- tracker: createRedirectTracker({
626
- cache,
627
- redirects: new RedirectRepository(db),
628
- enabled: config.trackRedirects,
629
- instruct: () =>
630
- appendCacheInstruction(db, {
631
- kind: 'content',
632
- payload: { redirects: true },
633
- by: schema.nodeId,
634
- }),
635
- }),
636
- }
637
- const afterSync = async (report: SyncReport | undefined) => {
638
- if (!report?.urls) return
639
- await redirectAfterUrlChange(urlChange, report.urls.before)
640
- log.info('Page addresses now {mode} the top-level page; old addresses redirect', {
641
- mode: report.urls.after.hideTopLevel ? 'leave out' : 'include',
642
- })
643
- }
644
- await afterSync(schema.report)
645
- // A snapshot of the views, so a template edited anywhere — the backoffice, a
646
- // deploy, a bucket synced underneath — is picked up without restarting this
647
- // node. `assertViewRuntime` first, because a cache directory the JSX runtime
648
- // cannot be resolved from fails every render rather than the boot.
649
- assertViewRuntime(config.componentsCacheDir)
650
- const snapshots = new ViewSnapshots({
651
- sourceDir: config.componentsDir,
652
- cacheDir: config.componentsCacheDir,
653
- limits: { ...(config.development ? DEVELOPMENT_LIMITS : {}), ...config.componentsSnapshot },
654
- onProblem: (message) => renderLog.error('{message}', { message }),
655
- // Only a change: every boot takes a generation, and saying so each time is
656
- // noise. The start banner names the one a node came up on.
657
- onSwap: (hash, previous) => {
658
- if (previous)
659
- renderLog.info('Views changed: generation {previous} to {hash}', {
660
- previous: previous.slice(0, 8),
661
- hash: hash.slice(0, 8),
602
+ // Story 214: a save under components/ swaps the views now rather than at the
603
+ // next render, and each swap checks the types again in the background.
604
+ const viewWatcher =
605
+ live && existsSync(config.componentsDir)
606
+ ? watchDirectory(config.componentsDir, () => {
607
+ void snapshots
608
+ .refresh()
609
+ .catch((error: unknown) =>
610
+ renderLog.error('Could not refresh the views: {error}', { error: String(error) }),
611
+ )
662
612
  })
663
- },
664
- })
665
- await snapshots.prepare()
666
- // Before the poller, which tells it to look again on a `views` instruction
667
- // from another node: a closure over a `const` declared later would be a
668
- // temporal dead zone waiting for the first instruction to land.
669
- const renderer = new Renderer({
670
- cache,
671
- componentsDir: config.componentsDir,
672
- snapshots,
673
- renderTimeoutMs: config.renderTimeoutMs,
674
- })
613
+ : undefined
614
+ const typesLog = logger('types')
615
+ const typeWatch = live
616
+ ? createTypeWatch({
617
+ check: (signal) => checkTypes(config.siteDir, { signal }),
618
+ onFindings: ({ problems, types }) => {
619
+ if (types.count === 0) typesLog.info('The components type-check cleanly')
620
+ else for (const problem of problems) typesLog.warning('{problem}', { problem })
621
+ live?.types(types)
622
+ },
623
+ })
624
+ : undefined
625
+ void typeWatch
626
+ ?.schedule()
627
+ .catch((error: unknown) =>
628
+ typesLog.error('The type check failed to run: {error}', { error: String(error) }),
629
+ )
675
630
  // The site's own redirects are code, so the database follows the file: rules it
676
631
  // no longer declares are removed, which is what makes deleting one from config
677
632
  // actually take effect.
@@ -702,121 +657,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
702
657
  }
703
658
  const deliverySettings = resolveDeliveryApiSettings(config.deliveryApi)
704
659
  const formCors = corsPolicy(deliverySettings)
705
- /**
706
- * The server halves of the site's bundles. Back-office routes answer only
707
- * where the backoffice is; member and public routes (story 186) wherever the
708
- * site is served.
709
- *
710
- * Capabilities are built here, from what this node already holds, so a bundle
711
- * is handed a narrow interface rather than the database. A bad bundle fails the
712
- * boot — see `createServerBundles`.
713
- */
714
- const asBundleMember = (member: {
715
- key: string
716
- name: string
717
- username: string
718
- email: string
719
- roles: string[]
720
- }): BundleMember => ({
721
- key: member.key,
722
- name: member.name,
723
- username: member.username,
724
- email: member.email,
725
- groups: member.roles,
726
- })
727
- // Story 198: media as the member, built at the first request, when the media
728
- // operations and the store it writes through exist.
729
- let bundleMedia: BundleMediaFactory | undefined
730
- let bundleMediaFolders = new Map<string, ResolvedMediaFolder[]>()
731
- const bundles =
732
- config.bundles.length > 0
733
- ? createServerBundles({
734
- bundles: config.bundles,
735
- packages: bundlePackages,
736
- coreVersion: VERSION,
737
- tables: (bundle) => {
738
- const chain = chains.find((candidate) => candidate.id === bundle.id)
739
- return chain ? createTablesCapability(db, chain.compiled.schema) : undefined
740
- },
741
- pluginApiPath: `${paths.pluginPath}/api`,
742
- host: {
743
- redirects: createBundleRedirects({ db, cache }),
744
- documents: {
745
- url: async (key, culture) => {
746
- const content = await cache.byKey(key, culture ?? null)
747
- return content && content.url !== '#' ? content.url : undefined
748
- },
749
- },
750
- log: bundleLog('bundle'),
751
- identityProviders: createBundleIdentityProviders({
752
- overrides: new IdentityProviderOverrides(db, config.secretKey),
753
- members: config.memberIdentityProviders,
754
- backoffice: config.backofficeIdentityProviders,
755
- memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
756
- backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
757
- groups: async (audience) =>
758
- audience === 'user'
759
- ? (await new UserGroupRepository(db).all()).map((g) => ({
760
- value: g.alias,
761
- name: g.name,
762
- }))
763
- : (
764
- await db.query<{ text: string }>(
765
- 'SELECT text FROM node WHERE node_object_type = ? ORDER BY text',
766
- [ObjectTypes.MemberGroup],
767
- )
768
- ).map((g) => ({ value: String(g.text), name: String(g.text) })),
769
- }),
770
- },
771
- log: (id) => bundleLog(id),
772
- callerHost: {
773
- media: (caller, bundle) => {
774
- bundleMedia ??= createBundleMedia({
775
- db,
776
- operations: managementDeps.mediaOperations as MediaOperations,
777
- files: mediaFiles,
778
- cache: mediaCache,
779
- folders: (id) => bundleMediaFolders.get(id) ?? [],
780
- bundleName: (id) => bundles?.mounted.find((b) => b.id === id)?.name ?? id,
781
- stream: (src, search) => streamMemberFile(src, search),
782
- })
783
- return bundleMedia(caller, bundle)
784
- },
785
- },
786
- site: {
787
- session: async (request) => {
788
- const session = await members.session(request)
789
- return session && { member: asBundleMember(session.member), verify: session.verify }
790
- },
791
- memberByToken: memberAuthorizationEnabled(deliverySettings)
792
- ? async (token) => {
793
- const named = await deliveryMembers.member(token)
794
- if (!named?.approved || named.lockedOut) return undefined
795
- const member = await new MemberRepository(db).byKey(named.key)
796
- return member && asBundleMember(member)
797
- }
798
- : undefined,
799
- cors: formCors,
800
- callerAddress: (request) =>
801
- callerAddress(peers.get(request), request.headers.get('x-forwarded-for')),
802
- },
803
- })
804
- : undefined
805
- if (bundles) {
806
- // A declared folder that is not there would fail on the first upload; the
807
- // boot says so instead, naming the bundle and the path.
808
- const names = new Map(bundles.mounted.map((bundle) => [bundle.id, bundle.name]))
809
- const resolved = await resolveBundleMediaFolders(
810
- db,
811
- config.bundles,
812
- (id) => names.get(id) ?? id,
813
- )
814
- if (resolved.problems.length > 0)
815
- throw new Error(
816
- `The configured bundles cannot be mounted:\n- ${resolved.problems.join('\n- ')}`,
817
- )
818
- bundleMediaFolders = resolved.folders
819
- }
820
660
  for (const bundle of bundles?.mounted ?? []) {
821
661
  if (servesBackOffice)
822
662
  log.info('Bundle {name} answering below {prefix} for the {section} section', {
@@ -824,20 +664,30 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
824
664
  prefix: bundle.prefix,
825
665
  section: bundle.section,
826
666
  })
827
- if (config.role !== 'api' && bundle.routes.some((route) => route.audience !== 'backoffice'))
828
- log.info('Bundle {name} answering members and visitors below {prefix}', {
667
+ const paths = bundle.routes
668
+ .filter((route) => route.audience === 'site')
669
+ .map((route) => route.path)
670
+ if (config.role !== 'api' && paths.length > 0)
671
+ log.info('Bundle {name} answering on the site at {paths}', {
829
672
  name: bundle.name,
830
- prefix: bundle.sitePrefix,
673
+ paths: paths.join(', '),
831
674
  })
832
675
  }
833
676
  {
834
- const named = bundleRouteGroups(config.bundles)
677
+ const named = [
678
+ ...bundleRouteGroups(config.bundles),
679
+ ...(config.routes ?? []).flatMap((route) =>
680
+ typeof route.options.members === 'object' ? route.options.members.groups : [],
681
+ ),
682
+ ]
835
683
  if (named.length > 0) {
836
684
  const existing = new Set(
837
685
  (
838
- await db.query<{ text: string }>('SELECT text FROM node WHERE node_object_type = ?', [
839
- ObjectTypes.MemberGroup,
840
- ])
686
+ await db.q
687
+ .selectFrom('node')
688
+ .select('text')
689
+ .where('node_object_type', '=', ObjectTypes.MemberGroup)
690
+ .execute()
841
691
  ).map((row) => String(row.text).toLowerCase()),
842
692
  )
843
693
  for (const group of named.filter((name) => !existing.has(name.toLowerCase())))
@@ -853,40 +703,11 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
853
703
  { name },
854
704
  )
855
705
 
856
- const poller = new CacheInstructionPoller({
857
- db,
858
- nodeId: schema.nodeId,
859
- nodeState: schema.nodeState,
860
- role: config.role,
861
- // `schema` and `content` change what renders: schema alters property
862
- // definitions. `views` changes the code that renders it, which is a new
863
- // snapshot rather than anything in the published cache.
864
- onInstruction: (kind, payload) => {
865
- if (kind !== 'components') return cache.invalidate()
866
- // The hash only says when to stop looking eagerly; the snapshot is always
867
- // of the bytes this node reads, so a superseded one is harmless.
868
- snapshots.announce(typeof payload.hash === 'string' ? payload.hash : undefined)
869
- },
870
- // Behind the latest committed checkpoint: rebuilt now rather than on the next
871
- // read, so an idle node catches up and says so (story 174).
872
- content: {
873
- served: () => cache.served(),
874
- covered: (checkpoint) => cache.covered(checkpoint),
875
- behind: () => {
876
- cache.invalidate()
877
- void cache
878
- .snapshot()
879
- .catch((error: unknown) =>
880
- renderLog.error('Could not rebuild the published cache: {error}', { error }),
881
- )
882
- },
883
- },
884
- media: {
885
- apply: (change) => mediaCache.apply(change),
886
- clear: () => mediaCache.clear(),
887
- },
888
- })
889
- await poller.start(config.development ? 2_000 : 5_000)
706
+ for (const { kind, path } of await unresolvedStatusPages(cache, config.pages).catch(() => []))
707
+ renderLog.warning(
708
+ "pages.{kind} is '{path}', which no published page answers; that status shows a plain page until one does.",
709
+ { kind, path },
710
+ )
890
711
  const watcher =
891
712
  config.development && owns
892
713
  ? watchSchema(
@@ -917,6 +738,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
917
738
  // the path it owns.
918
739
  if (report.state?.version) schema.nodeState.version = report.state.version
919
740
  schemaLog.info('Schema {version} applied', { version: report.state?.version ?? '' })
741
+ live?.changed('schema')
920
742
  }
921
743
  },
922
744
  )
@@ -962,7 +784,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
962
784
  onChange: (key) => mediaCache.drop([key]),
963
785
  nodeId: schema.nodeId,
964
786
  bundleFolders: () =>
965
- [...bundleMediaFolders].flatMap(([id, folders]) =>
787
+ [...core.bundleMediaFolders()].flatMap(([id, folders]) =>
966
788
  folders.map((folder) => ({
967
789
  bundle: bundles?.mounted.find((b) => b.id === id)?.name ?? id,
968
790
  nodePath: folder.nodePath,
@@ -1042,7 +864,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1042
864
  },
1043
865
  sitemap: (request, host) => seo.sitemapItems(request, host),
1044
866
  notFound: async (host, path) => {
1045
- const found = await seo.notFound(host, path)
867
+ // The page a rendered site answers with, so an app shows the same one (story 208).
868
+ const found =
869
+ (await resolveStatusPage(cache, config.pages, 'notFound', host, path)) ??
870
+ (await seo.notFound(host, path))
1046
871
  return found && { key: found.content.key, culture: found.culture }
1047
872
  },
1048
873
  preview: async (request, keyed) => {
@@ -1107,6 +932,44 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1107
932
  })
1108
933
  const seoPath = `${paths.pluginPath}/api/seo`
1109
934
 
935
+ // Story 211: the site's routes and its bundles' site routes, at their own
936
+ // paths, ahead of content finding; one pipeline answers bundles' back-office
937
+ // routes too.
938
+ const declaredRoutes: DeclaredRoute[] = [
939
+ ...(config.routes ?? []).map(
940
+ (route): DeclaredRoute => ({ route: route as SiteRoute, owner: 'the site' }),
941
+ ),
942
+ ...(bundles?.siteRoutes() ?? []),
943
+ ]
944
+ {
945
+ const problems = siteRouteProblems(declaredRoutes, config.backOfficePath)
946
+ if (problems.length > 0)
947
+ throw new Error(`The site's routes cannot be mounted:\n- ${problems.join('\n- ')}`)
948
+ }
949
+ const siteRoutes = createRoutes<RequestMember>(declaredRoutes, {
950
+ backOfficePath: config.backOfficePath,
951
+ timeoutMs: config.routeTimeoutMs,
952
+ defaultPerMinute: config.routeRateLimitPerMinute,
953
+ siteFor: (member) => siteServicesFor(member),
954
+ session: (request) => members.session(request),
955
+ memberByToken: memberAuthorizationEnabled(deliverySettings)
956
+ ? async (token) => {
957
+ const named = await deliveryMembers.member(token)
958
+ if (!named?.approved || named.lockedOut) return undefined
959
+ return (await new MemberRepository(db).byKey(named.key)) ?? undefined
960
+ }
961
+ : undefined,
962
+ callerAddress: (request) =>
963
+ callerAddress(peers.get(request), request.headers.get('x-forwarded-for')) ?? 'unknown',
964
+ statusPage: (request, outcome) => {
965
+ const url = new URL(request.url)
966
+ return statusResponse(request, url.pathname, url.host, undefined, outcome)
967
+ },
968
+ logError: (message, properties) => renderLog.error(message, properties),
969
+ showDetails: config.errors.showDetails,
970
+ cors: formCors,
971
+ })
972
+
1110
973
  const notImplementedLog = logger('not-implemented')
1111
974
  const notImplemented = new NotImplementedLog((line, entry) => {
1112
975
  // The console line is the development aid; the file keeps it for the log viewer
@@ -1115,44 +978,20 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1115
978
  ...entry,
1116
979
  })
1117
980
  })
1118
- // The site's config may name a store; without one the environment decides,
1119
- // and that falls back to the media directory on this disk.
1120
- // A site pulled with `--lazy-media` reads files through from its remote (story 108).
1121
- const mediaStore = withRemoteMedia(
1122
- config.mediaStore ?? (await mediaStoreFromEnvironment(config.mediaDir)),
1123
- config.siteDir,
1124
- )
1125
- // Resolved once: constructing it twice would warn twice about a provider that
1126
- // is half-configured, and the adapters are cheap but not free of side effects.
1127
- const email = resolveEmailPort(config)
1128
981
  const emailStatus = emailAvailability(email)
1129
982
  // Whether an invitation or a reset link can reach anyone at all, which is what
1130
983
  // gates the options rather than `emailStatus.available`: development delivers
1131
984
  // to the console, and that is a working flow for the person using it.
1132
985
  const canSendUserLinks = Boolean(resolveUserLinkSender(config, email))
1133
- // Story 045: a change queues the e-mails its subscribers asked for. Nothing is
1134
- // queued on a site that cannot send; development sends to the console.
1135
- const notifier = createContentNotifier(db, { canSend: Boolean(email) })
1136
- const mediaFiles = new MediaFileStore(mediaStore)
1137
986
  const images = new ImageProcessor(mediaStore)
987
+ // Asked at boot, so the first AVIF request does not wait on it.
988
+ void canEncodeAvif()
1138
989
  const publicMedia = mediaStore.publicUrl?.('media/file')
1139
990
  if (publicMedia)
1140
991
  log.warning(
1141
992
  'Media files are also served from {where}. Protected files are always sent by this site and never from there, but anyone with a file’s address there can open it: keep protected files in a store nothing public serves.',
1142
993
  { where: publicMedia.replace(/media\/file$/, '') },
1143
994
  )
1144
- const webhooks = createWebhookService({
1145
- db,
1146
- schemaDir: config.schemaDir,
1147
- filesWritable: config.schemaWritable,
1148
- secretKey: config.secretKey,
1149
- bundles: config.bundles,
1150
- onFilesChanged: config.schemaStore
1151
- ? async () => {
1152
- await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
1153
- }
1154
- : undefined,
1155
- })
1156
995
  /**
1157
996
  * What an open backoffice hears of a change: the event hub drops its cached
1158
997
  * copy, whatever was queued gets indexed now, and an open preview reloads.
@@ -1160,35 +999,51 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1160
999
  */
1161
1000
  function announce(event: ServerEvent): void {
1162
1001
  events.broadcast('notify', [event])
1163
- jobs.kickSearchIndexing()
1164
1002
  if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
1165
1003
  previewHub.broadcast('refreshed', [event.key])
1166
1004
  }
1167
- // Recorded content events become deliveries and notifications here (story 171).
1168
- const dispatcher = createContentDispatcher({ db, webhooks, notifier })
1169
- // Document writes record and announce themselves through this, from every entry point.
1170
- const contentEvents = createContentEventSink({
1171
- webhooks,
1172
- notifier,
1173
- live: announce,
1174
- nudge: () => dispatcher.nudge(),
1175
- })
1176
1005
 
1177
1006
  const managementDeps = createDeps({
1178
1007
  config,
1179
1008
  paths,
1180
- extensions,
1009
+ hiddenByRoutes: async () => {
1010
+ const snapshot = await cache.snapshot()
1011
+ const hidden: Array<{ route: string; owner: string; page: string; url: string }> = []
1012
+ for (const [url, content] of snapshot.byRoute) {
1013
+ const found = siteRoutes.match(url)
1014
+ if (found)
1015
+ hidden.push({
1016
+ route: found.entry.route.path,
1017
+ owner: found.entry.owner,
1018
+ page: content.name,
1019
+ url,
1020
+ })
1021
+ }
1022
+ return hidden
1023
+ },
1024
+ // A server bundle's screens show only while it is on (story 222).
1025
+ extensions: {
1026
+ ...extensions,
1027
+ list: () =>
1028
+ extensions
1029
+ .list()
1030
+ .filter(
1031
+ (extension) =>
1032
+ !extension.bundle.carries.server || bundleGrants.isOn(extension.bundle.id),
1033
+ ),
1034
+ },
1181
1035
  db,
1182
1036
  webhooks,
1183
1037
  contentEvents,
1184
- nudgeEvents: () => dispatcher.nudge(),
1038
+ nudgeEvents: () => wake('events'),
1039
+ operations: core.operations,
1185
1040
  cache,
1186
1041
  previewInApp: appPreview,
1187
1042
  schema,
1188
1043
  mediaFiles,
1189
1044
  email,
1190
1045
  notifier,
1191
- onSearchQueued: () => jobs.kickSearchIndexing(),
1046
+ onSearchQueued: () => wake('search'),
1192
1047
  // This node looks again at once; the others are told to. The write has
1193
1048
  // already landed wherever `componentsDir` points, so there is nothing to
1194
1049
  // distribute — only the fact that it happened.
@@ -1273,59 +1128,17 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1273
1128
  role: config.role,
1274
1129
  content: contentFreshness(),
1275
1130
  components: snapshots.status(),
1131
+ // Where jobs run, and on a node that leaves them to a worker whether one
1132
+ // is running them; reported, never drained on (story 223).
1133
+ ...(config.role === 'web' ? {} : { jobs: core.workerWatch.status() }),
1276
1134
  }
1277
1135
  }
1278
1136
 
1279
1137
  const events = createServerEventHub()
1280
1138
  const previewHub = createServerEventHub({ name: 'PreviewHub' })
1281
- const jobs = createBackgroundJobs({
1282
- db,
1283
- cache,
1284
- approvals: managementDeps.approvals as Approvals | undefined,
1285
- operations: managementDeps.documentOperations as DocumentOperations,
1286
- dispatcher,
1287
- eventRetentionDays: config.eventRetentionDays,
1288
- nodeState: schema.nodeState,
1289
- nodeId: schema.nodeId,
1290
- versionCleanup: config.versionCleanup,
1291
- auditRetentionDays: config.auditRetentionDays,
1292
- mediaFiles,
1293
- // The workflow queue drains here rather than in the request: a submission is
1294
- // stored first, and an e-mail that cannot be sent yet must not cost it.
1295
- webhooks,
1296
- formWorkflows: createWorkflowRunner({
1297
- db,
1298
- forms,
1299
- email,
1300
- mediaFiles,
1301
- nodeState: schema.nodeState,
1302
- nodeId: schema.nodeId,
1303
- onContentChanged: () => cache.invalidate(),
1304
- operations: managementDeps.documentOperations,
1305
- bundleWorkflows: formTypes.workflows,
1306
- renderEmail: (alias, props) => renderer.renderEmail(alias, props),
1307
- site: async () => ({
1308
- name: (await seo.siteDefaults()).siteName || config.siteName,
1309
- url: config.applicationUrl,
1310
- }),
1311
- }),
1312
- contentNotifications: email
1313
- ? createContentNotificationRunner({
1314
- db,
1315
- email,
1316
- siteName: config.siteName,
1317
- editUrl: (key) => documentEditUrl(config, key),
1318
- })
1319
- : undefined,
1320
- onDocumentChanged: (key) =>
1321
- events.broadcast('notify', [
1322
- { eventSource: 'Umbraco:CMS:Document', eventType: 'Updated', key },
1323
- ]),
1324
- })
1325
- // Scheduled publishing and version cleanup are writes on a timer. Running them
1326
- // on every node would have two processes publishing the same document in the
1327
- // same second, so only an owner starts them.
1328
- if (owns) jobs.start()
1139
+ // Jobs are writes on a timer, claimed so each runs once, and started where
1140
+ // this node runs them: an owner unless told to leave them to a worker.
1141
+ await core.startJobs()
1329
1142
  log.info('Crombolo {version} started on node {nodeId} as {role}', {
1330
1143
  version: VERSION,
1331
1144
  nodeId: schema.nodeId,
@@ -1344,10 +1157,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1344
1157
  // Imported only when configured: an unconfigured site has no git route and no
1345
1158
  // credentials anywhere near it.
1346
1159
  const auditPath = `${paths.pluginPath}/api/audit`
1160
+ const jobsPath = `${paths.pluginPath}/api/jobs`
1347
1161
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1348
1162
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1349
1163
  const bundleInstallPaths = new Set(
1350
- ['install', 'uninstall'].map((action) => `${paths.pluginPath}/api/bundles/${action}`),
1164
+ ['install', 'uninstall', 'grant', 'withdraw'].map(
1165
+ (action) => `${paths.pluginPath}/api/bundles/${action}`,
1166
+ ),
1351
1167
  )
1352
1168
  /** Per node: ten a minute for each person, three hundred in all. */
1353
1169
  const hostTokens = new AttemptLimiter({ max: 10, maxAll: 300, windowMs: 60_000 })
@@ -1377,6 +1193,15 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1377
1193
  * address it is answered with points back at the new paths.
1378
1194
  */
1379
1195
  async function fetch(request: Request): Promise<Response> {
1196
+ const response = await answer(request)
1197
+ // Readers are answered from the previous cache while it rebuilds (story
1198
+ // 175), so a change is in it before the request that made it is answered.
1199
+ if (request.method !== 'GET' && request.method !== 'HEAD' && cache.stale)
1200
+ await cache.fresh().catch(() => {})
1201
+ return response
1202
+ }
1203
+
1204
+ async function answer(request: Request): Promise<Response> {
1380
1205
  const url = new URL(request.url)
1381
1206
  const contract = contractPathFor(paths.backOfficePath, url.pathname)
1382
1207
  if (!contract) return route(request)
@@ -1441,6 +1266,17 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1441
1266
  if (response) return response
1442
1267
  }
1443
1268
 
1269
+ // Islands (story 209): the loader, and each generation's browser code.
1270
+ if (pathname === ISLAND_LOADER_PATH)
1271
+ return new Response(ISLAND_LOADER_SCRIPT, {
1272
+ headers: {
1273
+ 'content-type': 'text/javascript; charset=utf-8',
1274
+ 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1275
+ },
1276
+ })
1277
+ if (pathname.startsWith(`${ISLANDS_PATH}/`))
1278
+ return islandFile(pathname.slice(ISLANDS_PATH.length + 1))
1279
+
1444
1280
  // The progressive-enhancement script. A site adds it to a layout; a form
1445
1281
  // works without it, so nothing emits it automatically.
1446
1282
  if (pathname === FORM_SCRIPT_PATH)
@@ -1462,7 +1298,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1462
1298
  : new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } })
1463
1299
  }
1464
1300
 
1465
- // A bundle's member and public routes (story 186), wherever the site is served.
1301
+ // The script that calls the site's routes as a member, wherever the site is served.
1466
1302
  if (config.role !== 'api') {
1467
1303
  if (pathname === BUNDLE_SCRIPT_PATH)
1468
1304
  return new Response(BUNDLE_SCRIPT, {
@@ -1471,8 +1307,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1471
1307
  'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1472
1308
  },
1473
1309
  })
1474
- if (pathname.startsWith(`${BUNDLE_SITE_PATH}/`))
1475
- return (await bundles?.site(request, url)) ?? new Response('Not Found', { status: 404 })
1476
1310
  }
1477
1311
 
1478
1312
  // Not on an `api` node, which serves no public site to describe.
@@ -1480,9 +1314,189 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1480
1314
  return pathname === '/sitemap.xml' ? seo.sitemap(request, url.host) : seo.robots(request)
1481
1315
 
1482
1316
  if (pathname.startsWith('/media/')) return serveMedia(request, pathname, url.searchParams)
1317
+ if (live && config.role !== 'api') {
1318
+ if (pathname === LIVE_EVENTS_PATH) return live.stream(request)
1319
+ if (pathname === LIVE_RELOAD_SCRIPT_PATH)
1320
+ return new Response(LIVE_RELOAD_SCRIPT, {
1321
+ headers: {
1322
+ 'content-type': 'text/javascript; charset=utf-8',
1323
+ 'cache-control': 'no-cache',
1324
+ },
1325
+ })
1326
+ return withLiveReloadScript(await siteRequest(request, url))
1327
+ }
1328
+ return siteRequest(request, url)
1329
+ }
1330
+
1331
+ /** A site page in development, carrying the live-reload script (story 214). */
1332
+ async function withLiveReloadScript(response: Response): Promise<Response> {
1333
+ if (!response.body || !response.headers.get('content-type')?.startsWith('text/html'))
1334
+ return response
1335
+ const headers = new Headers(response.headers)
1336
+ headers.delete('content-length')
1337
+ return new Response(withLiveReload(await response.text()), {
1338
+ status: response.status,
1339
+ statusText: response.statusText,
1340
+ headers,
1341
+ })
1342
+ }
1343
+
1344
+ /** What a chain is carrying through one request (story 210). */
1345
+ interface ChainRun {
1346
+ original: URL
1347
+ budget: MiddlewareBudget
1348
+ preview: boolean
1349
+ /** Something read in the chain depends on who is asking. */
1350
+ personal: boolean
1351
+ /** The route stage has run; a rewrite it made is not routed through it again. */
1352
+ routed: boolean
1353
+ }
1354
+
1355
+ const chainOf = () => config.middleware
1356
+ const anyMiddleware = () => {
1357
+ const chain = chainOf()
1358
+ return Boolean(
1359
+ chain &&
1360
+ (hasMiddleware(chain.request) || hasMiddleware(chain.route) || hasMiddleware(chain.page)),
1361
+ )
1362
+ }
1363
+
1364
+ /** A site request: the middleware chain around crombolo's own handling, when the site has one. */
1365
+ async function siteRequest(request: Request, url: URL): Promise<Response> {
1366
+ if (!anyMiddleware()) return siteFiles(request)
1367
+ const run: ChainRun = {
1368
+ original: url,
1369
+ budget: {
1370
+ remainingMs:
1371
+ config.middlewareTimeoutMs > 0 ? config.middlewareTimeoutMs : Number.POSITIVE_INFINITY,
1372
+ },
1373
+ preview: Boolean(readCookie(request, PREVIEW_COOKIE) && (await authenticate(request))),
1374
+ personal: false,
1375
+ routed: false,
1376
+ }
1377
+ try {
1378
+ const response = await runStage({
1379
+ stage: 'request',
1380
+ chain: chainOf()?.request,
1381
+ request,
1382
+ budget: run.budget,
1383
+ context: (current) => chainContext(current, run, {}),
1384
+ inner: (current) => {
1385
+ assertSiteTarget(new URL(current.url), run)
1386
+ return siteFiles(current, run)
1387
+ },
1388
+ })
1389
+ return finishChain(response, run)
1390
+ } catch (error) {
1391
+ return middlewareFailure(request, url, error)
1392
+ }
1393
+ }
1394
+
1395
+ /** The site's stylesheets and scripts, or its pages. */
1396
+ async function siteFiles(request: Request, run?: ChainRun): Promise<Response> {
1397
+ const url = new URL(request.url)
1398
+ const pathname = url.pathname
1399
+ // A route wins at its path (story 211); an `api` node serves no site.
1400
+ if (config.role !== 'api') {
1401
+ const routed = await siteRoutes.handle(request, url)
1402
+ if (routed) return routed
1403
+ }
1483
1404
  if (pathname.startsWith('/css/')) return serveSiteFile(config.stylesheetsDir, pathname, '.css')
1484
1405
  if (pathname.startsWith('/scripts/')) return serveSiteFile(config.scriptsDir, pathname, '.js')
1485
- return renderSite(request, pathname, url.host)
1406
+ return renderSite(request, pathname, url.host, run)
1407
+ }
1408
+
1409
+ /** A rewrite stays on this site, among its own pages. */
1410
+ function assertSiteTarget(target: URL, run: ChainRun): void {
1411
+ if (target.origin !== run.original.origin)
1412
+ throw new MiddlewareError(
1413
+ 'the middleware chain',
1414
+ `A rewrite goes to a path on this site, not to ${target.origin}.`,
1415
+ )
1416
+ if (
1417
+ target.pathname !== run.original.pathname &&
1418
+ !isSitePath(target.pathname, config.backOfficePath)
1419
+ )
1420
+ throw new MiddlewareError(
1421
+ 'the middleware chain',
1422
+ `A rewrite cannot go to ${target.pathname}, which is not one of this site's pages.`,
1423
+ )
1424
+ }
1425
+
1426
+ /** What a middleware is given: its cookies mark the answer personal when read. */
1427
+ function chainContext(
1428
+ request: Request,
1429
+ run: ChainRun,
1430
+ extra: { page?: PublishedContent; member?: Awaited<ReturnType<typeof members.resolve>> },
1431
+ ) {
1432
+ return {
1433
+ url: new URL(request.url),
1434
+ get cookies() {
1435
+ run.personal = true
1436
+ return requestCookies(request)
1437
+ },
1438
+ site: () =>
1439
+ siteServicesFor(
1440
+ run.preview ? undefined : async () => (await members.session(request))?.member,
1441
+ )(),
1442
+ preview: run.preview,
1443
+ signal: request.signal,
1444
+ ...extra,
1445
+ }
1446
+ }
1447
+
1448
+ /** The chain's answer, kept private when it depended on who asked, and shown to an editor in preview. */
1449
+ function finishChain(response: Response, run: ChainRun): Response {
1450
+ const location = response.headers.get('location')
1451
+ if (run.preview && response.status >= 300 && response.status < 400 && location)
1452
+ return new Response(previewRedirectNotice(response.status, location), {
1453
+ headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': PRIVATE_NO_STORE },
1454
+ })
1455
+ if (!run.personal && !response.headers.has('set-cookie')) return response
1456
+ const headers = new Headers(response.headers)
1457
+ headers.set('cache-control', PRIVATE_NO_STORE)
1458
+ headers.delete('etag')
1459
+ return new Response(response.body, {
1460
+ status: response.status,
1461
+ statusText: response.statusText,
1462
+ headers,
1463
+ })
1464
+ }
1465
+
1466
+ /** A middleware that failed: logged by name with a reference, and answered with the error page. */
1467
+ async function middlewareFailure(request: Request, url: URL, error: unknown): Promise<Response> {
1468
+ if (request.signal.aborted) return new Response(null, { status: 499 })
1469
+ const name = error instanceof MiddlewareError ? error.middleware : 'the middleware chain'
1470
+ const message = error instanceof Error ? error.message : String(error)
1471
+ const cause = error instanceof MiddlewareError ? error.cause : error
1472
+ const reference = errorReference()
1473
+ renderLog.error('Middleware {name} failed on {path}, reference {reference}: {detail}', {
1474
+ name,
1475
+ path: url.pathname,
1476
+ reference,
1477
+ detail: cause instanceof Error ? (cause.stack ?? message) : message,
1478
+ })
1479
+ return statusResponse(
1480
+ request,
1481
+ url.pathname,
1482
+ url.host,
1483
+ undefined,
1484
+ {
1485
+ status: 500,
1486
+ name: 'serverError',
1487
+ errors: [],
1488
+ reference,
1489
+ ...(config.errors.showDetails
1490
+ ? {
1491
+ details: {
1492
+ message,
1493
+ ...(cause instanceof Error && cause.stack ? { stack: cause.stack } : {}),
1494
+ },
1495
+ }
1496
+ : {}),
1497
+ },
1498
+ { 'cache-control': PRIVATE_NO_STORE },
1499
+ )
1486
1500
  }
1487
1501
 
1488
1502
  /**
@@ -1498,7 +1512,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1498
1512
  // A content query is a POST that reads.
1499
1513
  if (pathname === contentQueryPath) return
1500
1514
  // Installs and removals write their own entry, with the package (story 194).
1501
- if (bundleInstallPaths.has(pathname)) return
1515
+ if (bundleInstallPaths.has(pathname) || pathname.startsWith(`${jobsPath}/`)) return
1502
1516
  const principal = await authenticate(request)
1503
1517
  if (!principal) return
1504
1518
  const plan = pluginAuditPlan(request.method, pathname.slice(prefix.length))
@@ -1639,7 +1653,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1639
1653
  if (bundles && pathname.startsWith(bundles.basePath)) {
1640
1654
  const principal = await authenticate(request)
1641
1655
  if (!principal) return new Response('Unauthorized', { status: 401 })
1642
- const answered = await bundles.handle(request, url, principal)
1656
+ const answered = await bundles.handle(request, url, principal, siteRoutes.invoke)
1643
1657
  if (answered) return answered
1644
1658
  }
1645
1659
 
@@ -1713,15 +1727,21 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1713
1727
  version?: unknown
1714
1728
  applyContent?: unknown
1715
1729
  acceptServerCode?: unknown
1730
+ grant?: unknown
1716
1731
  }
1717
1732
  const name = typeof body.name === 'string' ? body.name : ''
1718
1733
  const version = typeof body.version === 'string' ? body.version : undefined
1719
1734
  const acceptServerCode = body.acceptServerCode === true
1735
+ const grant = Array.isArray(body.grant)
1736
+ ? body.grant.filter((p): p is string => typeof p === 'string')
1737
+ : []
1720
1738
  const outcome =
1721
1739
  action === 'install'
1722
1740
  ? await marketplace.install(name, version, {
1723
1741
  applyContent: body.applyContent !== false,
1724
1742
  acceptServerCode,
1743
+ grant,
1744
+ by: principal.email,
1725
1745
  })
1726
1746
  : await marketplace.uninstall(name)
1727
1747
  log.info('{user} {action} the package {name}: {outcome}', {
@@ -1738,7 +1758,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1738
1758
  action: action === 'install' ? 'Install' : 'Uninstall',
1739
1759
  entityType: 'Bundle',
1740
1760
  entityName: outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
1741
- detail: action === 'install' && acceptServerCode ? 'accepted server code' : null,
1761
+ detail:
1762
+ action === 'install' && acceptServerCode
1763
+ ? `accepted server code; granted ${grant.length > 0 ? grant.join(', ') : 'nothing'}`
1764
+ : null,
1742
1765
  source: 'request',
1743
1766
  userKey: principal.id,
1744
1767
  userName: principal.name,
@@ -1747,6 +1770,47 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1747
1770
  return Response.json(outcome, { status: outcome.ok ? 200 : 400 })
1748
1771
  }
1749
1772
 
1773
+ // Story 222: an administrator grants a bundle the whole of what it asks
1774
+ // to do, or withdraws it, which turns the bundle off.
1775
+ if ((action === 'grant' || action === 'withdraw') && request.method === 'POST') {
1776
+ const body = (await request.json().catch(() => ({}))) as { id?: unknown }
1777
+ const id = typeof body.id === 'string' ? body.id : ''
1778
+ const pkg = extensions.bundles().bundles.find((candidate) => candidate.id === id)
1779
+ if (!pkg?.carries.server)
1780
+ return Response.json(
1781
+ { ok: false, message: `No installed bundle with a server half is called "${id}".` },
1782
+ { status: 404 },
1783
+ )
1784
+ if (action === 'withdraw') await bundleGrants.withdraw(id)
1785
+ const state =
1786
+ action === 'grant'
1787
+ ? await bundleGrants.grant(pkg, principal.email)
1788
+ : bundleGrants.state(pkg)
1789
+ await recordAudit(db, {
1790
+ category: 'system',
1791
+ action: action === 'grant' ? 'Grant' : 'Withdraw',
1792
+ entityType: 'Bundle',
1793
+ entityName: `${pkg.packageName}@${pkg.version}`,
1794
+ detail:
1795
+ action === 'grant'
1796
+ ? `granted ${state.declared.map((d) => d.permission).join(', ') || 'nothing'}`
1797
+ : 'withdrew its permissions; it is off',
1798
+ source: 'request',
1799
+ userKey: principal.id,
1800
+ userName: principal.name,
1801
+ ...clientAddress(request),
1802
+ })
1803
+ return Response.json({
1804
+ ok: true,
1805
+ on: state.on,
1806
+ missing: state.missing,
1807
+ message:
1808
+ action === 'grant'
1809
+ ? `${pkg.name} is turned on.`
1810
+ : `${pkg.name} is turned off until its permissions are approved again.`,
1811
+ })
1812
+ }
1813
+
1750
1814
  return new Response('Not Found', { status: 404 })
1751
1815
  }
1752
1816
 
@@ -2090,6 +2154,69 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2090
2154
  if (response) return response
2091
2155
  }
2092
2156
 
2157
+ // Non-contract, Settings: every owner's background jobs, and retrying a
2158
+ // failed one by hand (story 187).
2159
+ if (pathname === jobsPath || pathname.startsWith(`${jobsPath}/`)) {
2160
+ const principal = await authenticate(request)
2161
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2162
+ if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
2163
+ const queue = new JobRepository(db)
2164
+ if (pathname === jobsPath && request.method === 'GET') {
2165
+ const url = new URL(request.url)
2166
+ const state = url.searchParams.get('state')
2167
+ const listed = await queue.list({
2168
+ owner: url.searchParams.get('owner') || undefined,
2169
+ state: ['queued', 'running', 'succeeded', 'failed'].includes(state ?? '')
2170
+ ? (state as JobState)
2171
+ : undefined,
2172
+ skip: Math.max(0, Number(url.searchParams.get('skip')) || 0),
2173
+ take: Math.min(200, Math.max(1, Number(url.searchParams.get('take')) || 50)),
2174
+ })
2175
+ return Response.json({
2176
+ total: listed.total,
2177
+ // Set while this node leaves its jobs to a worker and none is running.
2178
+ waitingSince: core.workerWatch.status().waitingSince,
2179
+ items: listed.items.map((job) => ({
2180
+ id: job.id,
2181
+ owner: job.owner,
2182
+ name: job.name,
2183
+ state: job.state,
2184
+ attempts: job.attempts,
2185
+ maxAttempts: job.maxAttempts,
2186
+ nextAttemptAt: job.nextAttemptAt.toISOString(),
2187
+ progress: job.progress,
2188
+ error: job.lastError,
2189
+ queuedBy: job.queuedBy,
2190
+ createdAt: job.createdAt.toISOString(),
2191
+ finishedAt: job.finishedAt?.toISOString() ?? null,
2192
+ })),
2193
+ })
2194
+ }
2195
+ const retry = /^\/([0-9a-f-]{36})\/retry$/i.exec(pathname.slice(jobsPath.length))
2196
+ if (retry && request.method === 'POST') {
2197
+ const id = retry[1] as string
2198
+ const job = await queue.get(id)
2199
+ if (!job || !(await queue.retry(id)))
2200
+ return Response.json(
2201
+ { ok: false, message: 'Only a job that has failed can be run again.' },
2202
+ { status: 409 },
2203
+ )
2204
+ await recordAudit(db, {
2205
+ category: 'system',
2206
+ action: 'Retry',
2207
+ entityType: 'Job',
2208
+ entityName: `${job.owner}/${job.name}`,
2209
+ detail: job.lastError ? `after: ${job.lastError.slice(0, 200)}` : null,
2210
+ source: 'request',
2211
+ userKey: principal.id,
2212
+ userName: principal.name,
2213
+ ...clientAddress(request),
2214
+ })
2215
+ return Response.json({ ok: true, message: `${job.name} is queued to run again.` })
2216
+ }
2217
+ return new Response('Not Found', { status: 404 })
2218
+ }
2219
+
2093
2220
  // Non-contract, Settings: how page addresses are built (story 110).
2094
2221
  // Non-contract: finding pages by their facts (story 183), as the signed-in user.
2095
2222
  if (pathname === contentQueryPath) {
@@ -2212,7 +2339,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2212
2339
  }
2213
2340
  // A bundle's tables are part of what an upgrade changes, so the dashboard
2214
2341
  // that shows an upgrade's findings shows their steps too.
2215
- const bundles = await bundleTablesReport(db, chains)
2342
+ const bundles = await tablesReport(db, chains)
2216
2343
  const upgrades = summariseUpgrades(await readLedger(db), VERSION)
2217
2344
  // The answers a finding can be given, offered only to those who may import.
2218
2345
  const mayImport = hasSection(principal, 'packages')
@@ -2523,6 +2650,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2523
2650
  return renderer.renderModel(draft.content, draft.culture, {
2524
2651
  ...(await pageRequest(request)),
2525
2652
  search: siteSearchFor(db, cache, undefined),
2653
+ // The previewing editor is the visitor, with no member.
2654
+ site: siteServicesFor(undefined),
2526
2655
  // Blocks with no component say so here, and only here (story 184).
2527
2656
  preview: true,
2528
2657
  })
@@ -2533,6 +2662,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2533
2662
  return {
2534
2663
  origin: publicOrigin(request, config),
2535
2664
  url: request.url,
2665
+ headers: request.headers,
2536
2666
  seo: await seo.siteDefaults(),
2537
2667
  signal: request.signal,
2538
2668
  }
@@ -2655,7 +2785,90 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2655
2785
  }
2656
2786
  }
2657
2787
 
2658
- async function renderSite(request: Request, pathname: string, host: string): Promise<Response> {
2788
+ /**
2789
+ * A page, through the route and page stages of the chain when it has them:
2790
+ * the route stage once the page is found (a redirect the tables answer comes
2791
+ * first), the page stage once its access is decided. Access is always checked
2792
+ * on the page that finally renders.
2793
+ */
2794
+ async function renderSite(
2795
+ request: Request,
2796
+ pathname: string,
2797
+ host: string,
2798
+ run?: ChainRun,
2799
+ ): Promise<Response> {
2800
+ const chain = chainOf()
2801
+ if (!run || !chain) return renderPage(request, pathname, host)
2802
+ if (hasMiddleware(chain.route) && !run.routed) {
2803
+ const resolved = run.preview ? undefined : await cache.resolve(host, pathname)
2804
+ const redirected =
2805
+ resolved?.redirect !== undefined ||
2806
+ (!resolved && !run.preview && (await cache.redirect(host, pathname)) !== undefined)
2807
+ // The redirect tables answer first, and there is no page for the later stages.
2808
+ if (redirected) return renderPage(request, pathname, host)
2809
+ run.routed = true
2810
+ return runStage({
2811
+ stage: 'route',
2812
+ chain: chain.route,
2813
+ request,
2814
+ budget: run.budget,
2815
+ context: (current) => chainContext(current, run, { page: resolved?.content }),
2816
+ inner: (current) => {
2817
+ const to = new URL(current.url)
2818
+ if (to.pathname === pathname)
2819
+ return pageStage(current, pathname, host, run, resolved?.content)
2820
+ // Resolved again from the start: redirects, access, the page found there.
2821
+ assertSiteTarget(to, run)
2822
+ return renderSite(current, to.pathname, host, run)
2823
+ },
2824
+ })
2825
+ }
2826
+ return pageStage(request, pathname, host, run)
2827
+ }
2828
+
2829
+ /** The page stage: after access is decided, so it sees the page that renders and may not change it. */
2830
+ async function pageStage(
2831
+ request: Request,
2832
+ pathname: string,
2833
+ host: string,
2834
+ run: ChainRun,
2835
+ found?: PublishedContent,
2836
+ ): Promise<Response> {
2837
+ const chain = chainOf()
2838
+ if (!hasMiddleware(chain?.page)) return renderPage(request, pathname, host)
2839
+ const resolved = found || run.preview ? undefined : await cache.resolve(host, pathname)
2840
+ const content = found ?? resolved?.content
2841
+ // A redirect has no page to see, so the redirect tables and `umbracoRedirect` answer first.
2842
+ if (
2843
+ resolved?.redirect !== undefined ||
2844
+ (!content && !run.preview && (await cache.redirect(host, pathname)) !== undefined)
2845
+ )
2846
+ return renderPage(request, pathname, host)
2847
+ const member = run.preview ? undefined : (await members.session(request))?.member
2848
+ let shown = content
2849
+ if (content) {
2850
+ const decision = await members.decide(content, member)
2851
+ if (decision.status === 'substitute')
2852
+ shown = (await cache.byKey(decision.contentKey, content.culture)) ?? content
2853
+ }
2854
+ return runStage({
2855
+ stage: 'page',
2856
+ chain: chain?.page,
2857
+ request,
2858
+ budget: run.budget,
2859
+ context: (current) => chainContext(current, run, { page: shown, member }),
2860
+ inner: (current) => {
2861
+ if (new URL(current.url).pathname !== pathname)
2862
+ throw new MiddlewareError(
2863
+ 'the page stage',
2864
+ 'A rewrite is refused in the page stage: which page renders, and who may see it, is already decided.',
2865
+ )
2866
+ return renderPage(current, pathname, host)
2867
+ },
2868
+ })
2869
+ }
2870
+
2871
+ async function renderPage(request: Request, pathname: string, host: string): Promise<Response> {
2659
2872
  const preview = await renderPreview(request, pathname, host)
2660
2873
  // An `api` node renders for preview and nothing else. The backoffice opens a
2661
2874
  // site URL to preview a draft, so the renderer has to be here; serving the
@@ -2675,7 +2888,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2675
2888
  // A page that is not the same for everyone is never kept: a member's, a
2676
2889
  // preview, a form's answer, or anything in a members-only branch — which a
2677
2890
  // visitor sees as the login page, at the same address.
2678
- let personal = Boolean(preview || member || submission || cookie)
2891
+ // Whether the page itself read anything personal, the member included, it
2892
+ // says in its result (story 206).
2893
+ let personal = Boolean(preview || submission || cookie)
2679
2894
  const result =
2680
2895
  preview ??
2681
2896
  (await renderer.render(pathname, host, {
@@ -2687,6 +2902,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2687
2902
  return members.decide(content, member)
2688
2903
  },
2689
2904
  search: siteSearchFor(db, cache, member),
2905
+ site: siteServicesFor(member),
2690
2906
  ...(await pageRequest(request)),
2691
2907
  }))
2692
2908
  const cleared: Record<string, string> = cookie
@@ -2697,16 +2913,23 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2697
2913
  const response = new Response(result.html, {
2698
2914
  headers: { 'content-type': 'text/html; charset=utf-8', ...cleared },
2699
2915
  })
2700
- if (personal) {
2916
+ if (personal || result.personal) {
2701
2917
  response.headers.set('cache-control', PRIVATE_NO_STORE)
2702
2918
  return response
2703
2919
  }
2704
2920
  const ancestors = (await cache.navigation(result.content.culture)).ancestors(result.content)
2921
+ const item = {
2922
+ typeAlias: result.content.contentType.alias,
2923
+ value: (alias: string) => result.content.value(alias),
2924
+ }
2705
2925
  return cacheable(request, response, result.html, {
2706
- lifetime: lifetimeFor(caching, {
2707
- typeAlias: result.content.contentType.alias,
2708
- value: (alias) => result.content.value(alias),
2709
- }),
2926
+ // A page's own "Keep copies for" still wins over its template's `revalidate`.
2927
+ lifetime:
2928
+ (result.revalidate === undefined
2929
+ ? undefined
2930
+ : chosenLifetime(result.content.value(CACHE_KEEP_FOR_ALIAS))) ??
2931
+ revalidateLifetime(result.revalidate) ??
2932
+ lifetimeFor(caching, item),
2710
2933
  tags: [result.content.key, ...ancestors.map((a) => a.key)],
2711
2934
  tagHeader: caching.tagHeader,
2712
2935
  })
@@ -2723,6 +2946,36 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2723
2946
  status: 404,
2724
2947
  headers: { 'content-type': 'text/plain; charset=utf-8' },
2725
2948
  })
2949
+ case 'outcome': {
2950
+ const { outcome } = result
2951
+ const shared = !(personal || result.personal)
2952
+ const headers: Record<string, string> = {
2953
+ ...cleared,
2954
+ ...(shared ? {} : { 'cache-control': PRIVATE_NO_STORE }),
2955
+ }
2956
+ if (outcome.isRedirect) {
2957
+ const location = outcome.location as string
2958
+ // The preview frame stays put, and the editor is told where visitors go.
2959
+ if (preview)
2960
+ return new Response(previewRedirectNotice(outcome.status, location), {
2961
+ headers: { 'content-type': 'text/html; charset=utf-8', ...headers },
2962
+ })
2963
+ return new Response(null, { status: outcome.status, headers: { location, ...headers } })
2964
+ }
2965
+ return statusResponse(
2966
+ request,
2967
+ pathname,
2968
+ host,
2969
+ member,
2970
+ {
2971
+ status: outcome.status,
2972
+ name: outcome.name,
2973
+ message: outcome.message,
2974
+ errors: outcome.errors,
2975
+ },
2976
+ headers,
2977
+ )
2978
+ }
2726
2979
  case 'error': {
2727
2980
  // The visitor left and the render was stopped for it: nobody reads this
2728
2981
  // response, and it says nothing about the template.
@@ -2730,16 +2983,30 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2730
2983
  // Through `inSource`, so the file named is the one somebody can open
2731
2984
  // rather than the snapshot generation it was imported from.
2732
2985
  const detail = renderer.inSource(result.error.stack ?? result.error.message)
2733
- renderLog.error('Template error while rendering {name} ({key}): {detail}', {
2734
- name: result.content.name,
2735
- key: result.content.key,
2736
- detail,
2737
- })
2738
- return new Response(
2739
- config.development
2740
- ? `Template error while rendering '${result.content.name}':\n\n${detail}`
2741
- : 'Server Error',
2742
- { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } },
2986
+ const reference = errorReference()
2987
+ renderLog.error(
2988
+ 'Template error while rendering {name} ({key}), reference {reference}: {detail}',
2989
+ {
2990
+ name: result.content.name,
2991
+ key: result.content.key,
2992
+ reference,
2993
+ detail,
2994
+ },
2995
+ )
2996
+ const described = renderer.describeError(result.error)
2997
+ return statusResponse(
2998
+ request,
2999
+ pathname,
3000
+ host,
3001
+ member,
3002
+ {
3003
+ status: 500,
3004
+ name: 'serverError',
3005
+ errors: [],
3006
+ reference,
3007
+ ...(config.errors.showDetails ? { details: described } : {}),
3008
+ },
3009
+ { ...cleared, 'cache-control': PRIVATE_NO_STORE },
2743
3010
  )
2744
3011
  }
2745
3012
  default: {
@@ -2766,6 +3033,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2766
3033
  noNodesPage({ siteName: config.siteName, backOfficePath: config.backOfficePath }),
2767
3034
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } },
2768
3035
  )
3036
+ const configured = config.pages?.notFound !== undefined
3037
+ if (configured)
3038
+ return statusResponse(request, pathname, host, member, {
3039
+ status: 404,
3040
+ name: 'notFound',
3041
+ errors: [],
3042
+ })
2769
3043
  const page = await renderNotFoundPage(request, pathname, host, member)
2770
3044
  if (page) return page
2771
3045
  return new Response('Not Found', {
@@ -2776,6 +3050,88 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2776
3050
  }
2777
3051
  }
2778
3052
 
3053
+ /** A file of the islands' browser code, or their manifest, by the mode the site is in. */
3054
+ async function islandFile(path: string): Promise<Response> {
3055
+ const missing = () => new Response('Not Found', { status: 404 })
3056
+ const typed = (file: string, cache: string) =>
3057
+ new Response(Bun.file(file), {
3058
+ headers: {
3059
+ 'content-type': file.endsWith('.json')
3060
+ ? 'application/json; charset=utf-8'
3061
+ : file.endsWith('.css')
3062
+ ? 'text/css; charset=utf-8'
3063
+ : 'text/javascript; charset=utf-8',
3064
+ 'cache-control': cache,
3065
+ },
3066
+ })
3067
+ const [mode, ...rest] = path.split('/')
3068
+ if (mode === 'dev') {
3069
+ if (!config.development || !config.islands?.devServer || rest.join('/') !== 'manifest.json')
3070
+ return missing()
3071
+ return Response.json(
3072
+ devServerIslandManifest(config.islands.devServer, config.componentsDir),
3073
+ {
3074
+ headers: { 'cache-control': 'no-cache' },
3075
+ },
3076
+ )
3077
+ }
3078
+ if (mode === 'vite') {
3079
+ const manifestPath = config.islands?.manifest
3080
+ if (!manifestPath) return missing()
3081
+ const file = rest.join('/')
3082
+ if (file === 'manifest.json')
3083
+ return Response.json(viteIslandManifest(config.siteDir, manifestPath), {
3084
+ headers: { 'cache-control': config.development ? 'no-cache' : 'public, max-age=60' },
3085
+ })
3086
+ if (!file || rest.some((part) => part === '' || part === '.' || part === '..'))
3087
+ return missing()
3088
+ const built = join(viteOutDir(config.siteDir, manifestPath), ...rest)
3089
+ return existsSync(built) ? typed(built, 'public, max-age=31536000, immutable') : missing()
3090
+ }
3091
+ const built = builtIslandFile(config.componentsCacheDir, mode ?? '', rest.join('/'))
3092
+ return built ? typed(built, 'public, max-age=31536000, immutable') : missing()
3093
+ }
3094
+
3095
+ /**
3096
+ * A status answered by the site's own page for it, rendered at the address
3097
+ * asked for (story 206); else, for a 404, the page `seo.notFoundPage` names;
3098
+ * else a generic page. A status page that fails or throws an outcome falls to
3099
+ * the generic page, so it never loops.
3100
+ */
3101
+ async function statusResponse(
3102
+ request: Request,
3103
+ pathname: string,
3104
+ host: string,
3105
+ member: Awaited<ReturnType<typeof members.resolve>>,
3106
+ outcome: PageOutcome,
3107
+ headers: Record<string, string> = {},
3108
+ ): Promise<Response> {
3109
+ const html = { 'content-type': 'text/html; charset=utf-8', ...headers }
3110
+ const kind = statusPageKind(outcome.status)
3111
+ const found = await resolveStatusPage(cache, config.pages, kind, host, pathname)
3112
+ if (found) {
3113
+ const result = await renderer.renderModel(found.content, found.culture, {
3114
+ member,
3115
+ outcome,
3116
+ search: siteSearchFor(db, cache, member),
3117
+ site: siteServicesFor(member),
3118
+ ...(await pageRequest(request)),
3119
+ })
3120
+ if (result.status === 'ok')
3121
+ return new Response(result.html, { status: outcome.status, headers: html })
3122
+ if (result.status === 'error' && !request.signal.aborted)
3123
+ renderLog.error('Template error while rendering the {kind} page {name}: {detail}', {
3124
+ kind,
3125
+ name: found.content.name,
3126
+ detail: renderer.inSource(result.error.stack ?? result.error.message),
3127
+ })
3128
+ } else if (outcome.status === 404) {
3129
+ const page = await renderNotFoundPage(request, pathname, host, member)
3130
+ if (page) return page
3131
+ }
3132
+ return new Response(genericStatusPage(outcome), { status: outcome.status, headers: html })
3133
+ }
3134
+
2779
3135
  /**
2780
3136
  * The page chosen to answer an address nothing else does, with status 404. A
2781
3137
  * page that fails to render leaves the plain answer rather than a second error.
@@ -2816,6 +3172,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2816
3172
  renderer,
2817
3173
  snapshots,
2818
3174
  seededAdminPassword,
3175
+ bundleGrants,
3176
+ backgroundJobs: jobRunner,
3177
+ waitingBundles: () =>
3178
+ config.bundles.flatMap((bundle) => {
3179
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
3180
+ if (!pkg || bundleGrants.isOn(bundle.id)) return []
3181
+ return [{ id: bundle.id, missing: bundleGrants.state(pkg).missing }]
3182
+ }),
2819
3183
  schema,
2820
3184
  poll: () => poller.poll(),
2821
3185
  notImplemented,
@@ -2846,6 +3210,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2846
3210
  if (!request.headers.has('content-length') && request.headers.has('transfer-encoding'))
2847
3211
  return new Response('Length Required', { status: 411 })
2848
3212
  }
3213
+ // An open event stream outlives Bun's idle timeout.
3214
+ if (live && pathname === LIVE_EVENTS_PATH) bunServer.timeout(request, 0)
2849
3215
  const hubAt = contractPathFor(paths.backOfficePath, pathname) ?? pathname
2850
3216
  if (hubAt === hubPath || hubAt === previewHubPath) {
2851
3217
  const principal = await authenticate(request)
@@ -2858,15 +3224,19 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2858
3224
  },
2859
3225
  async close() {
2860
3226
  diagnostics.stop()
2861
- // A run already going finishes first: closing the database under a job
2862
- // left its locks behind for whatever used the database next.
2863
- await jobs.stop()
3227
+ // A run already going finishes first, or goes back in the queue: closing
3228
+ // the database under a job left its locks behind for whatever used it next.
3229
+ await core.stopJobs()
2864
3230
  // A dispatch a commit started finishes before the connection goes.
2865
3231
  await dispatcher.settled().catch(() => {})
2866
3232
  events.stop()
2867
3233
  previewHub.stop()
2868
3234
  watcher?.close()
3235
+ viewWatcher?.close()
3236
+ typeWatch?.stop()
3237
+ live?.close()
2869
3238
  poller.stop()
3239
+ await closeTables(chains)
2870
3240
  await db.close()
2871
3241
  },
2872
3242
  }
@@ -2885,3 +3255,16 @@ function withQuery(location: string, requestUrl: string): string {
2885
3255
  const query = new URL(requestUrl).search
2886
3256
  return query && !location.includes('?') ? `${location}${query}` : location
2887
3257
  }
3258
+
3259
+ /** A short code a visitor can quote, which the log line carries too. */
3260
+ function errorReference(): string {
3261
+ return crypto.randomUUID().replaceAll('-', '').slice(0, 10).toUpperCase()
3262
+ }
3263
+
3264
+ /** A template's `revalidate` as a lifetime: seconds, or false for as long as it is unchanged. */
3265
+ function revalidateLifetime(revalidate: number | false | undefined): Lifetime {
3266
+ if (revalidate === undefined) return undefined
3267
+ if (revalidate === false) return { maxAge: 31_536_000 }
3268
+ if (!Number.isFinite(revalidate) || revalidate < 0) return undefined
3269
+ return revalidate === 0 ? 'none' : { maxAge: Math.floor(revalidate) }
3270
+ }