@crombolo/transfer 0.48.1 → 0.50.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/transfer",
3
- "version": "0.48.1",
3
+ "version": "0.50.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. Content transfer for crombolo: bundles of content moved between environments.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,7 +28,7 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.48.1",
32
- "@crombolo/data": "0.48.1"
31
+ "@crombolo/core": "0.50.0",
32
+ "@crombolo/data": "0.50.0"
33
33
  }
34
34
  }
package/src/check.ts CHANGED
@@ -305,7 +305,10 @@ export async function checkBundle(
305
305
  const repoFor = (kind: BundleNode['kind']): DocumentRepository => {
306
306
  const found = byKind.get(kind)
307
307
  if (found) return found
308
- const repo = new DocumentRepository(db, { nodeState, kind })
308
+ const repo = new DocumentRepository(db, {
309
+ nodeState,
310
+ kind: kind === 'element-folder' ? 'element' : kind,
311
+ })
309
312
  byKind.set(kind, repo)
310
313
  return repo
311
314
  }
@@ -463,6 +466,78 @@ export async function checkBundle(
463
466
  return editors
464
467
  }
465
468
 
469
+ /**
470
+ * A Library folder is made if it is missing and otherwise left alone, so it
471
+ * takes none of the comparing a node with values does (story 283).
472
+ */
473
+ const carriedNodes = new Map(set.nodes.map((n) => [n.key, n]))
474
+ const checkFolder = async (
475
+ node: BundleNode,
476
+ name: string,
477
+ existing: NodeRow | undefined,
478
+ resolution: Resolution | undefined,
479
+ ): Promise<NodePlan> => {
480
+ const planned = (action: NodePlan['action']): NodePlan => ({
481
+ key: node.key,
482
+ name,
483
+ kind: node.kind,
484
+ action,
485
+ changing: [],
486
+ resolution,
487
+ })
488
+ const finding = (kind: Finding['kind'], code: string, message: string) =>
489
+ findings.push({
490
+ kind,
491
+ code,
492
+ subjectType: 'document',
493
+ subjectKey: node.key,
494
+ subjectName: name,
495
+ propertyAlias: null,
496
+ culture: null,
497
+ message,
498
+ link: null,
499
+ })
500
+ if (resolution === 'skip') return planned('skip')
501
+ if (existing && existing.objectType !== ObjectTypes.ElementContainer) {
502
+ finding('blocking', 'folder-key-taken', `the key of the folder "${name}" is in use here`)
503
+ return planned('skip')
504
+ }
505
+ const parent = node.parent ? carriedNodes.get(node.parent) : undefined
506
+ if (parent && parent.kind !== 'element-folder') {
507
+ finding('blocking', 'folder-parent-invalid', `"${name}" sits under something not a folder`)
508
+ return planned('skip')
509
+ }
510
+ if (existing && !existing.trashed) return planned('unchanged')
511
+ const atTop = !parent
512
+ if (atTop && options.under && options.under.objectType !== ObjectTypes.ElementContainer) {
513
+ finding(
514
+ 'blocking',
515
+ 'folder-under-invalid',
516
+ `the folder "${name}" can only be placed under another Library folder`,
517
+ )
518
+ return planned('skip')
519
+ }
520
+ if (existing) {
521
+ finding('auto', 'folder-restored', `"${name}" comes back out of the recycle bin`)
522
+ return planned('create')
523
+ }
524
+ const parentHere = atTop
525
+ ? (options.under ?? (node.parent ? await nodes.byKey(node.parent) : undefined))
526
+ : await nodes.byKey(parent.key)
527
+ const namesakes =
528
+ atTop && !parentHere && node.parent
529
+ ? []
530
+ : await nodes.childrenNamed(parentHere?.id ?? -1, [ObjectTypes.ElementContainer], name)
531
+ if (namesakes.length > 0)
532
+ finding(
533
+ 'auto',
534
+ 'folder-beside-namesake',
535
+ `a folder called "${name}" is already here; this one keeps its own key and sits beside it`,
536
+ )
537
+ finding('auto', 'new-node', `the folder "${name}" is new here`)
538
+ return planned('create')
539
+ }
540
+
466
541
  const siblingNames = new Map<string, Set<string>>()
467
542
  // What earlier imports applied: the third side of every comparison below.
468
543
  const appliedBefore = await new ContentAppliedRepository(db).byKeys(set.nodes.map((n) => n.key))
@@ -472,6 +547,10 @@ export async function checkBundle(
472
547
  const answers = resolutions[node.key]
473
548
  const resolution = answers?.[WHOLE_NODE] ?? options.resolveAll
474
549
  const existing = await nodes.byKey(node.key)
550
+ if (node.kind === 'element-folder') {
551
+ plan.push(await checkFolder(node, name, existing, resolution))
552
+ continue
553
+ }
475
554
  const editors = await editorsFor(node.contentType.alias)
476
555
  const typeMissing = !(await typeFor(node.contentType))
477
556
 
package/src/export.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  type BundleSnapshot,
35
35
  type BundleValue,
36
36
  type ContentSet,
37
+ ELEMENT_FOLDER_TYPE,
37
38
  } from './model.ts'
38
39
  import { referenceCandidates } from './references.ts'
39
40
 
@@ -43,6 +44,7 @@ const KINDS: Record<BundleKind, { objectType: string; contentKind: ContentKind }
43
44
  media: { objectType: ObjectTypes.Media, contentKind: 'media' },
44
45
  element: { objectType: ObjectTypes.Element, contentKind: 'element' },
45
46
  blueprint: { objectType: ObjectTypes.DocumentBlueprint, contentKind: 'blueprint' },
47
+ 'element-folder': { objectType: ObjectTypes.ElementContainer, contentKind: 'element' },
46
48
  }
47
49
 
48
50
  /** Editors that hold a file rather than a reference to one. */
@@ -168,6 +170,20 @@ function toBundleNode(
168
170
  }
169
171
  }
170
172
 
173
+ /** A Library folder: a name and a place, with no type, values or versions. */
174
+ function toFolderNode(node: NodeRow, parent: string | null): BundleNode {
175
+ return {
176
+ key: node.key,
177
+ kind: 'element-folder',
178
+ contentType: { ...ELEMENT_FOLDER_TYPE },
179
+ parent,
180
+ sortOrder: node.sortOrder,
181
+ template: null,
182
+ variants: [{ culture: null, segment: null, name: node.text ?? '', published: false }],
183
+ values: [],
184
+ }
185
+ }
186
+
171
187
  /** Every node of the selection, roots first and parents before children. */
172
188
  async function selected(
173
189
  db: Db,
@@ -176,7 +192,12 @@ async function selected(
176
192
  const byKind = new Map<string, BundleKind>(
177
193
  Object.entries(KINDS).map(([kind, v]) => [v.objectType, kind as BundleKind]),
178
194
  )
179
- const wanted: string[] = [ObjectTypes.Document, ObjectTypes.Media, ObjectTypes.Element]
195
+ const wanted: string[] = [
196
+ ObjectTypes.Document,
197
+ ObjectTypes.Media,
198
+ ObjectTypes.Element,
199
+ ObjectTypes.ElementContainer,
200
+ ]
180
201
  if (options.blueprints) wanted.push(ObjectTypes.DocumentBlueprint)
181
202
 
182
203
  const found = new Map<number, { node: NodeRow; kind: BundleKind }>()
@@ -190,6 +211,13 @@ async function selected(
190
211
  if (k) found.set(descendant.id, { node: descendant, kind: k })
191
212
  }
192
213
  }
214
+ // The folders above a Library item come with it, so it has somewhere to land.
215
+ for (const { node, kind } of [...found.values()]) {
216
+ if (kind !== 'element' && kind !== 'element-folder') continue
217
+ for (const ancestor of await nodes.ancestors(node.key))
218
+ if (ancestor.objectType === ObjectTypes.ElementContainer)
219
+ found.set(ancestor.id, { node: ancestor, kind: 'element-folder' })
220
+ }
193
221
  return [...found.values()].sort((a, b) => a.node.level - b.node.level || a.node.id - b.node.id)
194
222
  }
195
223
 
@@ -233,6 +261,21 @@ export async function exportBundle(db: Db, options: ExportOptions): Promise<Expo
233
261
  const counts: Partial<Record<BundleKind, number>> = {}
234
262
 
235
263
  for (const { node, kind } of chosen) {
264
+ // The parent travels as a key only when it is in the bundle; otherwise it is
265
+ // an expected dependency, which the destination must already have. The
266
+ // system containers — the tree root and the recycle bins — have real `node`
267
+ // rows with keys of their own, and a node sitting under one has no parent as
268
+ // far as a bundle is concerned.
269
+ const parentKey =
270
+ node.parentId <= 0
271
+ ? null
272
+ : (keyOfNodeId.get(node.parentId) ?? (await nodes.byId(node.parentId))?.key ?? null)
273
+ if (kind === 'element-folder') {
274
+ bundleNodes.push(toFolderNode(node, parentKey))
275
+ counts[kind] = (counts[kind] ?? 0) + 1
276
+ continue
277
+ }
278
+
236
279
  const repo = repoFor(kind)
237
280
  // Media is never published, so there is no published snapshot to prefer.
238
281
  const published =
@@ -249,15 +292,6 @@ export async function exportBundle(db: Db, options: ExportOptions): Promise<Expo
249
292
  for (const key of keys) referenced.add(key)
250
293
  }
251
294
 
252
- // The parent travels as a key only when it is in the bundle; otherwise it is
253
- // an expected dependency, which the destination must already have. The
254
- // system containers — the tree root and the recycle bins — have real `node`
255
- // rows with keys of their own, and a node sitting under one has no parent as
256
- // far as a bundle is concerned.
257
- const parentKey =
258
- node.parentId <= 0
259
- ? null
260
- : (keyOfNodeId.get(node.parentId) ?? (await nodes.byId(node.parentId))?.key ?? null)
261
295
  // A template's definition is its file, so the alias travels and the key does
262
296
  // not: the same view has a different key in every environment.
263
297
  const componentAlias = aggregate.componentKey
package/src/import.ts CHANGED
@@ -34,6 +34,7 @@
34
34
  * follow the bundle under the same rule.
35
35
  */
36
36
  import type { DocumentValue } from '@crombolo/core'
37
+ import { ObjectTypes } from '@crombolo/core'
37
38
  import {
38
39
  type AppliedState,
39
40
  appendCacheInstruction,
@@ -45,6 +46,7 @@ import {
45
46
  currentSchemaState,
46
47
  type Db,
47
48
  DocumentRepository,
49
+ FolderRepository,
48
50
  insideTransaction,
49
51
  Locks,
50
52
  MediaAccessRepository,
@@ -69,6 +71,7 @@ const CONTENT_KIND: Record<BundleKind, ContentKind> = {
69
71
  media: 'media',
70
72
  element: 'element',
71
73
  blueprint: 'blueprint',
74
+ 'element-folder': 'element',
72
75
  }
73
76
 
74
77
  export interface ImportOptions extends CheckOptions {
@@ -241,10 +244,42 @@ async function applyBundle(tx: Db, set: ContentSet, options: ImportOptions): Pro
241
244
  })
242
245
 
243
246
  const planByKey = new Map(check.plan.map((p) => [p.key, p]))
244
- const ordered = inTreeOrder(set.nodes).filter(
247
+ const ordered = inTreeOrder(set.nodes.filter((node) => node.kind !== 'element-folder')).filter(
245
248
  (node) => planByKey.get(node.key)?.action !== 'skip',
246
249
  )
247
250
 
251
+ // Library folders first, in the source's order within a parent, so an element
252
+ // lands in its folder. One that is here stays as it is (story 283).
253
+ const folders = new FolderRepository(tx, ObjectTypes.ElementContainer, ObjectTypes.Element)
254
+ const foldersHere = new Set<string>()
255
+ const madeFolders: string[] = []
256
+ const folderPlans: NodePlan[] = []
257
+ const carriedFolders = set.nodes
258
+ .filter((node) => node.kind === 'element-folder')
259
+ .sort((a, b) => a.sortOrder - b.sortOrder)
260
+ for (const node of inTreeOrder(carriedFolders)) {
261
+ const plan = planByKey.get(node.key)
262
+ if (!plan || plan.action === 'skip') continue
263
+ foldersHere.add(node.key)
264
+ folderPlans.push(plan)
265
+ if (plan.action !== 'create') continue
266
+ const parentKey =
267
+ node.parent && foldersHere.has(node.parent)
268
+ ? node.parent
269
+ : (options.under?.key ??
270
+ (node.parent && (await repoFor('element').nodes.byKey(node.parent))
271
+ ? node.parent
272
+ : null))
273
+ if (await folders.byKey(node.key)) await folders.restore(node.key, parentKey)
274
+ else
275
+ await folders.create({
276
+ key: node.key,
277
+ name: node.variants[0]?.name ?? '',
278
+ parentKey,
279
+ })
280
+ madeFolders.push(node.key)
281
+ }
282
+
248
283
  // What each node was before this run, read before anything is written:
249
284
  // the two numbers a revert needs to put the site back.
250
285
  const before = new Map<string, { head: number | undefined; published: number | undefined }>()
@@ -274,7 +309,10 @@ async function applyBundle(tx: Db, set: ContentSet, options: ImportOptions): Pro
274
309
  `No content type "${node.contentType.alias}" for "${node.key}", which the check should have refused.`,
275
310
  )
276
311
  const parentKey =
277
- node.parent && !created.has(node.parent) && !before.has(node.parent)
312
+ node.parent &&
313
+ !created.has(node.parent) &&
314
+ !before.has(node.parent) &&
315
+ !foldersHere.has(node.parent)
278
316
  ? (options.under?.key ?? null)
279
317
  : (node.parent ?? options.under?.key ?? null)
280
318
  await repo.create({
@@ -324,7 +362,7 @@ async function applyBundle(tx: Db, set: ContentSet, options: ImportOptions): Pro
324
362
  }
325
363
 
326
364
  // Pass two: the values, overlaid onto whatever is here.
327
- const applied: NodePlan[] = []
365
+ const applied: NodePlan[] = [...folderPlans]
328
366
  for (const node of ordered) {
329
367
  const plan = planByKey.get(node.key)
330
368
  const kept = new Set(plan?.keepLocal ?? [])
@@ -521,6 +559,16 @@ async function applyBundle(tx: Db, set: ContentSet, options: ImportOptions): Pro
521
559
  eventId: markers?.head ?? null,
522
560
  })
523
561
  }
562
+ for (const key of madeFolders)
563
+ await runs.record({
564
+ runId,
565
+ nodeKey: key,
566
+ kind: 'element-folder',
567
+ action: 'create',
568
+ beforeEventId: null,
569
+ beforePublishedEventId: null,
570
+ eventId: null,
571
+ })
524
572
  // What this run applied, for the next import to compare against. A node
525
573
  // that kept its own order keeps the order recorded before.
526
574
  const appliedRecords = new ContentAppliedRepository(tx)
@@ -548,7 +596,7 @@ async function applyBundle(tx: Db, set: ContentSet, options: ImportOptions): Pro
548
596
  await appliedRecords.record(node.key, runId, state)
549
597
  }
550
598
 
551
- await runs.finish(runId, ordered.length + people.length)
599
+ await runs.finish(runId, ordered.length + madeFolders.length + people.length)
552
600
 
553
601
  // Other nodes drop their published cache; this one already has.
554
602
  await appendCacheInstruction(tx, {
package/src/load.ts CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  type BundleValue,
26
26
  type BundleVariant,
27
27
  type ContentSet,
28
+ ELEMENT_FOLDER_TYPE,
28
29
  OLDEST_BUNDLE_FORMAT_VERSION,
29
30
  } from './model.ts'
30
31
  import { type BundlePeople, openPeople, type PeopleBlock, parsePeopleBlock } from './people.ts'
@@ -72,7 +73,7 @@ export interface LoadedBundle {
72
73
  blobs: Map<string, string>
73
74
  }
74
75
 
75
- const KINDS: readonly BundleKind[] = ['document', 'media', 'element', 'blueprint']
76
+ const KINDS: readonly BundleKind[] = ['document', 'media', 'element', 'blueprint', 'element-folder']
76
77
 
77
78
  const isRecord = (v: unknown): v is Record<string, unknown> =>
78
79
  typeof v === 'object' && v !== null && !Array.isArray(v)
@@ -147,8 +148,9 @@ export function parseNode(
147
148
  const key = str(raw.key)
148
149
  const kind = str(raw.kind) as BundleKind | undefined
149
150
  const contentType = isRecord(raw.contentType) ? raw.contentType : undefined
150
- const typeKey = str(contentType?.key)
151
- const typeAlias = str(contentType?.alias)
151
+ const isFolder = kind === 'element-folder'
152
+ const typeKey = isFolder ? ELEMENT_FOLDER_TYPE.key : str(contentType?.key)
153
+ const typeAlias = isFolder ? ELEMENT_FOLDER_TYPE.alias : str(contentType?.alias)
152
154
  if (!key) problems.push({ file, message: 'no key' })
153
155
  if (!kind || !KINDS.includes(kind))
154
156
  problems.push({ file, message: `kind must be one of ${KINDS.join(', ')}` })
@@ -170,6 +172,8 @@ export function parseNode(
170
172
  })
171
173
  : []
172
174
  if (variants.length === 0) problems.push({ file, message: 'no variants: a node needs a name' })
175
+ if (isFolder && values.length > 0)
176
+ problems.push({ file, message: 'a Library folder holds no values' })
173
177
 
174
178
  const access = parseAccess(raw.access)
175
179
  const mediaAccess = kind === 'media' ? parseMediaAccess(raw.mediaAccess) : undefined
package/src/model.ts CHANGED
@@ -20,11 +20,12 @@ import type { SiteDataBlock, SiteDataTable } from './site-data.ts'
20
20
  * it, and a site's code as a section (stories 192, 193).
21
21
  * 5: media listed in `media.json` at the root, each carried file at
22
22
  * `media/<key>` with a `bundle://` URI (story 195).
23
+ * 6: a Library folder may travel as a node (story 283).
23
24
  *
24
25
  * An older version is refused rather than read (no older layout is kept up),
25
26
  * with a message saying to rebuild it.
26
27
  */
27
- export const BUNDLE_FORMAT_VERSION = 5
28
+ export const BUNDLE_FORMAT_VERSION = 6
28
29
 
29
30
  /** The oldest version this reader reads: the first with media listed in `media.json`. */
30
31
  export const OLDEST_BUNDLE_FORMAT_VERSION = 5
@@ -63,7 +64,10 @@ export type BundleSection = keyof typeof BUNDLE_SECTIONS
63
64
  * The kinds that travel. `member` is deliberately absent: members are personal
64
65
  * data, and a bundle is a file that gets copied around and committed.
65
66
  */
66
- export type BundleKind = 'document' | 'media' | 'element' | 'blueprint'
67
+ export type BundleKind = 'document' | 'media' | 'element' | 'blueprint' | 'element-folder'
68
+
69
+ /** What a Library folder names as its type: it has none, only a name and a place. */
70
+ export const ELEMENT_FOLDER_TYPE = { key: '', alias: 'elementFolder' } as const
67
71
 
68
72
  /** Which snapshot of a node's values the bundle carries. */
69
73
  export type BundleSnapshot = 'published' | 'drafts'
package/src/revert.ts CHANGED
@@ -14,6 +14,7 @@
14
14
  * edited a page after the import, and discarding that without asking would be
15
15
  * the worst thing this command could do.
16
16
  */
17
+ import { ObjectTypes, SystemNodes } from '@crombolo/core'
17
18
  import {
18
19
  appendCacheInstruction,
19
20
  ContentAppliedRepository,
@@ -21,6 +22,7 @@ import {
21
22
  type Db,
22
23
  DocumentRepository,
23
24
  type Finding,
25
+ FolderRepository,
24
26
  Locks,
25
27
  type NodeRow,
26
28
  PublishBlockedError,
@@ -76,7 +78,7 @@ export interface RevertPlan {
76
78
  * run created, and `unrecycle` brings back what a *reverted* run recycled —
77
79
  * which is what makes a revert revertible in its own right.
78
80
  */
79
- action: 'restore' | 'recycle' | 'unrecycle' | 'skip' | 'gone' | 'remove'
81
+ action: 'restore' | 'recycle' | 'unrecycle' | 'skip' | 'gone' | 'remove' | 'keep'
80
82
  resolution: RevertResolution | undefined
81
83
  }
82
84
 
@@ -97,6 +99,8 @@ export interface RevertResult {
97
99
  removed: string[]
98
100
  }
99
101
 
102
+ const FOLDER_KIND = 'element-folder'
103
+
100
104
  const link = (backOfficePath: string | undefined, key: string): string | null =>
101
105
  backOfficePath ? `${backOfficePath}/section/content/workspace/document/edit/${key}` : null
102
106
 
@@ -207,6 +211,41 @@ export async function checkRevert(
207
211
  continue
208
212
  }
209
213
 
214
+ // A Library folder has no versions and nothing of its own to lose. It goes
215
+ // when it is empty and stays when anything else has come to sit in it.
216
+ if (change.kind === FOLDER_KIND) {
217
+ if (change.action === 'recycle') {
218
+ plan.push({ key: change.nodeKey, name, action: 'unrecycle', resolution })
219
+ continue
220
+ }
221
+ if (node.trashed) {
222
+ plan.push({ key: change.nodeKey, name, action: 'gone', resolution })
223
+ continue
224
+ }
225
+ const others = (
226
+ await docs.nodes.descendants(node, [ObjectTypes.Element, ObjectTypes.ElementContainer])
227
+ ).filter((d) => !ownKeys.has(d.key))
228
+ if (others.length > 0)
229
+ findings.push({
230
+ kind: 'auto',
231
+ code: 'folder-kept',
232
+ subjectType: 'document',
233
+ subjectKey: change.nodeKey,
234
+ subjectName: name,
235
+ propertyAlias: null,
236
+ culture: null,
237
+ message: `the folder "${name}" stays: ${others.length} other item(s) sit in it now`,
238
+ link: null,
239
+ })
240
+ plan.push({
241
+ key: change.nodeKey,
242
+ name,
243
+ action: others.length > 0 ? 'keep' : 'recycle',
244
+ resolution,
245
+ })
246
+ continue
247
+ }
248
+
210
249
  const created = change.action === 'create'
211
250
  const repo = repoFor(db, nodeState, change.kind)
212
251
 
@@ -274,7 +313,12 @@ function repoFor(
274
313
  inTreeLock = false,
275
314
  ): DocumentRepository {
276
315
  return new DocumentRepository(db, {
277
- kind: kind === 'media' || kind === 'element' || kind === 'blueprint' ? kind : 'document',
316
+ kind:
317
+ kind === FOLDER_KIND
318
+ ? 'element'
319
+ : kind === 'media' || kind === 'element' || kind === 'blueprint'
320
+ ? kind
321
+ : 'document',
278
322
  nodeState,
279
323
  inTreeLock,
280
324
  })
@@ -314,11 +358,17 @@ export async function revertRun(
314
358
  })
315
359
 
316
360
  const skipped = new Set(
317
- check.plan.filter((p) => p.action === 'skip' || p.action === 'gone').map((p) => p.key),
361
+ check.plan
362
+ .filter((p) => p.action === 'skip' || p.action === 'gone' || p.action === 'keep')
363
+ .map((p) => p.key),
318
364
  )
319
- const todo = changes.filter(
365
+ const affected = changes.filter(
320
366
  (c) => c.action !== 'skip' && !skipped.has(c.nodeKey) && !isPersonKind(c.kind),
321
367
  )
368
+ const todo = affected.filter((c) => c.kind !== FOLDER_KIND)
369
+ const folderChanges = affected.filter((c) => c.kind === FOLDER_KIND)
370
+ const folders = new FolderRepository(tx, ObjectTypes.ElementContainer, ObjectTypes.Element)
371
+ const applied = new ContentAppliedRepository(tx)
322
372
  // Members before the groups they belong to.
323
373
  const removed: string[] = []
324
374
  const order = ['member', 'user', 'member-group', 'user-group']
@@ -330,7 +380,7 @@ export async function revertRun(
330
380
  )
331
381
  removed.push(change.nodeKey)
332
382
  const byKey = new Map<string, NodeRow>()
333
- for (const change of todo) {
383
+ for (const change of affected) {
334
384
  const node = await repo(change.kind).nodes.byKey(change.nodeKey)
335
385
  if (node) byKey.set(change.nodeKey, node)
336
386
  }
@@ -351,6 +401,22 @@ export async function revertRun(
351
401
  if (markers) before.set(change.nodeKey, markers)
352
402
  }
353
403
 
404
+ // Folders the previous revert recycled come back first, so what was in them
405
+ // has somewhere to return to. It recorded them deepest first, so this is
406
+ // parents first, and it kept where each one was.
407
+ const folderPlaces = await applied.byKeys(folderChanges.map((c) => c.nodeKey))
408
+ const backFolders: string[] = []
409
+ for (const change of [...folderChanges].reverse()) {
410
+ if (change.action !== 'recycle') continue
411
+ const parent = folderPlaces.get(change.nodeKey)?.parent ?? null
412
+ await folders.restore(
413
+ change.nodeKey,
414
+ parent && (await repo(FOLDER_KIND).nodes.byKey(parent)) ? parent : null,
415
+ )
416
+ restored.push(change.nodeKey)
417
+ backFolders.push(change.nodeKey)
418
+ }
419
+
354
420
  // What the previous run recycled comes back out of the bin first, so the
355
421
  // rollback and publish below have a node in the tree to work on.
356
422
  for (const change of inTreeOrder(todo)) {
@@ -397,6 +463,17 @@ export async function revertRun(
397
463
  recycled.push(change.nodeKey)
398
464
  }
399
465
 
466
+ // Folders last and deepest first, once what the run put in them has gone, and
467
+ // only if nothing else is left in them.
468
+ const goneFolders: Array<{ key: string; parent: string | null }> = []
469
+ for (const change of inTreeOrder(folderChanges).reverse()) {
470
+ if (change.action === 'recycle' || (await folders.holdsAnything(change.nodeKey))) continue
471
+ const parent = (await folders.byKey(change.nodeKey))?.parentKey ?? null
472
+ await folders.toRecycleBin(change.nodeKey, SystemNodes.ElementRecycleBin)
473
+ recycled.push(change.nodeKey)
474
+ goneFolders.push({ key: change.nodeKey, parent })
475
+ }
476
+
400
477
  for (const change of todo) {
401
478
  const markers = await repo(change.kind).eventMarkers(change.nodeKey)
402
479
  const was = before.get(change.nodeKey)
@@ -412,9 +489,34 @@ export async function revertRun(
412
489
  eventId: markers?.head ?? null,
413
490
  })
414
491
  }
492
+ for (const [nodeKey, action] of [
493
+ ...goneFolders.map(({ key }) => [key, 'recycle'] as const),
494
+ ...backFolders.map((key) => [key, 'update'] as const),
495
+ ])
496
+ await runs.record({
497
+ runId: newRunId,
498
+ nodeKey,
499
+ kind: FOLDER_KIND,
500
+ action,
501
+ beforeEventId: null,
502
+ beforePublishedEventId: null,
503
+ eventId: null,
504
+ })
415
505
  // What the next import compares against goes back with the content.
416
- await new ContentAppliedRepository(tx).revert(runId)
417
- await runs.finish(newRunId, todo.length + removed.length)
506
+ await applied.revert(runId)
507
+ // A folder keeps no parent of its own in the bin, so this run notes it.
508
+ for (const { key, parent } of goneFolders)
509
+ await applied.record(key, newRunId, {
510
+ values: {},
511
+ names: {},
512
+ parent,
513
+ bundleSortOrder: 0,
514
+ sortOrder: 0,
515
+ })
516
+ await runs.finish(
517
+ newRunId,
518
+ todo.length + goneFolders.length + backFolders.length + removed.length,
519
+ )
418
520
  await runs.setStatus(runId, 'reverted')
419
521
 
420
522
  await appendCacheInstruction(tx, {