@crombolo/server 0.63.0 → 0.65.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.63.0",
3
+ "version": "0.65.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,19 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.63.0",
35
- "@crombolo/api-management": "0.63.0",
36
- "@crombolo/auth": "0.63.0",
37
- "@crombolo/backoffice-host": "0.63.0",
38
- "@crombolo/common": "0.63.0",
39
- "@crombolo/content": "0.63.0",
40
- "@crombolo/contracts": "0.63.0",
41
- "@crombolo/core": "0.63.0",
42
- "@crombolo/data": "0.63.0",
43
- "@crombolo/extension": "0.63.0",
44
- "@crombolo/render": "0.63.0",
45
- "@crombolo/schema": "0.63.0",
46
- "@crombolo/transfer": "0.63.0",
34
+ "@crombolo/api-delivery": "0.65.1",
35
+ "@crombolo/api-management": "0.65.1",
36
+ "@crombolo/auth": "0.65.1",
37
+ "@crombolo/backoffice-host": "0.65.1",
38
+ "@crombolo/common": "0.65.1",
39
+ "@crombolo/content": "0.65.1",
40
+ "@crombolo/contracts": "0.65.1",
41
+ "@crombolo/core": "0.65.1",
42
+ "@crombolo/data": "0.65.1",
43
+ "@crombolo/extension": "0.65.1",
44
+ "@crombolo/render": "0.65.1",
45
+ "@crombolo/schema": "0.65.1",
46
+ "@crombolo/transfer": "0.65.1",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
package/src/access.ts CHANGED
@@ -98,12 +98,16 @@ export function createNodeLookup(db: Db): NodeLookup {
98
98
  }
99
99
  }
100
100
 
101
- /** A user's languages, their groups' start nodes per tree (story 339), and group verbs. */
101
+ /**
102
+ * A user's languages, their groups' start nodes per tree (story 339), and group
103
+ * verbs; from the given groups instead while a session views as them (story 314).
104
+ */
102
105
  export async function loadAccess(
103
106
  db: Db,
104
107
  userId: number,
108
+ groupKeys?: readonly string[],
105
109
  ): Promise<Pick<Principal, 'languages' | 'startNodes' | 'groups'>> {
106
- const data = await new UserRepository(db).access(userId)
110
+ const data = await new UserRepository(db).access(userId, groupKeys)
107
111
  return {
108
112
  languages: data.languages,
109
113
  groups: data.groups,
@@ -43,7 +43,7 @@ import { aliasFromName } from '@crombolo/schema'
43
43
  import { readContentTypeUdt, writeContentTypeUdt } from '../content-type-udt.ts'
44
44
  import { classifyTypeChange } from '../schema-classify.ts'
45
45
  import { contentTypeJsonSchema, schemaForStorage, valueTypeName } from '../value-schemas.ts'
46
- import { createSchemaFileWriter, type SchemaFiles } from './schema-files.ts'
46
+ import { createSchemaFileWriter, type SchemaFiles, schemaProblems } from './schema-files.ts'
47
47
 
48
48
  async function toTreeItems(
49
49
  nodes: NodeRepository,
@@ -150,6 +150,43 @@ export function underSchemaLock<P extends object>(
150
150
  return locked
151
151
  }
152
152
 
153
+ class InvalidSchemaSave extends Error {
154
+ constructor(readonly problems: readonly string[]) {
155
+ super(problems.join('; '))
156
+ }
157
+ }
158
+
159
+ /**
160
+ * A save of a type or data type, in a transaction kept only when it leaves the
161
+ * definitions the schema files are written from no worse than it found them.
162
+ * Otherwise nothing is kept, and the save is refused saying why, so a file is
163
+ * never left behind its row. Problems that were there before are not its own.
164
+ */
165
+ export async function savedIfValid<T>(
166
+ db: Db,
167
+ files: SchemaFiles | undefined,
168
+ work: (tx: Db) => Promise<T>,
169
+ ): Promise<{ ok: true; value: T } | PortFailure> {
170
+ if (!files) return { ok: true, value: await work(db) }
171
+ const before = new Set(await schemaProblems(db, files))
172
+ try {
173
+ const value = await db.transaction(async (tx) => {
174
+ const value = await work(tx)
175
+ const added = (await schemaProblems(tx, files)).filter((p) => !before.has(p))
176
+ if (added.length > 0) throw new InvalidSchemaSave(added)
177
+ return value
178
+ })
179
+ return { ok: true, value }
180
+ } catch (error) {
181
+ if (!(error instanceof InvalidSchemaSave)) throw error
182
+ return {
183
+ ok: false,
184
+ status: 400,
185
+ reason: `This wasn't saved, because the site's definitions would no longer be valid: ${error.problems.join('; ')}`,
186
+ }
187
+ }
188
+ }
189
+
153
190
  export function createFolderPort(
154
191
  folders: FolderRepository,
155
192
  tree: ReturnType<typeof createSettingsTree>,
@@ -221,6 +258,9 @@ export function createContentTypePort(
221
258
  ): ContentTypePort {
222
259
  const kind = options.kind ?? 'document'
223
260
  const repo = new ContentTypeRepository(db, { nodeState: options.nodeState, kind })
261
+ /** The same repository over a transaction's handle, for a checked save. */
262
+ const repoOn = (handle: Db) =>
263
+ new ContentTypeRepository(handle, { nodeState: options.nodeState, kind })
224
264
  const nodes = repo.nodes
225
265
  const objectType = repo.objectType
226
266
  const containerType = CONTENT_TYPE_OBJECT_TYPES[kind].container
@@ -253,10 +293,11 @@ export function createContentTypePort(
253
293
  }
254
294
  const refused = files?.refuse(aggregate)
255
295
  if (refused) return refused
256
- // A new type can only be additive, and the version moves before the write so
257
- // the file that lands carries the version it belongs to.
296
+ const saved = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(aggregate))
297
+ if (!saved.ok) return saved
298
+ // A new type can only be additive, and the version moves before the file is
299
+ // written so the file that lands carries the version it belongs to.
258
300
  await files?.bumpVersion('additive')
259
- await repo.save(aggregate)
260
301
  await files?.write(aggregate)
261
302
  void principal
262
303
  return { ok: true as const }
@@ -271,10 +312,17 @@ export function createContentTypePort(
271
312
  const before = await repo.byKey(key)
272
313
  // Classified here, while the database still holds the old type: once it is
273
314
  // saved there is nothing left to compare it with.
274
- if (files)
275
- await files.bumpVersion(await classifyTypeChange(db, before, { ...aggregate, key }))
315
+ const change = files ? await classifyTypeChange(db, before, { ...aggregate, key }) : 'none'
276
316
  // The editor does not send tree placement; keep what the type has.
277
- await repo.save({ ...aggregate, key, parentKey: before?.parentKey ?? aggregate.parentKey })
317
+ const saved = await savedIfValid(db, schemaFiles, (tx) =>
318
+ repoOn(tx).save({
319
+ ...aggregate,
320
+ key,
321
+ parentKey: before?.parentKey ?? aggregate.parentKey,
322
+ }),
323
+ )
324
+ if (!saved.ok) return saved
325
+ await files?.bumpVersion(change)
278
326
  await files?.write({ ...aggregate, key }, before?.alias)
279
327
  void principal
280
328
  return { ok: true as const }
@@ -360,7 +408,8 @@ export function createContentTypePort(
360
408
  ? saved.key
361
409
  : aggregate.defaultComponentKey,
362
410
  }
363
- await repo.save(updated)
411
+ const kept = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(updated))
412
+ if (!kept.ok) return kept
364
413
  await files?.write(updated)
365
414
  void principal
366
415
  return { ok: true as const, key: saved.key }
@@ -505,7 +554,8 @@ export function createContentTypePort(
505
554
 
506
555
  if (!existing && (await repo.aliasExists(aggregate.alias)))
507
556
  return { status: 'invalid', reason: `The alias '${aggregate.alias}' is already in use.` }
508
- await repo.save(aggregate)
557
+ const saved = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(aggregate))
558
+ if (!saved.ok) return { status: 'invalid', reason: saved.reason }
509
559
  await files?.write(aggregate)
510
560
  return { status: 'ok', key: aggregate.key }
511
561
  },
@@ -608,8 +658,13 @@ export function createDataTypePort(db: Db, schemaFiles?: SchemaFiles): DataTypeP
608
658
  }
609
659
  },
610
660
  async save(model: DataTypeModel) {
611
- const saved = await repo.save(await withAlias(model))
612
- await files?.writeDataType(saved)
661
+ const aliased = await withAlias(model)
662
+ const saved = await savedIfValid(db, schemaFiles, (tx) =>
663
+ new DataTypeRepository(tx).save(aliased),
664
+ )
665
+ if (!saved.ok) return saved
666
+ await files?.writeDataType(saved.value)
667
+ return undefined
613
668
  },
614
669
  async remove(key) {
615
670
  const before = await repo.byKey(key)
@@ -96,7 +96,7 @@ export function createDocumentPort(
96
96
  /** The site's own directory: where `domains.toml` is, when the site keeps one. */
97
97
  siteDir?: string,
98
98
  /** Whether the site can send the e-mails a subscription asks for (story 045). */
99
- notificationsAvailable = true,
99
+ notificationsAvailable: boolean | (() => boolean) = true,
100
100
  ): DocumentPort {
101
101
  const repo = new DocumentRepository(db, options)
102
102
  const domains = new DomainRepository(db)
@@ -442,7 +442,11 @@ export function createDocumentPort(
442
442
  const userId = await userIdOf(principal)
443
443
  if (!node || node.objectType !== repo.objectType || userId === undefined) return 'notFound'
444
444
  // Clearing is always allowed; asking for something the site cannot send is not.
445
- if (!notificationsAvailable) {
445
+ if (
446
+ !(typeof notificationsAvailable === 'function'
447
+ ? notificationsAvailable()
448
+ : notificationsAvailable)
449
+ ) {
446
450
  const had = new Set(await notifications.subscribed(userId, node.id))
447
451
  if (actionIds.some((id) => !had.has(id))) return 'unavailable'
448
452
  }
@@ -72,6 +72,23 @@ export interface SchemaFileWriter {
72
72
  * `schema/content-types/`, media types `schema/media-types/`. Data types,
73
73
  * languages and the rewrite are the same whichever kind asks.
74
74
  */
75
+ /**
76
+ * What is wrong with the definitions as the files would be written from the
77
+ * database `db` sees. A save compares it before and after, inside its
78
+ * transaction, and refuses what it adds, so a file is never left behind its row.
79
+ */
80
+ export async function schemaProblems(db: Db, files: SchemaFiles): Promise<string[]> {
81
+ if (!existsSync(files.schemaDir) || !files.writable) return []
82
+ const set = await exportSchemaSet(
83
+ db,
84
+ loadSchemaDirectory(files.schemaDir, { formTypes: files.formTypes }).set.version,
85
+ )
86
+ return validateSchemaSet(set, {
87
+ componentAliases: files.componentAliases(),
88
+ types: files.formTypes,
89
+ }).map((p) => `${p.file}${p.path ? ` (${p.path})` : ''}: ${p.message}`)
90
+ }
91
+
75
92
  export function createSchemaFileWriter(
76
93
  db: Db,
77
94
  files: SchemaFiles,
@@ -134,18 +151,8 @@ export function createSchemaFileWriter(
134
151
  : (set.memberTypes ?? [])
135
152
  const type = list.find((t) => t.key === aggregate.key)
136
153
  if (!type) return
137
- const problems = validateSchemaSet(set, {
138
- componentAliases: files.componentAliases(),
139
- types: files.formTypes,
140
- })
141
- if (problems.length > 0) {
142
- const detail = problems.map((p) => `${p.file}: ${p.message}`).join('; ')
143
- logger('schema').error('Not writing {file}: {detail}', {
144
- file: fileNameFor(aggregate.alias),
145
- detail,
146
- })
147
- return
148
- }
154
+ // Checked before the save, which `schemaProblems` refuses, so the file always
155
+ // follows the database.
149
156
  mkdirSync(dir, { recursive: true })
150
157
  if (previousAlias && previousAlias !== aggregate.alias)
151
158
  rmSync(fileFor(previousAlias), { force: true })
@@ -172,21 +179,6 @@ export function createSchemaFileWriter(
172
179
  await settle()
173
180
  return
174
181
  }
175
- // The same guard `write` applies to a content type: a set that does not
176
- // validate never reaches the disk, because the file is what every other
177
- // node reads and what a deploy boots from.
178
- const problems = validateSchemaSet(set, {
179
- componentAliases: files.componentAliases(),
180
- types: files.formTypes,
181
- })
182
- if (problems.length > 0) {
183
- const detail = problems.map((p) => `${p.file}: ${p.message}`).join('; ')
184
- logger('schema').error('Not writing {file}: {detail}', {
185
- file: fileNameFor(model.alias),
186
- detail,
187
- })
188
- return
189
- }
190
182
  mkdirSync(join(files.schemaDir, 'data-types'), { recursive: true })
191
183
  writeFileSync(
192
184
  join(files.schemaDir, 'data-types', fileNameFor(model.alias)),
package/src/approvals.ts CHANGED
@@ -47,7 +47,7 @@ import {
47
47
  UserGroupRepository,
48
48
  } from '@crombolo/data'
49
49
  import type { ContentNotifier } from './content-notifications.ts'
50
- import type { EmailPort } from './email.ts'
50
+ import { type EmailPort, emailReady } from './email.ts'
51
51
 
52
52
  /** What publishing and unpublishing go through when approval says yes. */
53
53
  export interface ApprovalPublisher {
@@ -388,7 +388,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
388
388
  subject: string,
389
389
  body: string,
390
390
  ) => {
391
- if (!options.email) return
391
+ if (!emailReady(options.email)) return
392
392
  let emails: string[] = []
393
393
  if (to === 'editor') {
394
394
  const rows = await db.q
@@ -441,6 +441,26 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
441
441
  })
442
442
  }
443
443
 
444
+ /** Whether the person who made the change is in one of these groups. */
445
+ const requesterIn = async (
446
+ request: ApprovalRequest,
447
+ approvers: readonly string[],
448
+ actor: Principal | undefined,
449
+ ): Promise<boolean> => {
450
+ // Story 314: the requester viewing as groups is in exactly those.
451
+ if (actor?.viewingAs && normaliseUuid(actor.id) === request.requestedBy)
452
+ return actor.groups.some((g) => approvers.includes(g.alias))
453
+ const member = await db.q
454
+ .selectFrom('user_group_member as m')
455
+ .innerJoin('user_group as g', 'g.id', 'm.user_group_id')
456
+ .innerJoin('user_account as u', 'u.id', 'm.user_id')
457
+ .select((eb) => eb.fn.countAll().as('n'))
458
+ .where('u.key', '=', request.requestedBy)
459
+ .where('g.alias', 'in', approvers.length > 0 ? approvers : [''])
460
+ .execute()
461
+ return Number(member[0]?.n ?? 0) > 0
462
+ }
463
+
444
464
  /**
445
465
  * Stages just reached count the person who made the change as approving
446
466
  * when the workflow says so and they are in the stage's groups.
@@ -449,20 +469,13 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
449
469
  repo: ApprovalRepositoryType,
450
470
  request: ApprovalRequest,
451
471
  stages: readonly string[],
472
+ actor: Principal | undefined,
452
473
  ): Promise<void> => {
453
474
  for (const stage of stages) {
454
475
  const stepId = await repo.addStep(request.id, stage)
455
476
  if (request.workflow.selfApproval !== 'automatic') continue
456
477
  const approvers = stageOf(request.workflow, stage)?.approvers ?? []
457
- const member = await db.q
458
- .selectFrom('user_group_member as m')
459
- .innerJoin('user_group as g', 'g.id', 'm.user_group_id')
460
- .innerJoin('user_account as u', 'u.id', 'm.user_id')
461
- .select((eb) => eb.fn.countAll().as('n'))
462
- .where('u.key', '=', request.requestedBy)
463
- .where('g.alias', 'in', approvers.length > 0 ? approvers : [''])
464
- .execute()
465
- if (Number(member[0]?.n ?? 0) > 0)
478
+ if (await requesterIn(request, approvers, actor))
466
479
  await repo.record(request.id, {
467
480
  kind: 'approved',
468
481
  stepId,
@@ -478,6 +491,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
478
491
  const settle = async (
479
492
  repo: ApprovalRepositoryType,
480
493
  request: ApprovalRequest,
494
+ actor: Principal | undefined,
481
495
  ): Promise<boolean> => {
482
496
  for (let round = 0; round < request.workflow.stages.length + 1; round++) {
483
497
  const steps = await repo.steps(request.id)
@@ -499,7 +513,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
499
513
  if (workflowComplete(request.workflow, approved)) return true
500
514
  const next = stagesNowWaiting(request.workflow, approved, reached)
501
515
  if (next.length > 0) {
502
- await reach(repo, request, next)
516
+ await reach(repo, request, next, actor)
503
517
  const facts = await page(request.nodeKey)
504
518
  await notify(
505
519
  'approvers',
@@ -912,7 +926,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
912
926
  comment: [comment?.trim(), when && `to be ${when}`].filter(Boolean).join('\n\n') || null,
913
927
  })
914
928
  const first = startStages(workflow)
915
- await reach(repo, request, first)
929
+ await reach(repo, request, first, principal)
916
930
  await notify(
917
931
  'approvers',
918
932
  request,
@@ -920,7 +934,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
920
934
  `Waiting for your approval: ${facts.name}`,
921
935
  `${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${when ? ` It is to be ${when}.` : ''}${comment ? `\n\n${comment}` : ''}`,
922
936
  )
923
- const complete = await settle(repo, request)
937
+ const complete = await settle(repo, request, principal)
924
938
  await auditStep(
925
939
  principal,
926
940
  facts,
@@ -958,7 +972,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
958
972
  userKey: principal.id,
959
973
  comment: comment?.trim() || null,
960
974
  })
961
- const complete = await settle(repo, request)
975
+ const complete = await settle(repo, request, principal)
962
976
  await auditStep(
963
977
  principal,
964
978
  await page(request.nodeKey),
@@ -1011,7 +1025,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1011
1025
  (s) => (s.state === 'waiting' || s.state === 'approved') && redo.has(s.stage),
1012
1026
  ))
1013
1027
  await repo.setStepState(step.id, step.stage === from ? 'sent-back' : 'discarded')
1014
- await reach(repo, request, [to])
1028
+ await reach(repo, request, [to], principal)
1015
1029
  await notify(
1016
1030
  'approvers',
1017
1031
  request,
@@ -1019,7 +1033,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1019
1033
  `Back for your approval: ${facts?.name ?? 'a page'}`,
1020
1034
  `"${facts?.name}" was sent back to you${comment ? `:\n\n${comment}` : '.'}`,
1021
1035
  )
1022
- complete = await settle(repo, request)
1036
+ complete = await settle(repo, request, principal)
1023
1037
  }
1024
1038
  await auditStep(
1025
1039
  principal,
@@ -17,6 +17,7 @@ import {
17
17
  USER_DELEGATE,
18
18
  } from '@crombolo/backoffice-host/registry'
19
19
  import {
20
+ appendCacheInstruction,
20
21
  type Db,
21
22
  ExtensionSettingRepository,
22
23
  ownerTablesIn,
@@ -115,6 +116,8 @@ export interface SwitchOutcome {
115
116
  ok: boolean
116
117
  on?: boolean
117
118
  message: string
119
+ /** It is granted and on, and its server half could not start, saying why (story 346). */
120
+ couldNotStart?: string
118
121
  }
119
122
 
120
123
  export interface BundleAdmin {
@@ -172,8 +175,33 @@ export function createBundleAdmin(options: {
172
175
  failed?: () => readonly { id: string; reason: string }[]
173
176
  /** Stops an extension's running process, where this node runs one (story 328). */
174
177
  stopExtension?: (id: string) => Promise<void>
178
+ /**
179
+ * Brings an extension's server half to what its grant says now, on every node
180
+ * (story 346): started when granted and on, stopped when off, unmounted when
181
+ * removed. Answers whether it runs here, or why it could not start; nothing
182
+ * where no server runs here, as on the CLI.
183
+ */
184
+ changed?: (id: string) => Promise<{ running: boolean; reason?: string } | undefined>
175
185
  }): BundleAdmin {
176
186
  const { db, config, marketplace, extensions, bundleGrants } = options
187
+
188
+ /** Started, stopped or unmounted to match its grant; an answer that says when it could not start. */
189
+ const afterSwitch = async (
190
+ pkg: { id: string; name: string; carries: { server?: boolean } },
191
+ outcome: SwitchOutcome,
192
+ ): Promise<SwitchOutcome> => {
193
+ if (!outcome.ok || !pkg.carries.server) return outcome
194
+ const now = await options.changed?.(pkg.id).catch((error: unknown) => ({
195
+ running: false,
196
+ reason: error instanceof Error ? error.message : String(error),
197
+ }))
198
+ if (!outcome.on || now?.running !== false || !now.reason) return outcome
199
+ return {
200
+ ...outcome,
201
+ couldNotStart: now.reason,
202
+ message: `${outcome.message} It could not start: ${now.reason}`,
203
+ }
204
+ }
177
205
  const options_ = options
178
206
  /**
179
207
  * The data removed extensions left (story 328): an owner the tables ledger
@@ -459,6 +487,8 @@ export function createBundleAdmin(options: {
459
487
  .join(' '),
460
488
  }
461
489
  if (!before?.carries.server) return result
490
+ // One running in a process of its own is unmounted now; one the site's code imported waits.
491
+ if (id && (await options_.changed?.(id).catch(() => undefined))) return result
462
492
  markRestartPending(config.siteDir, `${name} removed`)
463
493
  return { ...result, restartPending: true }
464
494
  },
@@ -531,12 +561,12 @@ export function createBundleAdmin(options: {
531
561
  `granted ${LEVEL_WORDS[level].label}: ${asks.join(', ') || 'nothing'}${delegateKey ? `, acting for ${delegateKey} when nobody is using it` : ''}`,
532
562
  )
533
563
  const state = bundleGrants.state(pkg)
534
- return {
564
+ return afterSwitch(pkg, {
535
565
  status: 200,
536
566
  ok: true,
537
567
  on: state.on,
538
568
  message: `${pkg.name} is granted what it asks for.`,
539
- }
569
+ })
540
570
  },
541
571
 
542
572
  async setEnabled(actor, id, enabled) {
@@ -573,7 +603,7 @@ export function createBundleAdmin(options: {
573
603
  `${pkg.packageName}@${pkg.version}`,
574
604
  enabled ? 'enabled; it runs again' : 'disabled; it is off',
575
605
  )
576
- return {
606
+ const outcome = {
577
607
  status: 200,
578
608
  ok: true,
579
609
  on: state.on,
@@ -581,6 +611,7 @@ export function createBundleAdmin(options: {
581
611
  ? `${pkg.name} is turned on.`
582
612
  : `${pkg.name} is turned off until it is enabled again.`,
583
613
  }
614
+ return afterSwitch(pkg, outcome)
584
615
  },
585
616
  }
586
617
  }
@@ -643,5 +674,10 @@ export async function localBundleAdmin(
643
674
  marketplace,
644
675
  extensions,
645
676
  bundleGrants,
677
+ // A site running on this database starts or stops it when it hears (story 346).
678
+ changed: async (id) => {
679
+ await appendCacheInstruction(db, { kind: 'extensions', payload: { id } }).catch(() => null)
680
+ return undefined
681
+ },
646
682
  })
647
683
  }
@@ -2,7 +2,8 @@
2
2
  * A host installs a site's bundles itself and tells each node (story 181):
3
3
  * `reloadBundles()` reads the site's `package.json` and `node_modules` again,
4
4
  * so the back office serves what is there now. It never mounts a server half:
5
- * configured `bundles` are wired at boot only, and stay as they were.
5
+ * configured `bundles` are wired at boot only, and an installed extension starts
6
+ * when it is granted (story 346).
6
7
  */
7
8
  import type { BundlePackage, ExtensionRegistry } from '@crombolo/backoffice-host'
8
9
 
package/src/bundles.ts CHANGED
@@ -822,10 +822,20 @@ export interface ServerBundles {
822
822
  principal: Principal,
823
823
  invoke: RouteInvoker,
824
824
  ): Promise<Response | undefined>
825
- /** The bundles' site routes, for the server's route table, each given its bundle's capabilities. */
826
- siteRoutes(): DeclaredRoute[]
825
+ /**
826
+ * The bundles' site routes, for the server's route table, each given its
827
+ * bundle's capabilities; one bundle's when named.
828
+ */
829
+ siteRoutes(bundleId?: string): DeclaredRoute[]
827
830
  /** What a bundle's job is given: its capabilities for no caller, as on a public route (story 187). */
828
831
  jobContext(bundleId: string): Pick<BundleHost, BundleCapability> | undefined
832
+ /**
833
+ * Mounts one more bundle while the server runs (story 346), checked as boot
834
+ * checks them; answers why it cannot be, and mounts nothing then.
835
+ */
836
+ add(bundle: ServerBundle, pkg: BundlePackage): string[]
837
+ /** Unmounts a bundle: its routes answer nothing from now on. */
838
+ remove(bundleId: string): void
829
839
  }
830
840
 
831
841
  const JOB_CALLER: BundleCaller = Object.freeze({ kind: 'job' })
@@ -862,11 +872,12 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
862
872
  throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
863
873
 
864
874
  const basePath = `${options.pluginApiPath}/${BUNDLE_API_SEGMENT}/`
865
- const byId = new Map(options.bundles.map((bundle) => [bundle.id, bundle]))
866
- const logs = new Map(options.bundles.map((bundle) => [bundle.id, options.log(bundle.id)]))
875
+ const live = [...options.bundles]
876
+ const byId = new Map(live.map((bundle) => [bundle.id, bundle]))
877
+ const logs = new Map(live.map((bundle) => [bundle.id, options.log(bundle.id)]))
867
878
 
868
879
  const owners = new Map(options.packages.map((pkg) => [pkg.id, pkg]))
869
- const mounted: MountedBundle[] = options.bundles.map((bundle) => {
880
+ const mountedOf = (bundle: ServerBundle): MountedBundle => {
870
881
  const owner = owners.get(bundle.id) as BundlePackage
871
882
  return {
872
883
  id: bundle.id,
@@ -881,7 +892,8 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
881
892
  audience: onSite(route) ? ('site' as const) : ('backoffice' as const),
882
893
  })),
883
894
  }
884
- })
895
+ }
896
+ const mounted: MountedBundle[] = live.map(mountedOf)
885
897
 
886
898
  // Made once per bundle, at its first request, each on its own tables alone.
887
899
  const databases = new Map<string, TablesDatabase>()
@@ -1031,25 +1043,48 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
1031
1043
  const bundle = byId.get(bundleId)
1032
1044
  return bundle ? contextFor(bundle, JOB_CALLER) : undefined
1033
1045
  },
1034
- siteRoutes() {
1035
- return options.bundles.flatMap((bundle) =>
1036
- (bundle.routes ?? []).filter(onSite).map(
1037
- (route): DeclaredRoute => ({
1038
- route: whileOn(bundle.id, route as SiteRoute),
1039
- owner: `the bundle ${bundle.id}`,
1040
- extra: ({ member, via }) => {
1041
- const caller: BundleCaller = member
1042
- ? Object.freeze({
1043
- kind: 'member',
1044
- member: freezeMember(member as RequestMember),
1045
- via,
1046
- })
1047
- : PUBLIC_CALLER
1048
- return { bundle: contextFor(bundle, caller), caller }
1049
- },
1050
- }),
1051
- ),
1052
- )
1046
+ add(bundle, pkg) {
1047
+ const problems = byId.has(bundle.id)
1048
+ ? [`Bundle "${bundle.id}" is already mounted.`]
1049
+ : validateServerBundles([bundle], [pkg], options.coreVersion)
1050
+ if (problems.length > 0) return problems
1051
+ owners.set(pkg.id, pkg)
1052
+ live.push(bundle)
1053
+ byId.set(bundle.id, bundle)
1054
+ logs.set(bundle.id, options.log(bundle.id))
1055
+ mounted.push(mountedOf(bundle))
1056
+ return []
1057
+ },
1058
+ remove(bundleId) {
1059
+ const at = live.findIndex((bundle) => bundle.id === bundleId)
1060
+ if (at >= 0) live.splice(at, 1)
1061
+ const shown = mounted.findIndex((bundle) => bundle.id === bundleId)
1062
+ if (shown >= 0) mounted.splice(shown, 1)
1063
+ byId.delete(bundleId)
1064
+ logs.delete(bundleId)
1065
+ databases.delete(bundleId)
1066
+ },
1067
+ siteRoutes(bundleId) {
1068
+ return live
1069
+ .filter((bundle) => bundleId === undefined || bundle.id === bundleId)
1070
+ .flatMap((bundle) =>
1071
+ (bundle.routes ?? []).filter(onSite).map(
1072
+ (route): DeclaredRoute => ({
1073
+ route: whileOn(bundle.id, route as SiteRoute),
1074
+ owner: `the bundle ${bundle.id}`,
1075
+ extra: ({ member, via }) => {
1076
+ const caller: BundleCaller = member
1077
+ ? Object.freeze({
1078
+ kind: 'member',
1079
+ member: freezeMember(member as RequestMember),
1080
+ via,
1081
+ })
1082
+ : PUBLIC_CALLER
1083
+ return { bundle: contextFor(bundle, caller), caller }
1084
+ },
1085
+ }),
1086
+ ),
1087
+ )
1053
1088
  },
1054
1089
  async handle(request, url, principal, invoke) {
1055
1090
  const pathname = url.pathname