@crombolo/server 0.69.1 → 0.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/package.json +15 -14
  2. package/src/adapters/blueprints.ts +51 -5
  3. package/src/adapters/change-recording.ts +140 -0
  4. package/src/adapters/content.ts +132 -21
  5. package/src/adapters/documents.ts +26 -5
  6. package/src/adapters/elements.ts +3 -0
  7. package/src/adapters/media.ts +7 -1
  8. package/src/adapters/schema-files.ts +89 -1
  9. package/src/adapters/users.ts +17 -12
  10. package/src/adapters/workspace-dictionary.ts +287 -0
  11. package/src/adapters/workspace-file-port.ts +160 -0
  12. package/src/adapters/workspace-languages.ts +94 -0
  13. package/src/approvals-api.ts +16 -7
  14. package/src/bundle-api.ts +19 -16
  15. package/src/bundle-install.ts +4 -0
  16. package/src/change-transfer.ts +676 -0
  17. package/src/changes-api.ts +258 -0
  18. package/src/component-templates-api.ts +2 -2
  19. package/src/config.ts +195 -21
  20. package/src/content-events.ts +65 -1
  21. package/src/content-operations.ts +22 -3
  22. package/src/core.ts +2 -0
  23. package/src/environment-values-api.ts +161 -0
  24. package/src/external-sign-in.ts +9 -2
  25. package/src/index.ts +1 -0
  26. package/src/managed-users.ts +122 -0
  27. package/src/node-operations.ts +150 -2
  28. package/src/ports.ts +174 -52
  29. package/src/principal.ts +1 -0
  30. package/src/remote-changes.ts +279 -0
  31. package/src/remote-schema.ts +126 -0
  32. package/src/remote-workspaces.ts +82 -0
  33. package/src/remote.ts +289 -192
  34. package/src/schema-transfer.ts +240 -41
  35. package/src/schema.ts +7 -2
  36. package/src/seed/compile.ts +13 -1
  37. package/src/seed/values.ts +3 -0
  38. package/src/server.ts +965 -364
  39. package/src/settings.ts +137 -5
  40. package/src/site-sections.ts +1 -1
  41. package/src/user-admin.ts +2 -0
  42. package/src/workspace-access.ts +152 -0
  43. package/src/workspace-checks.ts +299 -0
  44. package/src/workspace-losses.ts +95 -0
  45. package/src/workspace-processes.ts +306 -0
  46. package/src/workspace-render-child.ts +168 -0
  47. package/src/workspace-schema-dir.ts +100 -0
  48. package/src/workspace-schema.ts +598 -0
  49. package/src/workspace-sites.ts +179 -0
  50. package/src/workspace-views.ts +121 -0
  51. package/src/workspaces.ts +1031 -0
@@ -12,7 +12,7 @@ import type {
12
12
  EventSink,
13
13
  MediaOperations,
14
14
  } from '@crombolo/content'
15
- import { currentSchemaState, type Db } from '@crombolo/data'
15
+ import { currentSchemaState, type Db, WorkspaceRepository } from '@crombolo/data'
16
16
  import { PublishedCache } from '@crombolo/render'
17
17
  import { createPublishedContentSource } from './adapters/documents.ts'
18
18
  import { backOfficeUrl } from './back-office-url.ts'
@@ -34,6 +34,13 @@ export interface SiteOperations {
34
34
  export async function siteDocumentOperations(
35
35
  db: Db,
36
36
  config: CromboloConfig,
37
+ options: {
38
+ /**
39
+ * Story 386: where workspaces are on, a command's change goes into this person's
40
+ * own workspace, opened for them and named when it is pushed or merged.
41
+ */
42
+ ownWorkspaceOf?: { key: string; name: string }
43
+ } = {},
37
44
  ): Promise<SiteOperations> {
38
45
  const state = await currentSchemaState(db)
39
46
  const nodeState = { version: state.version, revision: state.revision }
@@ -51,7 +58,7 @@ export async function siteDocumentOperations(
51
58
  const cache = new PublishedCache(createPublishedContentSource(db, { nodeState }))
52
59
  // The routes a redirect is tracked from are read from this cache once a change
53
60
  // has committed, so the change drops it first.
54
- const { documents: operations } = createNodeOperations({
61
+ const nodeOperations = createNodeOperations({
55
62
  db,
56
63
  config,
57
64
  cache,
@@ -65,7 +72,19 @@ export async function siteDocumentOperations(
65
72
  webhooks,
66
73
  backOfficeUrl: backOfficeUrl(config),
67
74
  })
68
- return { operations, events }
75
+ const owner = options.ownWorkspaceOf
76
+ if (owner && config.workspaces) {
77
+ const workspaces = new WorkspaceRepository(db)
78
+ const own =
79
+ (await workspaces.ownOf(owner.key)) ??
80
+ (await workspaces.open({
81
+ name: `Changes by ${owner.name}`,
82
+ ownerKey: owner.key,
83
+ personal: true,
84
+ }))
85
+ return { operations: nodeOperations.documentsIn(own), events }
86
+ }
87
+ return { operations: nodeOperations.documents, events }
69
88
  }
70
89
 
71
90
  /**
package/src/core.ts CHANGED
@@ -411,6 +411,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
411
411
  const publishedSource = createPublishedContentSource(db, {
412
412
  nodeState: schema.nodeState,
413
413
  nodeId: schema.nodeId,
414
+ environment: config.environment,
414
415
  })
415
416
  // Media is cached apart from the pages (story 197), item by item within a
416
417
  // budget, and shared by the published and draft caches: media has no drafts.
@@ -594,6 +595,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
594
595
  wake('search')
595
596
  },
596
597
  nudge: () => wake('events'),
598
+ changes: true,
597
599
  })
598
600
  const operations = createNodeOperations({
599
601
  db,
@@ -0,0 +1,161 @@
1
+ /**
2
+ * A property's value per environment, edited beside its field (story 387), at
3
+ * `<plugin>/api/environment-values`: which environment this copy of the site is and
4
+ * which the schema names; a page's properties that vary by environment, each with
5
+ * its shared value and every environment's own; and one environment's value set or
6
+ * cleared, saved as any edit of the page is. docs/environments.md.
7
+ */
8
+ import type { Principal } from '@crombolo/api-management/domain'
9
+ import { type DocumentOperations, userActor } from '@crombolo/content'
10
+ import { type DocumentValue, normaliseUuid } from '@crombolo/core'
11
+ import {
12
+ ContentTypeRepository,
13
+ type Db,
14
+ DocumentRepository,
15
+ type DocumentRepositoryOptions,
16
+ readEnvironments,
17
+ } from '@crombolo/data'
18
+
19
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
20
+ const json = (body: unknown, status = 200) => Response.json(body, { status })
21
+ const refused = (message: string, status: number) => json({ message }, status)
22
+
23
+ /** One property's values: the shared one, and each environment's that overrides it. */
24
+ export interface EnvironmentValues {
25
+ alias: string
26
+ name: string
27
+ culture: string | null
28
+ segment: string | null
29
+ shared: unknown
30
+ overrides: Array<{ environment: string; value: unknown; known: boolean }>
31
+ }
32
+
33
+ export function createEnvironmentValuesApi(
34
+ db: Db,
35
+ options: {
36
+ environment: () => string
37
+ repository: DocumentRepositoryOptions
38
+ documents: () => DocumentOperations
39
+ /** The values can only arrive by a change here (`environmentValues.readOnly`, or locked content). */
40
+ readOnly: () => boolean
41
+ },
42
+ ) {
43
+ /** The properties of a page that vary by environment, with each of their values. */
44
+ async function valuesOf(key: string): Promise<EnvironmentValues[] | undefined> {
45
+ const page = await new DocumentRepository(db, options.repository).byKey(key)
46
+ if (!page) return undefined
47
+ const type = await new ContentTypeRepository(db).byKey(page.contentTypeKey)
48
+ const names = new Set(await readEnvironments(db))
49
+ const varying = (type?.properties ?? []).filter((p) => p.variesByEnvironment)
50
+ const out: EnvironmentValues[] = []
51
+ for (const property of varying) {
52
+ const mine = page.values.filter((v) => v.alias === property.alias)
53
+ const slots = new Map<string, EnvironmentValues>()
54
+ const slotOf = (v: DocumentValue) => {
55
+ const id = `${v.culture ?? ''}|${v.segment ?? ''}`
56
+ let slot = slots.get(id)
57
+ if (!slot) {
58
+ slot = {
59
+ alias: property.alias,
60
+ name: property.name,
61
+ culture: v.culture,
62
+ segment: v.segment,
63
+ shared: null,
64
+ overrides: [],
65
+ }
66
+ slots.set(id, slot)
67
+ }
68
+ return slot
69
+ }
70
+ for (const v of mine) {
71
+ const slot = slotOf(v)
72
+ if (v.environment)
73
+ slot.overrides.push({
74
+ environment: v.environment,
75
+ value: v.value,
76
+ known: names.has(v.environment),
77
+ })
78
+ else slot.shared = v.value
79
+ }
80
+ if (slots.size === 0)
81
+ slots.set('|', {
82
+ alias: property.alias,
83
+ name: property.name,
84
+ culture: null,
85
+ segment: null,
86
+ shared: null,
87
+ overrides: [],
88
+ })
89
+ out.push(...slots.values())
90
+ }
91
+ return out
92
+ }
93
+
94
+ return {
95
+ valuesOf,
96
+
97
+ async handle(request: Request, principal: Principal, rest: string): Promise<Response> {
98
+ const parts = rest.split('/').filter(Boolean)
99
+ if (parts.length === 0 && request.method === 'GET')
100
+ return json({
101
+ current: options.environment(),
102
+ names: await readEnvironments(db),
103
+ readOnly: options.readOnly(),
104
+ })
105
+ const key = parts[0]
106
+ if (parts.length !== 1 || !key || !UUID.test(key))
107
+ return refused('There is no such page.', 404)
108
+ if (request.method === 'GET') {
109
+ // A page not saved yet has none: the editor asks as it opens one.
110
+ return json({ items: (await valuesOf(normaliseUuid(key))) ?? [] })
111
+ }
112
+ if (request.method !== 'PUT') return new Response(null, { status: 405 })
113
+ if (options.readOnly())
114
+ return refused(
115
+ "This environment's values arrive only by a change applied from where they are made.",
116
+ 409,
117
+ )
118
+ const asked = ((await request.json().catch(() => ({}))) ?? {}) as Record<string, unknown>
119
+ const alias = typeof asked.alias === 'string' ? asked.alias : ''
120
+ const environment = typeof asked.environment === 'string' ? asked.environment : ''
121
+ const culture = typeof asked.culture === 'string' ? asked.culture : null
122
+ const segment = typeof asked.segment === 'string' ? asked.segment : null
123
+ if (!alias || !/^[a-z][a-z0-9-]{0,63}$/.test(environment))
124
+ return refused('Name the property and the environment.', 400)
125
+ const page = await new DocumentRepository(db, options.repository).byKey(normaliseUuid(key))
126
+ if (!page) return refused('There is no such page.', 404)
127
+ const type = await new ContentTypeRepository(db).byKey(page.contentTypeKey)
128
+ if (!type?.properties.some((p) => p.alias === alias && p.variesByEnvironment))
129
+ return refused(`"${alias}" does not vary by environment.`, 400)
130
+ const same = (v: DocumentValue) =>
131
+ v.alias === alias &&
132
+ (v.culture ?? null) === culture &&
133
+ (v.segment ?? null) === segment &&
134
+ v.environment === environment
135
+ // Every value is sent: one it leaves out of the property's environments is cleared.
136
+ const values: DocumentValue[] = page.values.filter((v) => !same(v))
137
+ if (asked.value !== null && asked.value !== undefined && asked.value !== '')
138
+ values.push({ alias, culture, segment, environment, value: asked.value })
139
+ const saved = await options.documents().save(
140
+ userActor(principal),
141
+ page.key,
142
+ {
143
+ key: page.key,
144
+ contentTypeKey: page.contentTypeKey,
145
+ componentKey: page.componentKey,
146
+ parentKey: page.parentKey,
147
+ values,
148
+ variants: page.variants.map((v) => ({
149
+ culture: v.culture,
150
+ segment: v.segment,
151
+ name: v.name,
152
+ })),
153
+ },
154
+ // Saved on the copy it was just read at, as an editor's save names its revision.
155
+ page.revision ? { expectedRevision: page.revision } : {},
156
+ )
157
+ if (!saved.ok) return refused(saved.reason, saved.status)
158
+ return json({ items: (await valuesOf(page.key)) ?? [] })
159
+ },
160
+ }
161
+ }
@@ -134,6 +134,8 @@ export function createExternalSignIn(
134
134
  log?: (message: string) => void
135
135
  /** The provider as a sign-in uses it, with an administrator's overrides on top (story 033). */
136
136
  resolve?: (provider: IdentityProvider) => Promise<IdentityProvider>
137
+ /** Accounts come from a directory outside the site (story 389): none is made, no groups follow. */
138
+ managed?: () => boolean
137
139
  },
138
140
  ): ExternalSignIn {
139
141
  const logins = new ExternalLoginRepository(db)
@@ -215,6 +217,7 @@ export function createExternalSignIn(
215
217
  }
216
218
 
217
219
  const loginProvider = externalLoginProvider(audience.audience, provider.oidc.id)
220
+ const managed = options.managed?.() === true
218
221
  const linked = await logins.find(loginProvider, identity.subject)
219
222
  // A link to an account that has since been deleted counts for nothing.
220
223
  const linkedAccount = linked ? await audience.byKey(linked.ownerKey) : undefined
@@ -224,7 +227,11 @@ export function createExternalSignIn(
224
227
  linked: linkedAccount?.key,
225
228
  sameEmail: sameEmail?.key,
226
229
  identity,
227
- provider: { ...provider, name: provider.oidc.name },
230
+ provider: {
231
+ ...provider,
232
+ name: provider.oidc.name,
233
+ ...(managed ? { autoCreate: false } : {}),
234
+ },
228
235
  })
229
236
  // Story 364: what the remote's exchange finds this person by, from this issuer.
230
237
  const named = identity.identity
@@ -250,7 +257,7 @@ export function createExternalSignIn(
250
257
  break
251
258
  }
252
259
  }
253
- if (decision.kind !== 'create' && Object.keys(provider.groupMap).length > 0) {
260
+ if (!managed && decision.kind !== 'create' && Object.keys(provider.groupMap).length > 0) {
254
261
  const groups = syncedGroups(account.groups, identity.groups, provider.groupMap)
255
262
  if (groups.join('\n') !== account.groups.join('\n')) await audience.setGroups(account, groups)
256
263
  }
package/src/index.ts CHANGED
@@ -118,6 +118,7 @@ export * from './live-reload.ts'
118
118
  export * from './log-expressions.ts'
119
119
  export * from './log-viewer.ts'
120
120
  export * from './logging.ts'
121
+ export { MANAGED_OUTSIDE, managedHref } from './managed-users.ts'
121
122
  export * from './marketplace.ts'
122
123
  export * from './media-files.ts'
123
124
  export * from './media-folders.ts'
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Story 389: a site whose back-office people come from a directory outside it. Only
3
+ * the API clients `users.managedBy` names create, change, disable or delete a person,
4
+ * or change whom a group holds; everyone else is refused, administrators included.
5
+ * A person's own language, avatar, password and two-factor stay theirs, and API users
6
+ * stay the administrator's. docs/configuration.md, "Users managed from outside".
7
+ */
8
+ import type {
9
+ Principal,
10
+ UserGroupPort,
11
+ UserGroupStatus,
12
+ UserPort,
13
+ } from '@crombolo/api-management/domain'
14
+ import { normaliseUuid } from '@crombolo/core'
15
+ import { type Db, UserRepository } from '@crombolo/data'
16
+
17
+ /** What a refused change says, wherever it was asked. */
18
+ export const MANAGED_OUTSIDE =
19
+ "This site's people come from a directory outside it: add, change or remove them there."
20
+
21
+ /** The ports, with every change to a person kept for the directory's clients. */
22
+ export function managedUserPorts(
23
+ db: Db,
24
+ ports: { users: UserPort; groups: UserGroupPort },
25
+ managedBy: readonly string[],
26
+ ): { users: UserPort; groups: UserGroupPort } {
27
+ if (managedBy.length === 0) return ports
28
+ const clients = new Set(managedBy)
29
+ const repository = new UserRepository(db)
30
+ const isDirectory = (principal: Principal) =>
31
+ principal.viaClient !== undefined && clients.has(principal.viaClient)
32
+ const self = (principal: Principal, key: string) =>
33
+ normaliseUuid(principal.id) === normaliseUuid(key)
34
+ /** Whether the change is refused: someone else's, to a person rather than an API user. */
35
+ const refused = async (principal: Principal, keys: readonly string[]): Promise<boolean> => {
36
+ if (isDirectory(principal)) return false
37
+ const found = await repository.byKeys(keys)
38
+ return found.some((user) => user.kind !== 'Api')
39
+ }
40
+ const others = (principal: Principal, key: string) =>
41
+ self(principal, key) ? Promise.resolve(false) : refused(principal, [key])
42
+ const { users, groups } = ports
43
+ return {
44
+ users: {
45
+ ...users,
46
+ async create(principal, input) {
47
+ if (input.kind !== 'Api' && !isDirectory(principal))
48
+ return { status: 'ManagedOutside' as const }
49
+ return users.create(principal, input)
50
+ },
51
+ async invite(principal, input, message) {
52
+ if (!isDirectory(principal)) return { status: 'ManagedOutside' as const }
53
+ return users.invite(principal, input, message)
54
+ },
55
+ async resendInvite(principal, key, message) {
56
+ if (await refused(principal, [key])) return 'ManagedOutside'
57
+ return users.resendInvite(principal, key, message)
58
+ },
59
+ async update(principal, key, input) {
60
+ if (await refused(principal, [key])) return 'ManagedOutside'
61
+ return users.update(principal, key, input)
62
+ },
63
+ async delete(principal, keys) {
64
+ if (await refused(principal, keys)) return 'ManagedOutside'
65
+ return users.delete(principal, keys)
66
+ },
67
+ async setApproved(principal, keys, approved) {
68
+ if (await refused(principal, keys)) return 'ManagedOutside'
69
+ return users.setApproved(principal, keys, approved)
70
+ },
71
+ async unlock(principal, keys) {
72
+ if (await refused(principal, keys)) return 'ManagedOutside'
73
+ return users.unlock(principal, keys)
74
+ },
75
+ async setGroups(principal, keys, groupKeys) {
76
+ if (await refused(principal, keys)) return 'ManagedOutside'
77
+ return users.setGroups(principal, keys, groupKeys)
78
+ },
79
+ async changePassword(principal, key, password, old) {
80
+ if (await others(principal, key)) return 'ManagedOutside'
81
+ return users.changePassword(principal, key, password, old)
82
+ },
83
+ async resetPassword(principal, key) {
84
+ if (await others(principal, key)) return { status: 'ManagedOutside' as const }
85
+ return users.resetPassword(principal, key)
86
+ },
87
+ async setAvatar(principal, key, file) {
88
+ if (await others(principal, key)) return 'ManagedOutside'
89
+ return users.setAvatar(principal, key, file)
90
+ },
91
+ async removeAvatar(principal, key) {
92
+ if (await others(principal, key)) return 'ManagedOutside'
93
+ return users.removeAvatar(principal, key)
94
+ },
95
+ async mayManage(principal, key) {
96
+ if (await others(principal, key)) return 'ManagedOutside'
97
+ return users.mayManage ? users.mayManage(principal, key) : 'Success'
98
+ },
99
+ },
100
+ groups: {
101
+ ...groups,
102
+ async addUsers(principal, key, userKeys): Promise<UserGroupStatus> {
103
+ if (await refused(principal, userKeys)) return 'ManagedOutside'
104
+ return groups.addUsers(principal, key, userKeys)
105
+ },
106
+ async removeUsers(principal, key, userKeys): Promise<UserGroupStatus> {
107
+ if (await refused(principal, userKeys)) return 'ManagedOutside'
108
+ return groups.removeUsers(principal, key, userKeys)
109
+ },
110
+ },
111
+ }
112
+ }
113
+
114
+ /** The directory's address for one user, `{email}`, `{key}` and `{userName}` filled in. */
115
+ export const managedHref = (
116
+ template: string,
117
+ user: { key: string; email: string; userName: string },
118
+ ): string =>
119
+ template
120
+ .replaceAll('{email}', encodeURIComponent(user.email))
121
+ .replaceAll('{key}', encodeURIComponent(user.key))
122
+ .replaceAll('{userName}', encodeURIComponent(user.userName))
@@ -4,27 +4,41 @@
4
4
  * and shared by the Management API, the jobs and the command line, so a worker
5
5
  * (story 223) publishes a schedule exactly as an editor's node does.
6
6
  */
7
+ import type { Principal } from '@crombolo/api-management/domain'
7
8
  import {
8
9
  createDocumentOperations,
9
10
  createElementOperations,
10
11
  createMediaOperations,
12
+ createWorkspaceOperations,
11
13
  type DocumentOperations,
12
14
  type ElementOperations,
13
15
  type EventSink,
14
16
  type MediaOperations,
17
+ type MergePlan,
18
+ previewWorkspaceMerge,
19
+ runWorkspaceMerge,
15
20
  SILENT,
21
+ userActor,
22
+ type WorkspaceFileMerging,
23
+ type WorkspaceMergeOutcome,
24
+ workspaceAuditSink,
16
25
  } from '@crombolo/content'
17
26
  import {
18
27
  appendCacheInstruction,
19
28
  type Db,
20
29
  type NodeSchemaState,
21
30
  RedirectRepository,
31
+ type Workspace,
22
32
  } from '@crombolo/data'
23
33
  import type { PublishedCache } from '@crombolo/render'
24
34
  import { createElementPort } from './adapters/elements.ts'
25
35
  import { type Approvals, approvalsGate, createApprovals } from './approvals.ts'
26
36
  import type { CromboloConfig } from './config.ts'
27
- import { createElementEventSink, createMediaEventSink } from './content-events.ts'
37
+ import {
38
+ createElementEventSink,
39
+ createMediaEventSink,
40
+ workspaceElementEventSink,
41
+ } from './content-events.ts'
28
42
  import type { ContentNotifier } from './content-notifications.ts'
29
43
  import { writeDomainsFor } from './domains.ts'
30
44
  import type { EmailPort } from './email.ts'
@@ -32,15 +46,42 @@ import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
32
46
  import type { MediaFileStore } from './media-files.ts'
33
47
  import { createRedirectTracker, NO_REDIRECT_TRACKING, type RedirectTracker } from './redirects.ts'
34
48
  import type { WebhookService } from './webhooks.ts'
49
+ import { createWorkspaceSchema, type FileMergePlan } from './workspace-schema.ts'
35
50
 
36
51
  export interface NodeOperations {
37
52
  valueIntake: ReturnType<typeof createFileIntake>
38
53
  tracker: RedirectTracker
39
54
  approvals: Approvals
40
55
  documents: DocumentOperations
56
+ /** The document operations in a workspace (story 375). */
57
+ documentsIn(workspace: Workspace): DocumentOperations
58
+ /** Its media and Library operations (story 390). */
59
+ mediaIn(workspace: Workspace): MediaOperations
60
+ elementsIn(workspace: Workspace): ElementOperations
41
61
  media: MediaOperations
42
62
  /** Every Library write (story 361). */
43
63
  elements: ElementOperations
64
+ /** Merging a workspace into Shared (story 380). */
65
+ merge: WorkspaceMerging
66
+ }
67
+
68
+ /** A workspace's merge: what it would do, and doing it, as the person merging. */
69
+ export interface WorkspaceMerging {
70
+ preview(workspace: Workspace): Promise<MergePlan>
71
+ /** One workspace, several as one, or `only` one page of a person's own. */
72
+ run(
73
+ workspaces: Workspace | readonly Workspace[],
74
+ principal: Principal,
75
+ options: {
76
+ userId?: number
77
+ accepted?: readonly string[]
78
+ rehearse?: boolean
79
+ only?: string
80
+ /** Story 383: the identity its change takes, and the changes from other sites it applies. */
81
+ changeKey?: string
82
+ appliedChanges?: ReadonlyArray<{ key: string; name: string | null }>
83
+ },
84
+ ): Promise<WorkspaceMergeOutcome>
44
85
  }
45
86
 
46
87
  export interface NodeOperationsOptions {
@@ -138,5 +179,112 @@ export function createNodeOperations(options: NodeOperationsOptions): NodeOperat
138
179
  events: createElementEventSink(),
139
180
  onChange: () => cache?.invalidate(),
140
181
  })
141
- return { valueIntake: repository.valueIntake, tracker, approvals, documents, media, elements }
182
+ /** A workspace's media and Library (story 390): audited, announced nowhere else. */
183
+ const mediaIn = (workspace: Workspace): MediaOperations =>
184
+ createMediaOperations({
185
+ db,
186
+ repository: { ...repository, workspace: workspace.id },
187
+ events: workspaceAuditSink(workspace.name),
188
+ files: options.mediaFiles,
189
+ refusalReason,
190
+ })
191
+ const elementsIn = (workspace: Workspace): ElementOperations =>
192
+ createElementOperations({
193
+ db,
194
+ store: (tx) =>
195
+ createElementPort(tx, {
196
+ nodeState: options.nodeState,
197
+ nodeId: options.nodeId,
198
+ valueIntake: repository.valueIntake,
199
+ workspace: workspace.id,
200
+ }),
201
+ events: workspaceElementEventSink(workspace.name),
202
+ })
203
+ /** The document operations in a workspace (story 375): its pages, audited, announced nowhere else. */
204
+ const documentsIn = (workspace: Workspace): DocumentOperations =>
205
+ createWorkspaceOperations(
206
+ { db, repository, refusalReason },
207
+ { id: workspace.id, name: workspace.name },
208
+ )
209
+ const gate = approvalsGate(approvals)
210
+ // Story 376: a workspace's files merge before its pages, on the same transaction.
211
+ const workspaceSchema = options.nodeState
212
+ ? createWorkspaceSchema(db, options.config, {
213
+ nodeId: options.nodeId ?? 'node',
214
+ nodeState: options.nodeState,
215
+ })
216
+ : undefined
217
+ const files: WorkspaceFileMerging | undefined = workspaceSchema && {
218
+ async plan(workspaceId, tx) {
219
+ const planned = await workspaceSchema.plan(workspaceId, tx)
220
+ return {
221
+ conflicts: [
222
+ ...planned.conflicts.map(
223
+ (c) =>
224
+ `The ${c.definition ? 'definition' : 'file'} ${c.path} was changed in both the workspace and Shared.`,
225
+ ),
226
+ // Story 377: a component that would not work with Shared's, saying where.
227
+ ...planned.problems.map((p) => `A component would break: ${p}`),
228
+ ],
229
+ // Story 382: what loses data, removes or renames, each accepted by name or kind.
230
+ findings: planned.items
231
+ .filter((i) => i.accept)
232
+ .map((i) => ({
233
+ id: i.id,
234
+ kind: i.kind,
235
+ says: `${i.says}${i.pages ? ` ${i.pages} page(s) hold a value for it.` : ''} Accept "${i.id}" or "${i.kind}" to go ahead.`,
236
+ })),
237
+ ready: planned,
238
+ }
239
+ },
240
+ apply: (tx, ready) => workspaceSchema.apply(tx, ready as FileMergePlan),
241
+ }
242
+ const merge: WorkspaceMerging = {
243
+ preview: (workspace) => previewWorkspaceMerge(db, repository, workspace),
244
+ async run(chosen, principal, run) {
245
+ const list: readonly Workspace[] = Array.isArray(chosen) ? chosen : [chosen as Workspace]
246
+ const names = list.map((w) => `"${w.name}"`).join(', ')
247
+ const outcome = await runWorkspaceMerge(list, {
248
+ db,
249
+ repository,
250
+ events: options.contentEvents ?? SILENT,
251
+ actor: userActor(principal, {
252
+ via: `a merge of ${list.length > 1 ? 'the workspaces' : 'the workspace'} ${names}`,
253
+ }),
254
+ userId: run.userId,
255
+ userKey: principal.id,
256
+ accepted: run.accepted,
257
+ rehearse: run.rehearse,
258
+ ...(run.only === undefined ? {} : { only: run.only }),
259
+ ...(run.changeKey ? { changeKey: run.changeKey } : {}),
260
+ ...(run.appliedChanges ? { appliedChanges: run.appliedChanges } : {}),
261
+ ...(files ? { files } : {}),
262
+ publishRefusal: (key, action) => gate.publishRefusal(principal, key, action),
263
+ })
264
+ if (!outcome.ok || outcome.rehearsed) return outcome
265
+ cache?.invalidate()
266
+ // A page a workflow covers arrives as a draft, and its publish waits for approval.
267
+ for (const page of outcome.forApproval)
268
+ await approvals.send(
269
+ principal,
270
+ page.key,
271
+ page.action,
272
+ page.cultures,
273
+ `Merged from ${list.length > 1 ? 'the workspaces' : 'the workspace'} ${names}`,
274
+ )
275
+ return outcome
276
+ },
277
+ }
278
+ return {
279
+ valueIntake: repository.valueIntake,
280
+ tracker,
281
+ approvals,
282
+ merge,
283
+ documents,
284
+ documentsIn,
285
+ mediaIn,
286
+ elementsIn,
287
+ media,
288
+ elements,
289
+ }
142
290
  }