@stll/folio-core 0.71.0 → 0.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +2 -2
  2. package/dist/compat/eigenpal.d.ts +1 -2
  3. package/dist/compat/eigenpal.js +1 -2
  4. package/dist/controller/canonicalYjsRoom.d.ts +1 -1
  5. package/dist/controller/headerFooterEditorManager.d.ts +11 -7
  6. package/dist/controller/headerFooterEditorManager.js +39 -151
  7. package/dist/controller/hiddenEditorManager.d.ts +2 -37
  8. package/dist/controller/hiddenEditorManager.js +102 -294
  9. package/dist/controller/noteEditorManager.d.ts +3 -10
  10. package/dist/controller/noteEditorManager.js +33 -206
  11. package/dist/index.d.ts +1 -2
  12. package/dist/index.js +1 -2
  13. package/dist/managers/DocumentLoaderManager.d.ts +0 -4
  14. package/dist/managers/DocumentLoaderManager.js +4 -12
  15. package/dist/prosemirror/numberingAttr.d.ts +1 -2
  16. package/dist/prosemirror/numberingAttr.js +1 -2
  17. package/dist/prosemirror/outlineLevelAttr.d.ts +1 -2
  18. package/dist/prosemirror/outlineLevelAttr.js +1 -2
  19. package/dist/server.d.ts +1 -4
  20. package/dist/server.js +1 -4
  21. package/package.json +1 -3
  22. package/dist/controller/collaborationModules.d.ts +0 -3
  23. package/dist/controller/collaborationModules.js +0 -14
  24. package/dist/docx/server/materializeYjsDocx.d.ts +0 -30
  25. package/dist/docx/server/materializeYjsDocx.js +0 -96
  26. package/dist/docx/server/migrateYjsAttrSchema.d.ts +0 -53
  27. package/dist/docx/server/migrateYjsAttrSchema.js +0 -111
  28. package/dist/prosemirror/plugins/derivedFields.d.ts +0 -8
  29. package/dist/prosemirror/plugins/derivedFields.js +0 -52
  30. package/dist/prosemirror/yjsDocumentMetadata.d.ts +0 -89
  31. package/dist/prosemirror/yjsDocumentMetadata.js +0 -697
@@ -1,697 +0,0 @@
1
- import { PROSE_PARAGRAPH_SOURCE_CONTRACT_ATTR, getProseDocumentParagraphPropertySourceContract } from "../docx/paragraphPropertySource.js";
2
- import { isNoteReferenceOccurrenceId } from "./noteReferenceOccurrenceId.js";
3
- import { readRangeAnchorValues } from "./rangeAnchorAttrs.js";
4
- import { mintSectionProperties, parseSectionBreakType } from "./sectionCarrier.js";
5
- import { Result, TaggedError, panic } from "better-result";
6
- import { DRAWING_RAW_XML_MODES, outlineLevelFromStatedValue, paragraphNumberingFromSlots } from "@stll/docx-core/model";
7
- // src/prosemirror/yjsDocumentMetadata.ts
8
- const FolioYjsAttrSchemaVersionErrorBase = TaggedError("FolioYjsAttrSchemaVersionError");
9
- /**
10
- * Folio's own keys inside a collaboration document: one map, two independent
11
- * bindings.
12
- *
13
- * `paragraphSourceContract` binds the snapshot to the exact bytes of the DOCX
14
- * it was seeded from. `attrSchemaVersion` binds it to the shape of the node
15
- * attrs Folio persists. A snapshot can be current on one and stale on the
16
- * other, so neither key may be derived from the other.
17
- */
18
- const FOLIO_YJS_METADATA_MAP_NAME = "folio:document-metadata";
19
- const PARAGRAPH_SOURCE_CONTRACT_KEY = "paragraphSourceContract";
20
- const ATTR_SCHEMA_VERSION_KEY = "attrSchemaVersion";
21
- /**
22
- * Version 0 is every snapshot written before the marker existed. The marker
23
- * shipped without changing a single attr, so carrying a v0 snapshot to v1 is
24
- * the identity: it only stamps the key.
25
- */
26
- const stampMarkerOnly = () => 0;
27
- const isRecord = (value) => typeof value === "object" && value !== null;
28
- /** A shared text node, identified structurally to keep Yjs a type-only import. */
29
- const isXmlText = (child) => "toDelta" in child;
30
- /** The node types whose `fldLock` and `dirty` attrs version 2 rewrites. */
31
- const FIELD_ELEMENT_NAMES = /* @__PURE__ */ new Set(["field", "structuredField"]);
32
- const STATED_FLAG_ATTRS = ["fldLock", "dirty"];
33
- /**
34
- * Version 1 stored `fldLock` and `dirty` as booleans defaulting to `false`,
35
- * because the reader that filled them tested `=== true`. A field that authored
36
- * an explicit `w:fldLock="0"` and one that authored nothing were both stored as
37
- * `false`, so `false` never meant an explicit off and cannot be kept as one now
38
- * that `null` is the absence: a v1 snapshot's `false` would start writing an
39
- * attribute the document never carried.
40
- */
41
- const dropUnstatedFieldFlags = (fragment) => {
42
- let rewritten = 0;
43
- const visit = (node) => {
44
- if ("nodeName" in node && FIELD_ELEMENT_NAMES.has(node.nodeName)) {
45
- const attributes = node.getAttributes();
46
- let changed = false;
47
- for (const attr of STATED_FLAG_ATTRS) if (attributes[attr] === false) {
48
- node.removeAttribute(attr);
49
- changed = true;
50
- }
51
- if (changed) rewritten += 1;
52
- }
53
- for (const child of node.toArray()) if (typeof child !== "string" && "toArray" in child) visit(child);
54
- };
55
- visit(fragment);
56
- return rewritten;
57
- };
58
- /** The node type whose `outlineLevel` attrs version 7 rewrites. */
59
- const PARAGRAPH_ELEMENT_NAME = "paragraph";
60
- /** A stored outline level, or the absence of one in this carrier. */
61
- const versionSixOutlineLevel = (value) => {
62
- if (typeof value !== "number") return;
63
- return outlineLevelFromStatedValue(value) ?? null;
64
- };
65
- /** Rewrite one persisted paragraph-formatting carrier when it stores a v6 number. */
66
- const versionSixFormatting = (value) => {
67
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
68
- const outlineLevel = versionSixOutlineLevel(Reflect.get(value, "outlineLevel"));
69
- if (outlineLevel === void 0) return null;
70
- const migrated = { ...value };
71
- if (outlineLevel === null) Reflect.deleteProperty(migrated, "outlineLevel");
72
- else migrated["outlineLevel"] = outlineLevel;
73
- return migrated;
74
- };
75
- /** Rewrite outline levels in paragraph-property-change formatting carriers. */
76
- const versionSixPropertyChanges = (value) => {
77
- if (!Array.isArray(value)) return null;
78
- const changes = [];
79
- let changed = false;
80
- for (const change of value) {
81
- if (typeof change !== "object" || change === null || Array.isArray(change)) return null;
82
- const migrated = { ...change };
83
- for (const tier of ["previousFormatting", "currentFormatting"]) {
84
- const formatting = versionSixFormatting(change[tier]);
85
- if (formatting !== null) {
86
- migrated[tier] = formatting;
87
- changed = true;
88
- }
89
- }
90
- changes.push(migrated);
91
- }
92
- return changed ? changes : null;
93
- };
94
- /**
95
- * Version 6 stored `outlineLevel` as the `w:outlineLvl w:val` number, with 9
96
- * meaning body text and every consumer deciding that for itself. Version 7
97
- * stores `OutlineLevel`, so the number has to be mapped: 0..8 become the
98
- * heading arm, 9 becomes the body-text arm, and anything else is dropped,
99
- * matching the parse boundary. It cannot be left alone and read lazily,
100
- * because ProseMirror copies a stored attr into the node without validating
101
- * and the strict validator would then panic on the first read of an untouched
102
- * room.
103
- */
104
- const outlineLevelBecomesAUnion = (fragment) => {
105
- let rewritten = 0;
106
- const visit = (node) => {
107
- if ("nodeName" in node && node.nodeName === PARAGRAPH_ELEMENT_NAME) {
108
- const attributes = node.getAttributes();
109
- let changed = false;
110
- const outlineLevel = versionSixOutlineLevel(attributes["outlineLevel"]);
111
- if (outlineLevel !== void 0) {
112
- if (outlineLevel === null) node.removeAttribute("outlineLevel");
113
- else node.setAttribute("outlineLevel", outlineLevel);
114
- changed = true;
115
- }
116
- for (const attr of ["_originalFormatting", "_resolvedFormatting"]) {
117
- const formatting = versionSixFormatting(attributes[attr]);
118
- if (formatting !== null) {
119
- node.setAttribute(attr, formatting);
120
- changed = true;
121
- }
122
- }
123
- const propertyChanges = versionSixPropertyChanges(attributes["_propertyChanges"]);
124
- if (propertyChanges !== null) {
125
- node.setAttribute("_propertyChanges", propertyChanges);
126
- changed = true;
127
- }
128
- if (changed) rewritten += 1;
129
- }
130
- for (const child of node.toArray()) if (typeof child !== "string" && "toArray" in child) visit(child);
131
- };
132
- visit(fragment);
133
- return rewritten;
134
- };
135
- /**
136
- * Version 3 adds `docxRotation`, `docxFlipH` and `docxFlipV` to the drawing
137
- * nodes. A v2 snapshot states none of them, and `readAuthoredTransform` reads
138
- * such a node from its `transform` CSS, which is the only record it ever had,
139
- * so nothing has to be rewritten. The marker still moves: a v3 snapshot read
140
- * by a v2 build would have the three attrs dropped without a trace.
141
- */
142
- const drawingTransformAttrsAreAdditive = () => 0;
143
- /** The node type whose relationship and raw-XML attrs version 4 rewrites. */
144
- const IMAGE_ELEMENT_NAME = "image";
145
- /**
146
- * Stands in for the capture marker a node migrated to `previewOnly` never had.
147
- *
148
- * `drawingFromImageAttrs` reads the marker's presence and never its value: the
149
- * editor projection is lossy, so a value compared against the image rebuilt
150
- * from it would report an untouched round trip as an edit. What the marker has
151
- * to say here is that the node still holds the capture it was projected with,
152
- * which is exactly the condition the step selects on.
153
- */
154
- const CARRIED_PREVIEW_CAPTURE = "carriedPreviewCapture";
155
- /** Rewrite one stored image node, answering whether anything changed. */
156
- const migrateImageNode = (node) => {
157
- const attributes = node.getAttributes();
158
- const rId = attributes["rId"];
159
- const dropsEmptyId = rId === "";
160
- const classifies = !(typeof rId === "string" && rId.length > 0) && typeof attributes["_docxRawXml"] === "string" && attributes["_docxRawXmlMode"] === void 0;
161
- if (dropsEmptyId) node.removeAttribute("rId");
162
- if (classifies) {
163
- node.setAttribute("_docxRawXmlMode", DRAWING_RAW_XML_MODES.PREVIEW_ONLY);
164
- node.setAttribute("_docxRawImageFingerprint", CARRIED_PREVIEW_CAPTURE);
165
- }
166
- return dropsEmptyId || classifies;
167
- };
168
- /**
169
- * Version 3 spelled "this drawing carries no relationship" two ways.
170
- *
171
- * `rId: ""` is not a key any relationship answers to, so an image that stated
172
- * it was a drawing with no relationship saying it had one: it reached a save
173
- * as `r:embed=""`, and only the lookups that knew to ask about both spellings
174
- * read it as the absence it was. The model has one spelling now, so the attr
175
- * loses the other.
176
- *
177
- * The same pass classifies the drawings that spelling hid. A VML shape folio
178
- * cannot project is carried as a render of its markup, and version 3 projected
179
- * that render as an ordinary editable picture: an edit dropped the capture, and
180
- * the save wrote the render into the package as a picture in place of the
181
- * shape. An image node that holds a capture, names no relationship and states
182
- * no mode is exactly that drawing, because every other captured drawing either
183
- * names a relationship or states its mode. Still holding the capture is what
184
- * says the node has not been edited, which is what the stamped marker means.
185
- */
186
- const classifyUnrelatedCapturedDrawings = (fragment) => {
187
- let rewritten = 0;
188
- const visit = (node) => {
189
- if ("nodeName" in node && node.nodeName === IMAGE_ELEMENT_NAME && migrateImageNode(node)) rewritten += 1;
190
- for (const child of node.toArray()) if (typeof child !== "string" && "toArray" in child) visit(child);
191
- };
192
- visit(fragment);
193
- return rewritten;
194
- };
195
- /** The node types whose stated cell width version 5 backfills. */
196
- const TABLE_CELL_ELEMENT_NAMES = /* @__PURE__ */ new Set(["tableCell", "tableHeader"]);
197
- /** Write a node attribute the binding stores as JSON. */
198
- const setJsonAttribute = (node, name, value) => {
199
- node.setAttribute(name, value);
200
- };
201
- const statedWidthOf = (attributes) => {
202
- const original = attributes["_originalFormatting"];
203
- if (typeof original !== "object" || original === null || !("width" in original)) return;
204
- const { width } = original;
205
- if (typeof width !== "object" || width === null) return;
206
- const value = attributes["width"];
207
- return typeof value === "number" ? {
208
- value,
209
- type: attributes["widthType"] ?? Reflect.get(width, "type")
210
- } : width;
211
- };
212
- /**
213
- * Version 5 adds `_authoredWidth` to table cells. Version 4 wrote `w:tcW`
214
- * from the resolved cell width, including cells that stated no preferred
215
- * width. `_originalFormatting.width` records which cells authored one, so
216
- * only those cells receive the new attr.
217
- */
218
- const backfillStatedCellWidths = (fragment) => {
219
- let rewritten = 0;
220
- const visit = (node) => {
221
- if ("nodeName" in node && TABLE_CELL_ELEMENT_NAMES.has(node.nodeName)) {
222
- const attributes = node.getAttributes();
223
- const stated = statedWidthOf(attributes);
224
- if (stated !== void 0) {
225
- setJsonAttribute(node, "_authoredWidth", stated);
226
- rewritten += 1;
227
- }
228
- }
229
- for (const child of node.toArray()) if (typeof child !== "string" && "toArray" in child) visit(child);
230
- };
231
- visit(fragment);
232
- return rewritten;
233
- };
234
- /**
235
- * Version 6 gives `tableRow`'s `hidden` attr the `null` default the other
236
- * tri-states carry. Up to version 5 it defaulted to `false`, and the reader
237
- * that filled it took only an explicit on, so a row that authored
238
- * `<w:hidden w:val="0"/>` and one that authored nothing were both stored as
239
- * `false`. `false` therefore never meant an explicit off and cannot be kept as
240
- * one: a version-5 snapshot's `false` would start writing an element the
241
- * document never carried. The explicit offs it does hold travelled as captured
242
- * bytes on `_originalFormatting`, which the step leaves alone.
243
- */
244
- const dropUnstatedRowHidden = (fragment) => {
245
- let rewritten = 0;
246
- const visit = (node) => {
247
- if ("nodeName" in node && node.nodeName === "tableRow") {
248
- if (node.getAttributes()["hidden"] === false) {
249
- node.removeAttribute("hidden");
250
- rewritten += 1;
251
- }
252
- }
253
- for (const child of node.toArray()) if (typeof child !== "string" && "toArray" in child) visit(child);
254
- };
255
- visit(fragment);
256
- return rewritten;
257
- };
258
- /**
259
- * The `_propertyChanges` entries a paragraph carries, as a version-7 snapshot
260
- * stored them: an array of records whose `previousFormatting` may carry the
261
- * numbering the paragraph had before a `w:pPrChange`.
262
- */
263
- const versionSevenPropertyChanges = (value) => {
264
- if (!Array.isArray(value)) return null;
265
- const changes = [];
266
- for (const change of value) {
267
- if (typeof change !== "object" || change === null || Array.isArray(change)) return null;
268
- changes.push(change);
269
- }
270
- return changes;
271
- };
272
- /** The two paragraph attrs, and the two formatting fields, that state numbering. */
273
- const NUMBERING_ATTR_KEYS = ["numPr", "numPrFromStyle"];
274
- /**
275
- * One stored two-slot value, as the union. `null` is an object that stated
276
- * neither slot, which stated nothing; `undefined` is a value this step must
277
- * leave exactly as it found it.
278
- *
279
- * A value that already carries a `kind` is one of those. Version 7 wrote the
280
- * model's union into `_originalFormatting` and into a recorded
281
- * `currentFormatting` while the `numPr` attr beside them still held the two
282
- * slots, so a version-7 paragraph can hold both spellings at once: that
283
- * divergence is what version 8 exists to end.
284
- */
285
- const versionSevenNumbering = (value) => {
286
- if (typeof value !== "object" || value === null || Array.isArray(value)) return;
287
- if (typeof Reflect.get(value, "kind") === "string") return;
288
- const numId = Reflect.get(value, "numId");
289
- const ilvl = Reflect.get(value, "ilvl");
290
- return paragraphNumberingFromSlots({
291
- ilvl: typeof ilvl === "number" ? ilvl : void 0,
292
- numId: typeof numId === "number" ? numId : void 0
293
- }) ?? null;
294
- };
295
- /**
296
- * A stored formatting record with its numbering keys carried forward, or
297
- * `null` when it holds nothing this step rewrites. `null` inside the record
298
- * survives: in `previousFormatting` it is the tombstone for "the paragraph
299
- * carried no numbering before the change".
300
- */
301
- const versionSevenFormatting = (value) => {
302
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
303
- const stored = { ...value };
304
- let changed = false;
305
- for (const key of NUMBERING_ATTR_KEYS) {
306
- const migrated = versionSevenNumbering(stored[key]);
307
- if (migrated === void 0) continue;
308
- changed = true;
309
- if (migrated === null) Reflect.deleteProperty(stored, key);
310
- else stored[key] = migrated;
311
- }
312
- return changed ? stored : null;
313
- };
314
- /**
315
- * Version 7 stored `numPr` as the two `<w:numPr>` slots, with the reserved
316
- * `numId` 0 for a cancellation and a bare `ilvl` for a level stated without an
317
- * id. Version 8 stores the model's union, so the pair has to be mapped:
318
- * `numId` 0 becomes `none` whatever level sat beside it (a cancellation names
319
- * no id for a level to belong to), an `ilvl` without a `numId` becomes
320
- * `levelOnly`, the two together become `reference`, and an object stating
321
- * neither slot stated nothing is dropped. An absent attr stays absent.
322
- *
323
- * Like the version-7 step it cannot be left to a lazy read: ProseMirror copies
324
- * a stored attr into the node without validating, and
325
- * `optionalParagraphNumbering` would then refuse the first read of an
326
- * untouched room.
327
- */
328
- const numberingBecomesAUnion = (fragment) => {
329
- let rewritten = 0;
330
- const visit = (node) => {
331
- if ("nodeName" in node && node.nodeName === PARAGRAPH_ELEMENT_NAME) {
332
- const attributes = node.getAttributes();
333
- let changed = false;
334
- for (const attr of NUMBERING_ATTR_KEYS) {
335
- const migrated = versionSevenNumbering(attributes[attr]);
336
- if (migrated === void 0) continue;
337
- changed = true;
338
- if (migrated === null) node.removeAttribute(attr);
339
- else node.setAttribute(attr, migrated);
340
- }
341
- const originalFormatting = versionSevenFormatting(attributes["_originalFormatting"]);
342
- if (originalFormatting !== null) {
343
- changed = true;
344
- node.setAttribute("_originalFormatting", originalFormatting);
345
- }
346
- const changes = versionSevenPropertyChanges(attributes["_propertyChanges"]);
347
- if (changes !== null) {
348
- let changesChanged = false;
349
- const migratedChanges = [];
350
- for (const change of changes) {
351
- const migrated = Object.assign({}, change);
352
- for (const tier of ["previousFormatting", "currentFormatting"]) {
353
- const formatting = versionSevenFormatting(change[tier]);
354
- if (formatting !== null) {
355
- migrated[tier] = formatting;
356
- changesChanged = true;
357
- }
358
- }
359
- migratedChanges.push(migrated);
360
- }
361
- if (changesChanged) {
362
- changed = true;
363
- node.setAttribute("_propertyChanges", migratedChanges);
364
- }
365
- }
366
- if (changed) rewritten += 1;
367
- }
368
- for (const child of node.toArray()) if (typeof child !== "string" && "toArray" in child) visit(child);
369
- };
370
- visit(fragment);
371
- return rewritten;
372
- };
373
- /**
374
- * Version 9 makes `_sectionProperties` the one carrier of a section break.
375
- * Earlier snapshots could state `sectionBreakType` instead, and the save leg
376
- * minted a `SectionProperties` from it. The attr is gone from the schema, so
377
- * the migration must mint that record before ProseMirror drops the old key.
378
- * A paragraph that already has the record keeps it as the authority.
379
- */
380
- const SECTION_BREAK_TYPE_ATTR = "sectionBreakType";
381
- const SECTION_PROPERTIES_ATTR = "_sectionProperties";
382
- const mintSectionPropertiesFromBreakType = (fragment) => {
383
- let rewritten = 0;
384
- const visit = (node) => {
385
- if ("nodeName" in node && node.nodeName === PARAGRAPH_ELEMENT_NAME) {
386
- const attributes = node.getAttributes();
387
- if (SECTION_BREAK_TYPE_ATTR in attributes) {
388
- const breakType = parseSectionBreakType(attributes[SECTION_BREAK_TYPE_ATTR]);
389
- if (breakType !== null && attributes[SECTION_PROPERTIES_ATTR] == null) node.setAttribute(SECTION_PROPERTIES_ATTR, mintSectionProperties(breakType));
390
- node.removeAttribute(SECTION_BREAK_TYPE_ATTR);
391
- rewritten += 1;
392
- }
393
- }
394
- for (const child of node.toArray()) if (typeof child !== "string" && "toArray" in child) visit(child);
395
- };
396
- visit(fragment);
397
- return rewritten;
398
- };
399
- /** The node types whose `showingPlaceholder` attr version 10 rewrites. */
400
- const SDT_ELEMENT_NAMES = /* @__PURE__ */ new Set(["sdt", "blockSdt"]);
401
- /**
402
- * Version 9 stored `showingPlaceholder` as a boolean defaulting to `false`.
403
- * A control that authored an explicit off and one that authored nothing were
404
- * both stored as `false`, so the old false cannot become a newly authored
405
- * `<w:showingPlcHdr w:val="0"/>` when the absence is now `null`.
406
- */
407
- const dropUnstatedPlaceholderFlags = (fragment) => {
408
- let rewritten = 0;
409
- const visit = (node) => {
410
- if ("nodeName" in node && SDT_ELEMENT_NAMES.has(node.nodeName)) {
411
- if (node.getAttributes()["showingPlaceholder"] === false) {
412
- node.removeAttribute("showingPlaceholder");
413
- rewritten += 1;
414
- }
415
- }
416
- for (const child of node.toArray()) if (typeof child !== "string" && "toArray" in child) visit(child);
417
- };
418
- visit(fragment);
419
- return rewritten;
420
- };
421
- /**
422
- * Version 11 renames the persisted `pageBreakRunOwner` mark to `runIdentity`.
423
- * Unknown mark names make y-prosemirror delete their covered text, so the
424
- * Y.Text delta must be rewritten before the ProseMirror document is built.
425
- */
426
- const renamePageBreakRunOwnerMarkAttr = (fragment) => {
427
- const OLD_MARK_NAME = "pageBreakRunOwner";
428
- const NEW_MARK_NAME = "runIdentity";
429
- let rewritten = 0;
430
- const rewriteText = (sharedText) => {
431
- let index = 0;
432
- const ranges = [];
433
- for (const op of sharedText.toDelta()) {
434
- const insert = op.insert;
435
- const length = typeof insert === "string" ? insert.length : 1;
436
- const attributes = op.attributes;
437
- if (isRecord(attributes) && OLD_MARK_NAME in attributes) ranges.push({
438
- at: index,
439
- length,
440
- owner: attributes[OLD_MARK_NAME]
441
- });
442
- index += length;
443
- }
444
- for (const { at, length, owner } of ranges) {
445
- const identity = isRecord(owner) && typeof owner["id"] === "number" ? { id: owner["id"] } : {};
446
- sharedText.format(at, length, {
447
- [OLD_MARK_NAME]: null,
448
- [NEW_MARK_NAME]: identity
449
- });
450
- rewritten += 1;
451
- }
452
- };
453
- const visit = (node) => {
454
- for (const child of node.toArray()) {
455
- if (typeof child === "string") continue;
456
- if (isXmlText(child)) {
457
- rewriteText(child);
458
- continue;
459
- }
460
- if ("toArray" in child) visit(child);
461
- }
462
- };
463
- visit(fragment);
464
- return rewritten;
465
- };
466
- /** Every attr-schema version this build reads, oldest first, with no gaps. */
467
- const FOLIO_YJS_ATTR_SCHEMA_VERSIONS = [
468
- 0,
469
- 1,
470
- 2,
471
- 3,
472
- 4,
473
- 5,
474
- 6,
475
- 7,
476
- 8,
477
- 9,
478
- 10,
479
- 11,
480
- 12,
481
- 13,
482
- 14,
483
- 15
484
- ];
485
- /**
486
- * The one place a persisted attr-shape change is decided.
487
- *
488
- * Changing the shape of any node or mark attr Folio persists means: append the
489
- * new version to {@link FOLIO_YJS_ATTR_SCHEMA_VERSIONS}, map the previous
490
- * version to the step that rewrites it, and map the new version to `"current"`.
491
- * The map is total over the version union, so a version added without a
492
- * decision does not compile, and `migrateFolioYjsSnapshot` picks the new step
493
- * up without being touched.
494
- */
495
- const ATTR_SCHEMA_MIGRATIONS = {
496
- 0: stampMarkerOnly,
497
- 1: dropUnstatedFieldFlags,
498
- 2: drawingTransformAttrsAreAdditive,
499
- 3: classifyUnrelatedCapturedDrawings,
500
- 4: backfillStatedCellWidths,
501
- 5: dropUnstatedRowHidden,
502
- 6: outlineLevelBecomesAUnion,
503
- 7: numberingBecomesAUnion,
504
- 8: mintSectionPropertiesFromBreakType,
505
- 9: dropUnstatedPlaceholderFlags,
506
- 10: renamePageBreakRunOwnerMarkAttr,
507
- 11: stampMarkerOnly,
508
- 12: stampMarkerOnly,
509
- 13: stampMarkerOnly,
510
- 14: orderRangeAnchorMarkers,
511
- 15: "current"
512
- };
513
- /**
514
- * The attr-schema version this build writes. Derived against the migration map
515
- * so the constant and the map cannot disagree.
516
- */
517
- const FOLIO_YJS_ATTR_SCHEMA_VERSION = 15;
518
- const ORDERED_RANGE_ANCHOR_SCHEMA_VERSION = 15;
519
- const FolioYjsRangeAnchorSchemaErrorBase = TaggedError("FolioYjsRangeAnchorSchemaError");
520
- /** A stored point anchor must retain a valid, ordered source-marker pair. */
521
- var FolioYjsRangeAnchorSchemaError = class extends FolioYjsRangeAnchorSchemaErrorBase {};
522
- /** Validate every old pair before any migration is allowed to mutate the fragment. */
523
- const legacyRangeAnchors = (fragment, schemaVersion) => {
524
- const changes = [];
525
- const visit = (node) => {
526
- if ("nodeName" in node && node.nodeName === "rangeAnchor") {
527
- const attrs = node.getAttributes();
528
- const markers = readRangeAnchorValues([attrs["start"], attrs["end"]]);
529
- if (!markers.ok) throw new FolioYjsRangeAnchorSchemaError({
530
- schemaVersion,
531
- message: `Yjs schema ${schemaVersion} has an invalid point-range marker pair. Rebuild the collaboration state from the saved DOCX.`
532
- });
533
- changes.push({
534
- node,
535
- attrs: markers.value
536
- });
537
- }
538
- for (const child of node.toArray()) if (typeof child !== "string" && !isXmlText(child) && "toArray" in child) visit(child);
539
- };
540
- visit(fragment);
541
- return changes;
542
- };
543
- /** Version 14 atoms each held one pair; the same ordered pair is a sequence in 15. */
544
- function orderRangeAnchorMarkers(fragment) {
545
- const changes = legacyRangeAnchors(fragment, 14);
546
- for (const { node, attrs } of changes) {
547
- setJsonAttribute(node, "markers", attrs.markers);
548
- node.removeAttribute("start");
549
- node.removeAttribute("end");
550
- }
551
- return changes.length;
552
- }
553
- const STATED_NUMBERING_SOURCE_SCHEMA_VERSION = 13;
554
- const FolioYjsNoteReferenceSchemaErrorBase = TaggedError("FolioYjsNoteReferenceSchemaError");
555
- var FolioYjsNoteReferenceSchemaError = class extends FolioYjsNoteReferenceSchemaErrorBase {};
556
- const FolioYjsNumberingSourceSchemaErrorBase = TaggedError("FolioYjsNumberingSourceSchemaError");
557
- var FolioYjsNumberingSourceSchemaError = class extends FolioYjsNumberingSourceSchemaErrorBase {};
558
- /** Older snapshots can hold a resolved style reference where a stated override belongs. */
559
- const requireStatedNumberingSources = (fragment, schemaVersion) => {
560
- if (schemaVersion >= STATED_NUMBERING_SOURCE_SCHEMA_VERSION) return;
561
- const pending = [];
562
- const visit = (node) => {
563
- if ("getAttributes" in node) pending.push(node.getAttributes());
564
- for (const child of node.toArray()) if (typeof child !== "string" && !isXmlText(child) && "toArray" in child) visit(child);
565
- };
566
- visit(fragment);
567
- const seen = /* @__PURE__ */ new WeakSet();
568
- while (pending.length > 0) {
569
- const value = pending.pop();
570
- if (typeof value !== "object" || value === null || seen.has(value)) continue;
571
- seen.add(value);
572
- if (Array.isArray(value)) {
573
- for (const entry of value) pending.push(entry);
574
- continue;
575
- }
576
- if (!isRecord(value)) continue;
577
- const numbering = value["numPr"];
578
- if (isRecord(value["numPrFromStyle"]) && isRecord(numbering) && (numbering["kind"] === "reference" || "numId" in numbering)) throw new FolioYjsNumberingSourceSchemaError({
579
- schemaVersion,
580
- requiredSchemaVersion: STATED_NUMBERING_SOURCE_SCHEMA_VERSION,
581
- message: `Yjs schema ${schemaVersion} has ambiguous numbering ownership; schema ${STATED_NUMBERING_SOURCE_SCHEMA_VERSION} requires stated numbering overrides. Rebuild the collaboration state from the saved DOCX.`
582
- });
583
- for (const entry of Object.values(value)) pending.push(entry);
584
- }
585
- };
586
- /** Check before any migration mutates the snapshot or any PM builder can drop text. */
587
- const requireNoteOccurrenceAttribution = (fragment, schemaVersion) => {
588
- const visit = (node) => {
589
- for (const child of node.toArray()) {
590
- if (typeof child === "string") continue;
591
- if (!isXmlText(child)) {
592
- if ("toArray" in child) visit(child);
593
- continue;
594
- }
595
- for (const op of child.toDelta()) {
596
- const attributes = op.attributes;
597
- if (!isRecord(attributes) || attributes["footnoteRef"] == null) continue;
598
- const reference = attributes["footnoteRef"];
599
- if (isRecord(reference) && isNoteReferenceOccurrenceId(reference["occurrenceId"])) continue;
600
- throw new FolioYjsNoteReferenceSchemaError({
601
- schemaVersion,
602
- requiredSchemaVersion: 15,
603
- message: `Yjs schema ${schemaVersion} has unattributed note references; schema 15 requires occurrence identities. Rebuild the collaboration state from the saved DOCX.`
604
- });
605
- }
606
- }
607
- };
608
- visit(fragment);
609
- };
610
- /**
611
- * The steps that carry a snapshot written under `fromVersion` up to
612
- * {@link FOLIO_YJS_ATTR_SCHEMA_VERSION}, in order. Empty when the snapshot is
613
- * already current.
614
- */
615
- const attrSchemaMigrationSteps = (fromVersion) => FOLIO_YJS_ATTR_SCHEMA_VERSIONS.filter((version) => version >= fromVersion).flatMap((version) => {
616
- const step = ATTR_SCHEMA_MIGRATIONS[version];
617
- return step === "current" ? [] : [step];
618
- });
619
- /**
620
- * Carry a fragment this build is about to read or write up to the attr shape
621
- * this build writes, and stamp the marker.
622
- *
623
- * Every entry point that hands a fragment to `initProseMirrorDoc` calls this,
624
- * for two reasons that are the same reason. A step that rewrites values has to
625
- * run before a node is built from them, or the build reads the old shape as
626
- * the new one. And the marker has to say what the fragment may now hold before
627
- * the first edit writes an attr of this build's shape into it, because an
628
- * older build reading an unmarked snapshot drops what it does not know without
629
- * a trace.
630
- *
631
- * Returns how many elements the steps rewrote.
632
- */
633
- const applyAttrSchemaMigrations = (ydoc, fragment, fromVersion) => {
634
- requireNoteOccurrenceAttribution(fragment, fromVersion);
635
- requireStatedNumberingSources(fragment, fromVersion);
636
- if (fromVersion < ORDERED_RANGE_ANCHOR_SCHEMA_VERSION) legacyRangeAnchors(fragment, fromVersion);
637
- if (fromVersion === 15) return 0;
638
- let rewritten = 0;
639
- ydoc.transact(() => {
640
- for (const step of attrSchemaMigrationSteps(fromVersion)) rewritten += step(fragment);
641
- writeYjsAttrSchemaVersion(ydoc);
642
- });
643
- return rewritten;
644
- };
645
- /** Raised when a snapshot's attr-schema marker is ahead of the running code. */
646
- var FolioYjsAttrSchemaVersionError = class extends FolioYjsAttrSchemaVersionErrorBase {};
647
- const isReadableVersion = (marker) => typeof marker === "number" && Number.isInteger(marker) && marker >= 0 && marker <= 15;
648
- /**
649
- * The attr-schema version a collaboration document was written under.
650
- *
651
- * An absent marker is version 0: every snapshot predates the marker, so no
652
- * backfill is needed to classify one. An older version loads, because
653
- * {@link attrSchemaMigrationSteps} says what it means. A marker this
654
- * build does not know is a snapshot written by newer code, and reading it would
655
- * be a silent misread: ProseMirror copies unknown attr values into the node
656
- * verbatim and drops unknown keys without a trace. It fails instead.
657
- */
658
- const readYjsAttrSchemaVersion = (ydoc) => {
659
- const marker = ydoc.getMap(FOLIO_YJS_METADATA_MAP_NAME).get(ATTR_SCHEMA_VERSION_KEY);
660
- if (marker === void 0) return Result.ok(0);
661
- if (isReadableVersion(marker)) return Result.ok(marker);
662
- return Result.err(new FolioYjsAttrSchemaVersionError({
663
- marker,
664
- message: "The collaboration snapshot was written by a newer Folio attr schema than this build reads.",
665
- supportedVersion: 15
666
- }));
667
- };
668
- const proseDocumentParagraphSourceContract = (document) => {
669
- return getProseDocumentParagraphPropertySourceContract(document);
670
- };
671
- /** Stamp the attr-schema version of the build that wrote the current fragment. */
672
- const writeYjsAttrSchemaVersion = (ydoc) => {
673
- ydoc.getMap(FOLIO_YJS_METADATA_MAP_NAME).set(ATTR_SCHEMA_VERSION_KEY, 15);
674
- };
675
- /**
676
- * Write both metadata bindings for a freshly seeded collaboration document.
677
- * The attr-schema version is written unconditionally; the paragraph-source
678
- * contract only when the seeding document carries one, because a document
679
- * built in memory rather than parsed from a package has no source to bind to.
680
- */
681
- const writeYjsDocumentMetadata = (ydoc, document) => {
682
- writeYjsAttrSchemaVersion(ydoc);
683
- const contract = proseDocumentParagraphSourceContract(document);
684
- if (contract) ydoc.getMap(FOLIO_YJS_METADATA_MAP_NAME).set(PARAGRAPH_SOURCE_CONTRACT_KEY, contract);
685
- };
686
- const readYjsParagraphSourceContract = (ydoc) => {
687
- const contract = ydoc.getMap(FOLIO_YJS_METADATA_MAP_NAME).get(PARAGRAPH_SOURCE_CONTRACT_KEY);
688
- return typeof contract === "string" ? contract : null;
689
- };
690
- const withParagraphSourceContract = (document, contract) => {
691
- if (document.type.name !== "doc") panic("A paragraph-property source contract can only attach to a document node");
692
- return document.type.create({
693
- ...document.attrs,
694
- [PROSE_PARAGRAPH_SOURCE_CONTRACT_ATTR]: contract
695
- }, document.content, document.marks);
696
- };
697
- export { FOLIO_YJS_ATTR_SCHEMA_VERSION, FolioYjsAttrSchemaVersionError, FolioYjsNoteReferenceSchemaError, FolioYjsNumberingSourceSchemaError, FolioYjsRangeAnchorSchemaError, applyAttrSchemaMigrations, attrSchemaMigrationSteps, proseDocumentParagraphSourceContract, readYjsAttrSchemaVersion, readYjsParagraphSourceContract, withParagraphSourceContract, writeYjsAttrSchemaVersion, writeYjsDocumentMetadata };