@crombolo/server 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/core.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  appendCacheInstruction,
13
13
  type JobWake,
14
14
  notifyJobs,
15
+ OwnerSetupNeededError,
15
16
  RedirectRepository,
16
17
  SITE_OWNER,
17
18
  UserGroupRepository,
@@ -36,7 +37,14 @@ import { recordAudit } from './adapters/audit.ts'
36
37
  import { createMediaSource, createPublishedContentSource } from './adapters/documents.ts'
37
38
  import { backOfficeUrl, documentEditUrl } from './back-office-url.ts'
38
39
  import { BACKOFFICE_EXTERNAL_PATH } from './backoffice-external.ts'
39
- import { APPROVED_BY_CODE, createBundleGrants, declaredPermissions } from './bundle-grants.ts'
40
+ import { actAsChoice, createBundleApi, extensionPrincipal } from './bundle-api.ts'
41
+ import {
42
+ APPROVED_BY_CODE,
43
+ createBundleGrants,
44
+ declaredOrigins,
45
+ declaredPermissions,
46
+ isSchema3,
47
+ } from './bundle-grants.ts'
40
48
  import {
41
49
  type BundleMediaFactory,
42
50
  createBundleMedia,
@@ -52,6 +60,13 @@ import { databaseFor, openTables, siteTablesProblems, tablesChains } from './cus
52
60
  import { attachDatabase, bootstrapDatabase } from './database.ts'
53
61
  import { createDiagnostics } from './diagnostics.ts'
54
62
  import { resolveEmailPort } from './email.ts'
63
+ import { createExtensionComponents } from './extension-components.ts'
64
+ import {
65
+ entryCovers,
66
+ extensionEntryProblems,
67
+ readRecordedExtensions,
68
+ startExtensions,
69
+ } from './extension-discovery.ts'
55
70
  import { createFormRegistry, formSigningSecret, signFormToken } from './form-submit.ts'
56
71
  import { formTypesOf } from './form-types.ts'
57
72
  import { createWorkflowRunner } from './form-workflows.ts'
@@ -66,6 +81,7 @@ import { logger } from './logging.ts'
66
81
  import { MediaFileStore } from './media-files.ts'
67
82
  import { mediaStoreFromEnvironment } from './media-store.ts'
68
83
  import { createNodeOperations } from './node-operations.ts'
84
+ import { OutboundRefused, pinnedFetch } from './outbound-address.ts'
69
85
  import {
70
86
  CORE_JOB_OWNER,
71
87
  createJobRunner,
@@ -78,7 +94,7 @@ import { createRedirectTracker } from './redirects.ts'
78
94
  import { withRemoteMedia } from './remote-media.ts'
79
95
  import { bootSchema, CacheInstructionPoller } from './schema.ts'
80
96
  import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
81
- import { apiUserPrincipal, createSiteContent } from './site-content.ts'
97
+ import { apiUserPrincipal, createSiteContent, userPrincipalByKey } from './site-content.ts'
82
98
  import { SITE_EVENT_JOB, siteEventJob, siteEventProblems } from './site-events.ts'
83
99
  import { createSiteQueries, queryProblems } from './site-queries.ts'
84
100
  import { createSiteServices } from './site-services.ts'
@@ -143,7 +159,46 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
143
159
  // On every role: a bundle's form types are needed wherever forms render and
144
160
  // submit, and its member and public routes wherever the site is served. Its
145
161
  // tables are migrated only by the nodes that own the database.
146
- const bundlePackages = extensions.bundles().bundles
162
+ const discovered = extensions.bundles()
163
+ const bundlePackages = discovered.bundles
164
+ let bundleDispatch: ((request: Request) => Promise<Response>) | undefined
165
+ // An extension from before story 306 does not say what it is: it is turned
166
+ // off, not mounted, and the site starts without it.
167
+ const untyped = new Set(discovered.problems.flatMap((found) => found.untyped?.id ?? []))
168
+ if (config.bundles.some((bundle) => untyped.has(bundle.id))) {
169
+ for (const bundle of config.bundles.filter((candidate) => untyped.has(candidate.id)))
170
+ log.warning(
171
+ 'The bundle {id} is turned off: it does not say it is an extension. Install a version that does.',
172
+ { id: bundle.id },
173
+ )
174
+ config.bundles = config.bundles.filter((bundle) => !untyped.has(bundle.id))
175
+ }
176
+ // Story 310: installed extensions run once granted, with nothing imported by
177
+ // the site; one still imported the old way is the site's own code, and runs in
178
+ // this process as before. Story 311: the rest each run in a Deno process.
179
+ const wiredByImport = new Set(
180
+ config.bundles
181
+ .filter((bundle) => bundlePackages.some((pkg) => pkg.id === bundle.id))
182
+ .map((bundle) => bundle.id),
183
+ )
184
+ for (const id of wiredByImport)
185
+ log.warning(
186
+ 'The extension {id} is imported in crombolo.config.ts, so it runs inside the site, unconfined: list it under extensions instead, and it runs apart.',
187
+ { id },
188
+ )
189
+ const entryProblems = extensionEntryProblems(config.extensions, bundlePackages)
190
+ if (entryProblems.length > 0)
191
+ throw new Error(`The installed extensions cannot be started:\n- ${entryProblems.join('\n- ')}`)
192
+ const extensionsStarted = await startExtensions(
193
+ config,
194
+ bundlePackages,
195
+ await readRecordedExtensions(config),
196
+ bundleLog,
197
+ )
198
+ const extensionProcesses = extensionsStarted.processes
199
+ const failedExtensions = extensionsStarted.failed
200
+ // In place: the caller's config is the server's, and later steps set it too.
201
+ config.bundles = [...config.bundles, ...extensionsStarted.bundles]
147
202
  const formTypes = formTypesOf(config)
148
203
  {
149
204
  const problems = [
@@ -163,14 +218,38 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
163
218
  throw new Error(`The site's own tables cannot be used:\n- ${site.join('\n- ')}`)
164
219
  }
165
220
  setFormFieldTypes(formTypes.types, formTypes.renderers)
166
- const chains = tablesChains(config, config.bundles, bundlePackages)
221
+ let chains = tablesChains(config, config.bundles, bundlePackages)
167
222
  // A `web` node reads the site's tables for its named queries, and nothing of a
168
223
  // bundle's; a worker runs bundles' jobs, so it opens every owner's.
224
+ let opened = config.role === 'web' ? chains.filter((chain) => chain.id === SITE_OWNER) : chains
225
+ let booted: Awaited<ReturnType<typeof bootstrapDatabase>>
226
+ for (;;) {
227
+ try {
228
+ booted = owns ? await bootstrapDatabase(config, chains) : await attachDatabase(config, opened)
229
+ break
230
+ } catch (error) {
231
+ // An extension whose role this database user may not create is left off,
232
+ // saying what to run; the site starts without it (story 311).
233
+ const process = extensionProcesses.find(
234
+ (candidate) => error instanceof OwnerSetupNeededError && candidate.id === error.owner,
235
+ )
236
+ if (!process) throw error
237
+ await process.stop()
238
+ extensionProcesses.splice(extensionProcesses.indexOf(process), 1)
239
+ failedExtensions.push({ id: process.id, reason: (error as Error).message })
240
+ bundleLog(process.id).error(
241
+ '{id} could not be started, and the site starts without it: {reason}',
242
+ {
243
+ id: process.id,
244
+ reason: (error as Error).message,
245
+ },
246
+ )
247
+ config.bundles = config.bundles.filter((bundle) => bundle.id !== process.id)
248
+ chains = tablesChains(config, config.bundles, bundlePackages)
249
+ opened = config.role === 'web' ? chains.filter((chain) => chain.id === SITE_OWNER) : chains
250
+ }
251
+ }
169
252
  const siteChains = chains.filter((chain) => chain.id === SITE_OWNER)
170
- const opened = config.role === 'web' ? siteChains : chains
171
- const booted = owns
172
- ? await bootstrapDatabase(config, chains)
173
- : await attachDatabase(config, opened)
174
253
  const { seededAdminPassword } = booted
175
254
  // Story 262: on every role, before anything reads, so each statement is a span.
176
255
  await startTelemetry({
@@ -199,11 +278,20 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
199
278
  if (!runsJobs(config)) wake('jobs')
200
279
  },
201
280
  })
202
- for (const bundle of config.bundles) {
203
- const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
204
- if (!pkg) continue
281
+ for (const pkg of bundlePackages) {
282
+ const entry = config.extensions?.[pkg.id]
283
+ // The site's code grants what it names (story 310), or what an old-style
284
+ // import wires; anything else waits for a grant recorded here.
285
+ const byCode = wiredByImport.has(pkg.id) || entryCovers(pkg, entry)
286
+ if (!byCode) continue
287
+ const bundle = { id: pkg.id }
205
288
  // Recorded where the database is written, and audited when it changes.
206
- if (owns && (await bundleGrants.grant(pkg, APPROVED_BY_CODE)))
289
+ if (
290
+ owns &&
291
+ (await bundleGrants.grant(pkg, APPROVED_BY_CODE, {
292
+ actAs: entry?.actAs ? actAsChoice(entry.actAs) : undefined,
293
+ }))
294
+ )
207
295
  await recordAudit(db, {
208
296
  category: 'system',
209
297
  action: 'Grant',
@@ -212,12 +300,31 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
212
300
  detail: `approved by the site's code: ${declaredPermissions(pkg).join(', ') || 'nothing'}`,
213
301
  source: 'boot',
214
302
  })
215
- if (!bundleGrants.isOn(bundle.id))
216
- log.warning('The bundle {bundle} is disabled by {by}; enable it in Packages → Installed.', {
303
+ const state = bundleGrants.state(pkg)
304
+ if (state.status === 'off')
305
+ log.warning('The bundle {bundle} is turned off by {by}; turn it on in Bundles → Installed.', {
306
+ bundle: bundle.id,
307
+ by: state.disabledBy ?? 'an administrator',
308
+ })
309
+ else if (state.status === 'waiting')
310
+ log.warning('The bundle {bundle} waits for a grant of {missing}.', {
217
311
  bundle: bundle.id,
218
- by: bundleGrants.state(pkg).disabledBy ?? 'an administrator',
312
+ missing: state.missing.join(', '),
219
313
  })
220
314
  }
315
+ // Story 309: a version that asks for less than was granted keeps running, its
316
+ // grant narrowed to what it asks for, audited.
317
+ if (owns)
318
+ for (const pkg of bundlePackages)
319
+ if (await bundleGrants.narrow(pkg))
320
+ await recordAudit(db, {
321
+ category: 'system',
322
+ action: 'Grant',
323
+ entityType: 'Bundle',
324
+ entityName: `${pkg.packageName}@${pkg.version}`,
325
+ detail: `narrowed to what it asks for: ${declaredPermissions(pkg).join(', ') || 'nothing'}`,
326
+ source: 'boot',
327
+ })
221
328
  // A configured schema store is copied down before anything reads `schema/`, and
222
329
  // becomes the schema directory for this boot. Everything after here — loading,
223
330
  // validation, hashing, sync, the writer — works on files exactly as it always has.
@@ -331,9 +438,19 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
331
438
  // Before the poller, which tells it to look again on a `views` instruction
332
439
  // from another node: a closure over a `const` declared later would be a
333
440
  // temporal dead zone waiting for the first instruction to land.
441
+ const extensionComponents = createExtensionComponents(
442
+ extensionProcesses.map((process) => ({
443
+ process,
444
+ granted: () => bundleGrants.granted(process.id),
445
+ layout: () =>
446
+ typeof process.settings.layout === 'string' ? process.settings.layout : undefined,
447
+ log: bundleLog(process.id),
448
+ })),
449
+ )
334
450
  const renderer = new Renderer({
335
451
  cache,
336
452
  componentsDir: config.componentsDir,
453
+ extensionComponents,
337
454
  snapshots,
338
455
  renderTimeoutMs: config.renderTimeoutMs,
339
456
  islandsManifest: (generation) =>
@@ -370,6 +487,10 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
370
487
  allowPrivateAddresses: config.webhooks?.allowPrivateAddresses ?? config.development,
371
488
  },
372
489
  isBundleOn: (bundleId) => bundleGrants.isOn(bundleId),
490
+ bundleOrigins: (bundleId) => {
491
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundleId)
492
+ return pkg && !isSchema3(pkg) ? declaredOrigins(pkg) : undefined
493
+ },
373
494
  // The site's own handlers (story 298): each event queues the job that runs one.
374
495
  siteEvents: {
375
496
  handles: (alias) => typeof config.events?.[alias] === 'function',
@@ -451,6 +572,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
451
572
  return chain ? databaseFor(chain) : undefined
452
573
  },
453
574
  isOn: (bundleId) => bundleGrants.isOn(bundleId),
575
+ granted: (bundleId) => bundleGrants.granted(bundleId),
454
576
  jobs: (bundleId, queuedBy) => jobRunner.jobsFor(bundleId, queuedBy),
455
577
  pluginApiPath: `${paths.pluginPath}/api`,
456
578
  host: {
@@ -486,6 +608,47 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
486
608
  },
487
609
  log: (id) => bundleLog(id),
488
610
  callerHost: {
611
+ // Story 308: the site's areas, as the extension or whom it acts for.
612
+ api: (caller, bundle) => {
613
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
614
+ const granted = () => bundleGrants.granted(bundle.id)
615
+ return createBundleApi({
616
+ bundleId: bundle.id,
617
+ origin: (config.applicationUrl || 'http://localhost').replace(/\/+$/, ''),
618
+ backOfficePath: config.backOfficePath,
619
+ granted,
620
+ dispatch: () => bundleDispatch,
621
+ principal: async () => {
622
+ const itself = extensionPrincipal(
623
+ { id: bundle.id, name: pkg?.name ?? bundle.id },
624
+ granted(),
625
+ )
626
+ const choice =
627
+ pkg && granted().includes('actAs') ? bundleGrants.state(pkg).grant?.actAs : null
628
+ if (!choice) return itself
629
+ if (choice === 'caller')
630
+ return caller.kind === 'backoffice' ? caller.principal : itself
631
+ return userPrincipalByKey(db, choice.slice(choice.indexOf(':') + 1))
632
+ },
633
+ })
634
+ },
635
+ fetch: (_caller, bundle) => {
636
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
637
+ return {
638
+ fetch: async (input, init) => {
639
+ const url = new URL(input instanceof Request ? input.url : String(input))
640
+ const origins = declaredOrigins(pkg)
641
+ if (!origins.includes(url.origin))
642
+ throw new OutboundRefused(
643
+ `${bundle.id} may not reach ${url.origin}: its http.outbound names ${origins.join(', ') || 'nothing'}.`,
644
+ )
645
+ return pinnedFetch(input, init, {
646
+ allowPrivateAddresses:
647
+ config.webhooks?.allowPrivateAddresses ?? config.development,
648
+ })
649
+ },
650
+ }
651
+ },
489
652
  media: (caller, bundle) => {
490
653
  bundleMedia ??= createBundleMedia({
491
654
  db,
@@ -675,6 +838,10 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
675
838
  // Where jobs are left to a worker: whether one is running them (decision 4).
676
839
  const workerWatch = createWorkerWatch({ db, config })
677
840
  return {
841
+ /** The server's own handler, which `api` calls through once the server is built (story 308). */
842
+ setBundleDispatch(dispatch: (request: Request) => Promise<Response>) {
843
+ bundleDispatch = dispatch
844
+ },
678
845
  diagnostics,
679
846
  extensions,
680
847
  paths,
@@ -732,14 +899,19 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
732
899
  else jobRunner.wake()
733
900
  })
734
901
  },
735
- /** Stops listening, the jobs and the runner, letting what is running finish or go back. */
902
+ /** Stops listening, the jobs and the runner, letting what is running finish or go back; then the extensions' processes. */
736
903
  async stopJobs(): Promise<void> {
737
904
  workerWatch.stop()
738
905
  await listening?.()
739
906
  listening = undefined
740
907
  await jobRunner.stop()
741
908
  await jobs.stop()
909
+ await Promise.all(extensionProcesses.map((process) => process.stop()))
742
910
  },
911
+ /** The extensions that are granted but could not start, and why (story 311). */
912
+ failedExtensions,
913
+ /** The extensions' components, which render in their processes (story 312). */
914
+ extensionComponents,
743
915
  }
744
916
  }
745
917
 
@@ -0,0 +1,101 @@
1
+ /**
2
+ * A Bundle Editor definition built as an extension for other sites (story 312):
3
+ * the templates and partial views it picks are its code, under `src/components/`
4
+ * with a factory that declares them, and render in its own process where it is
5
+ * installed. Its schema and pages name them by its id, `<id>/<alias>`. The rest
6
+ * is its payload, as data. docs/bundles.md, "The Bundle Editor".
7
+ */
8
+ import type { BundleFile, BundlePackageInfo, ContentSet } from '@crombolo/transfer'
9
+
10
+ const COMPONENTS = 'components/'
11
+
12
+ /** The factory the generated entry exports, which `crombolo.server` names. */
13
+ export const CREATED_EXTENSION_FACTORY = 'extension'
14
+
15
+ /** Each `"alias"` in a TOML string list or string that names a picked component, as `"<id>/alias"`. */
16
+ function renamed(text: string, id: string, aliases: ReadonlySet<string>): string {
17
+ const quoted = (value: string) =>
18
+ value.replace(/"([^"]+)"/g, (whole, alias: string) =>
19
+ aliases.has(alias) ? `"${id}/${alias}"` : whole,
20
+ )
21
+ return text
22
+ .replace(
23
+ /^(\s*components\s*=\s*\[)([^\]]*)(\])/gm,
24
+ (_, open, list, close) => `${open}${quoted(list)}${close}`,
25
+ )
26
+ .replace(
27
+ /^(\s*default-component\s*=\s*)("[^"]*")/gm,
28
+ (_, key, value) => `${key}${quoted(value)}`,
29
+ )
30
+ }
31
+
32
+ /** A component file's alias: its path under `components/`, a folder template by its folder. */
33
+ const aliasOf = (path: string) =>
34
+ path
35
+ .slice(COMPONENTS.length)
36
+ .replace(/\/page\.tsx$/, '')
37
+ .replace(/\.tsx$/, '')
38
+
39
+ /**
40
+ * The payload without its components, its schema and pages naming them under
41
+ * `id`, and the code that carries them; no code when nothing is picked.
42
+ */
43
+ export function createdExtension(
44
+ id: string,
45
+ sections: readonly BundleFile[],
46
+ set: ContentSet,
47
+ ): { payload: BundleFile[]; set: ContentSet; code?: BundlePackageInfo['code'] } {
48
+ const components = sections.filter((file) => file.path.startsWith(COMPONENTS))
49
+ if (components.length === 0) return { payload: [...sections], set }
50
+ // Each component it carries, by alias: what the picks were, whichever way they were named.
51
+ const aliases = new Set(
52
+ components.filter((file) => file.path.endsWith('.tsx')).map((file) => aliasOf(file.path)),
53
+ )
54
+ const payload = sections
55
+ .filter((file) => !file.path.startsWith(COMPONENTS))
56
+ .map((file) =>
57
+ file.path.startsWith('schema/') && file.path.endsWith('.toml') && file.text !== undefined
58
+ ? { ...file, text: renamed(file.text, id, aliases) }
59
+ : file,
60
+ )
61
+ const renamedSet: ContentSet = {
62
+ ...set,
63
+ nodes: set.nodes.map((node) =>
64
+ node.template && aliases.has(node.template)
65
+ ? { ...node, template: `${id}/${node.template}` }
66
+ : node,
67
+ ),
68
+ }
69
+ const declared = components.filter((file) => file.path.endsWith('.tsx'))
70
+ const entry = [
71
+ '// Written by the Bundle Editor (story 312): the components this extension brings.',
72
+ ...declared.map((file, index) => `import * as c${index} from './${file.path}'`),
73
+ '',
74
+ `export function ${CREATED_EXTENSION_FACTORY}() {`,
75
+ ' return {',
76
+ ` id: ${JSON.stringify(id)},`,
77
+ " section: 'content',",
78
+ ' capabilities: [],',
79
+ ' components: {',
80
+ ...declared.map((file, index) => ` ${JSON.stringify(aliasOf(file.path))}: c${index},`),
81
+ ' },',
82
+ ' }',
83
+ '}',
84
+ '',
85
+ ].join('\n')
86
+ return {
87
+ payload,
88
+ set: renamedSet,
89
+ code: {
90
+ entry: 'src/index.ts',
91
+ server: CREATED_EXTENSION_FACTORY,
92
+ permissions: {
93
+ templates: 'Renders the templates and partial views it brings in your pages',
94
+ },
95
+ files: [
96
+ { path: 'src/index.ts', text: entry },
97
+ ...components.map((file) => ({ ...file, path: `src/${file.path}` })),
98
+ ],
99
+ },
100
+ }
101
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * An extension's components, rendered in its own process (story 312). The page,
3
+ * its layouts and the site's components render here; when the render reaches one
4
+ * an extension owns, `<id>/<name>`, that one component is a `render` call to the
5
+ * extension, and its HTML goes in its place. docs/extensions.md, "Components".
6
+ */
7
+ import {
8
+ type ComponentModule,
9
+ markPersonal,
10
+ PublishedContent,
11
+ PublishedElement,
12
+ RawHtml,
13
+ } from '@crombolo/render'
14
+ import type { BundleLog } from './bundles.ts'
15
+ import type { ExtensionProcess } from './extension-process.ts'
16
+
17
+ /** One extension whose components may render: its process, and what it may do now. */
18
+ export interface ExtensionComponentSource {
19
+ process: ExtensionProcess
20
+ /** What it may use now, from its grant; `templates` is what lets it render. */
21
+ granted(): readonly string[]
22
+ /** The site layout its page templates sit in: its `layout` setting. */
23
+ layout(): string | undefined
24
+ log: BundleLog
25
+ }
26
+
27
+ export interface ExtensionComponents {
28
+ /** The component `<id>/<name>` as a module the renderer runs, or undefined when none is. */
29
+ module(alias: string): ComponentModule | undefined
30
+ /** The layout each extension's `layout` setting names, where one does. */
31
+ layouts(): { id: string; layout: string }[]
32
+ /** Every component the extensions offer, as `<id>/<name>` with the extension's name: for the template picker. */
33
+ listed(): { alias: string; extension: string }[]
34
+ }
35
+
36
+ const BLOCKS = 'blocks/'
37
+
38
+ /** How many pages and elements one render sends with their values; past it, values are calls. */
39
+ const VALUES_PER_RENDER = 200
40
+
41
+ /**
42
+ * The values sent with each page and element a render lends, so the component
43
+ * reads them synchronously, as a site component does (story 312).
44
+ */
45
+ function valuesSender(): (value: object) => Record<string, unknown> | undefined {
46
+ let left = VALUES_PER_RENDER
47
+ return (value) => {
48
+ if (!(value instanceof PublishedContent || value instanceof PublishedElement)) return undefined
49
+ if (left <= 0) return undefined
50
+ left -= 1
51
+ const values: Record<string, unknown> = {}
52
+ for (const { alias } of value.properties) {
53
+ if (alias in values) continue
54
+ try {
55
+ values[alias] = {
56
+ value: value.value(alias),
57
+ text: value.text(alias),
58
+ html: value.html(alias),
59
+ }
60
+ } catch {
61
+ // Left to a call, which says what went wrong.
62
+ }
63
+ }
64
+ return { $values: values }
65
+ }
66
+ }
67
+
68
+ export function createExtensionComponents(
69
+ sources: readonly ExtensionComponentSource[],
70
+ options: { timeoutMs?: number } = {},
71
+ ): ExtensionComponents {
72
+ const byId = new Map(sources.map((source) => [source.process.id, source]))
73
+ const warned = new Set<string>()
74
+ const offers = (source: ExtensionComponentSource, name: string) =>
75
+ source.process.description?.components?.some((component) => component.name === name) ?? false
76
+
77
+ const render = async (
78
+ source: ExtensionComponentSource,
79
+ name: string,
80
+ props: Record<string, unknown>,
81
+ ): Promise<RawHtml> => {
82
+ const id = source.process.id
83
+ if (!source.granted().includes('templates')) {
84
+ if (!warned.has(id)) {
85
+ warned.add(id)
86
+ source.log.warn(
87
+ 'The extension {id} was not granted templates, so its component {name} renders nothing.',
88
+ { id, name },
89
+ )
90
+ }
91
+ return new RawHtml('')
92
+ }
93
+ // A signed-in member may change what it renders, and its code cannot be read
94
+ // for `member` as a view's can: such a page is not shared.
95
+ if (props.member !== undefined) markPersonal()
96
+ const { searchParams, ...rest } = props
97
+ try {
98
+ const { value } = await source.process.call(
99
+ 'render',
100
+ { name },
101
+ // Read only if the component asks, since reading them makes the page personal.
102
+ { ...rest, readSearchParams: () => searchParams },
103
+ { timeoutMs: options.timeoutMs ?? 10_000, extra: valuesSender() },
104
+ )
105
+ return new RawHtml(typeof value === 'string' ? value : '')
106
+ } catch (error) {
107
+ source.log.error('The extension {id} could not render {name}: {error}', {
108
+ id,
109
+ name,
110
+ error: error instanceof Error ? error.message : String(error),
111
+ })
112
+ return new RawHtml('')
113
+ }
114
+ }
115
+
116
+ // The layout the administrator chose, else the one the component suggests: a
117
+ // site without that layout renders the body on its own.
118
+ const moduleFor = (source: ExtensionComponentSource, name: string): ComponentModule => ({
119
+ default: ((props: Record<string, unknown>) => render(source, name, props)) as never,
120
+ layout:
121
+ source.layout() ??
122
+ source.process.description?.components?.find((component) => component.name === name)?.layout,
123
+ })
124
+
125
+ return {
126
+ module(alias) {
127
+ // A block's component is found by its element type's alias, in whichever
128
+ // extension offers it.
129
+ if (alias.startsWith(BLOCKS)) {
130
+ const name = alias
131
+ const source = sources.find((candidate) => offers(candidate, name))
132
+ return source ? moduleFor(source, name) : undefined
133
+ }
134
+ const slash = alias.indexOf('/')
135
+ if (slash < 1) return undefined
136
+ const source = byId.get(alias.slice(0, slash))
137
+ const name = alias.slice(slash + 1)
138
+ return source && offers(source, name) ? moduleFor(source, name) : undefined
139
+ },
140
+ layouts() {
141
+ return sources.flatMap((source) => {
142
+ const layout = source.layout()
143
+ return layout ? [{ id: source.process.id, layout }] : []
144
+ })
145
+ },
146
+ listed() {
147
+ return sources.flatMap((source) =>
148
+ (source.process.description?.components ?? [])
149
+ .filter((component) => !component.name.startsWith(BLOCKS))
150
+ .map((component) => ({
151
+ alias: `${source.process.id}/${component.name}`,
152
+ extension: source.process.name,
153
+ })),
154
+ )
155
+ },
156
+ }
157
+ }