@crombolo/data 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.
@@ -81,6 +81,8 @@ export interface CurrentValue {
81
81
  alias: string
82
82
  culture: string | null
83
83
  segment: string | null
84
+ /** The environment it overrides the shared value for (story 387). */
85
+ environment?: string | null
84
86
  value: unknown
85
87
  }
86
88
 
@@ -88,6 +90,7 @@ export interface MigratedValue {
88
90
  alias: string
89
91
  culture: string | null
90
92
  segment: string | null
93
+ environment?: string | null
91
94
  value: unknown
92
95
  /** The event to file the value under; defaults to the row it supersedes. */
93
96
  eventId?: number
@@ -108,6 +111,8 @@ interface ValueRow {
108
111
  propertyTypeId: number
109
112
  languageId: number | null
110
113
  segment: string | null
114
+ /** The environment it overrides the shared value for, or null for the shared value (story 387). */
115
+ environment: string | null
111
116
  raw: unknown
112
117
  }
113
118
 
@@ -156,6 +161,8 @@ const KINDS: Record<
156
161
  recycleBin: number | undefined
157
162
  container: string | undefined
158
163
  lock: LockId
164
+ /** What an item of this kind made in a workspace is (stories 375, 390); none, never made in one. */
165
+ workspaceObjectType?: string
159
166
  }
160
167
  > = {
161
168
  document: {
@@ -163,12 +170,14 @@ const KINDS: Record<
163
170
  recycleBin: SystemNodes.ContentRecycleBin,
164
171
  container: undefined,
165
172
  lock: Locks.ContentTree,
173
+ workspaceObjectType: ObjectTypes.WorkspaceDocument,
166
174
  },
167
175
  media: {
168
176
  objectType: ObjectTypes.Media,
169
177
  recycleBin: SystemNodes.MediaRecycleBin,
170
178
  container: undefined,
171
179
  lock: Locks.MediaTree,
180
+ workspaceObjectType: ObjectTypes.WorkspaceMedia,
172
181
  },
173
182
  // Members are a flat list at the tree root: no bin to trash them into, and
174
183
  // no folders to gather them in.
@@ -183,6 +192,7 @@ const KINDS: Record<
183
192
  recycleBin: undefined,
184
193
  container: ObjectTypes.DocumentBlueprintContainer,
185
194
  lock: Locks.ContentTree,
195
+ workspaceObjectType: ObjectTypes.WorkspaceDocumentBlueprint,
186
196
  },
187
197
  // Umbraco 18's Elements: publishable content with no URL, gathered in folders
188
198
  // and trashed into a bin of its own at -22, as its Constants.System says.
@@ -191,6 +201,7 @@ const KINDS: Record<
191
201
  recycleBin: SystemNodes.ElementRecycleBin,
192
202
  container: ObjectTypes.ElementContainer,
193
203
  lock: Locks.ContentTree,
204
+ workspaceObjectType: ObjectTypes.WorkspaceElement,
194
205
  },
195
206
  }
196
207
 
@@ -204,6 +215,8 @@ export type ValueIntake = (
204
215
  ) => Promise<DocumentValue[]>
205
216
 
206
217
  export interface DocumentRepositoryOptions {
218
+ /** The environment whose own values rendering shows (story 387); the repository keeps every one. */
219
+ environment?: string
207
220
  /** The schema state this process runs at; writes are refused if the database is ahead. */
208
221
  nodeState?: NodeSchemaState
209
222
  /** Stamped on the cache instructions this repository appends. */
@@ -224,6 +237,8 @@ export interface DocumentRepositoryOptions {
224
237
  * transaction for the run, rather than one of each per node.
225
238
  */
226
239
  inTreeLock?: boolean
240
+ /** The workspace it reads and writes in (story 375); absent, Shared. */
241
+ workspace?: number
227
242
  }
228
243
 
229
244
  /** Thrown when a publish is refused by a business rule rather than failing. */
@@ -240,6 +255,66 @@ export class PublishBlockedError extends Error {
240
255
  /** The parent named for a new item is gone, or in the recycle bin. */
241
256
  export class InvalidParentError extends Error {}
242
257
 
258
+ /**
259
+ * One field of a page as a merge compares it (story 380): a value by
260
+ * `alias|culture|segment`, `@name` or `@name:<iso>`, or `@template` (a key).
261
+ * `undefined` is "not there".
262
+ */
263
+ export interface MergeField {
264
+ field: string
265
+ base: unknown
266
+ mine: unknown
267
+ theirs: unknown
268
+ /** Which value it is, when the field is a value. */
269
+ value?: {
270
+ alias: string
271
+ culture: string | null
272
+ segment: string | null
273
+ environment?: string | null
274
+ }
275
+ }
276
+
277
+ /** A page a workspace changed or made, as its merge reads it. */
278
+ export interface WorkspacePageMerge {
279
+ /** Pages, media or Library items (story 390). */
280
+ kind: ContentKind
281
+ key: string
282
+ nodeId: number
283
+ made: boolean
284
+ level: number
285
+ contentTypeKey: string
286
+ parentKey: string | null
287
+ /** Shared's latest event now, and the one the workspace began from. */
288
+ sharedHead: number | null
289
+ baseEvent: number | null
290
+ fields: MergeField[]
291
+ /**
292
+ * Published state for the page, and per language: as begun, in the workspace, in
293
+ * Shared now. `here` says the workspace published its own version, which a merge
294
+ * publishes; `sharedEdited` says Shared has changes it has not published.
295
+ */
296
+ published: {
297
+ base: boolean | null
298
+ mine: boolean
299
+ theirs: boolean
300
+ here: boolean
301
+ sharedEdited: boolean
302
+ }
303
+ cultures: Array<{ iso: string; base: boolean | null; mine: boolean; theirs: boolean }>
304
+ }
305
+
306
+ /** Something a workspace cannot hold yet (story 375), said in the editor's words. */
307
+ export class WorkspaceRefusedError extends Error {}
308
+
309
+ /** A page a workspace has touched: where it started from, and where it stands there. */
310
+ interface WorkspaceDocumentRow {
311
+ baseEventId: number | null
312
+ created: boolean
313
+ published: boolean
314
+ publishedEventId: number | null
315
+ edited: boolean
316
+ }
317
+
243
318
  /** The draft changed after the revision a write was based on (story 172). */
244
319
  export class StaleRevisionError extends Error {
245
320
  constructor(
@@ -299,8 +374,12 @@ function validateValues(
299
374
  return errors
300
375
  }
301
376
 
302
- const keyOf = (propertyTypeId: number, languageId: number | null, segment: string | null) =>
303
- `${propertyTypeId}|${languageId ?? ''}|${segment ?? ''}`
377
+ const keyOf = (
378
+ propertyTypeId: number,
379
+ languageId: number | null,
380
+ segment: string | null,
381
+ environment: string | null = null,
382
+ ) => `${propertyTypeId}|${languageId ?? ''}|${segment ?? ''}|${environment ?? ''}`
304
383
 
305
384
  /**
306
385
  * The value rows a published node shows, from its history in id order:
@@ -313,6 +392,7 @@ export function publishedValueRows<
313
392
  propertyTypeId: number
314
393
  languageId: number | null
315
394
  segment: string | null
395
+ environment?: string | null
316
396
  },
317
397
  >(
318
398
  history: readonly R[],
@@ -324,7 +404,7 @@ export function publishedValueRows<
324
404
  for (const row of history) {
325
405
  const limit = row.languageId === null ? invariantEventId : cutoff.get(row.languageId)
326
406
  if (limit === undefined || row.eventId > limit) continue
327
- chosen.set(keyOf(row.propertyTypeId, row.languageId, row.segment), row)
407
+ chosen.set(keyOf(row.propertyTypeId, row.languageId, row.segment, row.environment ?? null), row)
328
408
  }
329
409
  return [...chosen.values()]
330
410
  }
@@ -360,67 +440,1030 @@ const slices = <T>(items: readonly T[], size = 500): T[][] =>
360
440
  items.slice(n * size, (n + 1) * size),
361
441
  )
362
442
 
363
- export class DocumentRepository {
364
- #db: Db
365
- #nodes: NodeRepository
366
- #nodeState: NodeSchemaState
367
- #nodeId: string | undefined
368
- readonly kind: ContentKind
369
- readonly objectType: string
370
- #recycleBin: number | undefined
371
- #intake: ValueIntake | undefined
372
- #inTreeLock: boolean
443
+ export class DocumentRepository {
444
+ #db: Db
445
+ #nodes: NodeRepository
446
+ #nodeState: NodeSchemaState
447
+ #nodeId: string | undefined
448
+ readonly kind: ContentKind
449
+ readonly objectType: string
450
+ #recycleBin: number | undefined
451
+ #intake: ValueIntake | undefined
452
+ #inTreeLock: boolean
453
+ #workspace: number | undefined
454
+
455
+ constructor(db: Db, options: DocumentRepositoryOptions = {}) {
456
+ this.#db = db
457
+ this.#nodes = new NodeRepository(db)
458
+ this.#nodeState = options.nodeState ?? BASELINE_NODE_STATE
459
+ this.#nodeId = options.nodeId
460
+ this.kind = options.kind ?? 'document'
461
+ this.objectType = KINDS[this.kind].objectType
462
+ this.#recycleBin = KINDS[this.kind].recycleBin
463
+ this.#intake = options.valueIntake
464
+ this.#inTreeLock = options.inTreeLock ?? false
465
+ this.#workspace = options.workspace
466
+ }
467
+
468
+ /** The workspace it reads and writes in (story 375); undefined for Shared. */
469
+ get workspace(): number | undefined {
470
+ return this.#workspace
471
+ }
472
+
473
+ /** The same repository, in a workspace (undefined: Shared). */
474
+ inWorkspace(workspace: number | undefined): DocumentRepository {
475
+ return new DocumentRepository(this.#db, {
476
+ nodeState: this.#nodeState,
477
+ nodeId: this.#nodeId,
478
+ kind: this.kind,
479
+ valueIntake: this.#intake,
480
+ inTreeLock: this.#inTreeLock,
481
+ workspace,
482
+ })
483
+ }
484
+
485
+ get nodes(): NodeRepository {
486
+ return this.#nodes
487
+ }
488
+
489
+ /**
490
+ * The tree's lock, unless the caller already holds it. Every write goes
491
+ * through here, as every Umbraco content service write takes its tree's write
492
+ * lock: two saves, or a save and a move, never interleave. The node a write
493
+ * acts on is read inside, so it acts on where the node is now.
494
+ */
495
+ #withTree<T>(fn: () => Promise<T>): Promise<T> {
496
+ return this.#inTreeLock ? fn() : this.#db.locks.withLock(KINDS[this.kind].lock, fn)
497
+ }
498
+
499
+ /**
500
+ * Runs `fn` under the tree lock in one transaction, with a repository bound to
501
+ * it, so several writes commit together or not at all (story 170).
502
+ */
503
+ async atomically<T>(fn: (repo: DocumentRepository, tx: Db) => Promise<T>): Promise<T> {
504
+ return this.#withTree(() => this.#db.transaction((tx) => fn(this.#child(tx), tx)))
505
+ }
506
+
507
+ /** The same repository, on the same handle and inside the same lock, for another kind (story 390). */
508
+ ofKind(kind: ContentKind): DocumentRepository {
509
+ return new DocumentRepository(this.#db, {
510
+ nodeState: this.#nodeState,
511
+ nodeId: this.#nodeId,
512
+ kind,
513
+ valueIntake: this.#intake,
514
+ inTreeLock: this.#inTreeLock,
515
+ workspace: this.#workspace,
516
+ })
517
+ }
518
+
519
+ #child(tx: Db): DocumentRepository {
520
+ return new DocumentRepository(tx, {
521
+ nodeState: this.#nodeState,
522
+ nodeId: this.#nodeId,
523
+ kind: this.kind,
524
+ valueIntake: this.#intake,
525
+ // A child runs inside whatever its parent took.
526
+ inTreeLock: true,
527
+ workspace: this.#workspace,
528
+ })
529
+ }
530
+
531
+ // ---------------------------------------------------------------- workspaces (story 375)
532
+
533
+ /** Whether a node is one this repository may see: Shared's, or its workspace's own. */
534
+ sees(node: NodeRow): boolean {
535
+ if (node.objectType === this.objectType) return true
536
+ return (
537
+ this.#workspace !== undefined &&
538
+ node.objectType === KINDS[this.kind].workspaceObjectType &&
539
+ node.workspaceId === this.#workspace
540
+ )
541
+ }
542
+
543
+ async #workspaceDocument(nodeId: number): Promise<WorkspaceDocumentRow | undefined> {
544
+ if (this.#workspace === undefined) return undefined
545
+ const rows = await this.#db.q
546
+ .selectFrom('workspace_document')
547
+ .selectAll()
548
+ .where('workspace_id', '=', this.#workspace)
549
+ .where('node_id', '=', nodeId)
550
+ .execute()
551
+ const row = rows[0]
552
+ if (!row) return undefined
553
+ return {
554
+ baseEventId: row.base_event_id === null ? null : Number(row.base_event_id),
555
+ created: fromDbBool(row.created),
556
+ published: fromDbBool(row.published),
557
+ publishedEventId: row.published_event_id === null ? null : Number(row.published_event_id),
558
+ edited: fromDbBool(row.edited),
559
+ }
560
+ }
561
+
562
+ /**
563
+ * The workspace's row for a Shared page, made the first time it writes one:
564
+ * the event it starts from, and Shared's published state and languages as
565
+ * they stand, which it then keeps apart.
566
+ */
567
+ async #touch(node: NodeRow): Promise<WorkspaceDocumentRow> {
568
+ const workspace = this.#workspace as number
569
+ const existing = await this.#workspaceDocument(node.id)
570
+ if (existing) return existing
571
+ const head = await this.#headEvent(node.id)
572
+ const document = (
573
+ await this.#db.q
574
+ .selectFrom('document')
575
+ .select(['published', 'edited'])
576
+ .where('node_id', '=', node.id)
577
+ .execute()
578
+ )[0]
579
+ const row: WorkspaceDocumentRow = {
580
+ baseEventId: head?.id ?? null,
581
+ created: false,
582
+ published: fromDbBool(document?.published),
583
+ publishedEventId: (await this.#publishedEventId(node.id)) ?? null,
584
+ edited: fromDbBool(document?.edited),
585
+ }
586
+ await this.#db.q
587
+ .insertInto('workspace_document')
588
+ .values({
589
+ workspace_id: workspace,
590
+ node_id: node.id,
591
+ base_event_id: row.baseEventId,
592
+ created: this.#db.dialect.boolValue(false) as boolean,
593
+ published: this.#db.dialect.boolValue(row.published) as boolean,
594
+ published_event_id: row.publishedEventId,
595
+ edited: this.#db.dialect.boolValue(row.edited) as boolean,
596
+ // What Shared had published when the workspace began, for the merge (story 380).
597
+ base_published: this.#db.dialect.boolValue(row.published) as boolean,
598
+ })
599
+ .execute()
600
+ await this.#db.q
601
+ .insertInto('workspace_document_culture')
602
+ .columns([
603
+ 'workspace_id',
604
+ 'node_id',
605
+ 'language_id',
606
+ 'name',
607
+ 'available',
608
+ 'published',
609
+ 'edited',
610
+ 'published_event_id',
611
+ 'published_name',
612
+ 'base_published',
613
+ 'base_published_event_id',
614
+ ])
615
+ .expression((eb) =>
616
+ eb
617
+ .selectFrom('document_culture_variation')
618
+ .select([
619
+ eb.val(workspace).as('workspace_id'),
620
+ 'node_id',
621
+ 'language_id',
622
+ 'name',
623
+ 'available',
624
+ 'published',
625
+ 'edited',
626
+ 'published_event_id',
627
+ 'published_name',
628
+ 'published as base_published',
629
+ 'published_event_id as base_published_event_id',
630
+ ])
631
+ .where('node_id', '=', node.id),
632
+ )
633
+ .execute()
634
+ return row
635
+ }
636
+
637
+ async #setWorkspaceDocument(
638
+ nodeId: number,
639
+ change: Partial<Pick<WorkspaceDocumentRow, 'published' | 'publishedEventId' | 'edited'>>,
640
+ ): Promise<void> {
641
+ const b = (value: boolean) => this.#db.dialect.boolValue(value) as boolean
642
+ await this.#db.q
643
+ .updateTable('workspace_document')
644
+ .set({
645
+ ...(change.published === undefined ? {} : { published: b(change.published) }),
646
+ ...(change.publishedEventId === undefined
647
+ ? {}
648
+ : { published_event_id: change.publishedEventId }),
649
+ ...(change.edited === undefined ? {} : { edited: b(change.edited) }),
650
+ })
651
+ .where('workspace_id', '=', this.#workspace as number)
652
+ .where('node_id', '=', nodeId)
653
+ .execute()
654
+ }
655
+
656
+ /** An event of the workspace's: never current, never Shared's head. */
657
+ async #insertWorkspaceEvent(
658
+ nodeId: number,
659
+ kind: EventKind,
660
+ name: string,
661
+ userId: number | undefined,
662
+ templateId: number | null,
663
+ ): Promise<number> {
664
+ const workspace = this.#workspace as number
665
+ await this.#db.q
666
+ .insertInto('content_version')
667
+ .values({
668
+ node_id: nodeId,
669
+ kind,
670
+ version_date: DbDate.toDb(new Date()),
671
+ user_id: userId ?? null,
672
+ current: this.#db.dialect.boolValue(false) as boolean,
673
+ text: name,
674
+ prevent_cleanup: this.#db.dialect.boolValue(false) as boolean,
675
+ workspace_id: workspace,
676
+ })
677
+ .execute()
678
+ const rows = await this.#db.q
679
+ .selectFrom('content_version')
680
+ .select((eb) => eb.fn.max('id').as('id'))
681
+ .where('node_id', '=', nodeId)
682
+ .where('workspace_id', '=', workspace)
683
+ .execute()
684
+ const eventId = Number(rows[0]?.id)
685
+ await this.#db.q
686
+ .insertInto('document_version')
687
+ .values({
688
+ id: eventId,
689
+ template_id: templateId,
690
+ published: this.#db.dialect.boolValue(false) as boolean,
691
+ })
692
+ .execute()
693
+ return eventId
694
+ }
695
+
696
+ /** The workspace's latest event for a page, with its name, template and date. */
697
+ async #workspaceHead(nodeId: number) {
698
+ const rows = await this.#db.q
699
+ .selectFrom('content_version as cv')
700
+ .innerJoin('document_version as dv', 'dv.id', 'cv.id')
701
+ .leftJoin('node as tn', 'tn.id', 'dv.template_id')
702
+ .select([
703
+ 'cv.id',
704
+ 'cv.text',
705
+ 'cv.version_date',
706
+ 'dv.template_id',
707
+ 'tn.unique_id as template_key',
708
+ ])
709
+ .where('cv.node_id', '=', nodeId)
710
+ .where('cv.workspace_id', '=', this.#workspace as number)
711
+ .orderBy('cv.id', 'desc')
712
+ .limit(1)
713
+ .execute()
714
+ return rows[0]
715
+ }
716
+
717
+ /**
718
+ * The page as the workspace sees it: Shared's values as of the event it
719
+ * started from, newest per key, with the workspace's own laid over them. The
720
+ * workspace's row wins whatever its id, since an upgrade can append a Shared
721
+ * twin under an old event after the workspace wrote.
722
+ */
723
+ async #workspaceView(
724
+ nodeId: number,
725
+ wd: WorkspaceDocumentRow,
726
+ /** Only the workspace's own rows up to this event: what it published (story 379). */
727
+ upTo?: number,
728
+ ): Promise<ValueRow[]> {
729
+ const workspace = this.#workspace as number
730
+ const rows = await this.#db.q
731
+ .selectFrom('property_value')
732
+ .select([
733
+ 'id',
734
+ 'event_id',
735
+ 'property_type_id',
736
+ 'language_id',
737
+ 'segment',
738
+ 'environment',
739
+ 'int_value',
740
+ 'decimal_value',
741
+ 'date_value',
742
+ 'varchar_value',
743
+ 'text_value',
744
+ 'workspace_id',
745
+ ])
746
+ .where('node_id', '=', nodeId)
747
+ .where((eb) =>
748
+ wd.baseEventId === null
749
+ ? eb('workspace_id', '=', workspace)
750
+ : eb.or([
751
+ eb.and([eb('workspace_id', 'is', null), eb('event_id', '<=', wd.baseEventId)]),
752
+ eb('workspace_id', '=', workspace),
753
+ ]),
754
+ )
755
+ .orderBy('id')
756
+ .execute()
757
+ const shared = new Map<string, ValueRow>()
758
+ const mine = new Map<string, ValueRow>()
759
+ for (const row of rows) {
760
+ const value = this.#toValueRow(row)
761
+ if (upTo !== undefined && row.workspace_id !== null && value.eventId > upTo) continue
762
+ const key = keyOf(value.propertyTypeId, value.languageId, value.segment, value.environment)
763
+ ;(row.workspace_id === null ? shared : mine).set(key, value)
764
+ }
765
+ return [...new Map([...shared, ...mine]).values()]
766
+ }
767
+
768
+ /** A page the workspace has touched, as an editor in it sees it. */
769
+ async #loadInWorkspace(
770
+ node: NodeRow,
771
+ wd: WorkspaceDocumentRow,
772
+ ): Promise<DocumentAggregate | undefined> {
773
+ const workspace = this.#workspace as number
774
+ const rows = await this.#db.q
775
+ .selectFrom('content as c')
776
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
777
+ .innerJoin('node as ctn', 'ctn.id', 'ct.node_id')
778
+ .select([
779
+ 'c.content_type_id',
780
+ 'ct.alias as content_type_alias',
781
+ 'ct.icon as content_type_icon',
782
+ 'ct.list_view as content_type_collection',
783
+ 'ctn.unique_id as content_type_key',
784
+ 'ct.origin_key as content_type_origin_key',
785
+ ])
786
+ .where('c.node_id', '=', node.id)
787
+ .execute()
788
+ const row = rows[0]
789
+ const head = await this.#workspaceHead(node.id)
790
+ if (!row || !head) return undefined
791
+ const propertyTypes = await this.#propertyTypes(Number(row.content_type_id))
792
+ const languages = await this.#languages()
793
+ const values = this.#valuesFromRows(
794
+ await this.#workspaceView(node.id, wd),
795
+ propertyTypes,
796
+ languages,
797
+ )
798
+ const createDate = node.createDate ?? new Date()
799
+ const updateDate = DbDate.fromDb(head.version_date) ?? createDate
800
+ const cultureRows = await this.#db.q
801
+ .selectFrom('workspace_document_culture as wdc')
802
+ .innerJoin('language as l', 'l.id', 'wdc.language_id')
803
+ .select(['wdc.name', 'wdc.published', 'wdc.edited', 'wdc.available', 'l.iso_code'])
804
+ .where('wdc.workspace_id', '=', workspace)
805
+ .where('wdc.node_id', '=', node.id)
806
+ .execute()
807
+ const variants: DocumentVariant[] =
808
+ cultureRows.length === 0
809
+ ? [
810
+ {
811
+ culture: null,
812
+ segment: null,
813
+ name: String(head.text ?? node.text ?? ''),
814
+ state: stateFor(wd.published, wd.edited, node.trashed),
815
+ createDate,
816
+ updateDate,
817
+ publishDate: null,
818
+ },
819
+ ]
820
+ : cultureRows.map((culture) => ({
821
+ culture: String(culture.iso_code),
822
+ segment: null,
823
+ name: String(culture.name ?? ''),
824
+ state: stateFor(
825
+ fromDbBool(culture.published),
826
+ fromDbBool(culture.edited),
827
+ node.trashed,
828
+ fromDbBool(culture.available),
829
+ ),
830
+ createDate,
831
+ updateDate,
832
+ publishDate: null,
833
+ }))
834
+ const parent = node.parentId > 0 ? await this.#nodes.byId(node.parentId) : undefined
835
+ return {
836
+ key: node.key,
837
+ // A type made in the workspace is stored under a key of its own (story 376).
838
+ contentTypeKey: normaliseUuid(String(row.content_type_origin_key ?? row.content_type_key)),
839
+ contentTypeAlias: String(row.content_type_alias),
840
+ contentTypeIcon: String(row.content_type_icon ?? 'icon-document'),
841
+ contentTypeCollectionKey: row.content_type_collection
842
+ ? normaliseUuid(String(row.content_type_collection))
843
+ : null,
844
+ componentKey: head.template_key ? normaliseUuid(String(head.template_key)) : null,
845
+ parentKey: parent && parent.id !== SystemNodes.Root ? parent.key : null,
846
+ sortOrder: node.sortOrder,
847
+ isTrashed: node.trashed,
848
+ published: wd.published,
849
+ edited: wd.edited,
850
+ values,
851
+ variants,
852
+ revision: await this.#revision(node.id),
853
+ }
854
+ }
855
+
856
+ /** Names and languages a workspace save gives a page, kept apart from Shared's. */
857
+ async #writeWorkspaceCultures(
858
+ nodeId: number,
859
+ eventId: number,
860
+ variants: ReadonlyArray<{ culture: string | null; name: string }>,
861
+ ): Promise<void> {
862
+ const workspace = this.#workspace as number
863
+ const cultured = variants.filter((variant) => variant.culture !== null)
864
+ if (cultured.length === 0) return
865
+ const languages = await this.#languages()
866
+ const idByIso = new Map(languages.map((l) => [l.isoCode.toLowerCase(), l.id]))
867
+ const t = this.#db.dialect.boolValue(true) as boolean
868
+ const f = this.#db.dialect.boolValue(false) as boolean
869
+ for (const variant of cultured) {
870
+ const languageId = idByIso.get(String(variant.culture).toLowerCase())
871
+ if (!languageId) continue
872
+ await this.#db.q
873
+ .insertInto('content_version_culture_variation')
874
+ .values({
875
+ version_id: eventId,
876
+ language_id: languageId,
877
+ name: variant.name,
878
+ date: DbDate.toDb(new Date()),
879
+ })
880
+ .execute()
881
+ const changed = await this.#db.q
882
+ .updateTable('workspace_document_culture')
883
+ .set({ name: variant.name, available: t, edited: t })
884
+ .where('workspace_id', '=', workspace)
885
+ .where('node_id', '=', nodeId)
886
+ .where('language_id', '=', languageId)
887
+ .executeTakeFirst()
888
+ if (Number(changed.numUpdatedRows ?? 0) === 0)
889
+ await this.#db.q
890
+ .insertInto('workspace_document_culture')
891
+ .values({
892
+ workspace_id: workspace,
893
+ node_id: nodeId,
894
+ language_id: languageId,
895
+ name: variant.name,
896
+ available: t,
897
+ published: f,
898
+ edited: t,
899
+ published_event_id: null,
900
+ published_name: null,
901
+ })
902
+ .execute()
903
+ }
904
+ }
905
+
906
+ /** The languages of a page in the workspace: those it has, or those published there. */
907
+ async #workspaceCultures(nodeId: number, which: 'available' | 'published'): Promise<string[]> {
908
+ const rows = await this.#db.q
909
+ .selectFrom('workspace_document_culture as wdc')
910
+ .innerJoin('language as l', 'l.id', 'wdc.language_id')
911
+ .select('l.iso_code')
912
+ .where('wdc.workspace_id', '=', this.#workspace as number)
913
+ .where('wdc.node_id', '=', nodeId)
914
+ .where(`wdc.${which}`, '=', this.#db.dialect.boolValue(true) as boolean)
915
+ .execute()
916
+ return rows.map((row) => String(row.iso_code))
917
+ }
918
+
919
+ /** Whether every ancestor is published as the workspace sees it. */
920
+ async #ancestorsPublishedInWorkspace(node: NodeRow): Promise<boolean> {
921
+ const ids = node.path
922
+ .split(',')
923
+ .map(Number)
924
+ .filter((id) => id > 0 && id !== node.id)
925
+ for (const id of ids) {
926
+ const mine = await this.#workspaceDocument(id)
927
+ if (mine) {
928
+ if (!mine.published) return false
929
+ continue
930
+ }
931
+ const shared = await this.#db.q
932
+ .selectFrom('document')
933
+ .select('published')
934
+ .where('node_id', '=', id)
935
+ .execute()
936
+ if (!fromDbBool(shared[0]?.published)) return false
937
+ }
938
+ return true
939
+ }
940
+
941
+ /**
942
+ * Publishes a page in the workspace only (story 375): Shared's published
943
+ * page, its flags and the published cache are untouched, and the usual rules
944
+ * are checked against what the workspace sees.
945
+ */
946
+ async #publishInWorkspace(
947
+ node: NodeRow,
948
+ cultures: readonly string[] | null,
949
+ ): Promise<DocumentAggregate | undefined> {
950
+ if (node.trashed) throw new PublishBlockedError('The document is in the recycle bin.')
951
+ if (!(await this.#ancestorsPublishedInWorkspace(node)))
952
+ throw new PublishBlockedError('An ancestor is not published.')
953
+ await this.#touch(node)
954
+ const variant = await this.#variesByCulture(node.id)
955
+ const available = variant ? await this.#workspaceCultures(node.id, 'available') : []
956
+ const targets = variant ? (cultures && cultures.length > 0 ? [...cultures] : available) : null
957
+ if (targets) {
958
+ const missing = targets.filter(
959
+ (c) => !available.some((a) => a.toLowerCase() === c.toLowerCase()),
960
+ )
961
+ if (missing.length > 0)
962
+ throw new PublishBlockedError(
963
+ `The document has no ${missing.join(', ')} variant to publish.`,
964
+ )
965
+ const published = await this.#workspaceCultures(node.id, 'published')
966
+ const settled = new Set([...targets, ...published].map((c) => c.toLowerCase()))
967
+ const mandatory = (await this.#languages()).filter(
968
+ (l) => l.isMandatory && !settled.has(l.isoCode.toLowerCase()),
969
+ )
970
+ if (mandatory.length > 0)
971
+ throw new PublishBlockedError(
972
+ `The mandatory ${mandatory.map((l) => l.isoCode).join(', ')} must be published too.`,
973
+ )
974
+ }
975
+ await this.#assertMandatoryFilled(node, targets)
976
+ const head = (await this.#workspaceHead(node.id)) ?? undefined
977
+ const shared = head ? undefined : await this.#headEvent(node.id)
978
+ const eventId = await this.#insertWorkspaceEvent(
979
+ node.id,
980
+ 'publish',
981
+ String(head?.text ?? shared?.name ?? node.text ?? ''),
982
+ undefined,
983
+ head
984
+ ? head.template_id === null
985
+ ? null
986
+ : Number(head.template_id)
987
+ : (shared?.templateId ?? null),
988
+ )
989
+ await this.#setWorkspaceDocument(node.id, {
990
+ published: true,
991
+ publishedEventId: eventId,
992
+ edited: false,
993
+ })
994
+ const languages = await this.#languages()
995
+ for (const iso of targets ?? []) {
996
+ const languageId = languages.find((l) => l.isoCode.toLowerCase() === iso.toLowerCase())?.id
997
+ if (!languageId) continue
998
+ await this.#db.q
999
+ .updateTable('workspace_document_culture')
1000
+ .set((eb) => ({
1001
+ published: this.#db.dialect.boolValue(true) as boolean,
1002
+ edited: this.#db.dialect.boolValue(false) as boolean,
1003
+ published_event_id: eventId,
1004
+ published_name: eb.ref('name'),
1005
+ }))
1006
+ .where('workspace_id', '=', this.#workspace as number)
1007
+ .where('node_id', '=', node.id)
1008
+ .where('language_id', '=', languageId)
1009
+ .execute()
1010
+ }
1011
+ return this.#load(node)
1012
+ }
1013
+
1014
+ /** Unpublishes a page in the workspace only, or the languages named. */
1015
+ async #unpublishInWorkspace(
1016
+ node: NodeRow,
1017
+ cultures: readonly string[] | null,
1018
+ ): Promise<DocumentAggregate | undefined> {
1019
+ await this.#touch(node)
1020
+ const languages = await this.#languages()
1021
+ const mandatory = new Set(
1022
+ languages.filter((l) => l.isMandatory).map((l) => l.isoCode.toLowerCase()),
1023
+ )
1024
+ const everything =
1025
+ !cultures || cultures.length === 0 || cultures.some((c) => mandatory.has(c.toLowerCase()))
1026
+ const isoCodes = everything ? await this.#workspaceCultures(node.id, 'available') : cultures
1027
+ for (const iso of isoCodes) {
1028
+ const languageId = languages.find((l) => l.isoCode.toLowerCase() === iso.toLowerCase())?.id
1029
+ if (!languageId) continue
1030
+ await this.#db.q
1031
+ .updateTable('workspace_document_culture')
1032
+ .set({
1033
+ published: this.#db.dialect.boolValue(false) as boolean,
1034
+ edited: this.#db.dialect.boolValue(true) as boolean,
1035
+ })
1036
+ .where('workspace_id', '=', this.#workspace as number)
1037
+ .where('node_id', '=', node.id)
1038
+ .where('language_id', '=', languageId)
1039
+ .execute()
1040
+ }
1041
+ if (everything || (await this.#workspaceCultures(node.id, 'published')).length === 0)
1042
+ await this.#setWorkspaceDocument(node.id, { published: false, edited: true })
1043
+ return this.#load(node)
1044
+ }
1045
+
1046
+ // ---------------------------------------------------------------- merging (story 380)
1047
+
1048
+ /** Each page the workspace changed or made, with every field as begun, in it, and in Shared now. */
1049
+ async workspaceMergePages(): Promise<WorkspacePageMerge[]> {
1050
+ const workspace = this.#workspace
1051
+ if (workspace === undefined) return []
1052
+ const rows = await this.#db.q
1053
+ .selectFrom('workspace_document as wd')
1054
+ .innerJoin('node as n', 'n.id', 'wd.node_id')
1055
+ .select(['wd.node_id', 'n.level'])
1056
+ .where('wd.workspace_id', '=', workspace)
1057
+ // This kind's only: pages, media or Library items (story 390).
1058
+ .where('n.node_object_type', 'in', [
1059
+ this.objectType,
1060
+ KINDS[this.kind].workspaceObjectType ?? this.objectType,
1061
+ ])
1062
+ .orderBy('n.level')
1063
+ .orderBy('n.id')
1064
+ .execute()
1065
+ const out: WorkspacePageMerge[] = []
1066
+ for (const row of rows) {
1067
+ const node = await this.#nodes.byId(Number(row.node_id))
1068
+ const wd = node ? await this.#workspaceDocument(node.id) : undefined
1069
+ if (node && wd) out.push(await this.#mergePage(node, wd))
1070
+ }
1071
+ return out
1072
+ }
1073
+
1074
+ async #mergePage(node: NodeRow, wd: WorkspaceDocumentRow): Promise<WorkspacePageMerge> {
1075
+ const workspace = this.#workspace as number
1076
+ const contentTypeNodeId = (await this.#contentTypeNodeId(node.id)) as number
1077
+ const propertyTypes = await this.#propertyTypes(contentTypeNodeId)
1078
+ const languages = await this.#languages()
1079
+ const isoById = new Map(languages.map((l) => [l.id, l.isoCode]))
1080
+ type Held = {
1081
+ value: unknown
1082
+ alias: string
1083
+ culture: string | null
1084
+ segment: string | null
1085
+ environment?: string | null
1086
+ }
1087
+ const asValues = (rows: readonly ValueRow[]) => {
1088
+ const map = new Map<string, Held>()
1089
+ // A field's id names its environment only when it has one: shared ids are as before.
1090
+ for (const v of this.#valuesFromRows(rows, propertyTypes, languages))
1091
+ map.set(
1092
+ `${v.alias}|${v.culture ?? ''}|${v.segment ?? ''}${v.environment ? `|${v.environment}` : ''}`,
1093
+ {
1094
+ value: v.value,
1095
+ alias: v.alias,
1096
+ culture: v.culture,
1097
+ segment: v.segment,
1098
+ ...(v.environment ? { environment: v.environment } : {}),
1099
+ },
1100
+ )
1101
+ return map
1102
+ }
1103
+ const base =
1104
+ wd.baseEventId === null
1105
+ ? new Map<string, Held>()
1106
+ : asValues(await this.#valueRowsAsOf(node.id, { eventId: wd.baseEventId }))
1107
+ const mine = asValues(await this.#workspaceView(node.id, wd))
1108
+ const theirs = wd.created
1109
+ ? new Map<string, Held>()
1110
+ : asValues(await this.#currentValueRows(node.id))
1111
+ const fields: MergeField[] = []
1112
+ for (const field of new Set([...base.keys(), ...mine.keys(), ...theirs.keys()])) {
1113
+ const known = mine.get(field) ?? theirs.get(field) ?? base.get(field)
1114
+ fields.push({
1115
+ field,
1116
+ base: wd.created ? undefined : (base.get(field)?.value ?? null),
1117
+ mine: mine.get(field)?.value ?? null,
1118
+ theirs: wd.created ? undefined : (theirs.get(field)?.value ?? null),
1119
+ ...(known
1120
+ ? {
1121
+ value: {
1122
+ alias: known.alias,
1123
+ culture: known.culture,
1124
+ segment: known.segment,
1125
+ ...(known.environment ? { environment: known.environment } : {}),
1126
+ },
1127
+ }
1128
+ : {}),
1129
+ })
1130
+ }
1131
+
1132
+ // Names and the template: as begun, in the workspace, and in Shared now.
1133
+ const eventFacts = async (eventId: number | null | undefined) => {
1134
+ if (eventId === null || eventId === undefined) return undefined
1135
+ const found = await this.#db.q
1136
+ .selectFrom('content_version as cv')
1137
+ .innerJoin('document_version as dv', 'dv.id', 'cv.id')
1138
+ .leftJoin('node as tn', 'tn.id', 'dv.template_id')
1139
+ .select(['cv.text', 'tn.unique_id as template_key'])
1140
+ .where('cv.id', '=', eventId)
1141
+ .execute()
1142
+ const cultureNames = await this.#db.q
1143
+ .selectFrom('content_version_culture_variation')
1144
+ .select(['language_id', 'name'])
1145
+ .where('version_id', '=', eventId)
1146
+ .execute()
1147
+ return {
1148
+ name: String(found[0]?.text ?? ''),
1149
+ template: found[0]?.template_key ? normaliseUuid(String(found[0].template_key)) : null,
1150
+ cultures: new Map(
1151
+ cultureNames.map((c) => [isoById.get(Number(c.language_id)) ?? '', String(c.name ?? '')]),
1152
+ ),
1153
+ }
1154
+ }
1155
+ const head = await this.#workspaceHead(node.id)
1156
+ const baseFacts = await eventFacts(wd.baseEventId)
1157
+ const mineFacts = await eventFacts(head ? Number(head.id) : null)
1158
+ const sharedHead = wd.created ? undefined : await this.#headEvent(node.id)
1159
+ const theirsFacts = await eventFacts(sharedHead?.id)
1160
+ fields.push(
1161
+ { field: '@name', base: baseFacts?.name, mine: mineFacts?.name, theirs: theirsFacts?.name },
1162
+ {
1163
+ field: '@template',
1164
+ base: baseFacts?.template,
1165
+ mine: mineFacts?.template ?? null,
1166
+ theirs: theirsFacts?.template,
1167
+ },
1168
+ )
373
1169
 
374
- constructor(db: Db, options: DocumentRepositoryOptions = {}) {
375
- this.#db = db
376
- this.#nodes = new NodeRepository(db)
377
- this.#nodeState = options.nodeState ?? BASELINE_NODE_STATE
378
- this.#nodeId = options.nodeId
379
- this.kind = options.kind ?? 'document'
380
- this.objectType = KINDS[this.kind].objectType
381
- this.#recycleBin = KINDS[this.kind].recycleBin
382
- this.#intake = options.valueIntake
383
- this.#inTreeLock = options.inTreeLock ?? false
1170
+ // Per language: names and published state.
1171
+ const mineCultures = await this.#db.q
1172
+ .selectFrom('workspace_document_culture as wdc')
1173
+ .innerJoin('language as l', 'l.id', 'wdc.language_id')
1174
+ .select(['l.iso_code', 'wdc.name', 'wdc.published', 'wdc.base_published'])
1175
+ .where('wdc.workspace_id', '=', workspace)
1176
+ .where('wdc.node_id', '=', node.id)
1177
+ .execute()
1178
+ const theirsCultures = new Map(
1179
+ (
1180
+ await this.#db.q
1181
+ .selectFrom('document_culture_variation as dcv')
1182
+ .innerJoin('language as l', 'l.id', 'dcv.language_id')
1183
+ .select(['l.iso_code', 'dcv.name', 'dcv.published'])
1184
+ .where('dcv.node_id', '=', node.id)
1185
+ .execute()
1186
+ ).map((c) => [String(c.iso_code), c]),
1187
+ )
1188
+ const cultures: WorkspacePageMerge['cultures'] = []
1189
+ for (const c of mineCultures) {
1190
+ const iso = String(c.iso_code)
1191
+ const theirsCulture = theirsCultures.get(iso)
1192
+ fields.push({
1193
+ field: `@name:${iso}`,
1194
+ base: wd.created ? undefined : (baseFacts?.cultures.get(iso) ?? null),
1195
+ mine: String(c.name ?? ''),
1196
+ theirs: wd.created ? undefined : theirsCulture ? String(theirsCulture.name ?? '') : null,
1197
+ })
1198
+ cultures.push({
1199
+ iso,
1200
+ base: c.base_published === null ? null : fromDbBool(c.base_published),
1201
+ mine: fromDbBool(c.published),
1202
+ theirs: fromDbBool(theirsCulture?.published),
1203
+ })
1204
+ }
1205
+ const document = (
1206
+ await this.#db.q
1207
+ .selectFrom('document')
1208
+ .select(['published', 'edited'])
1209
+ .where('node_id', '=', node.id)
1210
+ .execute()
1211
+ )[0]
1212
+ const publishedHere =
1213
+ wd.published &&
1214
+ wd.publishedEventId !== null &&
1215
+ (
1216
+ await this.#db.q
1217
+ .selectFrom('content_version')
1218
+ .select('id')
1219
+ .where('id', '=', wd.publishedEventId)
1220
+ .where('workspace_id', '=', workspace)
1221
+ .execute()
1222
+ ).length > 0
1223
+ const based = (
1224
+ await this.#db.q
1225
+ .selectFrom('workspace_document')
1226
+ .select('base_published')
1227
+ .where('workspace_id', '=', workspace)
1228
+ .where('node_id', '=', node.id)
1229
+ .execute()
1230
+ )[0]
1231
+ const parent = node.parentId > 0 ? await this.#nodes.byId(node.parentId) : undefined
1232
+ const typeRow = (
1233
+ await this.#db.q
1234
+ .selectFrom('node')
1235
+ .select('unique_id')
1236
+ .where('id', '=', contentTypeNodeId)
1237
+ .execute()
1238
+ )[0]
1239
+ return {
1240
+ kind: this.kind,
1241
+ key: node.key,
1242
+ nodeId: node.id,
1243
+ made: wd.created,
1244
+ level: node.level,
1245
+ contentTypeKey: normaliseUuid(String(typeRow?.unique_id)),
1246
+ parentKey: parent && parent.id !== SystemNodes.Root ? parent.key : null,
1247
+ sharedHead: sharedHead?.id ?? null,
1248
+ baseEvent: wd.baseEventId,
1249
+ fields,
1250
+ published: {
1251
+ base:
1252
+ based === undefined || based.base_published === null
1253
+ ? null
1254
+ : fromDbBool(based.base_published),
1255
+ mine: wd.published,
1256
+ theirs: wd.created ? false : fromDbBool(document?.published),
1257
+ here: publishedHere,
1258
+ sharedEdited: wd.created ? false : fromDbBool(document?.edited),
1259
+ },
1260
+ cultures,
1261
+ }
384
1262
  }
385
1263
 
386
- get nodes(): NodeRepository {
387
- return this.#nodes
1264
+ /** Shared's latest event for a page, which a pending change is checked against (story 380). */
1265
+ async sharedHeadEvent(nodeId: number): Promise<number | null> {
1266
+ return (await this.#headEvent(nodeId))?.id ?? null
388
1267
  }
389
1268
 
390
1269
  /**
391
- * The tree's lock, unless the caller already holds it. Every write goes
392
- * through here, as every Umbraco content service write takes its tree's write
393
- * lock: two saves, or a save and a move, never interleave. The node a write
394
- * acts on is read inside, so it acts on where the node is now.
1270
+ * Answers a page's conflicts in the workspace (story 380): it begins again from
1271
+ * Shared's latest, keeping its own value where the answer is `mine` and taking
1272
+ * Shared's where it is `theirs`, so a merge then finds nothing to ask.
395
1273
  */
396
- #withTree<T>(fn: () => Promise<T>): Promise<T> {
397
- return this.#inTreeLock ? fn() : this.#db.locks.withLock(KINDS[this.kind].lock, fn)
1274
+ async rebaseWorkspacePage(
1275
+ key: string,
1276
+ answers: Readonly<Record<string, 'mine' | 'theirs'>>,
1277
+ ): Promise<boolean> {
1278
+ const workspace = this.#workspace
1279
+ if (workspace === undefined) throw new WorkspaceRefusedError('Only a workspace rebases a page.')
1280
+ return this.#withTree(() =>
1281
+ this.#db.transaction(async (tx) => {
1282
+ const repo = this.#child(tx)
1283
+ const node = await repo.nodes.byKey(key)
1284
+ const wd = node ? await repo.#workspaceDocument(node.id) : undefined
1285
+ if (!node || !wd || wd.created) return false
1286
+ const merge = await repo.#mergePage(node, wd)
1287
+ const head = await repo.#headEvent(node.id)
1288
+ await tx.q
1289
+ .updateTable('workspace_document')
1290
+ .set({ base_event_id: head?.id ?? null })
1291
+ .where('workspace_id', '=', workspace)
1292
+ .where('node_id', '=', node.id)
1293
+ .execute()
1294
+ const types = new Map(
1295
+ (await repo.#propertyTypes((await repo.#contentTypeNodeId(node.id)) as number)).map(
1296
+ (p) => [p.alias, p],
1297
+ ),
1298
+ )
1299
+ const languages = await repo.#languages()
1300
+ for (const field of merge.fields) {
1301
+ const value = field.value
1302
+ if (answers[field.field] !== 'theirs' || !value) continue
1303
+ // Taking Shared's: the workspace's own rows for the field go, so it reads Shared's.
1304
+ const type = types.get(value.alias)
1305
+ if (!type) continue
1306
+ const languageId = value.culture
1307
+ ? (languages.find((l) => l.isoCode.toLowerCase() === value.culture?.toLowerCase())
1308
+ ?.id ?? null)
1309
+ : null
1310
+ await tx.q
1311
+ .deleteFrom('property_value')
1312
+ .where('workspace_id', '=', workspace)
1313
+ .where('node_id', '=', node.id)
1314
+ .where('property_type_id', '=', type.id)
1315
+ .where('language_id', languageId === null ? 'is' : '=', languageId)
1316
+ .where('segment', value.segment === null ? 'is' : '=', value.segment)
1317
+ .where(
1318
+ 'environment',
1319
+ value.environment ? '=' : 'is',
1320
+ (value.environment ?? null) as string,
1321
+ )
1322
+ .execute()
1323
+ }
1324
+ // A language's name taken from Shared is the workspace's for that language now.
1325
+ for (const field of merge.fields) {
1326
+ if (!field.field.startsWith('@name:') || answers[field.field] !== 'theirs') continue
1327
+ const language = languages.find(
1328
+ (l) => l.isoCode.toLowerCase() === field.field.slice(6).toLowerCase(),
1329
+ )
1330
+ if (!language) continue
1331
+ await tx.q
1332
+ .updateTable('workspace_document_culture')
1333
+ .set({ name: String(field.theirs ?? '') })
1334
+ .where('workspace_id', '=', workspace)
1335
+ .where('node_id', '=', node.id)
1336
+ .where('language_id', '=', language.id)
1337
+ .execute()
1338
+ }
1339
+ const name = answers['@name'] === 'theirs'
1340
+ const template = answers['@template'] === 'theirs'
1341
+ if ((name || template) && head) {
1342
+ const mineHead = await repo.#workspaceHead(node.id)
1343
+ await repo.#insertWorkspaceEvent(
1344
+ node.id,
1345
+ 'save',
1346
+ name ? head.name : String(mineHead?.text ?? head.name),
1347
+ undefined,
1348
+ template
1349
+ ? head.templateId
1350
+ : mineHead?.template_id === null || mineHead?.template_id === undefined
1351
+ ? null
1352
+ : Number(mineHead.template_id),
1353
+ )
1354
+ }
1355
+ return true
1356
+ }),
1357
+ )
398
1358
  }
399
1359
 
400
1360
  /**
401
- * Runs `fn` under the tree lock in one transaction, with a repository bound to
402
- * it, so several writes commit together or not at all (story 170).
1361
+ * A page made in a workspace becomes Shared's (story 380): its node is a
1362
+ * document of the site's again, and the workspace's own rows for it go, the
1363
+ * merge writing it as a Shared save next. Called inside the merge.
403
1364
  */
404
- async atomically<T>(fn: (repo: DocumentRepository, tx: Db) => Promise<T>): Promise<T> {
405
- return this.#withTree(() => this.#db.transaction((tx) => fn(this.#child(tx), tx)))
1365
+ /** Whether a page is of a type only its workspace has (story 376). */
1366
+ async madeOfWorkspaceType(nodeId: number): Promise<boolean> {
1367
+ const rows = await this.#db.q
1368
+ .selectFrom('content as c')
1369
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
1370
+ .select('ct.workspace_id')
1371
+ .where('c.node_id', '=', nodeId)
1372
+ .execute()
1373
+ return rows[0]?.workspace_id !== null && rows[0]?.workspace_id !== undefined
406
1374
  }
407
1375
 
408
- #child(tx: Db): DocumentRepository {
409
- return new DocumentRepository(tx, {
410
- nodeState: this.#nodeState,
411
- nodeId: this.#nodeId,
412
- kind: this.kind,
413
- valueIntake: this.#intake,
414
- // A child runs inside whatever its parent took.
415
- inTreeLock: true,
416
- })
1376
+ async adoptWorkspacePage(nodeId: number): Promise<void> {
1377
+ // A page of a type made in the workspace takes Shared's type of that key, which
1378
+ // the merge's files have just made (story 376).
1379
+ const type = (
1380
+ await this.#db.q
1381
+ .selectFrom('content as c')
1382
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
1383
+ .select('ct.origin_key')
1384
+ .where('c.node_id', '=', nodeId)
1385
+ .where('ct.workspace_id', 'is not', null)
1386
+ .execute()
1387
+ )[0]
1388
+ if (type?.origin_key) {
1389
+ const shared = await this.#nodes.byKey(String(type.origin_key))
1390
+ if (shared)
1391
+ await this.#db.q
1392
+ .updateTable('content')
1393
+ .set({ content_type_id: shared.id })
1394
+ .where('node_id', '=', nodeId)
1395
+ .execute()
1396
+ }
1397
+ const versions = () =>
1398
+ this.#db.q
1399
+ .selectFrom('content_version')
1400
+ .select('id')
1401
+ .where('node_id', '=', nodeId)
1402
+ .where('workspace_id', 'is not', null)
1403
+ await this.#db.q
1404
+ .deleteFrom('property_value')
1405
+ .where('node_id', '=', nodeId)
1406
+ .where('workspace_id', 'is not', null)
1407
+ .execute()
1408
+ await this.#db.q
1409
+ .deleteFrom('content_version_culture_variation')
1410
+ .where('version_id', 'in', versions())
1411
+ .execute()
1412
+ await this.#db.q.deleteFrom('document_version').where('id', 'in', versions()).execute()
1413
+ await this.#db.q
1414
+ .deleteFrom('content_version')
1415
+ .where('node_id', '=', nodeId)
1416
+ .where('workspace_id', 'is not', null)
1417
+ .execute()
1418
+ for (const table of ['workspace_document_culture', 'workspace_document'] as const)
1419
+ await this.#db.q.deleteFrom(table).where('node_id', '=', nodeId).execute()
1420
+ await this.#db.q
1421
+ .updateTable('node')
1422
+ .set({ node_object_type: this.objectType, workspace_id: null })
1423
+ .where('id', '=', nodeId)
1424
+ .execute()
1425
+ }
1426
+
1427
+ /**
1428
+ * Records a move, reorder or delete of a Shared page, to be done at merge, with
1429
+ * where the page stood then, so the merge can tell what Shared did since (story
1430
+ * 380). The latest of a kind stands for the page.
1431
+ */
1432
+ async #recordPending(
1433
+ node: NodeRow,
1434
+ kind: 'move' | 'sort' | 'trash' | 'delete',
1435
+ change: { targetParentId?: number | null; sortOrder?: number | null; userId?: number } = {},
1436
+ ): Promise<void> {
1437
+ const workspace = this.#workspace as number
1438
+ await this.#db.q
1439
+ .deleteFrom('workspace_pending')
1440
+ .where('workspace_id', '=', workspace)
1441
+ .where('node_id', '=', node.id)
1442
+ .where('kind', '=', kind)
1443
+ .execute()
1444
+ await this.#db.q
1445
+ .insertInto('workspace_pending')
1446
+ .values({
1447
+ workspace_id: workspace,
1448
+ node_id: node.id,
1449
+ kind,
1450
+ target_parent_id: change.targetParentId ?? null,
1451
+ sort_order: change.sortOrder ?? null,
1452
+ user_id: change.userId ?? null,
1453
+ recorded_at: DbDate.toDb(new Date()),
1454
+ base_parent_id: node.parentId,
1455
+ base_sort_order: node.sortOrder,
1456
+ base_event_id: (await this.#headEvent(node.id))?.id ?? null,
1457
+ name: node.text,
1458
+ })
1459
+ .execute()
417
1460
  }
418
1461
 
419
1462
  // ---------------------------------------------------------------- reads
420
1463
 
421
1464
  async byKey(key: string): Promise<DocumentAggregate | undefined> {
422
1465
  const node = await this.#nodes.byKey(key)
423
- if (!node || node.objectType !== this.objectType) return undefined
1466
+ if (!node || !this.sees(node)) return undefined
424
1467
  return this.#load(node)
425
1468
  }
426
1469
 
@@ -437,7 +1480,15 @@ export class DocumentRepository {
437
1480
  ): Promise<Page<NodeRow>> {
438
1481
  const parentId = parentKey ? (await this.#nodes.byKey(parentKey))?.id : SystemNodes.Root
439
1482
  if (parentId === undefined) return { total: 0, items: [] }
440
- return this.#nodes.children(parentId, this.objectType, skip, take, false, excludeKeys)
1483
+ return this.#nodes.children(
1484
+ parentId,
1485
+ this.objectType,
1486
+ skip,
1487
+ take,
1488
+ false,
1489
+ excludeKeys,
1490
+ this.#workspace,
1491
+ )
441
1492
  }
442
1493
 
443
1494
  /** The recycle bin's tree: trashed documents, top level being what was trashed directly. */
@@ -483,6 +1534,7 @@ export class DocumentRepository {
483
1534
  'u.key as user_key',
484
1535
  ])
485
1536
  .where('cv.node_id', '=', node.id)
1537
+ .where('cv.workspace_id', 'is', null)
486
1538
  .orderBy('cv.id', 'desc')
487
1539
  .execute()
488
1540
  return rows.map((row) => ({
@@ -505,6 +1557,7 @@ export class DocumentRepository {
505
1557
  */
506
1558
  /** Every published node of this kind, for the published cache. Elements too. */
507
1559
  async loadPublished(asOfSchemaStateId?: number): Promise<PublishedNodeRow[]> {
1560
+ if (this.#workspace !== undefined) return this.#workspacePublished(asOfSchemaStateId)
508
1561
  const t = this.#db.dialect.boolValue(true) as boolean
509
1562
  const f = this.#db.dialect.boolValue(false) as boolean
510
1563
  const rows = await this.#db.q
@@ -592,6 +1645,92 @@ export class DocumentRepository {
592
1645
  return published
593
1646
  }
594
1647
 
1648
+ /**
1649
+ * The site as a workspace has it published (story 379): Shared's published
1650
+ * pages, with each page the workspace changed as it has it. One it published is
1651
+ * its own published version; one it changed but did not publish is as Shared
1652
+ * had it published when the workspace first changed it; one it took down, or
1653
+ * that was not published when it began, is not there; and one it made and
1654
+ * published is added. Its moves and deletes wait for the merge.
1655
+ */
1656
+ async #workspacePublished(asOfSchemaStateId?: number): Promise<PublishedNodeRow[]> {
1657
+ const workspace = this.#workspace as number
1658
+ const shared = await this.inWorkspace(undefined).loadPublished(asOfSchemaStateId)
1659
+ const byId = new Map(shared.map((row) => [row.id, row]))
1660
+ const touched = await this.#db.q
1661
+ .selectFrom('workspace_document')
1662
+ .select('node_id')
1663
+ .where('workspace_id', '=', workspace)
1664
+ .execute()
1665
+ for (const { node_id } of touched) {
1666
+ const node = await this.#nodes.byId(Number(node_id))
1667
+ const wd = node ? await this.#workspaceDocument(node.id) : undefined
1668
+ if (!node || !wd || node.trashed) continue
1669
+ const row = wd.published ? await this.#workspacePublishedRow(node, wd) : undefined
1670
+ if (row) byId.set(node.id, row)
1671
+ else byId.delete(node.id)
1672
+ }
1673
+ return [...byId.values()].sort(
1674
+ (a, b) => a.level - b.level || a.sortOrder - b.sortOrder || a.id - b.id,
1675
+ )
1676
+ }
1677
+
1678
+ /** One page as the workspace has it published: its own version, or Shared's as it began. */
1679
+ async #workspacePublishedRow(
1680
+ node: NodeRow,
1681
+ wd: WorkspaceDocumentRow,
1682
+ ): Promise<PublishedNodeRow | undefined> {
1683
+ const workspace = this.#workspace as number
1684
+ const eventId = wd.publishedEventId
1685
+ if (eventId === null) return undefined
1686
+ const event = (
1687
+ await this.#db.q
1688
+ .selectFrom('content_version as cv')
1689
+ .innerJoin('document_version as dv', 'dv.id', 'cv.id')
1690
+ .leftJoin('template as tpl', 'tpl.node_id', 'dv.template_id')
1691
+ .select(['cv.text', 'cv.version_date', 'cv.workspace_id', 'tpl.alias as template_alias'])
1692
+ .where('cv.id', '=', eventId)
1693
+ .execute()
1694
+ )[0]
1695
+ if (!event) return undefined
1696
+ const own = event.workspace_id !== null && Number(event.workspace_id) === workspace
1697
+ const contentTypeNodeId = (await this.#contentTypeNodeId(node.id)) as number
1698
+ const propertyTypes = (await this.#propertyTypes(contentTypeNodeId)).filter((p) => !p.pending)
1699
+ const languages = await this.#languages()
1700
+ const rows = own
1701
+ ? await this.#workspaceView(node.id, wd, eventId)
1702
+ : await this.#valueRowsAsOf(node.id, { eventId })
1703
+ const typeRows = await this.#db.q
1704
+ .selectFrom('content_type')
1705
+ .select('alias')
1706
+ .where('node_id', '=', await this.#readTypeNodeId(contentTypeNodeId))
1707
+ .execute()
1708
+ const cultures = await this.#db.q
1709
+ .selectFrom('workspace_document_culture as wdc')
1710
+ .innerJoin('language as l', 'l.id', 'wdc.language_id')
1711
+ .select(['l.iso_code', 'wdc.name', 'wdc.published'])
1712
+ .where('wdc.workspace_id', '=', workspace)
1713
+ .where('wdc.node_id', '=', node.id)
1714
+ .execute()
1715
+ const live = cultures.filter((c) => fromDbBool(c.published))
1716
+ return {
1717
+ id: node.id,
1718
+ key: node.key,
1719
+ parentId: node.parentId,
1720
+ level: node.level,
1721
+ path: node.path,
1722
+ sortOrder: node.sortOrder,
1723
+ name: String(event.text ?? node.text ?? ''),
1724
+ contentTypeAlias: String(typeRows[0]?.alias ?? ''),
1725
+ componentAlias: (event.template_alias as string | null) ?? null,
1726
+ createDate: node.createDate ?? new Date(),
1727
+ updateDate: DbDate.fromDb(event.version_date) ?? new Date(),
1728
+ cultures: live.map((c) => String(c.iso_code)),
1729
+ names: Object.fromEntries(live.map((c) => [String(c.iso_code), String(c.name ?? '')])),
1730
+ values: this.#valuesFromRows(rows, propertyTypes, languages),
1731
+ }
1732
+ }
1733
+
595
1734
  /**
596
1735
  * The nodes of this kind not in the bin, with the values an editor sees now:
597
1736
  * what media is read as, having no publish. Without a filter every one, read
@@ -704,6 +1843,7 @@ export class DocumentRepository {
704
1843
  'property_type_id',
705
1844
  'language_id',
706
1845
  'segment',
1846
+ 'environment',
707
1847
  'int_value',
708
1848
  'decimal_value',
709
1849
  'date_value',
@@ -722,7 +1862,7 @@ export class DocumentRepository {
722
1862
  for (const [id, history] of await this.#valueHistoryFor(slice, stateId)) {
723
1863
  const latest = new Map<string, ValueRow>()
724
1864
  for (const row of history)
725
- latest.set(keyOf(row.propertyTypeId, row.languageId, row.segment), row)
1865
+ latest.set(keyOf(row.propertyTypeId, row.languageId, row.segment, row.environment), row)
726
1866
  rowsById.set(id, [...latest.values()])
727
1867
  }
728
1868
  }
@@ -830,19 +1970,31 @@ export class DocumentRepository {
830
1970
  this.#db.transaction(async (tx) => {
831
1971
  const repo = this.#child(tx)
832
1972
  const state = await assertNodeMayWrite(tx, this.#nodeState)
833
- const contentTypeNode = await repo.nodes.byKey(input.contentTypeKey)
1973
+ const contentTypeNode =
1974
+ (await repo.nodes.byKey(input.contentTypeKey)) ??
1975
+ (await repo.#workspaceTypeNode(input.contentTypeKey))
834
1976
  if (!contentTypeNode) throw new Error(`Unknown content type '${input.contentTypeKey}'.`)
835
1977
 
836
1978
  const parent = input.parentKey ? await repo.nodes.byKey(input.parentKey) : undefined
837
1979
  if (input.parentKey && !parent)
838
1980
  throw new InvalidParentError('The parent could not be found.')
839
1981
  if (parent?.trashed) throw new InvalidParentError('The parent is in the recycle bin.')
1982
+ const workspace = this.#workspace
1983
+ if (workspace !== undefined && !KINDS[this.kind].workspaceObjectType)
1984
+ throw new WorkspaceRefusedError('This is made in Shared only.')
1985
+ if (parent && workspace !== undefined && !repo.sees(parent))
1986
+ throw new InvalidParentError('The parent could not be found.')
840
1987
  const parentId = parent?.id ?? SystemNodes.Root
841
1988
  const name = input.variants[0]?.name ?? ''
842
1989
  const node = await repo.nodes.create({
843
1990
  key: input.key,
844
1991
  parentId,
845
- objectType: this.objectType,
1992
+ // A page made in a workspace is its own until it is merged (story 375).
1993
+ objectType:
1994
+ workspace === undefined
1995
+ ? this.objectType
1996
+ : (KINDS[this.kind].workspaceObjectType as string),
1997
+ ...(workspace === undefined ? {} : { workspaceId: workspace }),
846
1998
  text: name,
847
1999
  userId: input.userId,
848
2000
  // A media folder comes before the files beside it in the tree (story 246).
@@ -869,6 +2021,33 @@ export class DocumentRepository {
869
2021
  const templateId = input.componentKey
870
2022
  ? ((await repo.nodes.byKey(input.componentKey))?.id ?? null)
871
2023
  : null
2024
+ if (workspace !== undefined) {
2025
+ const f = tx.dialect.boolValue(false) as boolean
2026
+ await tx.q
2027
+ .insertInto('workspace_document')
2028
+ .values({
2029
+ workspace_id: workspace,
2030
+ node_id: node.id,
2031
+ base_event_id: null,
2032
+ created: tx.dialect.boolValue(true) as boolean,
2033
+ published: f,
2034
+ published_event_id: null,
2035
+ edited: tx.dialect.boolValue(true) as boolean,
2036
+ })
2037
+ .execute()
2038
+ const eventId = await repo.#insertWorkspaceEvent(
2039
+ node.id,
2040
+ 'save',
2041
+ name,
2042
+ input.userId,
2043
+ templateId,
2044
+ )
2045
+ await repo.#appendValues(node.id, eventId, state, contentTypeNode.id, input.values)
2046
+ await repo.#writeWorkspaceCultures(node.id, eventId, input.variants)
2047
+ const made = await repo.#load({ ...node, text: name })
2048
+ if (!made) throw new Error('Document could not be read back after creation.')
2049
+ return made
2050
+ }
872
2051
  const eventId = await repo.#insertEvent(
873
2052
  node.id,
874
2053
  'save',
@@ -936,6 +2115,7 @@ export class DocumentRepository {
936
2115
  'pv.schema_state_id',
937
2116
  'pv.language_id',
938
2117
  'pv.segment',
2118
+ 'pv.environment',
939
2119
  'pv.int_value',
940
2120
  'pv.decimal_value',
941
2121
  'pv.date_value',
@@ -962,6 +2142,7 @@ export class DocumentRepository {
962
2142
  alias: String(row.alias),
963
2143
  culture: row.language_id === null ? null : (isoById.get(Number(row.language_id)) ?? null),
964
2144
  segment: (row.segment as string | null) ?? null,
2145
+ environment: (row.environment as string | null) ?? null,
965
2146
  value,
966
2147
  })
967
2148
  }
@@ -999,7 +2180,7 @@ export class DocumentRepository {
999
2180
  const idByIso = new Map(languages.map((l) => [l.isoCode.toLowerCase(), l.id]))
1000
2181
  const current = new Map(
1001
2182
  (await repo.#currentValueRows(node.id)).map((row) => [
1002
- keyOf(row.propertyTypeId, row.languageId, row.segment),
2183
+ keyOf(row.propertyTypeId, row.languageId, row.segment, row.environment),
1003
2184
  row,
1004
2185
  ]),
1005
2186
  )
@@ -1023,7 +2204,9 @@ export class DocumentRepository {
1023
2204
  if (!propertyType) continue
1024
2205
  const culture = propertyType.variesByCulture ? value.culture : null
1025
2206
  const languageId = culture ? (idByIso.get(culture.toLowerCase()) ?? null) : null
1026
- const existing = current.get(keyOf(propertyType.id, languageId, value.segment ?? null))
2207
+ const existing = current.get(
2208
+ keyOf(propertyType.id, languageId, value.segment ?? null, value.environment ?? null),
2209
+ )
1027
2210
  const eventId = value.eventId ?? existing?.eventId ?? fallbackEvent
1028
2211
  await repo.#insertValue(
1029
2212
  node.id,
@@ -1032,6 +2215,7 @@ export class DocumentRepository {
1032
2215
  value.storage ? { ...propertyType, storage: value.storage } : propertyType,
1033
2216
  languageId,
1034
2217
  value.segment ?? null,
2218
+ value.environment ?? null,
1035
2219
  value.value,
1036
2220
  existing?.id,
1037
2221
  )
@@ -1055,16 +2239,31 @@ export class DocumentRepository {
1055
2239
  const repo = this.#child(tx)
1056
2240
  const state = await assertNodeMayWrite(tx, this.#nodeState)
1057
2241
  const node = await repo.nodes.byKey(input.key)
1058
- if (!node) return undefined
2242
+ if (!node || !repo.sees(node)) return undefined
1059
2243
  await repo.#assertRevision(node.id, input.expectedRevision)
1060
2244
  const contentTypeNodeId = await repo.#contentTypeNodeId(node.id)
1061
2245
  if (!contentTypeNodeId) return undefined
1062
2246
 
1063
2247
  const name = input.variants[0]?.name ?? node.text ?? ''
1064
- await repo.nodes.rename(node.id, name)
1065
2248
  const templateId = input.componentKey
1066
2249
  ? ((await repo.nodes.byKey(input.componentKey))?.id ?? null)
1067
2250
  : null
2251
+ if (repo.#workspace !== undefined) {
2252
+ // Shared's node, its tree name and its files are untouched until a merge.
2253
+ await repo.#touch(node)
2254
+ const eventId = await repo.#insertWorkspaceEvent(
2255
+ node.id,
2256
+ 'save',
2257
+ name,
2258
+ input.userId,
2259
+ templateId,
2260
+ )
2261
+ await repo.#appendValues(node.id, eventId, state, contentTypeNodeId, input.values)
2262
+ await repo.#writeWorkspaceCultures(node.id, eventId, input.variants)
2263
+ await repo.#setWorkspaceDocument(node.id, { edited: true })
2264
+ return repo.#load(node)
2265
+ }
2266
+ await repo.nodes.rename(node.id, name)
1068
2267
  const eventId = await repo.#insertEvent(
1069
2268
  node.id,
1070
2269
  'save',
@@ -1104,8 +2303,9 @@ export class DocumentRepository {
1104
2303
  const repo = this.#child(tx)
1105
2304
  await assertNodeMayWrite(tx, this.#nodeState)
1106
2305
  const node = await repo.nodes.byKey(key)
1107
- if (!node) return undefined
2306
+ if (!node || !repo.sees(node)) return undefined
1108
2307
  await repo.#assertRevision(node.id, options.expectedRevision)
2308
+ if (repo.#workspace !== undefined) return repo.#publishInWorkspace(node, cultures)
1109
2309
  if (options.expectedHead !== undefined) {
1110
2310
  const head = (await repo.#headEvent(node.id))?.id
1111
2311
  if (head !== options.expectedHead)
@@ -1153,7 +2353,11 @@ export class DocumentRepository {
1153
2353
  .updateTable('document_version')
1154
2354
  .set({ published: f })
1155
2355
  .where('id', 'in', (eb) =>
1156
- eb.selectFrom('content_version').select('id').where('node_id', '=', node.id),
2356
+ eb
2357
+ .selectFrom('content_version')
2358
+ .select('id')
2359
+ .where('node_id', '=', node.id)
2360
+ .where('workspace_id', 'is', null),
1157
2361
  )
1158
2362
  .execute()
1159
2363
  const eventId = await repo.#insertEvent(
@@ -1247,7 +2451,8 @@ export class DocumentRepository {
1247
2451
  const repo = this.#child(tx)
1248
2452
  await assertNodeMayWrite(tx, this.#nodeState)
1249
2453
  const node = await repo.nodes.byKey(key)
1250
- if (!node) return undefined
2454
+ if (!node || !repo.sees(node)) return undefined
2455
+ if (repo.#workspace !== undefined) return repo.#unpublishInWorkspace(node, cultures)
1251
2456
 
1252
2457
  const mandatory = new Set(
1253
2458
  (await repo.#languages()).filter((l) => l.isMandatory).map((l) => l.isoCode.toLowerCase()),
@@ -1262,7 +2467,11 @@ export class DocumentRepository {
1262
2467
  .updateTable('document_version')
1263
2468
  .set({ published: tx.dialect.boolValue(false) as boolean })
1264
2469
  .where('id', 'in', (eb) =>
1265
- eb.selectFrom('content_version').select('id').where('node_id', '=', node.id),
2470
+ eb
2471
+ .selectFrom('content_version')
2472
+ .select('id')
2473
+ .where('node_id', '=', node.id)
2474
+ .where('workspace_id', 'is', null),
1266
2475
  )
1267
2476
  .execute()
1268
2477
  await tx.q
@@ -1302,6 +2511,7 @@ export class DocumentRepository {
1302
2511
  versionId: string,
1303
2512
  options: { expectedRevision?: string } = {},
1304
2513
  ): Promise<DocumentAggregate | undefined> {
2514
+ this.#refuseInWorkspace('An earlier version can be brought back in Shared only, for now.')
1305
2515
  return this.#withTree(() => this.#rollback(versionId, options.expectedRevision))
1306
2516
  }
1307
2517
 
@@ -1316,17 +2526,39 @@ export class DocumentRepository {
1316
2526
  }
1317
2527
 
1318
2528
  async #revision(nodeId: number): Promise<string> {
2529
+ if (await this.#workspaceDocument(nodeId)) {
2530
+ const workspace = this.#workspace as number
2531
+ const mine = await this.#db.q
2532
+ .selectNoFrom((eb) => [
2533
+ eb
2534
+ .selectFrom('content_version')
2535
+ .select((e) => e.fn.max('id').as('id'))
2536
+ .where('node_id', '=', nodeId)
2537
+ .where('workspace_id', '=', workspace)
2538
+ .as('head'),
2539
+ eb
2540
+ .selectFrom('property_value')
2541
+ .select((e) => e.fn.max('id').as('id'))
2542
+ .where('node_id', '=', nodeId)
2543
+ .where('workspace_id', '=', workspace)
2544
+ .as('value'),
2545
+ ])
2546
+ .execute()
2547
+ return revisionString(mine[0]?.head, mine[0]?.value)
2548
+ }
1319
2549
  const rows = await this.#db.q
1320
2550
  .selectNoFrom((eb) => [
1321
2551
  eb
1322
2552
  .selectFrom('content_version')
1323
2553
  .select((e) => e.fn.max('id').as('id'))
1324
2554
  .where('node_id', '=', nodeId)
2555
+ .where('workspace_id', 'is', null)
1325
2556
  .as('head'),
1326
2557
  eb
1327
2558
  .selectFrom('property_value')
1328
2559
  .select((e) => e.fn.max('id').as('id'))
1329
2560
  .where('node_id', '=', nodeId)
2561
+ .where('workspace_id', 'is', null)
1330
2562
  .as('value'),
1331
2563
  ])
1332
2564
  .execute()
@@ -1410,6 +2642,7 @@ export class DocumentRepository {
1410
2642
  async moveToRecycleBin(key: string): Promise<boolean> {
1411
2643
  const bin = this.#recycleBin
1412
2644
  if (bin === undefined) return false
2645
+ if (this.#workspace !== undefined) return this.#removeInWorkspace(key, 'trash')
1413
2646
  return this.#withTree(() =>
1414
2647
  this.#db.transaction(async (tx) => {
1415
2648
  const repo = this.#child(tx)
@@ -1465,9 +2698,31 @@ export class DocumentRepository {
1465
2698
  }
1466
2699
 
1467
2700
  async delete(key: string): Promise<boolean> {
2701
+ if (this.#workspace !== undefined) return this.#removeInWorkspace(key, 'delete')
1468
2702
  return this.#withTree(() => this.#delete(key))
1469
2703
  }
1470
2704
 
2705
+ /**
2706
+ * A delete in a workspace: a page made there goes, with its branch; a Shared
2707
+ * page is recorded as going, and goes at merge (story 375).
2708
+ */
2709
+ async #removeInWorkspace(key: string, kind: 'trash' | 'delete'): Promise<boolean> {
2710
+ return this.#withTree(() =>
2711
+ this.#db.transaction(async (tx) => {
2712
+ const repo = this.#child(tx)
2713
+ const node = await repo.nodes.byKey(key)
2714
+ if (!node || !repo.sees(node)) return false
2715
+ if (node.workspaceId === this.#workspace) await deleteNodeRows(tx, { branch: node })
2716
+ else await repo.#recordPending(node, kind)
2717
+ return true
2718
+ }),
2719
+ )
2720
+ }
2721
+
2722
+ #refuseInWorkspace(reason: string): void {
2723
+ if (this.#workspace !== undefined) throw new WorkspaceRefusedError(reason)
2724
+ }
2725
+
1471
2726
  async #delete(key: string): Promise<boolean> {
1472
2727
  return this.#db.transaction(async (tx) => {
1473
2728
  const node = await new NodeRepository(tx).byKey(key)
@@ -1500,7 +2755,21 @@ export class DocumentRepository {
1500
2755
  const repo = this.#child(tx)
1501
2756
  await assertNodeMayWrite(tx, this.#nodeState)
1502
2757
  const node = await repo.nodes.byKey(key)
1503
- if (!node || node.objectType !== this.objectType) return 'notFound'
2758
+ if (!node || !repo.sees(node)) return 'notFound'
2759
+ if (this.#workspace !== undefined) {
2760
+ const target = targetKey ? await repo.nodes.byKey(targetKey) : undefined
2761
+ if (targetKey && (!target || !repo.sees(target))) return 'notFound'
2762
+ if (target && (target.id === node.id || target.path.startsWith(`${node.path},`)))
2763
+ return 'invalid'
2764
+ // A page made here moves; a Shared page's move waits for the merge.
2765
+ if (node.workspaceId === this.#workspace)
2766
+ await repo.nodes.move(node.id, target?.id ?? SystemNodes.Root)
2767
+ else
2768
+ await repo.#recordPending(node, 'move', {
2769
+ targetParentId: target?.id ?? SystemNodes.Root,
2770
+ })
2771
+ return 'moved'
2772
+ }
1504
2773
  const target = targetKey ? await repo.nodes.byKey(targetKey) : undefined
1505
2774
  const container = KINDS[this.kind].container
1506
2775
  if (
@@ -1562,6 +2831,7 @@ export class DocumentRepository {
1562
2831
  targetKey: string | null,
1563
2832
  options: { includeDescendants: boolean; userId?: number },
1564
2833
  ): Promise<string | undefined> {
2834
+ this.#refuseInWorkspace('Copying a page is done in Shared only, for now.')
1565
2835
  const source = await this.byKey(key)
1566
2836
  if (!source) return undefined
1567
2837
  if (targetKey) {
@@ -1617,17 +2887,21 @@ export class DocumentRepository {
1617
2887
  const byKey = new Map(nodes.map((n) => [n.key, n]))
1618
2888
  for (const item of sorting) {
1619
2889
  const node = byKey.get(normaliseUuid(item.key))
1620
- if (!node || node.parentId !== parentId || node.objectType !== this.objectType)
1621
- return 'notFound'
2890
+ if (!node || node.parentId !== parentId || !this.sees(node)) return 'notFound'
1622
2891
  }
1623
2892
  for (const item of sorting) {
1624
2893
  const node = byKey.get(normaliseUuid(item.key)) as NodeRow
2894
+ if (this.#workspace !== undefined && node.workspaceId !== this.#workspace) {
2895
+ // Shared's order is kept until the merge.
2896
+ await this.#child(tx).#recordPending(node, 'sort', { sortOrder: item.sortOrder })
2897
+ continue
2898
+ }
1625
2899
  await tx.q
1626
2900
  .updateTable('node')
1627
2901
  .set({ sort_order: item.sortOrder })
1628
2902
  .where('id', '=', node.id)
1629
2903
  .execute()
1630
- await this.#child(tx).#instructContent(node.key)
2904
+ if (this.#workspace === undefined) await this.#child(tx).#instructContent(node.key)
1631
2905
  }
1632
2906
  return 'sorted'
1633
2907
  }),
@@ -1671,6 +2945,7 @@ export class DocumentRepository {
1671
2945
  key: string,
1672
2946
  targetKey: string | null | undefined,
1673
2947
  ): Promise<'restored' | 'notFound' | 'invalid'> {
2948
+ this.#refuseInWorkspace('The recycle bin is Shared’s: restore a page there.')
1674
2949
  return this.#withTree(async () =>
1675
2950
  this.#db.transaction(async (tx) => {
1676
2951
  const repo = this.#child(tx)
@@ -1718,6 +2993,9 @@ export class DocumentRepository {
1718
2993
  cultures: readonly string[] | null,
1719
2994
  includeUnpublished: boolean,
1720
2995
  ): Promise<{ published: string[]; failed: Array<{ key: string; reason: string }> } | undefined> {
2996
+ this.#refuseInWorkspace(
2997
+ 'Publish each page in a workspace; a whole branch is published in Shared.',
2998
+ )
1721
2999
  return this.#withTree(() => this.#publishBranch(key, cultures, includeUnpublished))
1722
3000
  }
1723
3001
 
@@ -1826,8 +3104,9 @@ export class DocumentRepository {
1826
3104
  }>,
1827
3105
  ): Promise<boolean> {
1828
3106
  const node = await this.#nodes.byKey(key)
1829
- if (!node || node.objectType !== this.objectType) return false
3107
+ if (!node || !this.sees(node)) return false
1830
3108
  const languages = await this.#languages()
3109
+ const workspace = this.#workspace ?? null
1831
3110
  await this.#db.transaction(async (tx) => {
1832
3111
  for (const entry of entries) {
1833
3112
  const languageId = entry.culture
@@ -1838,12 +3117,19 @@ export class DocumentRepository {
1838
3117
  .deleteFrom('content_schedule')
1839
3118
  .where('node_id', '=', node.id)
1840
3119
  .where('language_id', languageId === null ? 'is' : '=', languageId)
3120
+ .where('workspace_id', workspace === null ? 'is' : '=', workspace)
1841
3121
  .execute()
1842
3122
  const add = async (action: 'Release' | 'Expire', date: Date | null) => {
1843
3123
  if (!date) return
1844
3124
  await tx.q
1845
3125
  .insertInto('content_schedule')
1846
- .values({ node_id: node.id, language_id: languageId, action, date: DbDate.toDb(date) })
3126
+ .values({
3127
+ node_id: node.id,
3128
+ language_id: languageId,
3129
+ action,
3130
+ date: DbDate.toDb(date),
3131
+ workspace_id: workspace,
3132
+ })
1847
3133
  .execute()
1848
3134
  }
1849
3135
  await add('Release', entry.publishTime)
@@ -1865,6 +3151,10 @@ export class DocumentRepository {
1865
3151
  .leftJoin('language as l', 'l.id', 's.language_id')
1866
3152
  .select(['s.id', 's.action', 's.date', 'l.iso_code'])
1867
3153
  .where('s.node_id', '=', node.id)
3154
+ .$if(this.#workspace === undefined, (q) => q.where('s.workspace_id', 'is', null))
3155
+ .$if(this.#workspace !== undefined, (q) =>
3156
+ q.where('s.workspace_id', '=', this.#workspace as number),
3157
+ )
1868
3158
  .orderBy('s.date')
1869
3159
  .execute()
1870
3160
  return rows.map((row) => ({
@@ -1888,6 +3178,8 @@ export class DocumentRepository {
1888
3178
  .select(['s.id', 's.action', 'n.unique_id', 'l.iso_code'])
1889
3179
  .where('s.date', '<=', DbDate.toDb(now))
1890
3180
  .where('n.node_object_type', '=', this.objectType)
3181
+ // A workspace's schedules wait for it to be served (story 379).
3182
+ .where('s.workspace_id', 'is', null)
1891
3183
  .orderBy('s.date')
1892
3184
  .orderBy('s.id')
1893
3185
  .execute()
@@ -1973,6 +3265,7 @@ export class DocumentRepository {
1973
3265
  .innerJoin('document_version as dv', 'dv.id', 'cv.id')
1974
3266
  .select(['cv.id', 'cv.version_date', 'cv.current', 'cv.prevent_cleanup', 'dv.published'])
1975
3267
  .where('cv.node_id', '=', nodeId)
3268
+ .where('cv.workspace_id', 'is', null)
1976
3269
  .orderBy('cv.id')
1977
3270
  .execute()
1978
3271
  ).map((row) => ({
@@ -1981,6 +3274,18 @@ export class DocumentRepository {
1981
3274
  pinned:
1982
3275
  fromDbBool(row.current) || fromDbBool(row.published) || fromDbBool(row.prevent_cleanup),
1983
3276
  }))
3277
+ // A workspace reads Shared as of the event it started from, so that event stays (story 375).
3278
+ const bases = new Set(
3279
+ (
3280
+ await this.#db.q
3281
+ .selectFrom('workspace_document')
3282
+ .select('base_event_id')
3283
+ .where('node_id', '=', nodeId)
3284
+ .where('base_event_id', 'is not', null)
3285
+ .execute()
3286
+ ).map((row) => Number(row.base_event_id)),
3287
+ )
3288
+ for (const event of events) if (bases.has(event.id)) event.pinned = true
1984
3289
  const kept = new Set<number>()
1985
3290
  const latestPerDay = new Map<string, number>()
1986
3291
  for (const event of events) {
@@ -1998,8 +3303,9 @@ export class DocumentRepository {
1998
3303
 
1999
3304
  const rows = await this.#db.q
2000
3305
  .selectFrom('property_value')
2001
- .select(['id', 'property_type_id', 'language_id', 'segment', 'event_id'])
3306
+ .select(['id', 'property_type_id', 'language_id', 'segment', 'environment', 'event_id'])
2002
3307
  .where('node_id', '=', nodeId)
3308
+ .where('workspace_id', 'is', null)
2003
3309
  .orderBy('event_id')
2004
3310
  .orderBy('id')
2005
3311
  .execute()
@@ -2010,6 +3316,7 @@ export class DocumentRepository {
2010
3316
  Number(row.property_type_id),
2011
3317
  row.language_id === null ? null : Number(row.language_id),
2012
3318
  row.segment,
3319
+ row.environment,
2013
3320
  )
2014
3321
  const list = eventsByKey.get(key) ?? []
2015
3322
  if (list.at(-1) !== Number(row.event_id)) list.push(Number(row.event_id))
@@ -2022,6 +3329,7 @@ export class DocumentRepository {
2022
3329
  Number(row.property_type_id),
2023
3330
  row.language_id === null ? null : Number(row.language_id),
2024
3331
  row.segment,
3332
+ row.environment,
2025
3333
  )
2026
3334
  const written = eventsByKey.get(key) as number[]
2027
3335
  const next = written[written.indexOf(eventId) + 1] ?? Number.POSITIVE_INFINITY
@@ -2085,6 +3393,8 @@ export class DocumentRepository {
2085
3393
  // ------------------------------------------------------------ internals
2086
3394
 
2087
3395
  async #load(node: NodeRow): Promise<DocumentAggregate | undefined> {
3396
+ const touched = await this.#workspaceDocument(node.id)
3397
+ if (touched) return this.#loadInWorkspace(node, touched)
2088
3398
  const t = this.#db.dialect.boolValue(true) as boolean
2089
3399
  const rows = await this.#db.q
2090
3400
  .selectFrom('node as n')
@@ -2128,11 +3438,13 @@ export class DocumentRepository {
2128
3438
  .selectFrom('content_version as cvm')
2129
3439
  .select((e) => e.fn.max('cvm.id').as('id'))
2130
3440
  .whereRef('cvm.node_id', '=', 'n.id')
3441
+ .where('cvm.workspace_id', 'is', null)
2131
3442
  .as('head_id'),
2132
3443
  eb
2133
3444
  .selectFrom('property_value as pvm')
2134
3445
  .select((e) => e.fn.max('pvm.id').as('id'))
2135
3446
  .whereRef('pvm.node_id', '=', 'n.id')
3447
+ .where('pvm.workspace_id', 'is', null)
2136
3448
  .as('last_value_id'),
2137
3449
  ])
2138
3450
  .where('n.id', '=', node.id)
@@ -2233,12 +3545,50 @@ export class DocumentRepository {
2233
3545
  }
2234
3546
 
2235
3547
  /** Property types of a content type, including everything it composes; retired ones excluded. */
3548
+ /** A type made in this workspace, by the key it stands for (story 376). */
3549
+ async #workspaceTypeNode(key: string): Promise<NodeRow | undefined> {
3550
+ if (this.#workspace === undefined) return undefined
3551
+ const rows = await this.#db.q
3552
+ .selectFrom('content_type')
3553
+ .select('node_id')
3554
+ .where('workspace_id', '=', this.#workspace)
3555
+ .where('origin_key', '=', normaliseUuid(key))
3556
+ .where('retired_at', 'is', null)
3557
+ .execute()
3558
+ return rows[0] ? this.#nodes.byId(Number(rows[0].node_id)) : undefined
3559
+ }
3560
+
3561
+ /**
3562
+ * The type a page is read and written by: in a workspace, its copy of the
3563
+ * page's type where it has one (story 376), and the page's own otherwise.
3564
+ */
3565
+ async #readTypeNodeId(contentTypeNodeId: number): Promise<number> {
3566
+ if (this.#workspace === undefined) return contentTypeNodeId
3567
+ const key = (await this.#nodes.byId(contentTypeNodeId))?.key
3568
+ if (!key) return contentTypeNodeId
3569
+ const rows = await this.#db.q
3570
+ .selectFrom('content_type')
3571
+ .select('node_id')
3572
+ .where('workspace_id', '=', this.#workspace)
3573
+ .where('origin_key', '=', normaliseUuid(key))
3574
+ .where('retired_at', 'is', null)
3575
+ .execute()
3576
+ return rows[0] ? Number(rows[0].node_id) : contentTypeNodeId
3577
+ }
3578
+
2236
3579
  async #propertyTypes(contentTypeNodeId: number): Promise<PropertyTypeRow[]> {
2237
- const rows = await this.#withAncestry(contentTypeNodeId)
3580
+ const rows = await this.#withAncestry(await this.#readTypeNodeId(contentTypeNodeId))
2238
3581
  .selectFrom('property_type as p')
2239
3582
  .innerJoin('data_type as d', 'd.node_id', 'p.data_type_id')
2240
3583
  .leftJoin('schema_state as ss', 'ss.id', 'p.since_state_id')
3584
+ // A workspace's copy of a property reads and writes Shared's values while
3585
+ // they are stored the same way; a changed storage reads empty (story 376).
3586
+ .leftJoin('property_type as sp', 'sp.unique_id', 'p.origin_key')
3587
+ .leftJoin('data_type as sd', 'sd.node_id', 'sp.data_type_id')
2241
3588
  .select([
3589
+ 'sp.id as shared_id',
3590
+ 'sd.db_type as shared_db_type',
3591
+ 'sp.variations as shared_variations',
2242
3592
  'p.id',
2243
3593
  'p.alias',
2244
3594
  'p.name',
@@ -2260,7 +3610,13 @@ export class DocumentRepository {
2260
3610
  .orderBy('p.id')
2261
3611
  .execute()
2262
3612
  return rows.map((row) => ({
2263
- id: Number(row.id),
3613
+ id:
3614
+ row.shared_id !== null &&
3615
+ row.shared_id !== undefined &&
3616
+ String(row.shared_db_type) === String(row.db_type) &&
3617
+ Number(row.shared_variations) === Number(row.variations)
3618
+ ? Number(row.shared_id)
3619
+ : Number(row.id),
2264
3620
  alias: String(row.alias),
2265
3621
  name: String(row.name),
2266
3622
  variesByCulture: flagVariesByCulture(Number(row.variations)),
@@ -2290,6 +3646,8 @@ export class DocumentRepository {
2290
3646
  * to the editor on an old node as well as to its renderer.
2291
3647
  */
2292
3648
  async #visibleValueRows(nodeId: number): Promise<ValueRow[]> {
3649
+ const touched = await this.#workspaceDocument(nodeId)
3650
+ if (touched) return this.#workspaceView(nodeId, touched)
2293
3651
  const stateId = await visibleStateIdFor(this.#db, this.#nodeState)
2294
3652
  return stateId === undefined
2295
3653
  ? this.#currentValueRows(nodeId)
@@ -2305,6 +3663,7 @@ export class DocumentRepository {
2305
3663
  'property_type_id',
2306
3664
  'language_id',
2307
3665
  'segment',
3666
+ 'environment',
2308
3667
  'int_value',
2309
3668
  'decimal_value',
2310
3669
  'date_value',
@@ -2329,13 +3688,20 @@ export class DocumentRepository {
2329
3688
  (eb) =>
2330
3689
  eb
2331
3690
  .selectFrom('property_value')
2332
- .select((e) => ['property_type_id', 'language_id', 'segment', e.fn.max('id').as('id')])
3691
+ .select((e) => [
3692
+ 'property_type_id',
3693
+ 'language_id',
3694
+ 'segment',
3695
+ 'environment',
3696
+ e.fn.max('id').as('id'),
3697
+ ])
2333
3698
  .where('node_id', '=', nodeId)
3699
+ .where('workspace_id', 'is', null)
2334
3700
  .$if(eventId !== undefined, (q) => q.where('event_id', '<=', eventId as number))
2335
3701
  .$if(schemaStateId !== undefined, (q) =>
2336
3702
  q.where('schema_state_id', '<=', schemaStateId as number),
2337
3703
  )
2338
- .groupBy(['property_type_id', 'language_id', 'segment'])
3704
+ .groupBy(['property_type_id', 'language_id', 'segment', 'environment'])
2339
3705
  .as('latest'),
2340
3706
  (join) => join.onRef('latest.id', '=', 'pv.id'),
2341
3707
  )
@@ -2345,6 +3711,7 @@ export class DocumentRepository {
2345
3711
  'pv.property_type_id',
2346
3712
  'pv.language_id',
2347
3713
  'pv.segment',
3714
+ 'pv.environment',
2348
3715
  'pv.int_value',
2349
3716
  'pv.decimal_value',
2350
3717
  'pv.date_value',
@@ -2362,6 +3729,7 @@ export class DocumentRepository {
2362
3729
  languageId:
2363
3730
  row.language_id === null || row.language_id === undefined ? null : Number(row.language_id),
2364
3731
  segment: (row.segment as string | null) ?? null,
3732
+ environment: (row.environment as string | null) ?? null,
2365
3733
  eventId: Number(row.event_id),
2366
3734
  raw: row,
2367
3735
  }
@@ -2399,6 +3767,7 @@ export class DocumentRepository {
2399
3767
  alias: propertyType.alias,
2400
3768
  culture: row.languageId === null ? null : (isoById.get(row.languageId) ?? null),
2401
3769
  segment: row.segment,
3770
+ ...(row.environment ? { environment: row.environment } : {}),
2402
3771
  value: toEditorValue(propertyType.editorAlias, value),
2403
3772
  editorAlias: propertyType.editorAlias,
2404
3773
  config: propertyType.config,
@@ -2469,13 +3838,16 @@ export class DocumentRepository {
2469
3838
  // row superseded is the true current one.
2470
3839
  const current = new Map(
2471
3840
  (await this.#visibleValueRows(nodeId)).map((row) => [
2472
- keyOf(row.propertyTypeId, row.languageId, row.segment),
3841
+ keyOf(row.propertyTypeId, row.languageId, row.segment, row.environment),
2473
3842
  row,
2474
3843
  ]),
2475
3844
  )
2476
3845
  const trueCurrent = new Map(
2477
- (await this.#currentValueRows(nodeId)).map((row) => [
2478
- keyOf(row.propertyTypeId, row.languageId, row.segment),
3846
+ (this.#workspace !== undefined
3847
+ ? [...current.values()]
3848
+ : await this.#currentValueRows(nodeId)
3849
+ ).map((row) => [
3850
+ keyOf(row.propertyTypeId, row.languageId, row.segment, row.environment),
2479
3851
  row,
2480
3852
  ]),
2481
3853
  )
@@ -2486,7 +3858,12 @@ export class DocumentRepository {
2486
3858
  if (!propertyType) continue
2487
3859
  const culture = propertyType.variesByCulture ? value.culture : null
2488
3860
  const languageId = culture ? (idByIso.get(culture.toLowerCase()) ?? null) : null
2489
- const key = keyOf(propertyType.id, languageId, value.segment ?? null)
3861
+ const key = keyOf(
3862
+ propertyType.id,
3863
+ languageId,
3864
+ value.segment ?? null,
3865
+ value.environment ?? null,
3866
+ )
2490
3867
  if (seen.has(key)) continue
2491
3868
  seen.add(key)
2492
3869
  const existing = current.get(key)
@@ -2502,15 +3879,20 @@ export class DocumentRepository {
2502
3879
  propertyType,
2503
3880
  languageId,
2504
3881
  value.segment ?? null,
3882
+ value.environment ?? null,
2505
3883
  value.value,
2506
3884
  trueCurrent.get(key)?.id ?? existing?.id,
2507
3885
  )
2508
3886
  }
2509
- // A value that was current but is no longer sent is cleared, as a version.
3887
+ // A value that was current but is no longer sent is cleared, as a version. A
3888
+ // property's environment values stay unless the save sends some for it: the
3889
+ // editor sends only the shared value (story 387).
3890
+ const sendsEnvironment = new Set(values.filter((v) => v.environment).map((v) => v.alias))
2510
3891
  for (const [key, row] of current) {
2511
3892
  if (seen.has(key)) continue
2512
3893
  const propertyType = byId.get(row.propertyTypeId)
2513
3894
  if (!propertyType) continue
3895
+ if (row.environment && !sendsEnvironment.has(propertyType.alias)) continue
2514
3896
  const raw = (row.raw as Record<string, unknown>)[STORAGE_COLUMN[propertyType.storage]]
2515
3897
  if (raw === null || raw === undefined) continue
2516
3898
  await this.#insertValue(
@@ -2520,6 +3902,7 @@ export class DocumentRepository {
2520
3902
  propertyType,
2521
3903
  row.languageId,
2522
3904
  row.segment,
3905
+ row.environment,
2523
3906
  null,
2524
3907
  trueCurrent.get(key)?.id ?? row.id,
2525
3908
  )
@@ -2562,13 +3945,16 @@ export class DocumentRepository {
2562
3945
  })
2563
3946
  }
2564
3947
  const currentByKey = new Map(
2565
- current.map((row) => [keyOf(row.propertyTypeId, row.languageId, row.segment), row]),
3948
+ current.map((row) => [
3949
+ keyOf(row.propertyTypeId, row.languageId, row.segment, row.environment),
3950
+ row,
3951
+ ]),
2566
3952
  )
2567
3953
  const seen = new Set<string>()
2568
3954
  for (const row of target) {
2569
3955
  const propertyType = types.get(row.propertyTypeId)
2570
3956
  if (!propertyType) continue
2571
- const key = keyOf(row.propertyTypeId, row.languageId, row.segment)
3957
+ const key = keyOf(row.propertyTypeId, row.languageId, row.segment, row.environment)
2572
3958
  seen.add(key)
2573
3959
  const column = STORAGE_COLUMN[propertyType.storage]
2574
3960
  const wanted = this.#fromStorage(
@@ -2592,6 +3978,7 @@ export class DocumentRepository {
2592
3978
  propertyType,
2593
3979
  row.languageId,
2594
3980
  row.segment,
3981
+ row.environment,
2595
3982
  wanted,
2596
3983
  existing?.id,
2597
3984
  )
@@ -2607,6 +3994,7 @@ export class DocumentRepository {
2607
3994
  propertyType,
2608
3995
  row.languageId,
2609
3996
  row.segment,
3997
+ row.environment,
2610
3998
  null,
2611
3999
  row.id,
2612
4000
  )
@@ -2620,11 +4008,14 @@ export class DocumentRepository {
2620
4008
  propertyType: PropertyTypeRow,
2621
4009
  languageId: number | null,
2622
4010
  segment: string | null,
4011
+ environment: string | null,
2623
4012
  value: unknown,
2624
4013
  supersedes: number | undefined,
2625
4014
  ): Promise<void> {
2626
4015
  const column = STORAGE_COLUMN[propertyType.storage]
2627
- if (supersedes !== undefined) {
4016
+ // A workspace's value is never current: Shared's stays what everyone reads.
4017
+ const inWorkspace = this.#workspace !== undefined
4018
+ if (supersedes !== undefined && !inWorkspace) {
2628
4019
  await this.#db.q
2629
4020
  .updateTable('property_value')
2630
4021
  .set({ is_current: this.#db.dialect.boolValue(false) as boolean })
@@ -2638,9 +4029,11 @@ export class DocumentRepository {
2638
4029
  property_type_id: propertyType.id,
2639
4030
  language_id: languageId,
2640
4031
  segment,
4032
+ environment,
2641
4033
  event_id: eventId,
2642
4034
  schema_state_id: schemaStateId,
2643
- is_current: this.#db.dialect.boolValue(true) as boolean,
4035
+ is_current: this.#db.dialect.boolValue(!inWorkspace) as boolean,
4036
+ workspace_id: this.#workspace ?? null,
2644
4037
  [column]: this.#toStorage(value, propertyType.storage),
2645
4038
  sortable_value: typeof value === 'string' ? value.slice(0, 512) : null,
2646
4039
  } as Insertable<CoreTables['property_value']>)
@@ -2805,6 +4198,15 @@ export class DocumentRepository {
2805
4198
  if (rows.length === 0) return []
2806
4199
  const ids = rows.map((row) => row.id)
2807
4200
  const counts = await this.#nodes.childCounts(ids, this.objectType)
4201
+ if (this.#workspace !== undefined)
4202
+ for (const row of await this.#db.q
4203
+ .selectFrom('node')
4204
+ .select((eb) => ['parent_id', eb.fn.countAll().as('n')])
4205
+ .where('parent_id', 'in', ids)
4206
+ .where('workspace_id', '=', this.#workspace)
4207
+ .groupBy('parent_id')
4208
+ .execute())
4209
+ counts.set(Number(row.parent_id), (counts.get(Number(row.parent_id)) ?? 0) + Number(row.n))
2808
4210
  const facts = await this.#db.q
2809
4211
  .selectFrom('node as n')
2810
4212
  .innerJoin('content as c', 'c.node_id', 'n.id')
@@ -2890,7 +4292,37 @@ export class DocumentRepository {
2890
4292
 
2891
4293
  const items: DocumentTreeItem[] = []
2892
4294
  for (const row of rows) {
4295
+ // A page the workspace changed or made is named and stated as it is there.
4296
+ const touched = await this.#workspaceDocument(row.id)
4297
+ const mine = touched ? await this.#loadInWorkspace(row, touched) : undefined
2893
4298
  const fact = factsById.get(row.id)
4299
+ if (mine) {
4300
+ const parent = row.parentId > 0 ? above.get(row.parentId) : undefined
4301
+ items.push({
4302
+ workspaceChanged: true,
4303
+ key: row.key,
4304
+ name: mine.variants[0]?.name ?? row.text ?? '',
4305
+ hasChildren: (counts.get(row.id) ?? 0) > 0,
4306
+ parentKey: parent ? parent.key : null,
4307
+ contentTypeKey: mine.contentTypeKey,
4308
+ contentTypeCollectionKey: mine.contentTypeCollectionKey,
4309
+ icon: mine.contentTypeIcon,
4310
+ isTrashed: row.trashed,
4311
+ createDate: row.createDate ?? new Date(),
4312
+ ancestorKeys: pathIds(row)
4313
+ .map((id) => above.get(id))
4314
+ .filter((n): n is NodeRow => n !== undefined && this.sees(n))
4315
+ .map((a) => a.key),
4316
+ isProtected: guarded.has(row.id) || pathIds(row).some((id) => guarded.has(id)),
4317
+ variants: mine.variants.map((v) => ({
4318
+ culture: v.culture,
4319
+ name: v.name,
4320
+ state: v.state,
4321
+ scheduledForPublish: scheduled(row.id, v.culture),
4322
+ })),
4323
+ })
4324
+ continue
4325
+ }
2894
4326
  if (!fact) continue
2895
4327
  const ancestors = pathIds(row)
2896
4328
  .map((id) => above.get(id))
@@ -2974,6 +4406,7 @@ export class DocumentRepository {
2974
4406
  .updateTable('content_version')
2975
4407
  .set({ current: f })
2976
4408
  .where('node_id', '=', nodeId)
4409
+ .where('workspace_id', 'is', null)
2977
4410
  .execute()
2978
4411
  await this.#db.q
2979
4412
  .insertInto('content_version')
@@ -2991,6 +4424,7 @@ export class DocumentRepository {
2991
4424
  .selectFrom('content_version')
2992
4425
  .select((eb) => eb.fn.max('id').as('id'))
2993
4426
  .where('node_id', '=', nodeId)
4427
+ .where('workspace_id', 'is', null)
2994
4428
  .execute()
2995
4429
  const eventId = Number(rows[0]?.id)
2996
4430
  await this.#db.q
@@ -3016,6 +4450,7 @@ export class DocumentRepository {
3016
4450
  .innerJoin('document_version as dv', 'dv.id', 'cv.id')
3017
4451
  .select(['cv.id', 'cv.text', 'cv.user_id', 'dv.template_id'])
3018
4452
  .where('cv.node_id', '=', nodeId)
4453
+ .where('cv.workspace_id', 'is', null)
3019
4454
  .orderBy('cv.id', 'desc')
3020
4455
  .limit(1)
3021
4456
  .execute()
@@ -3050,6 +4485,7 @@ export class DocumentRepository {
3050
4485
  .selectFrom('property_value')
3051
4486
  .select((eb) => eb.fn.countAll().as('n'))
3052
4487
  .where('node_id', '=', nodeId)
4488
+ .where('workspace_id', 'is', null)
3053
4489
  .where('event_id', '>', publishedId)
3054
4490
  .execute()
3055
4491
  const names = await this.#db.q
@@ -3058,6 +4494,7 @@ export class DocumentRepository {
3058
4494
  .selectFrom('content_version')
3059
4495
  .select('text')
3060
4496
  .where('node_id', '=', nodeId)
4497
+ .where('workspace_id', 'is', null)
3061
4498
  .orderBy('id', 'desc')
3062
4499
  .limit(1)
3063
4500
  .as('head'),
@@ -3077,6 +4514,7 @@ export class DocumentRepository {
3077
4514
  .selectFrom('property_value')
3078
4515
  .select((eb) => eb.fn.countAll().as('n'))
3079
4516
  .where('node_id', '=', nodeId)
4517
+ .where('workspace_id', 'is', null)
3080
4518
  .where('event_id', '>', culture.eventId)
3081
4519
  .where((eb) =>
3082
4520
  eb.or([eb('language_id', '=', culture.languageId), eb('language_id', 'is', null)]),
@@ -3327,6 +4765,7 @@ export class DocumentRepository {
3327
4765
  'property_type_id',
3328
4766
  'language_id',
3329
4767
  'segment',
4768
+ 'environment',
3330
4769
  'int_value',
3331
4770
  'decimal_value',
3332
4771
  'date_value',
@@ -3334,6 +4773,7 @@ export class DocumentRepository {
3334
4773
  'text_value',
3335
4774
  ])
3336
4775
  .where('node_id', 'in', ids)
4776
+ .where('workspace_id', 'is', null)
3337
4777
  .$if(schemaStateId !== undefined, (q) =>
3338
4778
  q.where('schema_state_id', '<=', schemaStateId as number),
3339
4779
  )
@@ -3403,6 +4843,7 @@ export class DocumentRepository {
3403
4843
  'property_type_id',
3404
4844
  'language_id',
3405
4845
  'segment',
4846
+ 'environment',
3406
4847
  'int_value',
3407
4848
  'decimal_value',
3408
4849
  'date_value',
@@ -3410,6 +4851,7 @@ export class DocumentRepository {
3410
4851
  'text_value',
3411
4852
  ])
3412
4853
  .where('node_id', '=', nodeId)
4854
+ .where('workspace_id', 'is', null)
3413
4855
  .where('event_id', '<=', latest)
3414
4856
  .$if(schemaStateId !== undefined, (q) =>
3415
4857
  q.where('schema_state_id', '<=', schemaStateId as number),
@@ -3492,16 +4934,49 @@ export async function latestContentVersionId(db: Db): Promise<number> {
3492
4934
  const rows = await db.q
3493
4935
  .selectFrom('content_version')
3494
4936
  .select((eb) => eb.fn.max('id').as('n'))
4937
+ .where('workspace_id', 'is', null)
3495
4938
  .execute()
3496
4939
  return Number(rows[0]?.n ?? 0)
3497
4940
  }
3498
4941
 
4942
+ /** Each top-most workspace page beneath `branch`, moved to the top of the tree and marked orphaned. */
4943
+ async function keepWorkspacePages(tx: Db, branch: Pick<NodeRow, 'id' | 'path'>): Promise<void> {
4944
+ const found = await tx.q
4945
+ .selectFrom('node')
4946
+ .select(['id', 'path', 'workspace_id'])
4947
+ .where('path', 'like', `${branch.path},%`)
4948
+ .where('workspace_id', 'is not', null)
4949
+ .orderBy('level')
4950
+ .execute()
4951
+ const nodes = new NodeRepository(tx)
4952
+ const moved: string[] = []
4953
+ for (const row of found) {
4954
+ const path = String(row.path)
4955
+ if (moved.some((top) => path.startsWith(`${top},`))) continue
4956
+ const id = Number(row.id)
4957
+ await nodes.move(id, SystemNodes.Root)
4958
+ moved.push(path)
4959
+ await tx.q
4960
+ .insertInto('workspace_pending')
4961
+ .values({
4962
+ workspace_id: Number(row.workspace_id),
4963
+ node_id: id,
4964
+ kind: 'orphaned',
4965
+ target_parent_id: null,
4966
+ sort_order: null,
4967
+ user_id: null,
4968
+ recorded_at: DbDate.toDb(new Date()),
4969
+ })
4970
+ .execute()
4971
+ }
4972
+ }
4973
+
3499
4974
  /**
3500
4975
  * Every row a node owns, then the node, for a branch (`branch`: the node and all
3501
4976
  * below it, by path) or a set of nodes (`ids`), a statement per table over the
3502
4977
  * whole set rather than one per node (story 246).
3503
4978
  */
3504
- async function deleteNodeRows(
4979
+ export async function deleteNodeRows(
3505
4980
  tx: Db,
3506
4981
  among: { branch: Pick<NodeRow, 'id' | 'path'> } | { ids: readonly number[] },
3507
4982
  ): Promise<void> {
@@ -3514,8 +4989,39 @@ async function deleteNodeRows(
3514
4989
  ? eb('id', 'in', [...among.ids])
3515
4990
  : eb.or([eb('id', '=', among.branch.id), eb('path', 'like', `${among.branch.path},%`)]),
3516
4991
  )
4992
+ // A page made in a workspace beneath a Shared page that goes is that workspace's
4993
+ // work: it moves to the top, marked for the merge to resolve (story 375).
4994
+ if (!('ids' in among)) await keepWorkspacePages(tx, among.branch)
3517
4995
  const versions = () =>
3518
4996
  tx.q.selectFrom('content_version').select('id').where('node_id', 'in', nodes())
4997
+ // A Shared page a workspace changed leaves a marker its merge must answer (story 380).
4998
+ const gone = await tx.q
4999
+ .selectFrom('workspace_document as wd')
5000
+ .innerJoin('node as n', 'n.id', 'wd.node_id')
5001
+ .select(['wd.workspace_id', 'n.id', 'n.text'])
5002
+ .where('n.id', 'in', nodes())
5003
+ .where('n.workspace_id', 'is', null)
5004
+ .execute()
5005
+ for (const table of [
5006
+ 'workspace_pending',
5007
+ 'workspace_document_culture',
5008
+ 'workspace_document',
5009
+ ] as const)
5010
+ await tx.q.deleteFrom(table).where('node_id', 'in', nodes()).execute()
5011
+ for (const row of gone)
5012
+ await tx.q
5013
+ .insertInto('workspace_pending')
5014
+ .values({
5015
+ workspace_id: Number(row.workspace_id),
5016
+ node_id: Number(row.id),
5017
+ kind: 'gone',
5018
+ target_parent_id: null,
5019
+ sort_order: null,
5020
+ user_id: null,
5021
+ recorded_at: DbDate.toDb(new Date()),
5022
+ name: (row.text as string | null) ?? null,
5023
+ })
5024
+ .execute()
3519
5025
  // Search providers outside the database lose nothing by cascade, so they are told (story 273).
3520
5026
  await recordSearchRemovals(
3521
5027
  tx,