@crombolo/content 0.76.0 → 0.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/content",
3
- "version": "0.76.0",
3
+ "version": "0.78.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The rules every page, media and Library write follows, whoever starts it: who may, where it may go, approvals, and what it announces. No transport.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -29,7 +29,7 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@crombolo/core": "0.76.0",
33
- "@crombolo/data": "0.76.0"
32
+ "@crombolo/core": "0.78.0",
33
+ "@crombolo/data": "0.78.0"
34
34
  }
35
35
  }
package/src/actor.ts CHANGED
@@ -57,6 +57,10 @@ export type Actor =
57
57
  user?: { id: string; name: string }
58
58
  /** Said with what it did, in notifications and the audit: `approved through "Legal"`. */
59
59
  note?: string
60
+ /** Story 414: the change whose schedule it carries out. */
61
+ change?: { key: string; name: string | null }
62
+ /** Story 413: the approval it carries out: the editor who asked, and the workflow. */
63
+ approval?: { editorKey: string; workflow: string }
60
64
  }
61
65
 
62
66
  /**
@@ -112,6 +116,8 @@ export const systemActor = (
112
116
  source?: ActorOrigin['source']
113
117
  user?: { id: string; name: string }
114
118
  note?: string
119
+ change?: { key: string; name: string | null }
120
+ approval?: { editorKey: string; workflow: string }
115
121
  } = {},
116
122
  ): Actor => ({
117
123
  kind: 'system',
@@ -119,6 +125,8 @@ export const systemActor = (
119
125
  origin: { source: options.source ?? 'job' },
120
126
  user: options.user,
121
127
  note: options.note,
128
+ ...(options.change ? { change: options.change } : {}),
129
+ ...(options.approval ? { approval: options.approval } : {}),
122
130
  })
123
131
 
124
132
  /** The name an audit entry or a notification gives the actor. */
package/src/events.ts CHANGED
@@ -13,21 +13,26 @@ export type DocumentEvent =
13
13
  | { type: 'saved'; key: string }
14
14
  | { type: 'createdAndPublished'; key: string; cultures: readonly string[] | null }
15
15
  | { type: 'savedAndPublished'; key: string; cultures: readonly string[] | null }
16
- | { type: 'published'; key: string; cultures: readonly string[] | null }
16
+ /** `scheduled`: it set or cleared a time as well (story 417). */
17
+ | { type: 'published'; key: string; cultures: readonly string[] | null; scheduled?: true }
17
18
  /** Only scheduled: nothing is published until the schedule fires. */
18
19
  | { type: 'scheduled'; key: string }
19
20
  /** A page and the pages below it: `published` names each one that went live. */
20
21
  | { type: 'branchPublished'; key: string; published: readonly string[] }
21
22
  | { type: 'unpublished'; key: string; cultures: readonly string[] | null }
22
23
  | { type: 'trashed'; key: string }
23
- /** `name` is read before it went, since it cannot be read after. */
24
- | { type: 'deleted'; key: string; name: string | null }
24
+ /**
25
+ * `name` is read before it went, since it cannot be read after. `was`: the page as it
26
+ * stood, when it was deleted from outside the recycle bin (story 411).
27
+ */
28
+ | { type: 'deleted'; key: string; name: string | null; was?: object }
25
29
  | { type: 'restored'; key: string }
26
30
  | { type: 'binEmptied' }
27
- | { type: 'moved'; key: string }
31
+ /** `from`: where it was before, as its change carries it (story 411). */
32
+ | { type: 'moved'; key: string; from?: { parentKey: string | null; trashed: boolean } }
28
33
  | { type: 'copied'; key: string; copyKey: string }
29
- /** `parentKey` null: the top level. */
30
- | { type: 'sorted'; parentKey: string | null }
34
+ /** `parentKey` null: the top level. `before`: the children's order before (story 411). */
35
+ | { type: 'sorted'; parentKey: string | null; before?: readonly string[] }
31
36
  | { type: 'rolledBack'; key: string; versionId: string }
32
37
  | { type: 'domainsAssigned'; key: string }
33
38
  | { type: 'publicAccessChanged'; key: string; change: 'added' | 'set' | 'removed' }
@@ -42,7 +47,23 @@ export interface EventSink {
42
47
  record(tx: Db, event: DocumentEvent, actor: Actor): Promise<void>
43
48
  afterCommit?(event: DocumentEvent, actor: Actor): void
44
49
  /** Story 397: a publish in a person's own workspace merged its page, recorded as `changeId`. */
45
- ownPublished?(tx: Db, published: { changeId: string; key: string }, actor: Actor): Promise<void>
50
+ ownPublished?(
51
+ tx: Db,
52
+ published: {
53
+ changeId: string
54
+ key: string
55
+ /** Story 411: what the page's merge did, other than a publish. */
56
+ kind?: 'unpublish' | 'move' | 'reorder' | 'delete' | 'schedule'
57
+ page?: { key: string; name: string | null }
58
+ /** Story 417: the times the merge set, per language, in UTC; empty when cleared. */
59
+ schedule?: ReadonlyArray<{
60
+ culture: string | null
61
+ publishTime: string | null
62
+ unpublishTime: string | null
63
+ }>
64
+ },
65
+ actor: Actor,
66
+ ): Promise<void>
46
67
  }
47
68
 
48
69
  /** A sink that hears nothing: for tests and tools that announce nothing. */
package/src/operations.ts CHANGED
@@ -464,6 +464,16 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
464
464
  try {
465
465
  const befores: unknown[] = []
466
466
  for (const node of writes) befores.push(await options.redirects?.capture(node.key))
467
+ // Story 411: where each was, for its change to carry the move.
468
+ const from = new Map<string, { parentKey: string | null; trashed: boolean }>()
469
+ for (const node of writes)
470
+ from.set(node.key, {
471
+ parentKey:
472
+ node.parentId === SystemNodes.Root
473
+ ? null
474
+ : ((await nodes.byId(node.parentId))?.key ?? null),
475
+ trashed: node.trashed,
476
+ })
467
477
  const done = await commit(
468
478
  actor,
469
479
  async (tx) => {
@@ -472,7 +482,11 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
472
482
  if ((await tx.move(node.key, targetKey)) === 'moved') out.push(node.key)
473
483
  return out
474
484
  },
475
- (moved) => moved.map((key): DocumentEvent => ({ type: 'moved', key })),
485
+ (moved) =>
486
+ moved.map((key): DocumentEvent => {
487
+ const was = from.get(key)
488
+ return was ? { type: 'moved', key, from: was } : { type: 'moved', key }
489
+ }),
476
490
  )
477
491
  changed()
478
492
  for (const before of befores) await options.redirects?.commit(before)
@@ -482,6 +496,10 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
482
496
  }
483
497
  }
484
498
 
499
+ /** The keys of a parent's children in their order (story 411): what a reorder changes. */
500
+ const childOrder = async (parentKey: string | null): Promise<string[]> =>
501
+ (await repo.children(parentKey, 0, 10_000)).items.map((n) => normaliseUuid(n.key))
502
+
485
503
  /**
486
504
  * Moves pages to the recycle bin in one transaction, every one checked first.
487
505
  * One already there is unchanged; one below another in the selection goes
@@ -738,6 +756,10 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
738
756
  ? immediate.flatMap((s) => (s.culture === null ? [] : [s.culture]))
739
757
  : request.cultures
740
758
  const before = scheduledOnly ? undefined : await options.redirects?.capture(key)
759
+ // Story 417: a time given, or one there to clear; a plain publish sends neither.
760
+ const touchesSchedule =
761
+ schedules.some((s) => s.publishTime !== null || s.unpublishTime !== null) ||
762
+ (schedules.length > 0 && (await repo.schedules(key)).length > 0)
741
763
  // The schedule and the publish are one change: neither lands without the other.
742
764
  const published = await commit(
743
765
  actor,
@@ -757,7 +779,15 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
757
779
  done === 'scheduled'
758
780
  ? [{ type: 'scheduled', key }]
759
781
  : done
760
- ? [{ type: 'published', key, cultures }]
782
+ ? [
783
+ {
784
+ type: 'published',
785
+ key,
786
+ cultures,
787
+ // Story 417: it set or cleared a time too, for its change to carry.
788
+ ...(touchesSchedule ? { scheduled: true } : {}),
789
+ },
790
+ ]
761
791
  : [],
762
792
  )
763
793
  if (published === 'scheduled') {
@@ -979,10 +1009,13 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
979
1009
  if (options_.fromBin && !node.trashed)
980
1010
  return refuse('invalid', 400, 'The document is not in the recycle bin')
981
1011
  if (!(await permits(actor, 'delete', options_.fromBin ? 'bin' : key))) return forbidden()
1012
+ // Story 411: one deleted from outside the bin, as it stood, for its change to carry.
1013
+ const was = node.trashed ? undefined : await repo.byKey(key)
982
1014
  const removed = await commit(
983
1015
  actor,
984
1016
  (tx) => tx.delete(key),
985
- (done) => (done ? [{ type: 'deleted', key, name: node.text ?? null }] : []),
1017
+ (done): DocumentEvent[] =>
1018
+ done ? [{ type: 'deleted', key, name: node.text ?? null, ...(was ? { was } : {}) }] : [],
986
1019
  )
987
1020
  if (!removed) return refuse('notFound', 404, NOT_FOUND)
988
1021
  changed()
@@ -1110,10 +1143,11 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
1110
1143
  }
1111
1144
  try {
1112
1145
  const before = await options.redirects?.captureChildren(parentKey)
1146
+ const order = await childOrder(parentKey)
1113
1147
  const result = await commit(
1114
1148
  actor,
1115
1149
  (tx) => tx.sort(parentKey, sorting),
1116
- (done) => (done === 'notFound' ? [] : [{ type: 'sorted', parentKey }]),
1150
+ (done) => (done === 'notFound' ? [] : [{ type: 'sorted', parentKey, before: order }]),
1117
1151
  )
1118
1152
  if (result === 'notFound')
1119
1153
  return refuse(
@@ -1138,10 +1172,11 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
1138
1172
  if (!(await permits(actor, 'sort', parentKey ?? 'root'))) return forbidden()
1139
1173
  try {
1140
1174
  const before = await options.redirects?.captureChildren(parentKey)
1175
+ const order = await childOrder(parentKey)
1141
1176
  const result = await commit(
1142
1177
  actor,
1143
1178
  (tx) => tx.sortChildrenBy(parentKey, field, direction),
1144
- (done) => (done === 'notFound' ? [] : [{ type: 'sorted', parentKey }]),
1179
+ (done) => (done === 'notFound' ? [] : [{ type: 'sorted', parentKey, before: order }]),
1145
1180
  )
1146
1181
  if (result === 'notFound') return refuse('notFound', 404, NOT_FOUND)
1147
1182
  changed()
@@ -5,7 +5,7 @@
5
5
  * reorder and delete is done; then the workspace is closed. Anything refused
6
6
  * undoes all of it. A rehearsal runs the same and undoes it on purpose.
7
7
  */
8
- import { type DocumentValue, ObjectTypes } from '@crombolo/core'
8
+ import { type DocumentValue, normaliseUuid, ObjectTypes } from '@crombolo/core'
9
9
  import {
10
10
  type ChangeItemInput,
11
11
  ChangeRepository,
@@ -14,6 +14,7 @@ import {
14
14
  DocumentRepository,
15
15
  type DocumentRepositoryOptions,
16
16
  Locks,
17
+ type ScheduleEntryAt,
17
18
  SystemNodes,
18
19
  TransferRunRepository,
19
20
  type Workspace,
@@ -100,23 +101,58 @@ export type WorkspaceMergeOutcome =
100
101
  }
101
102
  | { ok: false; blockers: string[]; plan: MergePlan }
102
103
 
104
+ /** A page whose schedule a workspace set, as its merge carries it (story 414). */
105
+ interface ScheduledPage {
106
+ nodeId: number
107
+ key: string
108
+ name: string
109
+ entries: ScheduleEntryAt[]
110
+ }
111
+
112
+ /** Whether two schedules are the same, entry by entry. Pure. */
113
+ const sameSchedule = (a: unknown, b: unknown) => JSON.stringify(a ?? []) === JSON.stringify(b ?? [])
114
+
103
115
  /** Where a deleted page's state is kept among its change's items (story 383). */
104
116
  export const REMOVED_PAGE_PREFIX = 'pages/'
105
117
 
118
+ /** Story 411: what a merge of a person's own page alone does, as its change is named and announced. */
119
+ export type OnlyKind = 'publish' | 'unpublish' | 'move' | 'reorder' | 'delete'
120
+
121
+ /**
122
+ * `only`: the pages of a person's own workspace that go alone (story 380), with what waits
123
+ * for a merge of them: a move, a reorder or a delete (story 411).
124
+ */
125
+ export interface OnlyOptions {
126
+ only?: string | readonly string[]
127
+ onlyKind?: OnlyKind
128
+ }
129
+
130
+ const onlyKeys = (only: OnlyOptions['only']): ReadonlySet<string> | undefined =>
131
+ only === undefined ? undefined : new Set(typeof only === 'string' ? [only] : only)
132
+
133
+ const ONLY_NAMES: Record<OnlyKind, string> = {
134
+ publish: 'Published',
135
+ unpublish: 'Unpublished',
136
+ move: 'Moved',
137
+ reorder: 'Reordered',
138
+ delete: 'Deleted',
139
+ }
140
+
106
141
  /** Records a merge as a change (story 381): its name, who made and merged it, its files and pages. */
107
142
  async function recordChange(
108
143
  tx: Db,
109
144
  list: readonly Workspace[],
110
- options: WorkspaceMergeOptions & { only?: string },
145
+ options: WorkspaceMergeOptions & OnlyOptions,
111
146
  items: readonly ChangeItemInput[],
112
147
  pages: readonly PageChange[],
113
148
  merged: Done['merged'],
149
+ done: Done['done'] = [],
114
150
  ): Promise<string> {
115
151
  const changes = new ChangeRepository(tx)
116
152
  const first = list[0] as Workspace
117
153
  const name =
118
154
  options.only !== undefined
119
- ? `Published "${merged[0]?.name ?? 'a page'}"`
155
+ ? `${ONLY_NAMES[options.onlyKind ?? 'publish']} "${merged[0]?.name ?? done[0]?.name ?? 'a page'}"`
120
156
  : list.map((w) => w.name).join(', ')
121
157
  const id = await changes.begin({
122
158
  kind: 'merge',
@@ -268,7 +304,7 @@ function betweenThem(plans: ReadonlyArray<{ workspace: Workspace; plan: MergePla
268
304
  */
269
305
  export async function runWorkspaceMerge(
270
306
  chosen: Workspace | readonly Workspace[],
271
- options: WorkspaceMergeOptions & { only?: string },
307
+ options: WorkspaceMergeOptions & OnlyOptions,
272
308
  ): Promise<WorkspaceMergeOutcome> {
273
309
  const list = Array.isArray(chosen) ? chosen : [chosen as Workspace]
274
310
  const documents = new DocumentRepository(options.db, options.repository)
@@ -287,14 +323,19 @@ export async function runWorkspaceMerge(
287
323
  await locked(() =>
288
324
  documents.atomically(async (shared, tx) => {
289
325
  const workspaces = new WorkspaceRepository(tx)
326
+ const only = onlyKeys(options.only)
290
327
  const narrowed = (plan: MergePlan): MergePlan =>
291
- options.only === undefined
328
+ only === undefined
292
329
  ? plan
293
330
  : {
294
- pages: plan.pages.filter((p) => p.page.key === options.only),
295
- pending: [],
296
- conflicts: plan.conflicts.filter((c) => c.key === options.only),
297
- findings: plan.findings.filter((f) => f.key === options.only),
331
+ pages: plan.pages.filter((p) => only.has(p.page.key)),
332
+ // Story 411: what waits for the merge of those pages goes with them.
333
+ pending:
334
+ options.onlyKind && options.onlyKind !== 'publish'
335
+ ? plan.pending.filter((p) => p.pending.key !== null && only.has(p.pending.key))
336
+ : [],
337
+ conflicts: plan.conflicts.filter((c) => c.key !== null && only.has(c.key)),
338
+ findings: plan.findings.filter((f) => f.key !== null && only.has(f.key)),
298
339
  }
299
340
  const first: Array<{ workspace: Workspace; plan: MergePlan }> = []
300
341
  for (const workspace of list)
@@ -348,7 +389,29 @@ export async function runWorkspaceMerge(
348
389
  fileBlockers.push(
349
390
  `"${page.name}" is of a type made in the workspace: merge the workspace to bring both.`,
350
391
  )
392
+ // Story 414: the schedules each workspace set, and any Shared changed since.
393
+ const schedules: ScheduledPage[][] = []
394
+ const scheduleBlockers: string[] = []
395
+ for (const workspace of list) {
396
+ const planned: ScheduledPage[] = []
397
+ for (const row of await workspaces.scheduled(workspace.id)) {
398
+ if (only !== undefined && !only.has(row.key)) continue
399
+ const entries = await shared.inWorkspace(workspace.id).scheduleEntries(row.key)
400
+ const now = await shared.scheduleEntries(row.key)
401
+ if (
402
+ !sameSchedule(now, row.base) &&
403
+ !sameSchedule(now, entries) &&
404
+ !(options.accepted ?? []).includes('schedule-changed')
405
+ )
406
+ scheduleBlockers.push(
407
+ `"${row.name}": its schedule was changed in Shared since. Accept "schedule-changed" to set it as the workspace has it.`,
408
+ )
409
+ planned.push({ nodeId: row.nodeId, key: row.key, name: row.name, entries })
410
+ }
411
+ schedules.push(planned)
412
+ }
351
413
  const blockers = [
414
+ ...scheduleBlockers,
352
415
  ...fileBlockers,
353
416
  ...betweenThem(first),
354
417
  ...first.flatMap(({ workspace, plan }) =>
@@ -366,6 +429,7 @@ export async function runWorkspaceMerge(
366
429
  await options.events.record(tx, event, options.actor)
367
430
  }
368
431
  const merged: Done['merged'] = []
432
+ const scheduled: string[] = []
369
433
  const forApproval: Done['forApproval'] = []
370
434
  const done: Done['done'] = []
371
435
  const pages: PageChange[] = []
@@ -389,14 +453,59 @@ export async function runWorkspaceMerge(
389
453
  pages,
390
454
  removed: items,
391
455
  })
456
+ // Story 414: its schedules set in Shared, and held by its change.
457
+ for (const page of schedules[n] ?? []) {
458
+ const had = await shared.scheduleEntries(page.key)
459
+ await shared.setSchedule(page.key, [
460
+ ...had
461
+ .filter((h) => !page.entries.some((e) => e.culture === h.culture))
462
+ .map((h) => ({ culture: h.culture, publishTime: null, unpublishTime: null })),
463
+ ...page.entries.map((e) => ({
464
+ culture: e.culture,
465
+ publishTime: e.publishTime ? new Date(e.publishTime) : null,
466
+ unpublishTime: e.unpublishTime ? new Date(e.unpublishTime) : null,
467
+ })),
468
+ ])
469
+ await record({ type: 'scheduled', key: page.key })
470
+ items.push({
471
+ path: `schedules/${page.key}`,
472
+ kind: 'page',
473
+ class: 'none',
474
+ before: null,
475
+ after: JSON.stringify(page.entries),
476
+ })
477
+ if (!pages.some((p) => p.key === page.key)) {
478
+ const at = await shared.eventMarkers(page.key)
479
+ pages.push({
480
+ key: page.key,
481
+ kind: 'document',
482
+ action: 'update',
483
+ beforeEventId: at?.head ?? null,
484
+ beforePublishedEventId: at?.published ?? null,
485
+ eventId: at?.head ?? null,
486
+ })
487
+ }
488
+ if (!merged.some((m) => m.key === page.key))
489
+ merged.push({ key: page.key, name: page.name, published: false, unpublished: false })
490
+ scheduled.push(page.key)
491
+ if (options.only !== undefined) await workspaces.dropSchedule(workspace.id, page.nodeId)
492
+ }
392
493
  if (options.only === undefined)
393
494
  await workspaces.closeMerged(workspace.id, options.userKey)
394
- else
495
+ else {
395
496
  for (const page of plan.pages)
396
497
  if (!page.page.made) await workspaces.dropPage(workspace.id, page.page.nodeId)
498
+ for (const { pending } of plan.pending)
499
+ await workspaces.dropPending(workspace.id, pending.nodeId)
500
+ }
397
501
  }
398
502
  // Story 381: the merge is a change, its files and pages each with before and after.
399
- const changeId = await recordChange(tx, list, options, items, pages, merged)
503
+ const changeId = await recordChange(tx, list, options, items, pages, merged, done)
504
+ // Story 414: each schedule it set names it, for when it fires.
505
+ if (scheduled.length > 0) {
506
+ const made = await new ChangeRepository(tx).byId(changeId)
507
+ if (made) for (const key of scheduled) await shared.scheduleSetBy(key, made.key)
508
+ }
400
509
  // Story 400: each workspace the merge closed, announced with the change it made.
401
510
  if (options.only === undefined) {
402
511
  const made = await new ChangeRepository(tx).byId(changeId)
@@ -409,8 +518,36 @@ export async function runWorkspaceMerge(
409
518
  )
410
519
  }
411
520
  const alone = options.only === undefined ? undefined : merged[0]
412
- if (alone?.published)
413
- await options.events.ownPublished?.(tx, { changeId, key: alone.key }, options.actor)
521
+ const kind = options.onlyKind ?? 'publish'
522
+ if (options.only !== undefined && kind !== 'publish') {
523
+ // Story 411: announced as what it did, naming the page a delete took.
524
+ const first = done.find((d) => d.key !== null) ?? merged[0]
525
+ if (first?.key)
526
+ await options.events.ownPublished?.(
527
+ tx,
528
+ {
529
+ changeId,
530
+ key: first.key,
531
+ kind,
532
+ ...(kind === 'delete' ? { page: { key: first.key, name: first.name } } : {}),
533
+ },
534
+ options.actor,
535
+ )
536
+ } else if (alone && (alone.published || scheduled.includes(alone.key))) {
537
+ // Story 414: a page only scheduled is announced as one published is; story 417:
538
+ // saying so, with its times, and a publish that set a time carrying them.
539
+ const times = schedules.flat().find((p) => p.key === alone.key)?.entries
540
+ await options.events.ownPublished?.(
541
+ tx,
542
+ {
543
+ changeId,
544
+ key: alone.key,
545
+ ...(alone.published ? {} : { kind: 'schedule' as const }),
546
+ ...(times ? { schedule: times } : {}),
547
+ },
548
+ options.actor,
549
+ )
550
+ }
414
551
  outcome = {
415
552
  ok: true,
416
553
  merged,
@@ -474,6 +611,16 @@ async function apply(
474
611
  await shared.unpublish(page.key, cultures)
475
612
  await record({ type: 'unpublished', key: page.key, cultures })
476
613
  unpublished = true
614
+ // Story 411: its change says it was taken down, as the page read back cannot.
615
+ const now = await shared.byKey(page.key)
616
+ if (now)
617
+ out.removed.push(
618
+ placeItem(
619
+ page.key,
620
+ { parentKey: now.parentKey, published: true },
621
+ { parentKey: now.parentKey, published: now.published },
622
+ ),
623
+ )
477
624
  }
478
625
  }
479
626
  out.merged.push({ key: page.key, name: pagePlan.name, published, unpublished })
@@ -490,13 +637,18 @@ async function apply(
490
637
 
491
638
  const keyOf = async (id: number | null) =>
492
639
  id === null || id === SystemNodes.Root ? null : ((await sharedAll.nodes.byId(id))?.key ?? null)
640
+ // Story 411: each parent's children's order before its first reorder, for the change.
641
+ const orders = new Map<string, { parentKey: string | null; before: string[] }>()
642
+ const childKeys = async (parentKey: string | null) =>
643
+ (await sharedAll.children(parentKey, 0, 10_000)).items.map((n) => normaliseUuid(n.key))
493
644
  for (const { pending } of plan.pending) {
494
645
  const key = pending.key
495
646
  if (pending.kind === 'gone' || key === null) continue
496
647
  const shared = sharedAll.ofKind(pending.objectKind ?? 'document')
497
648
  const before = await shared.eventMarkers(key)
498
649
  // A delete takes the page's history with it: its change keeps the page as it stood (story 383).
499
- if (pending.kind === 'delete') {
650
+ // Story 411: so does one moved to the bin, which the bin may empty before the change is taken.
651
+ if (pending.kind === 'delete' || pending.kind === 'trash') {
500
652
  const doc = await shared.byKey(key)
501
653
  if (doc)
502
654
  out.removed.push({
@@ -508,11 +660,27 @@ async function apply(
508
660
  })
509
661
  }
510
662
  if (pending.kind === 'move') {
511
- await shared.move(key, await keyOf(pending.targetParentId))
512
- await record({ type: 'moved', key })
663
+ const node = await shared.nodes.byId(pending.nodeId)
664
+ const from = {
665
+ parentKey: await keyOf(node?.parentId ?? null),
666
+ trashed: node?.trashed ?? false,
667
+ }
668
+ const to = await keyOf(pending.targetParentId)
669
+ await shared.move(key, to)
670
+ await record({ type: 'moved', key, from })
671
+ const published = (await shared.byKey(key))?.published ?? false
672
+ out.removed.push(
673
+ placeItem(
674
+ key,
675
+ { ...from, published, ...(from.trashed ? { trashed: true } : {}) },
676
+ { parentKey: to, published },
677
+ ),
678
+ )
513
679
  } else if (pending.kind === 'sort' && pending.sortOrder !== null) {
514
680
  const node = await shared.nodes.byId(pending.nodeId)
515
681
  const parentKey = await keyOf(node?.parentId ?? null)
682
+ const slot = parentKey ?? ''
683
+ if (!orders.has(slot)) orders.set(slot, { parentKey, before: await childKeys(parentKey) })
516
684
  await shared.sort(parentKey, [{ key, sortOrder: pending.sortOrder }])
517
685
  await record({ type: 'sorted', parentKey })
518
686
  } else if (pending.kind === 'trash') {
@@ -540,4 +708,28 @@ async function apply(
540
708
  eventId: after?.head ?? null,
541
709
  })
542
710
  }
711
+ for (const { parentKey, before } of orders.values()) {
712
+ const after = await childKeys(parentKey)
713
+ if (after.join() !== before.join())
714
+ out.removed.push({
715
+ path: `orders/${parentKey ? normaliseUuid(parentKey) : 'root'}`,
716
+ kind: 'page',
717
+ class: 'none',
718
+ before: JSON.stringify(before),
719
+ after: JSON.stringify(after),
720
+ })
721
+ }
543
722
  }
723
+
724
+ /** Story 411: a page's place before and after, as its change keeps it. */
725
+ const placeItem = (
726
+ key: string,
727
+ before: { parentKey: string | null; published: boolean; trashed?: boolean },
728
+ after: { parentKey: string | null; published: boolean },
729
+ ): ChangeItemInput => ({
730
+ path: `places/${normaliseUuid(key)}`,
731
+ kind: 'page',
732
+ class: 'none',
733
+ before: JSON.stringify(before),
734
+ after: JSON.stringify(after),
735
+ })