@crombolo/server 0.69.0 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/package.json +15 -14
  2. package/src/adapters/blueprints.ts +51 -5
  3. package/src/adapters/change-recording.ts +140 -0
  4. package/src/adapters/content.ts +132 -21
  5. package/src/adapters/documents.ts +26 -5
  6. package/src/adapters/elements.ts +3 -0
  7. package/src/adapters/media.ts +7 -1
  8. package/src/adapters/schema-files.ts +89 -1
  9. package/src/adapters/workspace-dictionary.ts +287 -0
  10. package/src/adapters/workspace-file-port.ts +160 -0
  11. package/src/adapters/workspace-languages.ts +94 -0
  12. package/src/approvals-api.ts +16 -7
  13. package/src/bundle-api.ts +19 -16
  14. package/src/bundle-install.ts +4 -0
  15. package/src/change-transfer.ts +676 -0
  16. package/src/changes-api.ts +258 -0
  17. package/src/component-templates-api.ts +2 -2
  18. package/src/config.ts +162 -22
  19. package/src/content-events.ts +65 -1
  20. package/src/content-operations.ts +22 -3
  21. package/src/core.ts +2 -0
  22. package/src/environment-values-api.ts +161 -0
  23. package/src/host-token.ts +30 -1
  24. package/src/node-operations.ts +150 -2
  25. package/src/ports.ts +174 -52
  26. package/src/remote-changes.ts +279 -0
  27. package/src/remote-schema.ts +126 -0
  28. package/src/remote-workspaces.ts +82 -0
  29. package/src/remote.ts +289 -192
  30. package/src/schema-transfer.ts +240 -41
  31. package/src/schema.ts +7 -2
  32. package/src/seed/compile.ts +13 -1
  33. package/src/seed/values.ts +3 -0
  34. package/src/server.ts +971 -364
  35. package/src/settings.ts +123 -5
  36. package/src/site-sections.ts +1 -1
  37. package/src/workspace-access.ts +152 -0
  38. package/src/workspace-checks.ts +299 -0
  39. package/src/workspace-losses.ts +95 -0
  40. package/src/workspace-processes.ts +306 -0
  41. package/src/workspace-render-child.ts +168 -0
  42. package/src/workspace-schema-dir.ts +100 -0
  43. package/src/workspace-schema.ts +598 -0
  44. package/src/workspace-sites.ts +179 -0
  45. package/src/workspace-views.ts +121 -0
  46. package/src/workspaces.ts +1031 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.69.0",
3
+ "version": "0.70.0",
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",
@@ -32,19 +32,19 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@crombolo/api-delivery": "0.69.0",
36
- "@crombolo/api-management": "0.69.0",
37
- "@crombolo/auth": "0.69.0",
38
- "@crombolo/backoffice-host": "0.69.0",
39
- "@crombolo/common": "0.69.0",
40
- "@crombolo/content": "0.69.0",
41
- "@crombolo/contracts": "0.69.0",
42
- "@crombolo/core": "0.69.0",
43
- "@crombolo/data": "0.69.0",
44
- "@crombolo/extension": "0.69.0",
45
- "@crombolo/render": "0.69.0",
46
- "@crombolo/schema": "0.69.0",
47
- "@crombolo/transfer": "0.69.0",
35
+ "@crombolo/api-delivery": "0.70.0",
36
+ "@crombolo/api-management": "0.70.0",
37
+ "@crombolo/auth": "0.70.0",
38
+ "@crombolo/backoffice-host": "0.70.0",
39
+ "@crombolo/common": "0.70.0",
40
+ "@crombolo/content": "0.70.0",
41
+ "@crombolo/contracts": "0.70.0",
42
+ "@crombolo/core": "0.70.0",
43
+ "@crombolo/data": "0.70.0",
44
+ "@crombolo/extension": "0.70.0",
45
+ "@crombolo/render": "0.70.0",
46
+ "@crombolo/schema": "0.70.0",
47
+ "@crombolo/transfer": "0.70.0",
48
48
  "@logtape/logtape": "^2.3.8",
49
49
  "@opentelemetry/api": "1.10.0",
50
50
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -67,6 +67,7 @@
67
67
  "deno": "2.9.6",
68
68
  "jose": "^6.2.12",
69
69
  "kysely": "0.29.6",
70
+ "node-diff3": "3.1.2",
70
71
  "sigstore": "^3.1.0"
71
72
  }
72
73
  }
@@ -6,26 +6,47 @@
6
6
  import type { BlueprintPort, Principal } from '@crombolo/api-management/domain'
7
7
  import { ObjectTypes, type TreeItem } from '@crombolo/core'
8
8
  import {
9
+ ChangeRepository,
9
10
  type Db,
10
11
  DocumentRepository,
11
12
  FolderRepository,
12
13
  LanguageRepository,
13
14
  type NodeSchemaState,
14
15
  type ValueIntake,
16
+ WorkspaceRepository,
15
17
  WriteRejectedError,
16
18
  } from '@crombolo/data'
17
19
  import { createFolderPort, createSettingsTree } from './content.ts'
18
20
 
19
21
  export function createBlueprintPort(
20
22
  db: Db,
21
- options: { nodeState?: NodeSchemaState; valueIntake?: ValueIntake } = {},
23
+ options: {
24
+ nodeState?: NodeSchemaState
25
+ valueIntake?: ValueIntake
26
+ /** A workspace's blueprints (story 392). */
27
+ workspace?: number
28
+ } = {},
22
29
  ): BlueprintPort {
23
30
  const repo = new DocumentRepository(db, {
24
31
  nodeState: options.nodeState,
25
32
  kind: 'blueprint',
26
33
  valueIntake: options.valueIntake,
34
+ workspace: options.workspace,
27
35
  })
28
- const documents = new DocumentRepository(db, { nodeState: options.nodeState })
36
+ const documents = new DocumentRepository(db, {
37
+ nodeState: options.nodeState,
38
+ workspace: options.workspace,
39
+ })
40
+ const workspace = options.workspace
41
+ const inWorkspace =
42
+ workspace === undefined
43
+ ? undefined
44
+ : async () => ({
45
+ id: workspace,
46
+ hidden: (await new WorkspaceRepository(db).pending(workspace))
47
+ .filter((p) => p.kind === 'delete' && p.key !== null)
48
+ .map((p) => p.key as string),
49
+ })
29
50
  const container = ObjectTypes.DocumentBlueprintContainer
30
51
  const folders = new FolderRepository(db, container, ObjectTypes.DocumentBlueprint)
31
52
 
@@ -33,8 +54,17 @@ export function createBlueprintPort(
33
54
  const blueprint = await repo.byKey(item.key)
34
55
  item.icon = blueprint?.contentTypeIcon ?? 'icon-blueprint'
35
56
  item.contentTypeKey = blueprint?.contentTypeKey ?? null
57
+ // In a workspace, the name it has there (story 392); the node's is Shared's.
58
+ if (workspace !== undefined && blueprint?.variants[0]?.name)
59
+ item.name = blueprint.variants[0].name
36
60
  }
37
- const tree = createSettingsTree(repo.nodes, container, ObjectTypes.DocumentBlueprint, decorate)
61
+ const tree = createSettingsTree(
62
+ repo.nodes,
63
+ container,
64
+ ObjectTypes.DocumentBlueprint,
65
+ decorate,
66
+ inWorkspace,
67
+ )
38
68
 
39
69
  const userIdOf = async (principal: Principal): Promise<number | undefined> => {
40
70
  const rows = await db.q
@@ -46,6 +76,11 @@ export function createBlueprintPort(
46
76
  }
47
77
  const defaultCulture = async (): Promise<string | undefined> =>
48
78
  (await new LanguageRepository(db).all()).find((l) => l.isDefault)?.isoCode
79
+ /** A save in Shared, recorded in its maker's change as a page's is (story 392). */
80
+ const recorded = async (principal: Principal, key: string | undefined) => {
81
+ if (workspace !== undefined || !key) return
82
+ await new ChangeRepository(db).pageSavedBy(principal.id, { key, kind: 'blueprint' })
83
+ }
49
84
  const failure = (error: unknown) => {
50
85
  if (error instanceof WriteRejectedError)
51
86
  return { ok: false as const, reason: error.message, status: 409 }
@@ -61,7 +96,12 @@ export function createBlueprintPort(
61
96
 
62
97
  async create(input, principal) {
63
98
  try {
64
- await repo.create({ ...input, componentKey: null, userId: await userIdOf(principal) })
99
+ const created = await repo.create({
100
+ ...input,
101
+ componentKey: null,
102
+ userId: await userIdOf(principal),
103
+ })
104
+ await recorded(principal, created.key)
65
105
  return { ok: true as const }
66
106
  } catch (error) {
67
107
  return failure(error)
@@ -78,6 +118,7 @@ export function createBlueprintPort(
78
118
  })
79
119
  if (!updated)
80
120
  return { ok: false as const, reason: 'The blueprint could not be found.', status: 404 }
121
+ await recorded(principal, key)
81
122
  return { ok: true as const }
82
123
  } catch (error) {
83
124
  return failure(error)
@@ -113,13 +154,18 @@ export function createBlueprintPort(
113
154
  variants,
114
155
  userId: await userIdOf(principal),
115
156
  })
157
+ await recorded(principal, created.key)
116
158
  return { ok: true as const, key: created.key }
117
159
  } catch (error) {
118
160
  return failure(error)
119
161
  }
120
162
  },
121
163
 
122
- remove: (key) => repo.delete(key),
164
+ async remove(key, principal) {
165
+ const removed = await repo.delete(key)
166
+ if (removed && principal) await recorded(principal, key)
167
+ return removed
168
+ },
123
169
 
124
170
  async move(key, targetKey) {
125
171
  const result = await repo.move(key, targetKey)
@@ -0,0 +1,140 @@
1
+ /**
2
+ * A direct edit of the site's definitions or files, recorded as a change by its
3
+ * author (story 381). A type or data type is recorded as its file, exported as
4
+ * the schema writes it, before and after the save; a component, stylesheet or
5
+ * script as its text. A person's edits gather in one change until ten minutes
6
+ * pass with none.
7
+ */
8
+ import type { FileResult, FileSystemPort } from '@crombolo/api-management/domain'
9
+ import { type ChangeClass, costlier } from '@crombolo/core'
10
+ import { ChangeRepository, type Db } from '@crombolo/data'
11
+ import {
12
+ describeFileChange,
13
+ exportSchemaSet,
14
+ fileNameFor,
15
+ type SchemaTypeKind,
16
+ TYPE_KIND_FILES,
17
+ writeContentType,
18
+ writeDataType,
19
+ } from '@crombolo/schema'
20
+
21
+ /** The class a file's change costs, by its items. */
22
+ const classOf = (path: string, before: string | null, after: string | null, definition: boolean) =>
23
+ describeFileChange(path, before, after, { definition }).reduce<ChangeClass>(
24
+ (worst, i) => costlier(worst, i.class),
25
+ 'none',
26
+ )
27
+
28
+ /** Records one file's direct edit, when someone made it and it changed. */
29
+ export async function recordEdit(
30
+ db: Db,
31
+ by: string | undefined,
32
+ path: string,
33
+ before: string | null,
34
+ after: string | null,
35
+ ): Promise<void> {
36
+ if (!by || before === after) return
37
+ const definition = path.startsWith('schema/')
38
+ await new ChangeRepository(db).recordEdit(by, {
39
+ path,
40
+ kind: before === null ? 'file-added' : after === null ? 'file-removed' : 'file-changed',
41
+ class: classOf(definition ? path.slice('schema/'.length) : path, before, after, definition),
42
+ before,
43
+ after,
44
+ })
45
+ }
46
+
47
+ /** A type's file as the schema writes it, from the database: its text, or null when there is none. */
48
+ export async function typeFile(
49
+ db: Db,
50
+ kind: SchemaTypeKind,
51
+ key: string,
52
+ ): Promise<{ path: string; text: string } | undefined> {
53
+ const set = await exportSchemaSet(db, '1.0.0')
54
+ const list =
55
+ kind === 'document'
56
+ ? set.contentTypes
57
+ : kind === 'media'
58
+ ? (set.mediaTypes ?? [])
59
+ : (set.memberTypes ?? [])
60
+ const type = list.find((t) => t.key?.toLowerCase() === key.toLowerCase())
61
+ return type
62
+ ? {
63
+ path: `schema/${TYPE_KIND_FILES[kind].dir}/${fileNameFor(type.alias)}`,
64
+ text: writeContentType(type, kind),
65
+ }
66
+ : undefined
67
+ }
68
+
69
+ /** A data type's file, likewise. */
70
+ export async function dataTypeFile(
71
+ db: Db,
72
+ key: string,
73
+ ): Promise<{ path: string; text: string } | undefined> {
74
+ const found = (await exportSchemaSet(db, '1.0.0')).dataTypes.find(
75
+ (d) => d.key?.toLowerCase() === key.toLowerCase(),
76
+ )
77
+ return found
78
+ ? { path: `schema/data-types/${fileNameFor(found.alias)}`, text: writeDataType(found) }
79
+ : undefined
80
+ }
81
+
82
+ /** A file area's port, each direct write recorded as its author's change. */
83
+ export function recordingFilePort(db: Db, prefix: string, port: FileSystemPort): FileSystemPort {
84
+ const textOf = async (path: string) => (await port.read(path))?.content ?? null
85
+ const keyOf = (path: string) => `${prefix}${path.replace(/^\/+/, '')}`
86
+ const recorded = async (
87
+ by: string | undefined,
88
+ path: string,
89
+ before: string | null,
90
+ run: () => Promise<FileResult>,
91
+ after: (result: FileResult & { ok: true }) => Promise<[string, string | null][]>,
92
+ ) => {
93
+ const result = await run()
94
+ if (!result.ok || !by) return result
95
+ for (const [at, text] of await after(result))
96
+ await recordEdit(db, by, keyOf(at), at === path ? before : null, text)
97
+ return result
98
+ }
99
+ return {
100
+ ...port,
101
+ async create(parentPath, name, content, by) {
102
+ return recorded(
103
+ by,
104
+ '',
105
+ null,
106
+ () => port.create(parentPath, name, content, by),
107
+ async (r) => [[r.path, await textOf(r.path)]],
108
+ )
109
+ },
110
+ async update(path, content, by) {
111
+ const before = by ? await textOf(path) : null
112
+ return recorded(
113
+ by,
114
+ path,
115
+ before,
116
+ () => port.update(path, content, by),
117
+ async (r) => [[r.path, await textOf(r.path)]],
118
+ )
119
+ },
120
+ async rename(path, name, by) {
121
+ const before = by ? await textOf(path) : null
122
+ const result = await port.rename(path, name, by)
123
+ if (result.ok && by && result.path !== path) {
124
+ await recordEdit(db, by, keyOf(path), before, null)
125
+ await recordEdit(db, by, keyOf(result.path), null, await textOf(result.path))
126
+ }
127
+ return result
128
+ },
129
+ async delete(path, by) {
130
+ const before = by ? await textOf(path) : null
131
+ return recorded(
132
+ by,
133
+ path,
134
+ before,
135
+ () => port.delete(path, by),
136
+ async () => [[path, null]],
137
+ )
138
+ },
139
+ }
140
+ }
@@ -38,12 +38,21 @@ import {
38
38
  Locks,
39
39
  type NodeRepository,
40
40
  type NodeRow,
41
+ WorkspaceFileRepository,
42
+ type WorkspaceScope,
41
43
  } from '@crombolo/data'
42
- import { aliasFromName } from '@crombolo/schema'
44
+ import { aliasFromName, fileNameFor, TYPE_KIND_FILES } from '@crombolo/schema'
43
45
  import { readContentTypeUdt, writeContentTypeUdt } from '../content-type-udt.ts'
44
46
  import { classifyTypeChange } from '../schema-classify.ts'
45
47
  import { contentTypeJsonSchema, schemaForStorage, valueTypeName } from '../value-schemas.ts'
46
- import { createSchemaFileWriter, type SchemaFiles, schemaProblems } from './schema-files.ts'
48
+ import { dataTypeFile, recordEdit, typeFile } from './change-recording.ts'
49
+ import {
50
+ createSchemaFileWriter,
51
+ createWorkspaceSchemaFileWriter,
52
+ type SchemaFiles,
53
+ schemaProblems,
54
+ workspaceSchemaProblems,
55
+ } from './schema-files.ts'
47
56
 
48
57
  async function toTreeItems(
49
58
  nodes: NodeRepository,
@@ -80,6 +89,8 @@ export function createSettingsTree(
80
89
  containerType: string,
81
90
  itemType: string,
82
91
  decorate: (item: TreeItem) => Promise<void>,
92
+ /** Story 392: a workspace's items too, without those it deleted. */
93
+ workspace?: () => Promise<{ id: number; hidden: readonly string[] } | undefined>,
83
94
  ) {
84
95
  const types = (foldersOnly: boolean | undefined) =>
85
96
  foldersOnly ? [containerType] : [containerType, itemType]
@@ -88,7 +99,13 @@ export function createSettingsTree(
88
99
  const items: TreeItem[] = []
89
100
  for (const row of rows) {
90
101
  const parent = row.parentId > 0 ? await nodes.byId(row.parentId) : undefined
91
- const inside = await nodes.childrenOf(row.id, [containerType, itemType], 0, 1)
102
+ const inside = await nodes.childrenOf(
103
+ row.id,
104
+ [containerType, itemType],
105
+ 0,
106
+ 1,
107
+ await workspace?.(),
108
+ )
92
109
  const item: TreeItem = {
93
110
  key: row.key,
94
111
  name: row.text ?? '',
@@ -111,6 +128,7 @@ export function createSettingsTree(
111
128
  types(paging.foldersOnly),
112
129
  paging.skip,
113
130
  paging.take,
131
+ await workspace?.(),
114
132
  )
115
133
  return { total: result.total, items: await shape(result.items) }
116
134
  }
@@ -166,13 +184,16 @@ export async function savedIfValid<T>(
166
184
  db: Db,
167
185
  files: SchemaFiles | undefined,
168
186
  work: (tx: Db) => Promise<T>,
187
+ /** What is wrong as `db` sees it, when not the site's files: a workspace's own (story 376). */
188
+ problemsOf?: (db: Db) => Promise<string[]>,
169
189
  ): 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))
190
+ const problems = problemsOf ?? (files ? (handle: Db) => schemaProblems(handle, files) : undefined)
191
+ if (!problems) return { ok: true, value: await work(db) }
192
+ const before = new Set(await problems(db))
172
193
  try {
173
194
  const value = await db.transaction(async (tx) => {
174
195
  const value = await work(tx)
175
- const added = (await schemaProblems(tx, files)).filter((p) => !before.has(p))
196
+ const added = (await problems(tx)).filter((p) => !before.has(p))
176
197
  if (added.length > 0) throw new InvalidSchemaSave(added)
177
198
  return value
178
199
  })
@@ -236,6 +257,8 @@ export interface ContentTypePortOptions extends ContentTypeRepositoryOptions {
236
257
  kind?: ContentTypeKind
237
258
  /** Lets "Create template" write the view file. */
238
259
  componentFiles?: ComponentFileStore
260
+ /** Called before a type is written in a workspace: its own types are built first (story 376). */
261
+ beforeWrite?: () => Promise<void>
239
262
  }
240
263
 
241
264
  /** Whether a tree item is the folder holding the types made from forms, and nothing else. */
@@ -257,15 +280,31 @@ export function createContentTypePort(
257
280
  options: ContentTypePortOptions = {},
258
281
  ): ContentTypePort {
259
282
  const kind = options.kind ?? 'document'
260
- const repo = new ContentTypeRepository(db, { nodeState: options.nodeState, kind })
283
+ const workspace = options.workspace
284
+ const scope = workspace ? { workspace } : {}
285
+ const repo = new ContentTypeRepository(db, { nodeState: options.nodeState, kind, ...scope })
261
286
  /** The same repository over a transaction's handle, for a checked save. */
262
287
  const repoOn = (handle: Db) =>
263
- new ContentTypeRepository(handle, { nodeState: options.nodeState, kind })
288
+ new ContentTypeRepository(handle, { nodeState: options.nodeState, kind, ...scope })
264
289
  const nodes = repo.nodes
265
290
  const objectType = repo.objectType
266
291
  const containerType = CONTENT_TYPE_OBJECT_TYPES[kind].container
267
292
  const folders = new FolderRepository(db, containerType, objectType)
268
- const files = schemaFiles ? createSchemaFileWriter(db, schemaFiles, kind) : undefined
293
+ const files = schemaFiles
294
+ ? workspace
295
+ ? createWorkspaceSchemaFileWriter(db, schemaFiles, kind, workspace)
296
+ : createSchemaFileWriter(db, schemaFiles, kind)
297
+ : undefined
298
+ /** A save kept only if it leaves the definitions no worse: the site's, or the workspace's. */
299
+ const checked = <T>(work: (tx: Db) => Promise<T>) =>
300
+ savedIfValid(
301
+ db,
302
+ schemaFiles,
303
+ work,
304
+ workspace && schemaFiles
305
+ ? (handle) => workspaceSchemaProblems(handle, schemaFiles, workspace)
306
+ : undefined,
307
+ )
269
308
  const templates = new ComponentRepository(db, options.componentFiles)
270
309
  const rewrite = () => files?.rewriteAll() ?? Promise.resolve()
271
310
 
@@ -293,13 +332,18 @@ export function createContentTypePort(
293
332
  }
294
333
  const refused = files?.refuse(aggregate)
295
334
  if (refused) return refused
296
- const saved = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(aggregate))
335
+ await options.beforeWrite?.()
336
+ const saved = await checked((tx) => repoOn(tx).save(aggregate))
297
337
  if (!saved.ok) return saved
298
338
  // A new type can only be additive, and the version moves before the file is
299
339
  // written so the file that lands carries the version it belongs to.
300
340
  await files?.bumpVersion('additive')
301
341
  await files?.write(aggregate)
302
- void principal
342
+ // Story 381: a direct edit of Shared is a change, by its author.
343
+ if (!workspace) {
344
+ const after = await typeFile(db, kind, aggregate.key)
345
+ if (after) await recordEdit(db, principal.id, after.path, null, after.text)
346
+ }
303
347
  return { ok: true as const }
304
348
  },
305
349
 
@@ -309,12 +353,14 @@ export function createContentTypePort(
309
353
  }
310
354
  const refused = files?.refuse(aggregate)
311
355
  if (refused) return refused
356
+ await options.beforeWrite?.()
312
357
  const before = await repo.byKey(key)
358
+ const fileBefore = workspace ? undefined : await typeFile(db, kind, key)
313
359
  // Classified here, while the database still holds the old type: once it is
314
360
  // saved there is nothing left to compare it with.
315
361
  const change = files ? await classifyTypeChange(db, before, { ...aggregate, key }) : 'none'
316
362
  // The editor does not send tree placement; keep what the type has.
317
- const saved = await savedIfValid(db, schemaFiles, (tx) =>
363
+ const saved = await checked((tx) =>
318
364
  repoOn(tx).save({
319
365
  ...aggregate,
320
366
  key,
@@ -324,14 +370,35 @@ export function createContentTypePort(
324
370
  if (!saved.ok) return saved
325
371
  await files?.bumpVersion(change)
326
372
  await files?.write({ ...aggregate, key }, before?.alias)
327
- void principal
373
+ if (!workspace) {
374
+ const after = await typeFile(db, kind, key)
375
+ // A rename moves the file: the old one goes, the new one comes.
376
+ if (fileBefore && after && fileBefore.path !== after.path) {
377
+ await recordEdit(db, principal.id, fileBefore.path, fileBefore.text, null)
378
+ await recordEdit(db, principal.id, after.path, null, after.text)
379
+ } else if (after)
380
+ await recordEdit(db, principal.id, after.path, fileBefore?.text ?? null, after.text)
381
+ }
328
382
  return { ok: true as const }
329
383
  },
330
384
 
331
- async remove(key) {
385
+ async remove(key, how = {}) {
386
+ await options.beforeWrite?.()
332
387
  const before = await repo.byKey(key)
388
+ if (
389
+ !workspace &&
390
+ before &&
391
+ !how.force &&
392
+ (await new WorkspaceFileRepository(db).changedInOpenWorkspace(
393
+ `schema/${TYPE_KIND_FILES[kind].dir}/${fileNameFor(before.alias)}`,
394
+ ))
395
+ )
396
+ return 'in-workspace' as const
397
+ const fileBefore = workspace ? undefined : await typeFile(db, kind, key)
333
398
  const removed = await repo.delete(key)
334
399
  if (removed && before) await files?.remove(before.alias)
400
+ if (removed && fileBefore)
401
+ await recordEdit(db, how.by, fileBefore.path, fileBefore.text, null)
335
402
  return removed
336
403
  },
337
404
 
@@ -613,12 +680,22 @@ export function createContentTypePort(
613
680
  )
614
681
  }
615
682
 
616
- export function createDataTypePort(db: Db, schemaFiles?: SchemaFiles): DataTypePort {
617
- const repo = new DataTypeRepository(db)
683
+ export function createDataTypePort(
684
+ db: Db,
685
+ schemaFiles?: SchemaFiles,
686
+ /** A workspace's data types (story 376), built before its first write. */
687
+ options: { workspace?: WorkspaceScope; beforeWrite?: () => Promise<void> } = {},
688
+ ): DataTypePort {
689
+ const workspace = options.workspace
690
+ const repo = new DataTypeRepository(db, workspace ? { workspace } : {})
618
691
  const nodes = repo.nodes
619
692
  const objectType = ObjectTypes.DataType
620
693
  const folders = new FolderRepository(db, ObjectTypes.DataTypeContainer, objectType)
621
- const files = schemaFiles ? createSchemaFileWriter(db, schemaFiles) : undefined
694
+ const files = schemaFiles
695
+ ? workspace
696
+ ? createWorkspaceSchemaFileWriter(db, schemaFiles, 'document', workspace)
697
+ : createSchemaFileWriter(db, schemaFiles)
698
+ : undefined
622
699
  const rewrite = () => files?.rewriteAll() ?? Promise.resolve()
623
700
  const tree = createSettingsTree(
624
701
  nodes,
@@ -657,21 +734,55 @@ export function createDataTypePort(db: Db, schemaFiles?: SchemaFiles): DataTypeP
657
734
  jsonSchema: schemaForStorage(model.dbType),
658
735
  }
659
736
  },
660
- async save(model: DataTypeModel) {
737
+ async save(model: DataTypeModel, principal: Principal) {
738
+ const fileBefore = workspace ? undefined : await dataTypeFile(db, model.key)
739
+ if (workspace && schemaFiles) {
740
+ const refused = files?.refuse({ alias: model.alias ?? model.name })
741
+ if (refused) return refused
742
+ }
743
+ await options.beforeWrite?.()
661
744
  const aliased = await withAlias(model)
662
- const saved = await savedIfValid(db, schemaFiles, (tx) =>
663
- new DataTypeRepository(tx).save(aliased),
745
+ const saved = await savedIfValid(
746
+ db,
747
+ schemaFiles,
748
+ (tx) => new DataTypeRepository(tx, workspace ? { workspace } : {}).save(aliased),
749
+ workspace && schemaFiles
750
+ ? (handle) => workspaceSchemaProblems(handle, schemaFiles, workspace)
751
+ : undefined,
664
752
  )
665
753
  if (!saved.ok) return saved
666
754
  await files?.writeDataType(saved.value)
755
+ if (!workspace) {
756
+ const after = await dataTypeFile(db, saved.value.key)
757
+ await recordEdit(
758
+ db,
759
+ principal?.id,
760
+ after?.path ?? fileBefore?.path ?? '',
761
+ fileBefore?.text ?? null,
762
+ after?.text ?? null,
763
+ )
764
+ }
667
765
  return undefined
668
766
  },
669
- async remove(key) {
767
+ async remove(key, how = {}) {
768
+ await options.beforeWrite?.()
670
769
  const before = await repo.byKey(key)
671
770
  if (!before) return false
672
771
  if ((await repo.referencedBy(key)).length > 0) return 'in-use'
772
+ if (
773
+ !workspace &&
774
+ before.alias &&
775
+ !how.force &&
776
+ (await new WorkspaceFileRepository(db).changedInOpenWorkspace(
777
+ `schema/data-types/${fileNameFor(before.alias)}`,
778
+ ))
779
+ )
780
+ return 'in-workspace' as const
781
+ const fileBefore = workspace ? undefined : await dataTypeFile(db, key)
673
782
  const removed = await repo.delete(key)
674
783
  if (removed && before.alias) await files?.removeDataType(before.alias)
784
+ if (removed && fileBefore)
785
+ await recordEdit(db, how.by, fileBefore.path, fileBefore.text, null)
675
786
  return removed
676
787
  },
677
788
  filter: (criteria, paging) => repo.filter(criteria, paging),
@@ -8,6 +8,7 @@ import type {
8
8
  SkipTake,
9
9
  } from '@crombolo/api-management/domain'
10
10
  import {
11
+ forEnvironment,
11
12
  normaliseUuid,
12
13
  ObjectTypes,
13
14
  type Page,
@@ -51,6 +52,8 @@ import {
51
52
  } from '../domains.ts'
52
53
  import { TemporaryFileMissingError } from '../file-intake.ts'
53
54
  import { NO_REDIRECT_TRACKING, type RedirectTracker } from '../redirects.ts'
55
+ import { workspaceDictionary } from './workspace-dictionary.ts'
56
+ import { workspaceLanguages } from './workspace-languages.ts'
54
57
 
55
58
  async function toTreeItems(
56
59
  repo: DocumentRepository,
@@ -574,7 +577,7 @@ export function createPublishedContentSource(
574
577
  updateDate: row.updateDate,
575
578
  cultures: row.cultures,
576
579
  names: row.names,
577
- properties: row.values.map((value) => ({
580
+ properties: forEnvironment(row.values, options.environment).map((value) => ({
578
581
  alias: value.alias,
579
582
  editorAlias: value.editorAlias ?? '',
580
583
  culture: value.culture,
@@ -585,14 +588,32 @@ export function createPublishedContentSource(
585
588
  }))
586
589
  },
587
590
  async loadLanguages() {
591
+ // Story 392: a workspace's site has the languages it holds.
592
+ const own =
593
+ options.workspace !== undefined
594
+ ? await workspaceLanguages(db, options.workspace)
595
+ : undefined
596
+ if (own)
597
+ return own.map((l) => ({
598
+ isoCode: l.isoCode,
599
+ isDefault: l.isDefault,
600
+ fallbackIsoCode: l.fallbackIsoCode,
601
+ }))
588
602
  return (await new LanguageRepository(db).all()).map((l) => ({
589
603
  isoCode: l.isoCode,
590
604
  isDefault: l.isDefault,
591
605
  fallbackIsoCode: l.fallbackIsoCode,
592
606
  }))
593
607
  },
594
- loadDictionary: () => new DictionaryRepository(db).translations(),
595
- loadDictionaryOutline: () => new DictionaryRepository(db).outline(),
608
+ // Story 392: a workspace's site reads the dictionary it holds.
609
+ loadDictionary: async () =>
610
+ (options.workspace !== undefined
611
+ ? (await workspaceDictionary(db, options.workspace))?.translations
612
+ : undefined) ?? new DictionaryRepository(db).translations(),
613
+ loadDictionaryOutline: async () =>
614
+ (options.workspace !== undefined
615
+ ? (await workspaceDictionary(db, options.workspace))?.outline
616
+ : undefined) ?? new DictionaryRepository(db).outline(),
596
617
  async loadDomains() {
597
618
  return (await new DomainRepository(db).all()).map((row) => ({
598
619
  nodeId: row.nodeId,
@@ -625,7 +646,7 @@ export function createPublishedContentSource(
625
646
  cultures: row.cultures,
626
647
  name: row.name,
627
648
  names: row.names,
628
- properties: row.values.map((value) => ({
649
+ properties: forEnvironment(row.values, options.environment).map((value) => ({
629
650
  alias: value.alias,
630
651
  editorAlias: value.editorAlias ?? '',
631
652
  culture: value.culture,
@@ -747,7 +768,7 @@ export async function loadDraftNode(
747
768
  names: Object.fromEntries(
748
769
  draft.variants.flatMap((v) => (v.culture ? [[v.culture, v.name]] : [])),
749
770
  ),
750
- properties: draft.values.map((value) => ({
771
+ properties: forEnvironment(draft.values, options.environment).map((value) => ({
751
772
  alias: value.alias,
752
773
  editorAlias: value.editorAlias ?? '',
753
774
  culture: value.culture,
@@ -77,6 +77,8 @@ export function createElementPort(
77
77
  valueIntake?: ValueIntake
78
78
  /** Told after every change, so pages that resolved an element refresh. */
79
79
  onChange?: () => void | Promise<void>
80
+ /** A workspace's Library (story 390): its changes are announced nowhere else. */
81
+ workspace?: number
80
82
  } = {},
81
83
  ): ElementPort {
82
84
  const repo = new DocumentRepository(db, { ...options, kind: 'element' })
@@ -84,6 +86,7 @@ export function createElementPort(
84
86
  const folders = new FolderRepository(db, ObjectTypes.ElementContainer, ObjectTypes.Element)
85
87
 
86
88
  const changed = async () => {
89
+ if (options.workspace !== undefined) return
87
90
  await appendCacheInstruction(db, {
88
91
  kind: 'content',
89
92
  payload: { elements: true },