@stll/docx-core 0.27.0 → 0.28.1

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.
@@ -0,0 +1,2698 @@
1
+ import "../document-DdWrTPQY.js";
2
+ import { r as hasIllegalXmlCharacters } from "../xmlEscape-T-2DeGlS.js";
3
+ import { Result, TaggedError, panic } from "better-result";
4
+ //#region src/ops/equality.ts
5
+ const NOTHING = /* @__PURE__ */ new Set();
6
+ const equal = (left, right, skipped) => {
7
+ if (Object.is(left, right)) return true;
8
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) return false;
9
+ if (Array.isArray(left) || Array.isArray(right)) {
10
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
11
+ return left.every((item, index) => equal(item, right[index], skipped));
12
+ }
13
+ const fields = (record) => {
14
+ const entries = Object.entries(record);
15
+ const skip = skipped(entries);
16
+ return entries.filter(([key, value]) => value !== void 0 && !skip.has(key));
17
+ };
18
+ const leftEntries = fields(left);
19
+ const rightEntries = new Map(fields(right));
20
+ if (leftEntries.length !== rightEntries.size) return false;
21
+ return leftEntries.every(([key, value]) => rightEntries.has(key) && equal(value, rightEntries.get(key), skipped));
22
+ };
23
+ const structurallyEqual = (left, right) => equal(left, right, () => NOTHING);
24
+ /**
25
+ * Paragraph fields a layout or numbering pass recomputes. They describe the
26
+ * content rather than being it, so they never make an operation's
27
+ * precondition stale.
28
+ */
29
+ const DERIVED_PARAGRAPH_FIELDS = /* @__PURE__ */ new Set(["listRendering", "renderedPageBreakBefore"]);
30
+ const derivedFields = (entries) => entries.some(([key, value]) => key === "type" && value === "paragraph") ? DERIVED_PARAGRAPH_FIELDS : NOTHING;
31
+ /**
32
+ * The equality an operation's precondition is checked under: structural,
33
+ * with the fields a relayout or renumbering recomputes left out. An undo is
34
+ * refused as stale when the content it expects has changed, never because
35
+ * numbering or pagination was recomputed since.
36
+ */
37
+ const equalForStaleness = (left, right) => equal(left, right, derivedFields);
38
+ //#endregion
39
+ //#region src/ops/types.ts
40
+ /** The operation schema this module reads and writes. */
41
+ const DOCUMENT_OP_SCHEMA_VERSION = 1;
42
+ /**
43
+ * The stories an operation can address. Headers, footers, notes and comment
44
+ * bodies are stories too; version 1 addresses the main story only.
45
+ */
46
+ const OP_STORIES = Object.freeze({ MAIN: "main" });
47
+ /**
48
+ * What a property set a patch leaves without keys becomes: absent, or an
49
+ * empty set. The two state the same thing; the choice is how an inverse
50
+ * gives back a record in the spelling it had.
51
+ */
52
+ const EMPTY_PROPERTY_SETS = Object.freeze({
53
+ OMIT: "omit",
54
+ KEEP: "keep"
55
+ });
56
+ /**
57
+ * Inserted text takes the properties of the run it joins: the run holding the
58
+ * unit before the position, or the one after it at the start of a paragraph.
59
+ */
60
+ const INHERIT_RUN_PROPS = "inherit";
61
+ /** The operation kinds of schema version 1. */
62
+ const DOCUMENT_OP_TYPES = Object.freeze({
63
+ INSERT_TEXT: "insertText",
64
+ INSERT_CONTENT: "insertContent",
65
+ DELETE_RANGE: "deleteRange",
66
+ SPLIT_INLINE: "splitInline",
67
+ JOIN_INLINE: "joinInline",
68
+ SET_RUN_PROPS: "setRunProps",
69
+ SET_PARAGRAPH_PROPS: "setParagraphProps",
70
+ SPLIT_BLOCK: "splitBlock",
71
+ JOIN_BLOCKS: "joinBlocks",
72
+ REPLACE_BLOCKS: "replaceBlocks"
73
+ });
74
+ /** An operation in the envelope it is journaled and sent in. */
75
+ const toOpEnvelope = (op) => ({
76
+ schema: 1,
77
+ op
78
+ });
79
+ //#endregion
80
+ //#region src/ops/blocks.ts
81
+ /**
82
+ * Finding and replacing paragraphs in a story.
83
+ *
84
+ * A story is a tree of block lists: the body, each table cell and each block
85
+ * content control holds one. A paragraph is found by its `w14:paraId`
86
+ * wherever it sits in that tree, and a replacement rebuilds only the records
87
+ * on the path to it, so every other block is `===` to its input.
88
+ */
89
+ const collectParagraphs = (blocks, list, out) => {
90
+ for (const [index, block] of blocks.entries()) switch (block.type) {
91
+ case "paragraph":
92
+ out.push({
93
+ list,
94
+ index,
95
+ paragraph: block
96
+ });
97
+ break;
98
+ case "table":
99
+ for (const [row, tableRow] of block.rows.entries()) for (const [cell, tableCell] of tableRow.cells.entries()) collectParagraphs(tableCell.content, [...list, {
100
+ kind: "tableCell",
101
+ block: index,
102
+ row,
103
+ cell
104
+ }], out);
105
+ break;
106
+ case "blockSdt":
107
+ collectParagraphs(block.content, [...list, {
108
+ kind: "blockSdt",
109
+ block: index
110
+ }], out);
111
+ break;
112
+ case "blockCustomXml":
113
+ collectParagraphs(block.content, [...list, {
114
+ kind: "blockCustomXml",
115
+ block: index
116
+ }], out);
117
+ break;
118
+ case "preservedBlock":
119
+ case "bookmarkStart":
120
+ case "bookmarkEnd": break;
121
+ default: return block;
122
+ }
123
+ };
124
+ /** The block-level content of a story. */
125
+ const storyBody = (document, story) => {
126
+ switch (story) {
127
+ case OP_STORIES.MAIN: return document.package.document;
128
+ default: return story;
129
+ }
130
+ };
131
+ /** Every paragraph of a story's block tree, in document order. */
132
+ const storyParagraphs = (body) => {
133
+ const out = [];
134
+ collectParagraphs(body.content, [], out);
135
+ return out;
136
+ };
137
+ const sameStep = (left, right) => {
138
+ switch (left.kind) {
139
+ case "tableCell": return right.kind === "tableCell" && left.block === right.block && left.row === right.row && left.cell === right.cell;
140
+ case "blockSdt": return right.kind === "blockSdt" && left.block === right.block;
141
+ case "blockCustomXml": return right.kind === "blockCustomXml" && left.block === right.block;
142
+ default: return left;
143
+ }
144
+ };
145
+ /** Whether two locations are in the same block list. */
146
+ const sameBlockList = (left, right) => left.length === right.length && left.every((step, index) => {
147
+ const other = right[index];
148
+ return other !== void 0 && sameStep(step, other);
149
+ });
150
+ const updateBlockList = (blocks, list, update) => {
151
+ const [step, ...rest] = list;
152
+ if (step === void 0) return update(blocks);
153
+ const block = blocks[step.block];
154
+ const out = [...blocks];
155
+ switch (step.kind) {
156
+ case "tableCell": {
157
+ const row = block?.type === "table" ? block.rows[step.row] : void 0;
158
+ const cell = row?.cells[step.cell];
159
+ if (block?.type !== "table" || row === void 0 || cell === void 0) return panic(`Block list step does not name a table cell at block ${step.block}.`);
160
+ const cells = [...row.cells];
161
+ cells[step.cell] = {
162
+ ...cell,
163
+ content: updateBlockList(cell.content, rest, update)
164
+ };
165
+ const rows = [...block.rows];
166
+ rows[step.row] = {
167
+ ...row,
168
+ cells
169
+ };
170
+ out[step.block] = {
171
+ ...block,
172
+ rows
173
+ };
174
+ return out;
175
+ }
176
+ case "blockSdt":
177
+ if (block?.type !== "blockSdt") return panic(`Block list step does not name a block content control at ${step.block}.`);
178
+ out[step.block] = {
179
+ ...block,
180
+ content: updateBlockList(block.content, rest, update)
181
+ };
182
+ return out;
183
+ case "blockCustomXml":
184
+ if (block?.type !== "blockCustomXml") return panic(`Block list step does not name a custom XML wrapper at ${step.block}.`);
185
+ out[step.block] = {
186
+ ...block,
187
+ content: updateBlockList(block.content, rest, update)
188
+ };
189
+ return out;
190
+ default: return step;
191
+ }
192
+ };
193
+ const breaksSection = (block) => block.type === "paragraph" && block.sectionProperties !== void 0;
194
+ /**
195
+ * The body's blocks grouped as the parser groups them into sections: each
196
+ * top-level paragraph carrying section properties ends one and the rest end
197
+ * the last. The last group is dropped when it is empty and an earlier section
198
+ * exists, as the parser does.
199
+ */
200
+ const sectionGroups = (content) => {
201
+ const groups = [];
202
+ let current = [];
203
+ for (const block of content) {
204
+ current.push(block);
205
+ if (breaksSection(block)) {
206
+ groups.push(current);
207
+ current = [];
208
+ }
209
+ }
210
+ if (current.length > 0 || groups.length === 0) groups.push(current);
211
+ return groups;
212
+ };
213
+ /**
214
+ * `sections`, the parser's per-section view of the body's top-level blocks,
215
+ * derived again from the body after an edit. Section `i` keeps every field of
216
+ * the section it replaces (properties, headers, footers) and holds group `i`;
217
+ * a section whose group is unchanged is the same object. Operations never
218
+ * add, remove or move a section break, so a different count is a bug here.
219
+ */
220
+ const deriveSections = (content, previous) => {
221
+ const groups = sectionGroups(content);
222
+ if (groups.length !== previous.length) return panic(`An edit changed the section count from ${previous.length} to ${groups.length}.`);
223
+ let changed = false;
224
+ const out = [];
225
+ for (const [index, section] of previous.entries()) {
226
+ const group = groups[index] ?? [];
227
+ const same = group.length === section.content.length && group.every((block, position) => block === section.content[position]);
228
+ changed ||= !same;
229
+ out.push(same ? section : {
230
+ ...section,
231
+ content: group
232
+ });
233
+ }
234
+ return changed ? out : previous;
235
+ };
236
+ /**
237
+ * A body holding other blocks, its section view derived from them. A view
238
+ * that does not line up with the blocks (a different section count) is left
239
+ * for {@link sectionsInStep} to report.
240
+ */
241
+ const withBodyContent = (body, content) => {
242
+ const next = {
243
+ ...body,
244
+ content
245
+ };
246
+ if (body.sections !== void 0 && sectionGroups(content).length === body.sections.length) next.sections = deriveSections(content, body.sections);
247
+ return next;
248
+ };
249
+ /**
250
+ * Whether a body's section view says what its blocks say: the same groups
251
+ * of structurally equal blocks, each ended by a paragraph whose section
252
+ * properties the section carries. A view out of step with its body cannot be
253
+ * edited: every edit derives the view again, and its inverse could not give
254
+ * back the stale one.
255
+ */
256
+ const sectionsInStep = (body) => {
257
+ const { sections } = body;
258
+ if (sections === void 0) return true;
259
+ const groups = sectionGroups(body.content);
260
+ if (groups.length !== sections.length) return false;
261
+ return sections.every((section, index) => {
262
+ const group = groups[index] ?? [];
263
+ if (!(group.length === section.content.length && group.every((block, position) => block === section.content[position] || structurallyEqual(block, section.content[position])))) return false;
264
+ const last = group.at(-1);
265
+ const stated = last?.type === "paragraph" && last.sectionProperties !== void 0 ? last.sectionProperties : body.finalSectionProperties;
266
+ return stated === void 0 || structurallyEqual(stated, section.properties);
267
+ });
268
+ };
269
+ /** The document with `count` paragraphs from `at` replaced. */
270
+ const replaceParagraphs = ({ document, story, at, count, replacement }) => {
271
+ const body = storyBody(document, story);
272
+ const content = updateBlockList(body.content, at.list, (blocks) => {
273
+ const out = [...blocks];
274
+ out.splice(at.index, count, ...replacement);
275
+ return out;
276
+ });
277
+ const nextBody = {
278
+ ...body,
279
+ content
280
+ };
281
+ if (body.sections !== void 0) nextBody.sections = deriveSections(content, body.sections);
282
+ switch (story) {
283
+ case OP_STORIES.MAIN: return {
284
+ ...document,
285
+ package: {
286
+ ...document.package,
287
+ document: nextBody
288
+ }
289
+ };
290
+ default: return story;
291
+ }
292
+ };
293
+ //#endregion
294
+ //#region src/ops/ids.ts
295
+ const isPlainRecord = (value) => {
296
+ const prototype = Object.getPrototypeOf(value);
297
+ return prototype === Object.prototype || prototype === null;
298
+ };
299
+ const walk = (value, visit, heldBy) => {
300
+ if (typeof value !== "object" || value === null) return;
301
+ if (Array.isArray(value)) {
302
+ for (const item of value) walk(item, visit, heldBy);
303
+ return;
304
+ }
305
+ if (value instanceof Map) {
306
+ for (const item of value.values()) walk(item, visit, heldBy);
307
+ return;
308
+ }
309
+ if (!isPlainRecord(value)) return;
310
+ const entries = Object.entries(value);
311
+ visit(entries, heldBy);
312
+ for (const [key, field] of entries) walk(field, visit, key);
313
+ };
314
+ /** The package's stories, each once: the body without its derived section view. */
315
+ const storiesOf = (pkg) => ({
316
+ ...pkg,
317
+ document: {
318
+ ...pkg.document,
319
+ sections: void 0
320
+ }
321
+ });
322
+ const fieldOf = (entries, name) => entries.find(([key]) => key === name)?.[1];
323
+ const paragraphIdOf = (entries) => {
324
+ if (fieldOf(entries, "type") !== "paragraph") return void 0;
325
+ const id = fieldOf(entries, "paraId");
326
+ return typeof id === "string" ? id : void 0;
327
+ };
328
+ /** Every `paraId` of every paragraph in a value, nested ones included, in document order. */
329
+ const paragraphIdsIn = (value) => {
330
+ const out = [];
331
+ walk(value, (entries) => {
332
+ const id = paragraphIdOf(entries);
333
+ if (id !== void 0) out.push(id);
334
+ });
335
+ return out;
336
+ };
337
+ /** Every paragraph id of a package, each story walked once. */
338
+ const packageParagraphIds = (pkg) => paragraphIdsIn(storiesOf(pkg));
339
+ /**
340
+ * The key two spellings of one id share. `ST_LongHexNumber` is hex, so
341
+ * `0000abcd` and `0000ABCD` are the same id; every lookup and comparison of
342
+ * paragraph ids goes through this.
343
+ */
344
+ const idKey = (id) => id.toUpperCase();
345
+ /** How many records carry each key. */
346
+ const countKeys = (keys) => {
347
+ const counts = /* @__PURE__ */ new Map();
348
+ for (const key of keys) counts.set(key, (counts.get(key) ?? 0) + 1);
349
+ return counts;
350
+ };
351
+ /** How many paragraphs carry each id, by {@link idKey}. */
352
+ const countIds = (ids) => countKeys(ids.map(idKey));
353
+ /** Whether `incoming` repeats an id of `existing` or of itself, by {@link idKey}. */
354
+ const collides = (existing, incoming) => {
355
+ const seen = /* @__PURE__ */ new Set();
356
+ return incoming.some((id) => {
357
+ const key = idKey(id);
358
+ const repeated = seen.has(key) || (existing.get(key) ?? 0) > 0;
359
+ seen.add(key);
360
+ return repeated;
361
+ });
362
+ };
363
+ /** `ST_LongHexNumber` as `w14:paraId` uses it: eight hex digits below `0x80000000`. */
364
+ const PARA_ID_PATTERN = /^[0-7][0-9A-Fa-f]{7}$/u;
365
+ /** Zero is reserved: it means "no id". */
366
+ const RESERVED_PARA_ID_PATTERN = /^0{8}$/u;
367
+ /** Whether an id can name a paragraph an operation creates. */
368
+ const isParaId = (id) => PARA_ID_PATTERN.test(id) && !RESERVED_PARA_ID_PATTERN.test(id);
369
+ /** The id spaces of revisions and content controls. */
370
+ const IDENTITY_SPACES = Object.freeze({
371
+ REVISION: "revision",
372
+ CONTROL: "control"
373
+ });
374
+ const slotKey = ({ space, id }) => `${space}:${id}`;
375
+ const revisionIdOf = (entries) => {
376
+ const info = fieldOf(entries, "info");
377
+ if (typeof info !== "object" || info === null) return void 0;
378
+ const infoEntries = Object.entries(info);
379
+ const id = fieldOf(infoEntries, "id");
380
+ return typeof id === "number" && typeof fieldOf(infoEntries, "author") === "string" ? id : void 0;
381
+ };
382
+ const controlIdOf = (entries) => {
383
+ const id = fieldOf(entries, "id");
384
+ return typeof fieldOf(entries, "sdtType") === "string" && typeof id === "number" ? id : void 0;
385
+ };
386
+ /**
387
+ * Every revision and content-control id in a value, as slot keys: tracked
388
+ * changes and property changes by their `info`, content controls by their
389
+ * properties.
390
+ */
391
+ const identityKeysIn = (value) => {
392
+ const out = [];
393
+ const stacked = /* @__PURE__ */ new Map();
394
+ walk(value, (entries, heldBy) => {
395
+ const revision = revisionIdOf(entries);
396
+ if (revision !== void 0) out.push(slotKey({
397
+ space: IDENTITY_SPACES.REVISION,
398
+ id: revision
399
+ }));
400
+ const control = controlIdOf(entries);
401
+ if (control === void 0) return;
402
+ if (heldBy === CONTENT_CONTROL_STACK) {
403
+ const record = Object.fromEntries(entries);
404
+ const seen = stacked.get(control) ?? [];
405
+ if (seen.some((other) => structurallyEqual(other, record))) return;
406
+ seen.push(record);
407
+ stacked.set(control, seen);
408
+ }
409
+ out.push(slotKey({
410
+ space: IDENTITY_SPACES.CONTROL,
411
+ id: control
412
+ }));
413
+ });
414
+ return out;
415
+ };
416
+ /** The field holding the stack of content controls a table row or cell sits inside. */
417
+ const CONTENT_CONTROL_STACK = "contentControls";
418
+ /** Every revision and content-control id of a package, each story walked once. */
419
+ const packageIdentityKeys = (pkg) => identityKeysIn(storiesOf(pkg));
420
+ //#endregion
421
+ //#region src/ops/offsets.ts
422
+ /**
423
+ * A paragraph's logical offset space.
424
+ *
425
+ * Every position an operation names is a count of units from the start of a
426
+ * paragraph:
427
+ *
428
+ * - a character of run text is one unit per UTF-16 code unit;
429
+ * - every other run child (tab, break, symbol, note reference, drawing,
430
+ * captured markup, field character) is one unit, except the cached
431
+ * rendered-page-break marker a layout pass writes, which is zero-width;
432
+ * - a field, an equation and a comment reference are one unit each, however
433
+ * much they hold;
434
+ * - captured inline markup is one unit when it shows text and none when it
435
+ * shows nothing;
436
+ * - bookmark, comment and move boundaries take no units;
437
+ * - hyperlinks, tracked changes, content controls and the transparent
438
+ * wrappers take none themselves: their content is counted in place.
439
+ *
440
+ * Tracked-deleted text counts like any other: the visible-text view is
441
+ * derived, and positions stay stable when a revision is accepted or rejected
442
+ * elsewhere in the paragraph.
443
+ */
444
+ /** How each paragraph child takes part in the offset space. */
445
+ const INLINE_KINDS = {
446
+ run: "run",
447
+ hyperlink: "container",
448
+ insertion: "container",
449
+ deletion: "container",
450
+ moveFrom: "container",
451
+ moveTo: "container",
452
+ inlineSdt: "container",
453
+ inlineWrapper: "container",
454
+ simpleField: "atom",
455
+ complexField: "atom",
456
+ mathEquation: "atom",
457
+ commentReference: "atom",
458
+ preservedInline: "opaque",
459
+ bookmarkStart: "openingMarker",
460
+ commentRangeStart: "openingMarker",
461
+ moveFromRangeStart: "openingMarker",
462
+ moveToRangeStart: "openingMarker",
463
+ bookmarkEnd: "closingMarker",
464
+ commentRangeEnd: "closingMarker",
465
+ moveFromRangeEnd: "closingMarker",
466
+ moveToRangeEnd: "closingMarker"
467
+ };
468
+ const isInlineContainer = (item) => INLINE_KINDS[item.type] === "container";
469
+ /** A zero-width boundary that opens a range: it belongs with what follows it. */
470
+ const isOpeningMarker = (item) => INLINE_KINDS[item.type] === "openingMarker";
471
+ /** Tracked content that direct text must not join: it is on its way out. */
472
+ const isRemovedRevision = (item) => item.type === "deletion" || item.type === "moveFrom";
473
+ const runContentWidth = (content) => {
474
+ switch (content.type) {
475
+ case "text": return content.text.length;
476
+ case "renderedPageBreak": return 0;
477
+ default: return 1;
478
+ }
479
+ };
480
+ const runWidth = (run) => {
481
+ let width = 0;
482
+ for (const content of run.content) width += runContentWidth(content);
483
+ return width;
484
+ };
485
+ const childrenOf = (container) => container.type === "hyperlink" ? container.children : container.content;
486
+ const inlineWidth = (item) => {
487
+ if (item.type === "run") return runWidth(item);
488
+ if (isInlineContainer(item)) return contentWidth(childrenOf(item));
489
+ if (item.type === "preservedInline") return item.text === "" ? 0 : 1;
490
+ return INLINE_KINDS[item.type] === "atom" ? 1 : 0;
491
+ };
492
+ const contentWidth = (items) => {
493
+ let width = 0;
494
+ for (const item of items) width += inlineWidth(item);
495
+ return width;
496
+ };
497
+ /** The number of logical units in a paragraph: its largest valid offset. */
498
+ const paragraphLength = (paragraph) => contentWidth(paragraph.content);
499
+ /** The character a unit that is not run text stands for in {@link paragraphLogicalText}. */
500
+ const OBJECT_REPLACEMENT_CHARACTER = "";
501
+ const appendLogicalText = (items, out) => {
502
+ for (const item of items) {
503
+ if (item.type === "run") {
504
+ for (const content of item.content) if (content.type === "text") out.push(content.text);
505
+ else if (runContentWidth(content) === 1) out.push("");
506
+ continue;
507
+ }
508
+ if (isInlineContainer(item)) {
509
+ appendLogicalText(childrenOf(item), out);
510
+ continue;
511
+ }
512
+ if (inlineWidth(item) === 1) out.push("");
513
+ }
514
+ };
515
+ /**
516
+ * The paragraph's offset space as a string: run text as it stands and
517
+ * {@link OBJECT_REPLACEMENT_CHARACTER} for every other unit, so index `i` of
518
+ * the string is unit `i` of the paragraph.
519
+ */
520
+ const paragraphLogicalText = (paragraph) => {
521
+ const out = [];
522
+ appendLogicalText(paragraph.content, out);
523
+ return out.join("");
524
+ };
525
+ const HYPERLINK_CHILD_TYPES = {
526
+ run: true,
527
+ bookmarkStart: true,
528
+ bookmarkEnd: true,
529
+ inlineWrapper: true,
530
+ preservedInline: true
531
+ };
532
+ const TRACKED_CHILD_TYPES = {
533
+ run: true,
534
+ hyperlink: true,
535
+ bookmarkStart: true,
536
+ bookmarkEnd: true,
537
+ moveFromRangeStart: true,
538
+ moveFromRangeEnd: true,
539
+ moveToRangeStart: true,
540
+ moveToRangeEnd: true,
541
+ simpleField: true,
542
+ complexField: true,
543
+ inlineSdt: true,
544
+ inlineWrapper: true,
545
+ mathEquation: true,
546
+ preservedInline: true,
547
+ insertion: true,
548
+ deletion: true,
549
+ moveFrom: true,
550
+ moveTo: true
551
+ };
552
+ const INLINE_SDT_CHILD_TYPES = {
553
+ run: true,
554
+ hyperlink: true,
555
+ bookmarkStart: true,
556
+ bookmarkEnd: true,
557
+ moveFromRangeStart: true,
558
+ moveFromRangeEnd: true,
559
+ moveToRangeStart: true,
560
+ moveToRangeEnd: true,
561
+ simpleField: true,
562
+ complexField: true,
563
+ inlineSdt: true,
564
+ inlineWrapper: true,
565
+ insertion: true,
566
+ deletion: true,
567
+ moveFrom: true,
568
+ moveTo: true,
569
+ mathEquation: true,
570
+ preservedInline: true
571
+ };
572
+ const isHyperlinkChild = (item) => Object.hasOwn(HYPERLINK_CHILD_TYPES, item.type);
573
+ const isTrackedChild = (item) => Object.hasOwn(TRACKED_CHILD_TYPES, item.type);
574
+ const isInlineSdtChild = (item) => Object.hasOwn(INLINE_SDT_CHILD_TYPES, item.type);
575
+ /**
576
+ * Narrow a rebuilt child list back to what its container admits. Every edit
577
+ * keeps the kinds it was given and adds only runs, which each container
578
+ * admits, so a child outside the container's content model is a bug here.
579
+ */
580
+ const narrowChildren = (items, admits, container) => {
581
+ const out = [];
582
+ for (const item of items) {
583
+ if (!admits(item)) return panic(`A ${item.type} cannot be a child of ${container}.`);
584
+ out.push(item);
585
+ }
586
+ return out;
587
+ };
588
+ /** The same container holding other children. */
589
+ const withChildren = (container, items) => {
590
+ switch (container.type) {
591
+ case "hyperlink": return {
592
+ ...container,
593
+ children: narrowChildren(items, isHyperlinkChild, container.type)
594
+ };
595
+ case "insertion":
596
+ case "deletion":
597
+ case "moveFrom":
598
+ case "moveTo": return {
599
+ ...container,
600
+ content: narrowChildren(items, isTrackedChild, container.type)
601
+ };
602
+ case "inlineSdt": return {
603
+ ...container,
604
+ content: narrowChildren(items, isInlineSdtChild, container.type)
605
+ };
606
+ case "inlineWrapper": return {
607
+ ...container,
608
+ content: [...items]
609
+ };
610
+ default: return container;
611
+ }
612
+ };
613
+ //#endregion
614
+ //#region src/ops/slots.ts
615
+ const revision = (id) => ({
616
+ space: IDENTITY_SPACES.REVISION,
617
+ id
618
+ });
619
+ /** The ids a record carries itself, in a fixed order; its children's are their own. */
620
+ const identitySlots = (record) => {
621
+ switch (record.type) {
622
+ case "paragraph": {
623
+ const out = (record.propertyChanges ?? []).map((change) => revision(change.info.id));
624
+ if (record.pPrMark !== void 0) out.push(revision(record.pPrMark.info.id));
625
+ return out;
626
+ }
627
+ case "run": return (record.propertyChanges ?? []).map((change) => revision(change.info.id));
628
+ case "insertion":
629
+ case "deletion":
630
+ case "moveFrom":
631
+ case "moveTo": return [revision(record.info.id)];
632
+ case "inlineSdt": return record.properties.id === void 0 ? [] : [{
633
+ space: IDENTITY_SPACES.CONTROL,
634
+ id: record.properties.id
635
+ }];
636
+ default: return [];
637
+ }
638
+ };
639
+ const withRunChangeIds = (changes, ids) => {
640
+ const out = [];
641
+ for (const [index, change] of changes.entries()) out.push({
642
+ ...change,
643
+ info: {
644
+ ...change.info,
645
+ id: ids[index] ?? change.info.id
646
+ }
647
+ });
648
+ return out;
649
+ };
650
+ const withParagraphChangeIds = (changes, ids) => {
651
+ const out = [];
652
+ for (const [index, change] of changes.entries()) out.push({
653
+ ...change,
654
+ info: {
655
+ ...change.info,
656
+ id: ids[index] ?? change.info.id
657
+ }
658
+ });
659
+ return out;
660
+ };
661
+ /** The same inline record carrying other ids, slot for slot. */
662
+ const withInlineIdentity = (node, ids) => {
663
+ switch (node.type) {
664
+ case "run": return node.propertyChanges === void 0 ? node : {
665
+ ...node,
666
+ propertyChanges: withRunChangeIds(node.propertyChanges, ids)
667
+ };
668
+ case "insertion":
669
+ case "deletion":
670
+ case "moveFrom":
671
+ case "moveTo": return {
672
+ ...node,
673
+ info: {
674
+ ...node.info,
675
+ id: ids[0] ?? node.info.id
676
+ }
677
+ };
678
+ case "inlineSdt": return node.properties.id === void 0 ? node : {
679
+ ...node,
680
+ properties: {
681
+ ...node.properties,
682
+ id: ids[0] ?? node.properties.id
683
+ }
684
+ };
685
+ default: return node;
686
+ }
687
+ };
688
+ /** The same paragraph carrying other ids on its own tracked changes, slot for slot. */
689
+ const withParagraphIdentity = (paragraph, ids) => {
690
+ const next = { ...paragraph };
691
+ const changes = paragraph.propertyChanges;
692
+ if (changes !== void 0) next.propertyChanges = withParagraphChangeIds(changes, ids);
693
+ if (paragraph.pPrMark !== void 0) {
694
+ const id = ids[changes?.length ?? 0] ?? paragraph.pPrMark.info.id;
695
+ next.pPrMark = {
696
+ ...paragraph.pPrMark,
697
+ info: {
698
+ ...paragraph.pPrMark.info,
699
+ id
700
+ }
701
+ };
702
+ }
703
+ return next;
704
+ };
705
+ /** A record with every id it carries set to zero: the form two records are compared in. */
706
+ const maskIdentity = (node) => {
707
+ const slots = identitySlots(node);
708
+ return slots.length === 0 ? node : withInlineIdentity(node, slots.map(() => 0));
709
+ };
710
+ //#endregion
711
+ //#region src/ops/leaves.ts
712
+ /**
713
+ * A paragraph's content as a sequence of leaves, and the three moves every
714
+ * edit is made of: partition the leaves between gaps, find the records that
715
+ * run across a gap, and merge records that meet at one.
716
+ *
717
+ * A leaf is a unit of the offset space (a character of run text, a tab, a
718
+ * field) or a zero-width child (a range marker, markup that shows nothing, a
719
+ * run or container with nothing in it). A gap is a place between two leaves:
720
+ * an offset plus how many zero-width leaves at that offset come before it.
721
+ *
722
+ * Partitioning keeps each record whose leaves all fall on one side as the
723
+ * same object and cuts the others in two, each half keeping every field of
724
+ * the original. Merging is the reverse: two records alike in everything but
725
+ * their content become one. Because a deletion is "keep the leaves outside
726
+ * the gaps" and an insertion is "cut at a gap and merge the new leaves in",
727
+ * each is the other's exact inverse, whatever the records around them hold.
728
+ */
729
+ const RUN_CONTENT_TYPES = {
730
+ text: true,
731
+ tab: true,
732
+ break: true,
733
+ symbol: true,
734
+ footnoteRef: true,
735
+ endnoteRef: true,
736
+ fieldChar: true,
737
+ instrText: true,
738
+ softHyphen: true,
739
+ noBreakHyphen: true,
740
+ renderedPageBreak: true,
741
+ preservedXml: true,
742
+ drawing: true,
743
+ shape: true
744
+ };
745
+ const isRunContent = (node) => Object.hasOwn(RUN_CONTENT_TYPES, node.type);
746
+ const isParagraphContent = (node) => !isRunContent(node);
747
+ /** The children of a run or container; `undefined` for anything that has none. */
748
+ const childNodes = (node) => {
749
+ if (node.type === "run") return node.content;
750
+ if (isRunContent(node)) return;
751
+ return isInlineContainer(node) ? childrenOf(node) : void 0;
752
+ };
753
+ const kindOf = (node) => {
754
+ if (node.type === "text") return node.text === "" ? "zeroWidth" : "characters";
755
+ const children = childNodes(node);
756
+ if (children !== void 0) return children.length === 0 ? "zeroWidth" : "branch";
757
+ if (isRunContent(node)) return runContentWidth(node) === 1 ? "unit" : "zeroWidth";
758
+ return inlineWidth(node) === 1 ? "unit" : "zeroWidth";
759
+ };
760
+ /**
761
+ * Whether a record is an empty run or an empty text node. Neither says
762
+ * anything, operations never create one, and a document is normalized so it
763
+ * holds none (see `contract.ts`): otherwise each is a zero-width leaf that
764
+ * positions would have to count. An empty hyperlink or content control is
765
+ * not empty in this sense: it is markup, and stays a zero-width leaf.
766
+ */
767
+ const isEmptyRecord = (node) => node.type === "text" && node.text === "" || node.type === "run" && node.content.length === 0;
768
+ const startCursor = () => ({
769
+ position: 0,
770
+ zeroWidthSeen: 0
771
+ });
772
+ const unitRegion = (gaps, unit) => {
773
+ let region = 0;
774
+ for (const gap of gaps) if (gap.offset <= unit) region += 1;
775
+ return region;
776
+ };
777
+ const zeroWidthRegion = (gaps, cursor) => {
778
+ let region = 0;
779
+ for (const gap of gaps) if (gap.offset < cursor.position || gap.offset === cursor.position && gap.zeroWidthBefore <= cursor.zeroWidthSeen) region += 1;
780
+ return region;
781
+ };
782
+ /** Narrow rebuilt children back to what their parent admits; anything else is a bug here. */
783
+ const narrowNodes = (nodes, admits) => {
784
+ const out = [];
785
+ for (const node of nodes) {
786
+ if (!admits(node)) return panic(`A ${node.type} is not admitted here.`);
787
+ out.push(node);
788
+ }
789
+ return out;
790
+ };
791
+ /** Paragraph children, narrowed from nodes. */
792
+ const asParagraphContent = (nodes) => narrowNodes(nodes, isParagraphContent);
793
+ /** The same run or container holding other children. */
794
+ const rebuildNode = (node, children) => {
795
+ if (node.type === "run") return {
796
+ ...node,
797
+ content: narrowNodes(children, isRunContent)
798
+ };
799
+ if (isRunContent(node) || !isInlineContainer(node)) return panic(`A ${node.type} has no children to rebuild.`);
800
+ return withChildren(node, narrowNodes(children, isParagraphContent));
801
+ };
802
+ const partitionNode = (node, gaps, cursor) => {
803
+ if (node.type === "text" && node.text !== "") {
804
+ const start = cursor.position;
805
+ const pieces = [];
806
+ let pieceStart = 0;
807
+ let region = unitRegion(gaps, start);
808
+ for (let index = 1; index < node.text.length; index += 1) {
809
+ const next = unitRegion(gaps, start + index);
810
+ if (next !== region) {
811
+ pieces.push([region, {
812
+ ...node,
813
+ text: node.text.slice(pieceStart, index)
814
+ }]);
815
+ pieceStart = index;
816
+ region = next;
817
+ }
818
+ }
819
+ cursor.position += node.text.length;
820
+ cursor.zeroWidthSeen = 0;
821
+ if (pieces.length === 0) return {
822
+ pieces: [[region, node]],
823
+ min: region,
824
+ max: region
825
+ };
826
+ pieces.push([region, {
827
+ ...node,
828
+ text: node.text.slice(pieceStart)
829
+ }]);
830
+ return {
831
+ pieces,
832
+ min: pieces[0]?.[0] ?? region,
833
+ max: region
834
+ };
835
+ }
836
+ const kind = kindOf(node);
837
+ switch (kind) {
838
+ case "unit": {
839
+ const region = unitRegion(gaps, cursor.position);
840
+ cursor.position += 1;
841
+ cursor.zeroWidthSeen = 0;
842
+ return {
843
+ pieces: [[region, node]],
844
+ min: region,
845
+ max: region
846
+ };
847
+ }
848
+ case "zeroWidth": {
849
+ const region = zeroWidthRegion(gaps, cursor);
850
+ cursor.zeroWidthSeen += 1;
851
+ return {
852
+ pieces: [[region, node]],
853
+ min: region,
854
+ max: region
855
+ };
856
+ }
857
+ case "characters": return panic("Run text is partitioned by character above.");
858
+ case "branch": {
859
+ const inner = partitionNodes(childNodes(node) ?? [], gaps, cursor);
860
+ if (inner.min === inner.max) return {
861
+ pieces: [[inner.min, node]],
862
+ min: inner.min,
863
+ max: inner.max
864
+ };
865
+ const pieces = [];
866
+ for (const [region, part] of inner.parts.entries()) if (part.length > 0) pieces.push([region, rebuildNode(node, part)]);
867
+ return {
868
+ pieces,
869
+ min: inner.min,
870
+ max: inner.max
871
+ };
872
+ }
873
+ default: return kind;
874
+ }
875
+ };
876
+ const partitionNodes = (items, gaps, cursor) => {
877
+ const parts = Array.from({ length: gaps.length + 1 }, () => []);
878
+ let min = Number.POSITIVE_INFINITY;
879
+ let max = Number.NEGATIVE_INFINITY;
880
+ for (const item of items) {
881
+ const piece = partitionNode(item, gaps, cursor);
882
+ for (const [region, node] of piece.pieces) parts[region]?.push(node);
883
+ min = Math.min(min, piece.min);
884
+ max = Math.max(max, piece.max);
885
+ }
886
+ return {
887
+ parts,
888
+ min,
889
+ max
890
+ };
891
+ };
892
+ /**
893
+ * The content between consecutive gaps, one list per region: the records of
894
+ * each region, cut where a gap passes through them. Gaps must be in order.
895
+ */
896
+ const partitionContent = (items, gaps) => partitionNodes(items, gaps, startCursor()).parts;
897
+ /**
898
+ * The records holding leaves of both region `first` and region `last`,
899
+ * outermost first. They form one chain: each is inside the one before.
900
+ */
901
+ const spanningRecords = (items, gaps, first, last) => {
902
+ const spine = [];
903
+ const cursor = startCursor();
904
+ let list = items;
905
+ while (list !== void 0) {
906
+ let found;
907
+ for (const item of list) {
908
+ const start = { ...cursor };
909
+ const { min, max } = partitionNode(item, gaps, cursor);
910
+ if (min <= first && max >= last) {
911
+ found = item;
912
+ cursor.position = start.position;
913
+ cursor.zeroWidthSeen = start.zeroWidthSeen;
914
+ break;
915
+ }
916
+ }
917
+ if (found === void 0) return spine;
918
+ spine.push(found);
919
+ list = found.type === "text" ? void 0 : childNodes(found);
920
+ }
921
+ return spine;
922
+ };
923
+ const childrenKey = (node) => node.type === "hyperlink" ? "children" : "content";
924
+ const ownFields = (node) => {
925
+ const key = childrenKey(node);
926
+ return Object.entries(node).filter(([name]) => name !== key);
927
+ };
928
+ /**
929
+ * Whether two records are alike in everything but their content and the ids
930
+ * they carry: merged, the first one's ids stand for both.
931
+ */
932
+ const sameOwnFields = (left, right) => left.type === right.type && structurallyEqual(Object.fromEntries(ownFields(maskIdentity(left))), Object.fromEntries(ownFields(maskIdentity(right))));
933
+ const EXACT_MERGE = Object.freeze({ mode: "exact" });
934
+ const mergeNode = (left, right, depth, rule, level) => {
935
+ const kind = kindOf(left);
936
+ if (kind !== kindOf(right) || kind !== "characters" && kind !== "branch") return;
937
+ if (left.type === "text" && right.type === "text") return depth === 1 ? {
938
+ ...left,
939
+ text: left.text + right.text
940
+ } : void 0;
941
+ const leftChildren = childNodes(left);
942
+ const rightChildren = childNodes(right);
943
+ if (leftChildren === void 0 || rightChildren === void 0 || !sameOwnFields(left, right)) return;
944
+ rule.onMerge?.(left, right, level);
945
+ const children = mergeLists(leftChildren, rightChildren, depth - 1, rule, level + 1);
946
+ if (children === void 0) return;
947
+ const merged = rebuildNode(left, children);
948
+ return rule.identity === "second" ? withInlineIdentity(merged, identitySlots(right).map(({ id }) => id)) : merged;
949
+ };
950
+ /**
951
+ * Two lists end to end, the last record of the first merged with the first of
952
+ * the second, and so on `depth` levels down. `undefined` when an exact merge
953
+ * meets records that cannot be merged.
954
+ */
955
+ const mergeLists = (left, right, depth, rule = EXACT_MERGE, level = 1) => {
956
+ if (depth === 0) return [...left, ...right];
957
+ const last = left.at(-1);
958
+ const first = right.at(0);
959
+ const merged = last === void 0 || first === void 0 ? void 0 : mergeNode(last, first, depth, rule, level);
960
+ if (merged === void 0) return rule.mode === "asFarAsAlike" ? [...left, ...right] : void 0;
961
+ return [
962
+ ...left.slice(0, -1),
963
+ merged,
964
+ ...right.slice(1)
965
+ ];
966
+ };
967
+ /** The zero-width leaves at an offset, in document order. */
968
+ const zeroWidthLeavesAt = (items, offset) => {
969
+ const out = [];
970
+ const cursor = startCursor();
971
+ const walk = (list) => {
972
+ for (const node of list) {
973
+ if (cursor.position > offset) return;
974
+ const kind = kindOf(node);
975
+ switch (kind) {
976
+ case "characters":
977
+ if (node.type === "text") cursor.position += node.text.length;
978
+ break;
979
+ case "unit":
980
+ cursor.position += 1;
981
+ break;
982
+ case "zeroWidth":
983
+ if (cursor.position === offset) out.push(node);
984
+ break;
985
+ case "branch":
986
+ walk(childNodes(node) ?? []);
987
+ break;
988
+ default: return kind;
989
+ }
990
+ }
991
+ };
992
+ walk(items);
993
+ return out;
994
+ };
995
+ /**
996
+ * The gap an insertion defaults to: before the first zero-width leaf at the
997
+ * offset that opens a range, so a marker opening there stays with what
998
+ * follows it and every other one with what precedes it.
999
+ */
1000
+ const defaultInsertionGap = (items, offset) => {
1001
+ const leaves = zeroWidthLeavesAt(items, offset);
1002
+ const opening = leaves.findIndex((leaf) => isParagraphContent(leaf) && isOpeningMarker(leaf));
1003
+ return {
1004
+ offset,
1005
+ zeroWidthBefore: opening === -1 ? leaves.length : opening
1006
+ };
1007
+ };
1008
+ /** Every run text in a list, nested ones included. */
1009
+ const textsIn = (items) => {
1010
+ const out = [];
1011
+ const walk = (list) => {
1012
+ for (const node of list) {
1013
+ if (node.type === "text") {
1014
+ out.push(node.text);
1015
+ continue;
1016
+ }
1017
+ const children = childNodes(node);
1018
+ if (children !== void 0) walk(children);
1019
+ }
1020
+ };
1021
+ walk(items);
1022
+ return out;
1023
+ };
1024
+ /**
1025
+ * The records every leaf of which lies between two gaps, nested ones
1026
+ * included: what an insertion put in, as opposed to records holding content
1027
+ * that was there before.
1028
+ */
1029
+ const recordsBetween = (items, from, to) => {
1030
+ const out = /* @__PURE__ */ new Set();
1031
+ const gaps = [from, to];
1032
+ const cursor = startCursor();
1033
+ const walk = (list) => {
1034
+ for (const node of list) {
1035
+ const start = { ...cursor };
1036
+ const { min, max } = partitionNode(node, gaps, cursor);
1037
+ if (min === 1 && max === 1) out.add(node);
1038
+ const children = childNodes(node);
1039
+ if (children !== void 0 && kindOf(node) === "branch" && !(min === 1 && max === 1)) {
1040
+ const end = { ...cursor };
1041
+ cursor.position = start.position;
1042
+ cursor.zeroWidthSeen = start.zeroWidthSeen;
1043
+ walk(children);
1044
+ cursor.position = end.position;
1045
+ cursor.zeroWidthSeen = end.zeroWidthSeen;
1046
+ } else if (min === 1 && max === 1 && children !== void 0) {
1047
+ const collect = (nodes) => {
1048
+ for (const child of nodes) {
1049
+ out.add(child);
1050
+ collect(childNodes(child) ?? []);
1051
+ }
1052
+ };
1053
+ collect(children);
1054
+ }
1055
+ }
1056
+ };
1057
+ walk(items);
1058
+ return out;
1059
+ };
1060
+ const advance = (node, cursor) => {
1061
+ const kind = kindOf(node);
1062
+ switch (kind) {
1063
+ case "characters":
1064
+ if (node.type === "text") cursor.position += node.text.length;
1065
+ cursor.zeroWidthSeen = 0;
1066
+ return;
1067
+ case "unit":
1068
+ cursor.position += 1;
1069
+ cursor.zeroWidthSeen = 0;
1070
+ return;
1071
+ case "zeroWidth":
1072
+ cursor.zeroWidthSeen += 1;
1073
+ return;
1074
+ case "branch":
1075
+ for (const child of childNodes(node) ?? []) advance(child, cursor);
1076
+ return;
1077
+ default: return kind;
1078
+ }
1079
+ };
1080
+ /**
1081
+ * Every run in document order with its gaps, runs inside hyperlinks, tracked
1082
+ * changes, content controls and wrappers included; runs inside a field are
1083
+ * part of the field's one unit and are not listed.
1084
+ */
1085
+ const runGaps = (items) => {
1086
+ const out = [];
1087
+ const cursor = startCursor();
1088
+ const walk = (list) => {
1089
+ for (const node of list) {
1090
+ if (node.type === "run") {
1091
+ const before = {
1092
+ offset: cursor.position,
1093
+ zeroWidthBefore: cursor.zeroWidthSeen
1094
+ };
1095
+ advance(node, cursor);
1096
+ out.push({
1097
+ node,
1098
+ before,
1099
+ after: {
1100
+ offset: cursor.position,
1101
+ zeroWidthBefore: cursor.zeroWidthSeen
1102
+ }
1103
+ });
1104
+ continue;
1105
+ }
1106
+ if (kindOf(node) === "branch") {
1107
+ walk(childNodes(node) ?? []);
1108
+ continue;
1109
+ }
1110
+ advance(node, cursor);
1111
+ }
1112
+ };
1113
+ walk(items);
1114
+ return out;
1115
+ };
1116
+ //#endregion
1117
+ //#region src/ops/refusal.ts
1118
+ /**
1119
+ * Why an operation was not applied. A refused operation changes nothing: the
1120
+ * document it was applied to is returned as it was.
1121
+ */
1122
+ const DOCUMENT_OP_REFUSAL_REASONS = Object.freeze({
1123
+ /** No paragraph in the story carries the id. */
1124
+ BLOCK_NOT_FOUND: "blockNotFound",
1125
+ /** An offset is not an integer from `0` to the paragraph's length, or a range runs backwards. */
1126
+ INVALID_OFFSET: "invalidOffset",
1127
+ /** A range starts and ends in different paragraphs or stories. */
1128
+ CROSS_BLOCK_RANGE: "crossBlockRange",
1129
+ /** A position falls between the two halves of a surrogate pair. */
1130
+ SPLITS_SURROGATE_PAIR: "splitsSurrogatePair",
1131
+ /** Inserted text is empty, holds a tab or line-break character, or cannot be written to XML. */
1132
+ INVALID_TEXT: "invalidText",
1133
+ /**
1134
+ * A paragraph id the operation (or its inverse) creates is not eight hex
1135
+ * digits below `0x80000000`, or is the reserved `00000000`.
1136
+ */
1137
+ INVALID_BLOCK_ID: "invalidBlockId",
1138
+ /**
1139
+ * An id the operation brings in (a paragraph id, or a revision or
1140
+ * content-control id a replacement carries) is already used in the package.
1141
+ */
1142
+ ID_COLLISION: "idCollision",
1143
+ /** The paragraphs to join or replace are not adjacent siblings of one container. */
1144
+ NOT_ADJACENT: "notAdjacent",
1145
+ /**
1146
+ * The operation would move or remove a section break (joining a paragraph
1147
+ * that ends a section, replacing paragraphs across or at one); that is a
1148
+ * section operation.
1149
+ */
1150
+ SECTION_BOUNDARY: "sectionBoundary",
1151
+ /** Direct text would land inside tracked-deleted or moved-away content. */
1152
+ INSIDE_TRACKED_DELETION: "insideTrackedDeletion",
1153
+ /**
1154
+ * The operation cuts a record carrying a revision or content-control id in
1155
+ * two and names too few `newIds` for the halves after the first.
1156
+ */
1157
+ NEEDS_NEW_IDS: "needsNewIds",
1158
+ /** A new revision or content-control id is not an integer from 0 to 2^31 - 1. */
1159
+ INVALID_NEW_ID: "invalidNewId",
1160
+ /**
1161
+ * The operation would merge two records carrying the same revision or
1162
+ * content-control id: nothing could tell them apart again to undo it.
1163
+ */
1164
+ SHARED_ID: "sharedId",
1165
+ /**
1166
+ * What the operation expects (paragraphs to replace, a slice to delete,
1167
+ * the values a patch replaced) is not what is there.
1168
+ */
1169
+ STALE: "stale",
1170
+ /**
1171
+ * The records at a position are not the shape the operation needs: an open
1172
+ * end meets a record it cannot merge with, records to join differ, a slice
1173
+ * would merge records that were separate, or there are fewer records to cut
1174
+ * than the operation names.
1175
+ */
1176
+ STRUCTURE_MISMATCH: "structureMismatch",
1177
+ /** Inserted content is empty, or holds an empty run or text node. */
1178
+ EMPTY_CONTENT: "emptyContent",
1179
+ /** A replacement names no paragraph to replace, or none to put in its place. */
1180
+ EMPTY_BLOCK_LIST: "emptyBlockList",
1181
+ /** Seed contract: a main-story paragraph has no `paraId`. */
1182
+ MISSING_BLOCK_ID: "missingBlockId",
1183
+ /** Seed contract: two paragraphs in the package carry one id. */
1184
+ DUPLICATE_BLOCK_ID: "duplicateBlockId",
1185
+ /** Seed contract: two records in the package carry one revision or content-control id. */
1186
+ DUPLICATE_RECORD_ID: "duplicateRecordId",
1187
+ /** Seed contract: the body's section view does not match its blocks. */
1188
+ SECTIONS_OUT_OF_STEP: "sectionsOutOfStep",
1189
+ /** Seed contract: the main story holds an empty run or empty text node. */
1190
+ EMPTY_RECORD: "emptyRecord"
1191
+ });
1192
+ /** An operation the document cannot take as stated. */
1193
+ var DocumentOpRefusal = class extends TaggedError("DocumentOpRefusal") {};
1194
+ //#endregion
1195
+ //#region src/ops/contract.ts
1196
+ /**
1197
+ * The seed contract: what a document must be for operations to apply to it.
1198
+ *
1199
+ * A host establishes it once, when a document enters the journal: run
1200
+ * `ensureParaIds` over the package bytes (it stamps every story, headers,
1201
+ * footers and notes included, and makes ids unique), parse, then
1202
+ * {@link normalizeForOps}. {@link validateOpsDocument} states the result:
1203
+ *
1204
+ * - every paragraph of the main story has a `w14:paraId`;
1205
+ * - no paragraph id repeats anywhere in the package, compared as hex, so an
1206
+ * inverse can always recreate the ids it removed;
1207
+ * - no revision id (tracked changes, property changes) or content-control id
1208
+ * repeats, so the one record carrying an id is the one it names;
1209
+ * - the body's section view says what its blocks say;
1210
+ * - the main story holds no empty run or empty text node.
1211
+ *
1212
+ * Paragraphs in text boxes, headers, footers, notes and comments are other
1213
+ * stories: they are not addressable in schema version 1, and their ids count
1214
+ * toward uniqueness like any other.
1215
+ *
1216
+ * Every operation checks the contract before applying and leaves it holding,
1217
+ * so a document an operation produced is not checked again: documents are
1218
+ * values, never modified in place.
1219
+ */
1220
+ /** A document that does not meet the seed contract. */
1221
+ var DocumentOpsContractError = class extends TaggedError("DocumentOpsContractError") {};
1222
+ const holdsEmptyRecord$1 = (nodes) => nodes.some((node) => isEmptyRecord(node) || holdsEmptyRecord$1(childNodes(node) ?? []));
1223
+ const violation = (document) => {
1224
+ const body = document.package.document;
1225
+ const paragraphs = storyParagraphs(body);
1226
+ if (paragraphs.some(({ paragraph }) => paragraph.paraId === void 0)) return new DocumentOpsContractError({
1227
+ reason: DOCUMENT_OP_REFUSAL_REASONS.MISSING_BLOCK_ID,
1228
+ message: "A main-story paragraph has no paraId; ensureParaIds establishes one."
1229
+ });
1230
+ const repeated = [...countIds(packageParagraphIds(document.package))].find(([, count]) => count > 1);
1231
+ if (repeated !== void 0) return new DocumentOpsContractError({
1232
+ reason: DOCUMENT_OP_REFUSAL_REASONS.DUPLICATE_BLOCK_ID,
1233
+ message: `${repeated[1]} paragraphs in the package are ${repeated[0]}.`
1234
+ });
1235
+ const repeatedRecord = [...countKeys(packageIdentityKeys(document.package))].find(([, count]) => count > 1);
1236
+ if (repeatedRecord !== void 0) return new DocumentOpsContractError({
1237
+ reason: DOCUMENT_OP_REFUSAL_REASONS.DUPLICATE_RECORD_ID,
1238
+ message: `${repeatedRecord[1]} records in the package carry ${repeatedRecord[0]}.`
1239
+ });
1240
+ if (!sectionsInStep(body)) return new DocumentOpsContractError({
1241
+ reason: DOCUMENT_OP_REFUSAL_REASONS.SECTIONS_OUT_OF_STEP,
1242
+ message: "The body's section view does not match its blocks."
1243
+ });
1244
+ if (paragraphs.some(({ paragraph }) => holdsEmptyRecord$1(paragraph.content))) return new DocumentOpsContractError({
1245
+ reason: DOCUMENT_OP_REFUSAL_REASONS.EMPTY_RECORD,
1246
+ message: "The main story holds an empty run or text node; normalizeForOps removes them."
1247
+ });
1248
+ };
1249
+ /** Documents known to meet the contract: checked ones and ones an operation produced. */
1250
+ const MEETS_CONTRACT = /* @__PURE__ */ new WeakSet();
1251
+ /** Check a document against the seed contract. */
1252
+ const validateOpsDocument = (document) => {
1253
+ if (MEETS_CONTRACT.has(document)) return Result.ok(document);
1254
+ const found = violation(document);
1255
+ if (found !== void 0) return Result.err(found);
1256
+ MEETS_CONTRACT.add(document);
1257
+ return Result.ok(document);
1258
+ };
1259
+ /** Record that an operation produced `document` from one that met the contract. */
1260
+ const meetsContract = (document) => {
1261
+ MEETS_CONTRACT.add(document);
1262
+ };
1263
+ const withoutEmpty = (nodes) => {
1264
+ let changed = false;
1265
+ const out = [];
1266
+ for (const node of nodes) {
1267
+ if (isEmptyRecord(node)) {
1268
+ changed = true;
1269
+ continue;
1270
+ }
1271
+ const children = childNodes(node);
1272
+ const kept = children === void 0 ? children : withoutEmpty(children);
1273
+ if (kept !== children && kept !== void 0) {
1274
+ changed = true;
1275
+ const rebuilt = rebuildNode(node, kept);
1276
+ if (!isEmptyRecord(rebuilt)) out.push(rebuilt);
1277
+ continue;
1278
+ }
1279
+ out.push(node);
1280
+ }
1281
+ return changed ? out : nodes;
1282
+ };
1283
+ const normalizeBlocks = (blocks) => {
1284
+ const out = [];
1285
+ for (const block of blocks) switch (block.type) {
1286
+ case "paragraph": {
1287
+ const content = withoutEmpty(block.content);
1288
+ out.push(content === block.content ? block : {
1289
+ ...block,
1290
+ content: asParagraphContent(content)
1291
+ });
1292
+ break;
1293
+ }
1294
+ case "table": {
1295
+ const rows = [];
1296
+ for (const row of block.rows) {
1297
+ const cells = [];
1298
+ for (const cell of row.cells) cells.push({
1299
+ ...cell,
1300
+ content: normalizeBlocks(cell.content)
1301
+ });
1302
+ rows.push({
1303
+ ...row,
1304
+ cells
1305
+ });
1306
+ }
1307
+ out.push({
1308
+ ...block,
1309
+ rows
1310
+ });
1311
+ break;
1312
+ }
1313
+ case "blockSdt":
1314
+ case "blockCustomXml":
1315
+ out.push({
1316
+ ...block,
1317
+ content: normalizeBlocks(block.content)
1318
+ });
1319
+ break;
1320
+ case "preservedBlock":
1321
+ case "bookmarkStart":
1322
+ case "bookmarkEnd":
1323
+ out.push(block);
1324
+ break;
1325
+ default: return block;
1326
+ }
1327
+ return out;
1328
+ };
1329
+ /**
1330
+ * The document with every empty run and empty text node of the main story
1331
+ * removed, and its section view derived again. Nothing else changes.
1332
+ */
1333
+ const normalizeForOps = (document) => {
1334
+ const body = document.package.document;
1335
+ return {
1336
+ ...document,
1337
+ package: {
1338
+ ...document.package,
1339
+ document: withBodyContent(body, normalizeBlocks(body.content))
1340
+ }
1341
+ };
1342
+ };
1343
+ //#endregion
1344
+ //#region src/ops/identity.ts
1345
+ /**
1346
+ * How an edit keeps the ids of identified records unique (see `slots.ts`).
1347
+ *
1348
+ * Cutting an identified record in two would leave both halves with its one
1349
+ * id, and operations mint no ids, so the operation that makes the cut names
1350
+ * the new ones (`newIds`): the half holding the start keeps the id, and every
1351
+ * later half takes the next new id, in document order. Merging two identified
1352
+ * records keeps the first one's ids and retires the second's; the inverse
1353
+ * that cuts them apart again names the retired ids, so it recreates them
1354
+ * exactly.
1355
+ */
1356
+ const visitNodes = (nodes, visit) => {
1357
+ for (const node of nodes) {
1358
+ visit(node);
1359
+ visitNodes(childNodes(node) ?? [], visit);
1360
+ }
1361
+ };
1362
+ /** The slot keys of paragraphs and everything in them, in document order. */
1363
+ const identityKeysOf = (paragraphs) => {
1364
+ const out = [];
1365
+ for (const paragraph of paragraphs) {
1366
+ for (const slot of identitySlots(paragraph)) out.push(slotKey(slot));
1367
+ visitNodes(paragraph.content, (node) => {
1368
+ for (const slot of identitySlots(node)) out.push(slotKey(slot));
1369
+ });
1370
+ }
1371
+ return out;
1372
+ };
1373
+ const recordsOf = (paragraphs) => {
1374
+ const out = new Set(paragraphs);
1375
+ for (const paragraph of paragraphs) visitNodes(paragraph.content, (node) => out.add(node));
1376
+ return out;
1377
+ };
1378
+ /**
1379
+ * Give fresh ids to the records an edit created that would otherwise share an
1380
+ * id. A record carried over from `before` unchanged keeps its ids. A record
1381
+ * the edit created (a half of a cut record, inserted content, a rebuilt
1382
+ * container) keeps an id no other record holds, and takes the next of
1383
+ * `newIds`, in document order, for one another record holds: the first half
1384
+ * of a cut record keeps the id, and the halves after it take new ones. Where
1385
+ * a record holding content that was there before and a record holding only
1386
+ * inserted content share an id, the first keeps it: the id stays with the
1387
+ * content it named.
1388
+ *
1389
+ * The seed contract makes every id unique, so the only records that share one
1390
+ * are those the edit created.
1391
+ */
1392
+ const freshenIdentities = ({ before, after, newIds, usedElsewhere, inserted = /* @__PURE__ */ new Set() }) => {
1393
+ const carried = recordsOf(before);
1394
+ const fixed = /* @__PURE__ */ new Set();
1395
+ const createdKeys = [];
1396
+ const note = (record, slots) => {
1397
+ for (const slot of slots) if (carried.has(record)) fixed.add(slotKey(slot));
1398
+ else createdKeys.push(slotKey(slot));
1399
+ };
1400
+ for (const paragraph of after) {
1401
+ note(paragraph, identitySlots(paragraph));
1402
+ visitNodes(paragraph.content, (node) => note(node, identitySlots(node)));
1403
+ }
1404
+ const repeats = /* @__PURE__ */ new Set();
1405
+ const needsFresh = createdKeys.some((key) => {
1406
+ const repeated = fixed.has(key) || repeats.has(key);
1407
+ repeats.add(key);
1408
+ return repeated;
1409
+ });
1410
+ if (!needsFresh && createdKeys.length === 0) return {
1411
+ kind: "fresh",
1412
+ paragraphs: [...after]
1413
+ };
1414
+ const elsewhere = usedElsewhere();
1415
+ if (!needsFresh && !createdKeys.some((key) => elsewhere.has(key))) return {
1416
+ kind: "fresh",
1417
+ paragraphs: [...after]
1418
+ };
1419
+ const keepers = /* @__PURE__ */ new Map();
1420
+ const claimed = /* @__PURE__ */ new Set();
1421
+ const created = [];
1422
+ const collect = (record, slots) => {
1423
+ if (!carried.has(record) && slots.length > 0) created.push([record, slots]);
1424
+ };
1425
+ for (const paragraph of after) {
1426
+ collect(paragraph, identitySlots(paragraph));
1427
+ visitNodes(paragraph.content, (node) => collect(node, identitySlots(node)));
1428
+ }
1429
+ for (const [record, slots] of [...created.filter(([candidate]) => !inserted.has(candidate)), ...created.filter(([candidate]) => inserted.has(candidate))]) for (const [index, slot] of slots.entries()) {
1430
+ const key = slotKey(slot);
1431
+ if (elsewhere.has(key) || fixed.has(key) || claimed.has(key)) continue;
1432
+ claimed.add(key);
1433
+ const kept = keepers.get(record) ?? /* @__PURE__ */ new Set();
1434
+ kept.add(index);
1435
+ keepers.set(record, kept);
1436
+ }
1437
+ const taken = /* @__PURE__ */ new Set([
1438
+ ...elsewhere,
1439
+ ...identityKeysOf(before),
1440
+ ...identityKeysOf(after)
1441
+ ]);
1442
+ const pools = {
1443
+ [IDENTITY_SPACES.REVISION]: newIds.revision ?? [],
1444
+ [IDENTITY_SPACES.CONTROL]: newIds.control ?? []
1445
+ };
1446
+ const next = {
1447
+ [IDENTITY_SPACES.REVISION]: 0,
1448
+ [IDENTITY_SPACES.CONTROL]: 0
1449
+ };
1450
+ let missing = 0;
1451
+ let invalid;
1452
+ const idsFor = (record, slots) => {
1453
+ if (carried.has(record)) return void 0;
1454
+ let changed = false;
1455
+ const ids = slots.map((slot, index) => {
1456
+ if (keepers.get(record)?.has(index) === true) return slot.id;
1457
+ const pool = pools[slot.space];
1458
+ const isTaken = (id) => taken.has(slotKey({
1459
+ space: slot.space,
1460
+ id
1461
+ }));
1462
+ let fresh = pool[next[slot.space]];
1463
+ while (fresh !== void 0 && Number.isInteger(fresh) && isTaken(fresh)) {
1464
+ next[slot.space] += 1;
1465
+ fresh = pool[next[slot.space]];
1466
+ }
1467
+ next[slot.space] += 1;
1468
+ if (fresh === void 0) {
1469
+ missing += 1;
1470
+ return slot.id;
1471
+ }
1472
+ if (!Number.isInteger(fresh) || fresh < 0 || fresh > 2147483647) {
1473
+ invalid ??= fresh;
1474
+ return slot.id;
1475
+ }
1476
+ taken.add(slotKey({
1477
+ space: slot.space,
1478
+ id: fresh
1479
+ }));
1480
+ changed = true;
1481
+ return fresh;
1482
+ });
1483
+ return changed ? ids : void 0;
1484
+ };
1485
+ const freshenNodes = (nodes) => {
1486
+ let changed = false;
1487
+ const out = [];
1488
+ for (const node of nodes) {
1489
+ const ids = idsFor(node, identitySlots(node));
1490
+ const own = ids === void 0 ? node : withInlineIdentity(node, ids);
1491
+ const children = childNodes(node);
1492
+ const freshened = children === void 0 ? children : freshenNodes(children);
1493
+ const result = freshened === children ? own : rebuildNode(own, freshened ?? []);
1494
+ changed ||= result !== node;
1495
+ out.push(result);
1496
+ }
1497
+ return changed ? out : nodes;
1498
+ };
1499
+ const paragraphs = [];
1500
+ for (const paragraph of after) {
1501
+ const ids = idsFor(paragraph, identitySlots(paragraph));
1502
+ const own = ids === void 0 ? paragraph : withParagraphIdentity(paragraph, ids);
1503
+ const content = freshenNodes(paragraph.content);
1504
+ paragraphs.push(content === paragraph.content ? own : {
1505
+ ...own,
1506
+ content: asParagraphContent(content)
1507
+ });
1508
+ }
1509
+ if (missing > 0) return {
1510
+ kind: "needsIds",
1511
+ missing
1512
+ };
1513
+ return invalid === void 0 ? {
1514
+ kind: "fresh",
1515
+ paragraphs
1516
+ } : {
1517
+ kind: "invalidId",
1518
+ id: invalid
1519
+ };
1520
+ };
1521
+ //#endregion
1522
+ //#region src/ops/patch.ts
1523
+ /**
1524
+ * The keys an object states.
1525
+ *
1526
+ * SAFETY: `Object.keys` widens to `string[]`. Both callers pass a model
1527
+ * property set or a patch over one, object literals whose own keys are all
1528
+ * keys of `Formatting`.
1529
+ */
1530
+ const ownKeys = (value) => Object.keys(value);
1531
+ /**
1532
+ * A property set with a patch applied: a value sets its key, `null` clears
1533
+ * it, an absent key is untouched. The input is not modified. A set left with
1534
+ * no keys is `undefined`, the model's spelling of "states nothing".
1535
+ */
1536
+ const applyFormattingPatch = (base, patch) => {
1537
+ const next = {};
1538
+ if (base !== void 0) {
1539
+ for (const key of ownKeys(base)) if (patch[key] === void 0) next[key] = base[key];
1540
+ }
1541
+ for (const key of ownKeys(patch)) {
1542
+ const value = patch[key];
1543
+ if (value !== void 0 && value !== null) next[key] = value;
1544
+ }
1545
+ return Object.keys(next).length === 0 ? void 0 : next;
1546
+ };
1547
+ /**
1548
+ * The patch that gives back what `patch` replaced in `base`: each key it names
1549
+ * set to the value it had, or cleared where it had none.
1550
+ */
1551
+ const priorValues = (base, patch) => {
1552
+ const restore = {};
1553
+ for (const key of ownKeys(patch)) {
1554
+ if (patch[key] === void 0) continue;
1555
+ const prior = base?.[key];
1556
+ restore[key] = prior === void 0 ? null : prior;
1557
+ }
1558
+ return restore;
1559
+ };
1560
+ //#endregion
1561
+ //#region src/ops/inline.ts
1562
+ /**
1563
+ * Edits over a paragraph's content in its logical offset space.
1564
+ *
1565
+ * Every function here is pure: it returns new arrays and records along the
1566
+ * path it changed and hands back every child it did not change as the same
1567
+ * object, so an untouched run is `===` to its input.
1568
+ */
1569
+ /** A run with the property set it states, or none. */
1570
+ const withRunFormatting = (run, formatting) => {
1571
+ const next = { ...run };
1572
+ if (formatting === void 0) delete next.formatting;
1573
+ else next.formatting = formatting;
1574
+ return next;
1575
+ };
1576
+ const withRunContent = (run, content) => ({
1577
+ ...run,
1578
+ content
1579
+ });
1580
+ /** Two property sets state the same thing; an absent set states nothing. */
1581
+ const sameRunFormatting = (left, right) => structurallyEqual(left ?? {}, right ?? {});
1582
+ /** How an inverse spells a property set it gives back: absent, or an empty set. */
1583
+ const emptySetSpelling = (formatting) => formatting !== void 0 && Object.keys(formatting).length === 0 ? EMPTY_PROPERTY_SETS.KEEP : EMPTY_PROPERTY_SETS.OMIT;
1584
+ /** A patched property set, spelled as `whenEmpty` says once it has no keys left. */
1585
+ const patchedSet = (base, patch, whenEmpty) => applyFormattingPatch(base, patch) ?? (whenEmpty === EMPTY_PROPERTY_SETS.KEEP ? {} : void 0);
1586
+ const newTextRun = (text, formatting) => {
1587
+ const content = [{
1588
+ type: "text",
1589
+ text
1590
+ }];
1591
+ return formatting === void 0 || Object.keys(formatting).length === 0 ? {
1592
+ type: "run",
1593
+ content
1594
+ } : {
1595
+ type: "run",
1596
+ formatting,
1597
+ content
1598
+ };
1599
+ };
1600
+ /**
1601
+ * Remove the leaves between two gaps. A record the range passes through keeps
1602
+ * its two ends as one record; one left with nothing goes. Returns the new
1603
+ * content and the slice removed, with its cut ends.
1604
+ */
1605
+ const deleteBetween = (items, from, to) => {
1606
+ const gaps = [from, to];
1607
+ const [before = [], middle = [], after = []] = partitionContent(items, gaps);
1608
+ const across = spanningRecords(items, gaps, 0, 2).length;
1609
+ return {
1610
+ content: asParagraphContent(mergeLists(before, after, across) ?? panic("The two ends of a cut record always merge.")),
1611
+ removed: {
1612
+ content: asParagraphContent(middle),
1613
+ openStart: spanningRecords(items, gaps, 0, 1).length,
1614
+ openEnd: spanningRecords(items, gaps, 1, 2).length
1615
+ }
1616
+ };
1617
+ };
1618
+ /**
1619
+ * Cut the content at a gap and put a slice in, merging its open ends with the
1620
+ * halves; `undefined` when an open end does not match the record it meets.
1621
+ */
1622
+ const insertSliceAt = (items, at, slice) => {
1623
+ const [before = [], after = []] = partitionContent(items, [at]);
1624
+ const withStart = mergeLists(before, slice.content, slice.openStart);
1625
+ const whole = withStart === void 0 ? void 0 : mergeLists(withStart, after, slice.openEnd, {
1626
+ mode: "exact",
1627
+ identity: "second"
1628
+ });
1629
+ return whole === void 0 ? void 0 : asParagraphContent(whole);
1630
+ };
1631
+ /** The gap after inserted content: its trailing zero-width leaves come before it. */
1632
+ const gapAfterInserted = (at, inserted) => {
1633
+ const width = contentWidth(inserted);
1634
+ const trailing = zeroWidthLeavesAt(inserted, width).length;
1635
+ return {
1636
+ offset: at.offset + width,
1637
+ zeroWidthBefore: width === 0 ? at.zeroWidthBefore + trailing : trailing
1638
+ };
1639
+ };
1640
+ /**
1641
+ * What undoes an insertion: removing the inserted leaves, then merging the
1642
+ * records the insertion cut back to how `before` had them, `join` levels
1643
+ * below the ones still running across the gap. `undefined` when the
1644
+ * insertion merged records that were separate before it: no deletion could
1645
+ * tell them apart again, so such an insertion is refused.
1646
+ */
1647
+ const insertionInverse = (before, after, start, end) => {
1648
+ const { content: restored, removed } = deleteBetween(after, start, end);
1649
+ const cut = spanningRecords(before, [start], 0, 1).length;
1650
+ const across = spanningRecords(restored, [start], 0, 1).length;
1651
+ return across > cut ? void 0 : {
1652
+ removed,
1653
+ join: cut - across
1654
+ };
1655
+ };
1656
+ /** Cut the innermost `depth` records running across a gap in two; `undefined` when fewer do. */
1657
+ const splitAt = (items, at, depth) => {
1658
+ const spine = spanningRecords(items, [at], 0, 1);
1659
+ if (depth > spine.length) return;
1660
+ const [before = [], after = []] = partitionContent(items, [at]);
1661
+ return asParagraphContent(mergeLists(before, after, spine.length - depth) ?? panic("The two ends of a cut record always merge."));
1662
+ };
1663
+ /** Two sets of new ids, each space's in order: `first`'s then `second`'s. */
1664
+ const concatIds = (first, second) => {
1665
+ const revision = [...first.revision ?? [], ...second.revision ?? []];
1666
+ const control = [...first.control ?? [], ...second.control ?? []];
1667
+ return {
1668
+ ...revision.length > 0 ? { revision } : {},
1669
+ ...control.length > 0 ? { control } : {}
1670
+ };
1671
+ };
1672
+ /** Whether a set of new ids names any. */
1673
+ const namesIds = (ids) => (ids.revision?.length ?? 0) > 0 || (ids.control?.length ?? 0) > 0;
1674
+ /**
1675
+ * Merge `left` and `right`, `depth` levels, retiring ids from level `from`
1676
+ * down. Two records carrying the same id cannot be merged: a cut could not
1677
+ * give them back two.
1678
+ */
1679
+ const mergeRetiring = (left, right, depth, from) => {
1680
+ const retired = {
1681
+ revision: [],
1682
+ control: []
1683
+ };
1684
+ let shared = false;
1685
+ const content = mergeLists(left, right, depth, {
1686
+ mode: "exact",
1687
+ onMerge: (first, second, level) => {
1688
+ if (level < from) return;
1689
+ const kept = identitySlots(first);
1690
+ for (const [index, slot] of identitySlots(second).entries()) {
1691
+ shared ||= kept[index]?.id === slot.id;
1692
+ retired[slot.space].push(slot.id);
1693
+ }
1694
+ }
1695
+ });
1696
+ if (content === void 0) return { kind: "notAlike" };
1697
+ if (shared) return { kind: "sharedId" };
1698
+ return {
1699
+ kind: "joined",
1700
+ content: asParagraphContent(content),
1701
+ retired: concatIds({}, retired)
1702
+ };
1703
+ };
1704
+ /** Merge the records meeting at a gap, `depth` levels below the ones already running across it. */
1705
+ const joinAt = (items, at, depth) => {
1706
+ const across = spanningRecords(items, [at], 0, 1).length;
1707
+ const [before = [], after = []] = partitionContent(items, [at]);
1708
+ return mergeRetiring(before, after, across + depth, across + 1);
1709
+ };
1710
+ /** A split paragraph's two halves and the records the cut ran through. */
1711
+ const cutAt = (items, at) => {
1712
+ const [before = [], after = []] = partitionContent(items, [at]);
1713
+ return {
1714
+ before: asParagraphContent(before),
1715
+ after: asParagraphContent(after),
1716
+ through: spanningRecords(items, [at], 0, 1)
1717
+ };
1718
+ };
1719
+ /** Two paragraphs' content end to end, `depth` levels of the records meeting there merged. */
1720
+ const joinContent = (first, second, depth) => mergeRetiring(first, second, depth, 1);
1721
+ const splitRun = (run, offset) => {
1722
+ const left = [];
1723
+ const right = [];
1724
+ let position = 0;
1725
+ for (const child of run.content) {
1726
+ const width = runContentWidth(child);
1727
+ const start = position;
1728
+ position += width;
1729
+ if (position <= offset) left.push(child);
1730
+ else if (start >= offset) right.push(child);
1731
+ else if (child.type === "text") {
1732
+ left.push({
1733
+ ...child,
1734
+ text: child.text.slice(0, offset - start)
1735
+ });
1736
+ right.push({
1737
+ ...child,
1738
+ text: child.text.slice(offset - start)
1739
+ });
1740
+ }
1741
+ }
1742
+ return {
1743
+ left: left.length === 0 ? void 0 : withRunContent(run, left),
1744
+ right: right.length === 0 ? void 0 : withRunContent(run, right)
1745
+ };
1746
+ };
1747
+ /** The run holding unit `unit`, or `undefined` when the unit is not run content. */
1748
+ const runAtUnit = (items, unit, insideRemovedRevision) => {
1749
+ let position = 0;
1750
+ for (const [index, item] of items.entries()) {
1751
+ const width = inlineWidth(item);
1752
+ const start = position;
1753
+ position += width;
1754
+ if (unit < start || unit >= position) continue;
1755
+ if (item.type === "run") return {
1756
+ path: [index],
1757
+ run: item,
1758
+ runOffset: unit - start,
1759
+ insideRemovedRevision
1760
+ };
1761
+ if (isInlineContainer(item)) {
1762
+ const hit = runAtUnit(childrenOf(item), unit - start, insideRemovedRevision || isRemovedRevision(item));
1763
+ return hit === void 0 ? void 0 : {
1764
+ ...hit,
1765
+ path: [index, ...hit.path]
1766
+ };
1767
+ }
1768
+ return;
1769
+ }
1770
+ };
1771
+ /**
1772
+ * The run inserted text joins: the one holding the unit before the position,
1773
+ * else the one holding the unit after it, skipping runs inside tracked
1774
+ * deletions and moved-away content.
1775
+ */
1776
+ const insertionHost = (items, offset) => {
1777
+ const before = offset > 0 ? runAtUnit(items, offset - 1, false) : void 0;
1778
+ if (before !== void 0 && !before.insideRemovedRevision) return {
1779
+ path: before.path,
1780
+ run: before.run,
1781
+ runOffset: before.runOffset + 1
1782
+ };
1783
+ const after = runAtUnit(items, offset, false);
1784
+ if (after !== void 0 && !after.insideRemovedRevision) return {
1785
+ path: after.path,
1786
+ run: after.run,
1787
+ runOffset: after.runOffset
1788
+ };
1789
+ };
1790
+ /** Replace the child at `path` with `replacement`. */
1791
+ const replaceAtPath = (items, path, replacement) => {
1792
+ const [index, ...rest] = path;
1793
+ if (index === void 0) return [...replacement];
1794
+ const out = [...items];
1795
+ if (rest.length === 0) {
1796
+ out.splice(index, 1, ...replacement);
1797
+ return out;
1798
+ }
1799
+ const item = items[index];
1800
+ if (item === void 0 || !isInlineContainer(item)) return panic(`Inline path step ${index} does not name a container.`);
1801
+ out[index] = withChildren(item, replaceAtPath(childrenOf(item), rest, replacement));
1802
+ return out;
1803
+ };
1804
+ /**
1805
+ * The run with text added at a unit offset, joining the text node there when
1806
+ * one does. An empty text node is a zero-width child of its own and is left
1807
+ * as it is.
1808
+ */
1809
+ const runWithText = (run, runOffset, text) => {
1810
+ let position = 0;
1811
+ let insertAt = 0;
1812
+ for (const [index, child] of run.content.entries()) {
1813
+ const width = runContentWidth(child);
1814
+ if (child.type === "text" && width > 0 && position <= runOffset && runOffset <= position + width) {
1815
+ const cut = runOffset - position;
1816
+ const content = [...run.content];
1817
+ content[index] = {
1818
+ ...child,
1819
+ text: child.text.slice(0, cut) + text + child.text.slice(cut)
1820
+ };
1821
+ return withRunContent(run, content);
1822
+ }
1823
+ position += width;
1824
+ if (position <= runOffset) insertAt = index + 1;
1825
+ }
1826
+ const content = [...run.content];
1827
+ content.splice(insertAt, 0, {
1828
+ type: "text",
1829
+ text
1830
+ });
1831
+ return withRunContent(run, content);
1832
+ };
1833
+ /**
1834
+ * Put a new run at a position that no run holds; `undefined` when the position
1835
+ * is inside tracked-deleted or moved-away content.
1836
+ */
1837
+ const insertRunAtSlot = (items, offset, run) => {
1838
+ let position = 0;
1839
+ let insertAt = 0;
1840
+ for (const [index, item] of items.entries()) {
1841
+ const width = inlineWidth(item);
1842
+ const start = position;
1843
+ position += width;
1844
+ if (start < offset && offset < position && isInlineContainer(item)) {
1845
+ if (isRemovedRevision(item)) return;
1846
+ const children = insertRunAtSlot(childrenOf(item), offset - start, run);
1847
+ if (children === void 0) return;
1848
+ const out = [...items];
1849
+ out[index] = withChildren(item, children);
1850
+ return out;
1851
+ }
1852
+ if (position <= offset) insertAt = index + 1;
1853
+ }
1854
+ const out = [...items];
1855
+ out.splice(insertAt, 0, run);
1856
+ return out;
1857
+ };
1858
+ /**
1859
+ * Insert text at a position; `undefined` when the position is inside
1860
+ * tracked-deleted or moved-away content and no other run borders it.
1861
+ */
1862
+ const insertTextInContent = (items, offset, text, runProps) => {
1863
+ const host = insertionHost(items, offset);
1864
+ const formatting = runProps === "inherit" ? void 0 : runProps;
1865
+ if (host === void 0) return insertRunAtSlot(items, offset, newTextRun(text, formatting));
1866
+ if (formatting === void 0 || sameRunFormatting(formatting, host.run.formatting)) return replaceAtPath(items, host.path, [runWithText(host.run, host.runOffset, text)]);
1867
+ const halves = splitRun(host.run, host.runOffset);
1868
+ const replacement = [];
1869
+ if (halves.left !== void 0) replacement.push(halves.left);
1870
+ replacement.push(newTextRun(text, formatting));
1871
+ if (halves.right !== void 0) replacement.push(halves.right);
1872
+ return replaceAtPath(items, host.path, replacement);
1873
+ };
1874
+ const patchRunsIn = (nodes, patch, whenEmpty, prior) => {
1875
+ const out = [];
1876
+ for (const node of nodes) {
1877
+ if (node.type === "run") {
1878
+ const formatting = patchedSet(node.formatting, patch, whenEmpty);
1879
+ if (runWidth(node) === 0 || sameRunFormatting(formatting, node.formatting)) {
1880
+ out.push(node);
1881
+ continue;
1882
+ }
1883
+ const run = withRunFormatting(node, formatting);
1884
+ prior.set(run, node.formatting);
1885
+ out.push(run);
1886
+ continue;
1887
+ }
1888
+ if (isParagraphContent(node) && isInlineContainer(node)) {
1889
+ const children = childrenOf(node);
1890
+ const next = patchRunsIn(children, patch, whenEmpty, prior);
1891
+ const same = next.every((child, index) => child === children[index]);
1892
+ out.push(same ? node : withChildren(node, asParagraphContent(next)));
1893
+ continue;
1894
+ }
1895
+ out.push(node);
1896
+ }
1897
+ return out;
1898
+ };
1899
+ const collectRuns = (nodes, out) => {
1900
+ for (const node of nodes) {
1901
+ if (node.type === "run") {
1902
+ if (runWidth(node) > 0) out.push(node);
1903
+ continue;
1904
+ }
1905
+ if (isParagraphContent(node) && isInlineContainer(node)) collectRuns(childrenOf(node), out);
1906
+ }
1907
+ };
1908
+ /** The runs a patch between two gaps reaches, cut at the gaps: those with units there. */
1909
+ const runsBetween = (items, from, to) => {
1910
+ const [, middle = []] = partitionContent(items, [from, to]);
1911
+ const out = [];
1912
+ collectRuns(middle, out);
1913
+ return out;
1914
+ };
1915
+ /**
1916
+ * Patch the run properties of every run between two gaps, cutting runs at the
1917
+ * gaps. A run the patch leaves as it was is not cut. `undefined` when no run
1918
+ * changes.
1919
+ *
1920
+ * `restoring` gives the changed runs back the values the patch replaced, one
1921
+ * patch per stretch of adjacent runs that had the same values. A run the
1922
+ * patch left alone ends a stretch, so a restoring patch never reaches it.
1923
+ */
1924
+ const patchRunsBetween = (items, from, to, patch, whenEmpty) => {
1925
+ const gaps = [from, to];
1926
+ const [before = [], middle = [], after = []] = partitionContent(items, gaps);
1927
+ const prior = /* @__PURE__ */ new Map();
1928
+ const patchedMiddle = patchRunsIn(middle, patch, whenEmpty, prior);
1929
+ if (prior.size === 0) return;
1930
+ const alike = { mode: "asFarAsAlike" };
1931
+ const content = asParagraphContent(mergeLists(mergeLists(before, patchedMiddle, spanningRecords(items, gaps, 0, 1).length, alike) ?? [], after, spanningRecords(items, gaps, 1, 2).length, alike) ?? []);
1932
+ const restoring = [];
1933
+ let stretchOpen = false;
1934
+ for (const { node, before: start, after: end } of runGaps(content)) {
1935
+ if (node.type !== "run") continue;
1936
+ if (!prior.has(node)) {
1937
+ if (runWidth(node) > 0) stretchOpen = false;
1938
+ continue;
1939
+ }
1940
+ const previous = prior.get(node);
1941
+ const restore = priorValues(previous, patch);
1942
+ const spelling = emptySetSpelling(previous);
1943
+ const key = JSON.stringify([restore, spelling]);
1944
+ const last = restoring.at(-1);
1945
+ if (stretchOpen && last !== void 0 && last.key === key) last.to = end;
1946
+ else restoring.push({
1947
+ from: start,
1948
+ to: end,
1949
+ patch: restore,
1950
+ whenEmpty: spelling,
1951
+ key
1952
+ });
1953
+ stretchOpen = true;
1954
+ }
1955
+ return {
1956
+ content,
1957
+ restoring: restoring.map(({ from: start, to: end, patch: restore, whenEmpty: spelling }) => ({
1958
+ from: start,
1959
+ to: end,
1960
+ patch: restore,
1961
+ whenEmpty: spelling
1962
+ }))
1963
+ };
1964
+ };
1965
+ //#endregion
1966
+ //#region src/ops/apply.ts
1967
+ /**
1968
+ * Apply a document operation and record its exact inverse.
1969
+ *
1970
+ * `applyDocumentOp` is total: it returns the new document or a typed refusal,
1971
+ * and a refused operation changes nothing. It is deterministic: no clock, no
1972
+ * randomness and no counter outside its inputs, so equal documents and equal
1973
+ * operations give equal results in any realm, whether or not their records
1974
+ * share objects. It is local: every block the operation does not name is the
1975
+ * same object in the output as in the input, and so is every package part
1976
+ * other than the story it edits. It applies only to a document that meets
1977
+ * the seed contract (`contract.ts`), and leaves the contract holding.
1978
+ *
1979
+ * The inverse is a list of ordinary operations, addressed by position like
1980
+ * the one it undoes, captured from the state the operation changed:
1981
+ *
1982
+ * | operation | inverse |
1983
+ * | ------------------- | --------------------------------------------------------- |
1984
+ * | `insertText` | `deleteRange` (its `join` merges a run the text cut) |
1985
+ * | `insertContent` | `deleteRange` (its `join` merges the records the cut left) |
1986
+ * | `deleteRange` | `insertContent` with the removed slice |
1987
+ * | `splitInline` | `joinInline` |
1988
+ * | `joinInline` | `splitInline` |
1989
+ * | `setRunProps` | `setRunProps` per stretch of prior values, joining cuts |
1990
+ * | `setParagraphProps` | `setParagraphProps` with the prior values |
1991
+ * | `splitBlock` | `joinBlocks` |
1992
+ * | `joinBlocks` | `splitBlock` with the second paragraph's fields |
1993
+ * | `replaceBlocks` | `replaceBlocks` |
1994
+ *
1995
+ * Each inverse carries its precondition: a deletion the slice it removes, a
1996
+ * patch the values it replaces, a join the fields of the paragraph it merges
1997
+ * away. An inverse applied to content that has changed since is refused as
1998
+ * stale. An inverse that cuts records apart again names the ids its forward
1999
+ * operation retired.
2000
+ */
2001
+ const UNTOUCHED = Object.freeze({
2002
+ modified: [],
2003
+ inserted: [],
2004
+ removed: []
2005
+ });
2006
+ const unchanged = (document) => Result.ok({
2007
+ document,
2008
+ inverse: [],
2009
+ touched: UNTOUCHED
2010
+ });
2011
+ const refusal = (op, reason, message) => new DocumentOpRefusal({
2012
+ message,
2013
+ reason,
2014
+ opType: op.type
2015
+ });
2016
+ const refuse = (op, reason, message) => Result.err(refusal(op, reason, message));
2017
+ /** Characters `insertText` does not carry: each is an inline atom of its own. */
2018
+ const NON_TEXT_CHARACTER_PATTERN = /[\t\n\r]/u;
2019
+ const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
2020
+ const isLowSurrogate = (code) => code >= 56320 && code <= 57343;
2021
+ /** The paragraph carrying an id, compared as hex; the contract makes it unique. */
2022
+ const findParagraph = (op, paragraphs, blockId) => {
2023
+ const key = idKey(blockId);
2024
+ const match = paragraphs.find(({ paragraph }) => idKey(paragraph.paraId ?? "") === key);
2025
+ return match === void 0 ? Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, `No paragraph is ${blockId}.`)) : Result.ok(match);
2026
+ };
2027
+ const locate = (document, op, story, blockId) => findParagraph(op, storyParagraphs(storyBody(document, story)), blockId);
2028
+ /** The gap a position names, or why it names none in this paragraph. */
2029
+ const resolveGap = (paragraph, position, fallback) => {
2030
+ const text = paragraphLogicalText(paragraph);
2031
+ const { offset, zeroWidthBefore } = position;
2032
+ if (!Number.isInteger(offset) || offset < 0 || offset > text.length) return DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET;
2033
+ if (offset > 0 && offset < text.length && isHighSurrogate(text.charCodeAt(offset - 1)) && isLowSurrogate(text.charCodeAt(offset))) return DOCUMENT_OP_REFUSAL_REASONS.SPLITS_SURROGATE_PAIR;
2034
+ const available = zeroWidthLeavesAt(paragraph.content, offset).length;
2035
+ if (zeroWidthBefore !== void 0) return Number.isInteger(zeroWidthBefore) && zeroWidthBefore >= 0 && zeroWidthBefore <= available ? {
2036
+ offset,
2037
+ zeroWidthBefore
2038
+ } : DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET;
2039
+ switch (fallback) {
2040
+ case "afterAll": return {
2041
+ offset,
2042
+ zeroWidthBefore: available
2043
+ };
2044
+ case "beforeAll": return {
2045
+ offset,
2046
+ zeroWidthBefore: 0
2047
+ };
2048
+ case "insertion": return defaultInsertionGap(paragraph.content, offset);
2049
+ default: return fallback;
2050
+ }
2051
+ };
2052
+ const isGap = (value) => typeof value === "object";
2053
+ /**
2054
+ * A range of one paragraph. Absent `zeroWidthBefore` leaves the zero-width
2055
+ * leaves at both ends outside the range.
2056
+ */
2057
+ const locateRange = (document, op, from, to) => {
2058
+ if (from.story !== to.story || idKey(from.blockId) !== idKey(to.blockId)) return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.CROSS_BLOCK_RANGE, "A range starts and ends in one paragraph."));
2059
+ const located = locate(document, op, from.story, from.blockId);
2060
+ if (located.isErr()) return Result.err(located.error);
2061
+ const { paragraph } = located.value;
2062
+ const start = resolveGap(paragraph, from, "afterAll");
2063
+ const end = resolveGap(paragraph, to, "beforeAll");
2064
+ const invalid = (reason) => Result.err(refusal(op, reason, `[${from.offset}, ${to.offset}) is not a range of ${from.blockId}.`));
2065
+ if (!isGap(start)) return invalid(start);
2066
+ if (!isGap(end)) return invalid(end);
2067
+ const statesZeroWidth = from.zeroWidthBefore !== void 0 || to.zeroWidthBefore !== void 0;
2068
+ if (start.offset > end.offset || start.offset === end.offset && start.zeroWidthBefore > end.zeroWidthBefore && statesZeroWidth) return invalid(DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET);
2069
+ const empty = start.offset === end.offset && start.zeroWidthBefore >= end.zeroWidthBefore;
2070
+ return Result.ok({
2071
+ story: from.story,
2072
+ location: located.value,
2073
+ from: start,
2074
+ to: end,
2075
+ empty
2076
+ });
2077
+ };
2078
+ const locatePosition = (document, op, at, fallback) => {
2079
+ const located = locate(document, op, at.story, at.blockId);
2080
+ if (located.isErr()) return Result.err(located.error);
2081
+ const gap = resolveGap(located.value.paragraph, at, fallback);
2082
+ if (!isGap(gap)) return Result.err(refusal(op, gap, `${at.offset} is not a position in ${at.blockId}.`));
2083
+ return Result.ok({
2084
+ location: located.value,
2085
+ gap
2086
+ });
2087
+ };
2088
+ /** A position naming its paragraph by the id the paragraph carries. */
2089
+ const positionAt = (story, paragraph, gap) => ({
2090
+ story,
2091
+ blockId: paragraph.paraId ?? "",
2092
+ offset: gap.offset,
2093
+ zeroWidthBefore: gap.zeroWidthBefore
2094
+ });
2095
+ const touchedBetween = (before, after) => {
2096
+ const beforeIds = before.flatMap(({ paraId }) => paraId === void 0 ? [] : [paraId]);
2097
+ const afterIds = after.flatMap(({ paraId }) => paraId === void 0 ? [] : [paraId]);
2098
+ const afterKeys = new Set(afterIds.map(idKey));
2099
+ const beforeKeys = new Set(beforeIds.map(idKey));
2100
+ return {
2101
+ modified: beforeIds.filter((id) => afterKeys.has(idKey(id))),
2102
+ inserted: afterIds.filter((id) => !beforeKeys.has(idKey(id))),
2103
+ removed: beforeIds.filter((id) => !afterKeys.has(idKey(id)))
2104
+ };
2105
+ };
2106
+ /** Revision and control ids the package uses outside `before`. */
2107
+ const identitiesOutside = (document, before) => {
2108
+ const counts = countKeys(packageIdentityKeys(document.package));
2109
+ for (const key of identityKeysIn(before)) counts.set(key, (counts.get(key) ?? 1) - 1);
2110
+ return new Set([...counts].flatMap(([key, count]) => count > 0 ? [key] : []));
2111
+ };
2112
+ /** `after` with the records the edit would leave sharing an id given the operation's new ids. */
2113
+ const withFreshIds = ({ document, op, before, after, newIds, inserted }) => {
2114
+ const freshened = freshenIdentities({
2115
+ before,
2116
+ after,
2117
+ newIds: newIds ?? {},
2118
+ usedElsewhere: () => identitiesOutside(document, before),
2119
+ ...inserted === void 0 ? {} : { inserted }
2120
+ });
2121
+ switch (freshened.kind) {
2122
+ case "needsIds": return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS, `The edit cuts records carrying ids and needs ${freshened.missing} more new ids.`));
2123
+ case "invalidId": return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, `${freshened.id} cannot be a new revision or content-control id here.`));
2124
+ case "fresh": return Result.ok(freshened.paragraphs);
2125
+ default: return freshened;
2126
+ }
2127
+ };
2128
+ /** Put `after` where `before` stands, its records given fresh ids where they need them. */
2129
+ const commit = (options) => {
2130
+ const paragraphs = withFreshIds(options);
2131
+ if (paragraphs.isErr()) return Result.err(paragraphs.error);
2132
+ const { document, story, at, before } = options;
2133
+ return Result.ok({
2134
+ document: replaceParagraphs({
2135
+ document,
2136
+ story,
2137
+ at,
2138
+ count: before.length,
2139
+ replacement: paragraphs.value
2140
+ }),
2141
+ paragraphs: paragraphs.value,
2142
+ touched: touchedBetween(before, paragraphs.value)
2143
+ });
2144
+ };
2145
+ const withContent = (paragraph, content) => content === paragraph.content ? paragraph : {
2146
+ ...paragraph,
2147
+ content: [...content]
2148
+ };
2149
+ /** An edit of one paragraph, committed, with the inverse built from the paragraph it became. */
2150
+ const editOne = (commitOptions, inverseOf) => {
2151
+ const { paragraph, at, document } = commitOptions;
2152
+ if (paragraph === at.paragraph) return unchanged(document);
2153
+ const committed = commit({
2154
+ ...commitOptions,
2155
+ before: [at.paragraph],
2156
+ after: [paragraph]
2157
+ });
2158
+ if (committed.isErr()) return Result.err(committed.error);
2159
+ const [result] = committed.value.paragraphs;
2160
+ if (result === void 0) return Result.ok({
2161
+ document: committed.value.document,
2162
+ inverse: [],
2163
+ touched: UNTOUCHED
2164
+ });
2165
+ const inverse = inverseOf(result);
2166
+ if (inverse.isErr()) return Result.err(inverse.error);
2167
+ return Result.ok({
2168
+ document: committed.value.document,
2169
+ inverse: inverse.value,
2170
+ touched: committed.value.touched
2171
+ });
2172
+ };
2173
+ /** Commit an insertion, recording the one deletion that undoes it. */
2174
+ const inserted = ({ document, op, story, location, content, start, end, newIds }) => editOne({
2175
+ document,
2176
+ op,
2177
+ story,
2178
+ at: location,
2179
+ paragraph: withContent(location.paragraph, content),
2180
+ newIds,
2181
+ inserted: recordsBetween(content, start, end)
2182
+ }, (result) => {
2183
+ const inverse = insertionInverse(location.paragraph.content, result.content, start, end);
2184
+ if (inverse === void 0) return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The insertion would merge records that were separate."));
2185
+ const deletion = {
2186
+ type: DOCUMENT_OP_TYPES.DELETE_RANGE,
2187
+ from: positionAt(story, result, start),
2188
+ to: positionAt(story, result, end),
2189
+ expected: inverse.removed
2190
+ };
2191
+ if (inverse.join > 0) deletion.join = inverse.join;
2192
+ return Result.ok([deletion]);
2193
+ });
2194
+ const insertText = (document, op) => {
2195
+ if (op.text === "" || NON_TEXT_CHARACTER_PATTERN.test(op.text) || hasIllegalXmlCharacters(op.text)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The text cannot be inserted.");
2196
+ const located = locatePosition(document, op, op.at, "afterAll");
2197
+ if (located.isErr()) return Result.err(located.error);
2198
+ const { location } = located.value;
2199
+ const { offset } = op.at;
2200
+ const content = insertTextInContent(location.paragraph.content, offset, op.text, op.runProps);
2201
+ if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INSIDE_TRACKED_DELETION, `${offset} in ${op.at.blockId} is inside tracked-removed content.`);
2202
+ const start = {
2203
+ offset,
2204
+ zeroWidthBefore: zeroWidthLeavesAt(content, offset).length
2205
+ };
2206
+ const end = {
2207
+ offset: offset + op.text.length,
2208
+ zeroWidthBefore: 0
2209
+ };
2210
+ return inserted({
2211
+ document,
2212
+ op,
2213
+ story: op.at.story,
2214
+ location,
2215
+ content,
2216
+ start,
2217
+ end,
2218
+ newIds: op.newIds
2219
+ });
2220
+ };
2221
+ const holdsEmptyRecord = (nodes) => nodes.some((node) => isEmptyRecord(node) || holdsEmptyRecord(childNodes(node) ?? []));
2222
+ const insertContent = (document, op) => {
2223
+ const slice = {
2224
+ ...op.slice,
2225
+ content: structuredClone(op.slice.content)
2226
+ };
2227
+ if (slice.content.length === 0 || holdsEmptyRecord(slice.content)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The slice holds nothing, or an empty run or text node.");
2228
+ if (!Number.isInteger(slice.openStart) || !Number.isInteger(slice.openEnd) || slice.openStart < 0 || slice.openEnd < 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Open depths are counts.");
2229
+ if (textsIn(slice.content).some(hasIllegalXmlCharacters)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The slice holds text that cannot be written.");
2230
+ const incoming = paragraphIdsIn(slice.content);
2231
+ if (incoming.length > 0 && collides(countIds(packageParagraphIds(document.package)), incoming)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The slice holds a paragraph id the package already uses.");
2232
+ const located = locatePosition(document, op, op.at, "insertion");
2233
+ if (located.isErr()) return Result.err(located.error);
2234
+ const { location, gap } = located.value;
2235
+ const content = insertSliceAt(location.paragraph.content, gap, slice);
2236
+ if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `The slice's open ends do not fit ${op.at.offset} in ${op.at.blockId}.`);
2237
+ return inserted({
2238
+ document,
2239
+ op,
2240
+ story: op.at.story,
2241
+ location,
2242
+ content,
2243
+ start: gap,
2244
+ end: gapAfterInserted(gap, slice.content),
2245
+ newIds: op.newIds
2246
+ });
2247
+ };
2248
+ /** A merge's content, or the refusal naming why it cannot be made. */
2249
+ const joinedContent = (op, joined, where) => {
2250
+ switch (joined.kind) {
2251
+ case "joined": return Result.ok({
2252
+ content: joined.content,
2253
+ retired: joined.retired
2254
+ });
2255
+ case "notAlike": return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `The records meeting ${where} cannot be merged.`));
2256
+ case "sharedId": return Result.err(refusal(op, DOCUMENT_OP_REFUSAL_REASONS.SHARED_ID, `The records meeting ${where} carry the same id.`));
2257
+ default: return joined;
2258
+ }
2259
+ };
2260
+ const isCount = (value) => Number.isInteger(value) && value >= 0;
2261
+ const deleteRange = (document, op) => {
2262
+ const join = op.join ?? 0;
2263
+ if (!isCount(join)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
2264
+ const located = locateRange(document, op, op.from, op.to);
2265
+ if (located.isErr()) return Result.err(located.error);
2266
+ const { story, location, from, to, empty } = located.value;
2267
+ const { expected } = op;
2268
+ if (empty) return expected === void 0 || expected.content.length === 0 ? unchanged(document) : refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The range to delete is empty.");
2269
+ const { paragraph } = location;
2270
+ const { content: remaining, removed } = deleteBetween(paragraph.content, from, to);
2271
+ if (expected !== void 0 && !equalForStaleness(expected, removed)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The range of ${op.from.blockId} holds other content than expected.`);
2272
+ if (removed.content.length === 0) return unchanged(document);
2273
+ let content = remaining;
2274
+ let retired = {};
2275
+ if (join > 0) {
2276
+ const joined = joinedContent(op, joinAt(remaining, from, join), `at ${from.offset}`);
2277
+ if (joined.isErr()) return Result.err(joined.error);
2278
+ ({content, retired} = joined.value);
2279
+ }
2280
+ return editOne({
2281
+ document,
2282
+ op,
2283
+ story,
2284
+ at: location,
2285
+ paragraph: withContent(paragraph, content),
2286
+ newIds: void 0
2287
+ }, (result) => {
2288
+ const insertion = {
2289
+ type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
2290
+ at: positionAt(story, result, from),
2291
+ slice: removed
2292
+ };
2293
+ if (namesIds(retired)) insertion.newIds = retired;
2294
+ return Result.ok([insertion]);
2295
+ });
2296
+ };
2297
+ const splitInline = (document, op) => {
2298
+ if (!isCount(op.depth) || op.depth === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A split cuts one level or more.");
2299
+ const located = locatePosition(document, op, op.at, "beforeAll");
2300
+ if (located.isErr()) return Result.err(located.error);
2301
+ const { location, gap } = located.value;
2302
+ const content = splitAt(location.paragraph.content, gap, op.depth);
2303
+ if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `Fewer than ${op.depth} records run across ${op.at.offset} in ${op.at.blockId}.`);
2304
+ return editOne({
2305
+ document,
2306
+ op,
2307
+ story: op.at.story,
2308
+ at: location,
2309
+ paragraph: withContent(location.paragraph, content),
2310
+ newIds: op.newIds
2311
+ }, (result) => Result.ok([{
2312
+ type: DOCUMENT_OP_TYPES.JOIN_INLINE,
2313
+ at: positionAt(op.at.story, result, gap),
2314
+ depth: op.depth
2315
+ }]));
2316
+ };
2317
+ const joinInline = (document, op) => {
2318
+ if (!isCount(op.depth) || op.depth === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join merges one level or more.");
2319
+ const located = locatePosition(document, op, op.at, "beforeAll");
2320
+ if (located.isErr()) return Result.err(located.error);
2321
+ const { location, gap } = located.value;
2322
+ const joined = joinedContent(op, joinAt(location.paragraph.content, gap, op.depth), `at ${op.at.offset} in ${op.at.blockId}`);
2323
+ if (joined.isErr()) return Result.err(joined.error);
2324
+ const { content, retired } = joined.value;
2325
+ return editOne({
2326
+ document,
2327
+ op,
2328
+ story: op.at.story,
2329
+ at: location,
2330
+ paragraph: withContent(location.paragraph, content),
2331
+ newIds: void 0
2332
+ }, (result) => {
2333
+ const split = {
2334
+ type: DOCUMENT_OP_TYPES.SPLIT_INLINE,
2335
+ at: positionAt(op.at.story, result, gap),
2336
+ depth: op.depth
2337
+ };
2338
+ if (namesIds(retired)) split.newIds = retired;
2339
+ return Result.ok([split]);
2340
+ });
2341
+ };
2342
+ /** Whether a property set states each key of `expected` as it says (`null`: absent). */
2343
+ const statesValues = (formatting, expected) => {
2344
+ const values = new Map(Object.entries(formatting ?? {}));
2345
+ return Object.entries(expected).every(([key, value]) => value === void 0 || structurallyEqual(values.get(key) ?? null, value));
2346
+ };
2347
+ const setRunProps = (document, op) => {
2348
+ const joinStart = op.joinStart ?? 0;
2349
+ const joinEnd = op.joinEnd ?? 0;
2350
+ if (!isCount(joinStart) || !isCount(joinEnd)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
2351
+ const located = locateRange(document, op, op.from, op.to);
2352
+ if (located.isErr()) return Result.err(located.error);
2353
+ const { story, location, from, to, empty } = located.value;
2354
+ if (empty) return unchanged(document);
2355
+ const { paragraph } = location;
2356
+ const { expected } = op;
2357
+ if (expected !== void 0 && !runsBetween(paragraph.content, from, to).every((run) => statesValues(run.formatting, expected))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The runs of ${op.from.blockId} state other values than expected.`);
2358
+ const patched = patchRunsBetween(paragraph.content, from, to, op.patch, op.whenEmpty);
2359
+ const patchedContent = patched?.content ?? paragraph.content;
2360
+ const freshened = withFreshIds({
2361
+ document,
2362
+ op,
2363
+ before: [paragraph],
2364
+ after: [withContent(paragraph, patchedContent)],
2365
+ newIds: op.newIds
2366
+ });
2367
+ if (freshened.isErr()) return Result.err(freshened.error);
2368
+ let content = freshened.value[0]?.content ?? patchedContent;
2369
+ const retiredAt = {
2370
+ from: {},
2371
+ to: {}
2372
+ };
2373
+ for (const [gap, depth, side] of [[
2374
+ from,
2375
+ joinStart,
2376
+ "from"
2377
+ ], [
2378
+ to,
2379
+ joinEnd,
2380
+ "to"
2381
+ ]]) {
2382
+ if (depth === 0) continue;
2383
+ const joined = joinedContent(op, joinAt(content, gap, depth), `at ${gap.offset}`);
2384
+ if (joined.isErr()) return Result.err(joined.error);
2385
+ content = joined.value.content;
2386
+ retiredAt[side] = joined.value.retired;
2387
+ }
2388
+ const result = withContent(paragraph, content);
2389
+ if (structurallyEqual(result.content, paragraph.content)) return unchanged(document);
2390
+ const inverse = (patched?.restoring ?? []).map((span) => ({
2391
+ type: DOCUMENT_OP_TYPES.SET_RUN_PROPS,
2392
+ from: positionAt(story, result, span.from),
2393
+ to: positionAt(story, result, span.to),
2394
+ patch: span.patch,
2395
+ whenEmpty: span.whenEmpty,
2396
+ expected: op.patch
2397
+ }));
2398
+ const cutAtGap = (gap) => spanningRecords(paragraph.content, [gap], 0, 1).length - spanningRecords(content, [gap], 0, 1).length;
2399
+ const first = inverse.at(0);
2400
+ const last = inverse.at(-1);
2401
+ if (first !== void 0 && last !== void 0) {
2402
+ const cutFrom = cutAtGap(from);
2403
+ const cutTo = cutAtGap(to);
2404
+ if (cutFrom > 0) first.joinStart = cutFrom;
2405
+ if (cutTo > 0) last.joinEnd = cutTo;
2406
+ if (namesIds(retiredAt.from)) first.newIds = concatIds(first.newIds ?? {}, retiredAt.from);
2407
+ if (namesIds(retiredAt.to)) last.newIds = concatIds(last.newIds ?? {}, retiredAt.to);
2408
+ }
2409
+ return Result.ok({
2410
+ document: replaceParagraphs({
2411
+ document,
2412
+ story,
2413
+ at: location,
2414
+ count: 1,
2415
+ replacement: [result]
2416
+ }),
2417
+ inverse,
2418
+ touched: touchedBetween([paragraph], [result])
2419
+ });
2420
+ };
2421
+ const withParagraphFormatting = (paragraph, formatting) => {
2422
+ const next = { ...paragraph };
2423
+ if (formatting === void 0) delete next.formatting;
2424
+ else next.formatting = formatting;
2425
+ return next;
2426
+ };
2427
+ const setParagraphProps = (document, op) => {
2428
+ const located = locate(document, op, op.story, op.blockId);
2429
+ if (located.isErr()) return Result.err(located.error);
2430
+ const { paragraph } = located.value;
2431
+ if (op.expected !== void 0 && !statesValues(paragraph.formatting, op.expected)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} states other paragraph properties than expected.`);
2432
+ const formatting = patchedSet(paragraph.formatting, op.patch, op.whenEmpty);
2433
+ if (structurallyEqual(formatting ?? {}, paragraph.formatting ?? {})) return unchanged(document);
2434
+ return editOne({
2435
+ document,
2436
+ op,
2437
+ story: op.story,
2438
+ at: located.value,
2439
+ paragraph: withParagraphFormatting(paragraph, formatting),
2440
+ newIds: void 0
2441
+ }, (result) => Result.ok([{
2442
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS,
2443
+ story: op.story,
2444
+ blockId: result.paraId ?? op.blockId,
2445
+ patch: priorValues(paragraph.formatting, op.patch),
2446
+ whenEmpty: emptySetSpelling(paragraph.formatting),
2447
+ expected: op.patch
2448
+ }]));
2449
+ };
2450
+ /** The fields of a paragraph a split gives the new half: all but its id, content and mark. */
2451
+ const splitFieldsOf = (paragraph) => {
2452
+ const fields = { ...paragraph };
2453
+ delete fields.type;
2454
+ delete fields.paraId;
2455
+ delete fields.content;
2456
+ delete fields.sectionProperties;
2457
+ delete fields.pPrMark;
2458
+ return fields;
2459
+ };
2460
+ const splitBlock = (document, op) => {
2461
+ if (!isParaId(op.newBlockId)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${op.newBlockId} is not a paragraph id.`);
2462
+ if (collides(countIds(packageParagraphIds(document.package)), [op.newBlockId])) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, `${op.newBlockId} is already used in the package.`);
2463
+ const located = locatePosition(document, op, op.at, "insertion");
2464
+ if (located.isErr()) return Result.err(located.error);
2465
+ const { location, gap } = located.value;
2466
+ const { paragraph } = location;
2467
+ const cut = cutAt(paragraph.content, gap);
2468
+ const first = {
2469
+ ...paragraph,
2470
+ content: cut.before
2471
+ };
2472
+ delete first.sectionProperties;
2473
+ delete first.pPrMark;
2474
+ if (op.firstMark !== void 0) first.pPrMark = op.firstMark;
2475
+ const second = {
2476
+ ...op.newParagraph ?? (paragraph.formatting === void 0 ? {} : { formatting: paragraph.formatting }),
2477
+ type: "paragraph",
2478
+ paraId: op.newBlockId,
2479
+ content: cut.after
2480
+ };
2481
+ if (paragraph.sectionProperties !== void 0) second.sectionProperties = paragraph.sectionProperties;
2482
+ if (paragraph.pPrMark !== void 0) second.pPrMark = paragraph.pPrMark;
2483
+ const committed = commit({
2484
+ document,
2485
+ op,
2486
+ story: op.at.story,
2487
+ at: location,
2488
+ before: [paragraph],
2489
+ after: [first, second],
2490
+ newIds: op.newIds
2491
+ });
2492
+ if (committed.isErr()) return Result.err(committed.error);
2493
+ const [, placedSecond] = committed.value.paragraphs;
2494
+ return Result.ok({
2495
+ document: committed.value.document,
2496
+ inverse: [{
2497
+ type: DOCUMENT_OP_TYPES.JOIN_BLOCKS,
2498
+ story: op.at.story,
2499
+ blockId: paragraph.paraId ?? op.at.blockId,
2500
+ nextBlockId: op.newBlockId,
2501
+ depth: cut.through.length,
2502
+ expectedSecond: splitFieldsOf(placedSecond ?? second)
2503
+ }],
2504
+ touched: committed.value.touched
2505
+ });
2506
+ };
2507
+ const joinBlocks = (document, op) => {
2508
+ const paragraphs = storyParagraphs(storyBody(document, op.story));
2509
+ const first = findParagraph(op, paragraphs, op.blockId);
2510
+ if (first.isErr()) return Result.err(first.error);
2511
+ const next = findParagraph(op, paragraphs, op.nextBlockId);
2512
+ if (next.isErr()) return Result.err(next.error);
2513
+ if (!sameBlockList(first.value.list, next.value.list) || next.value.index !== first.value.index + 1) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, `${op.nextBlockId} does not directly follow ${op.blockId}.`);
2514
+ const leading = first.value.paragraph;
2515
+ const trailing = next.value.paragraph;
2516
+ if (leading.sectionProperties !== void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, `${op.blockId} ends a section.`);
2517
+ if (op.expectedSecond !== void 0 && !equalForStaleness({
2518
+ type: "paragraph",
2519
+ ...splitFieldsOf(trailing)
2520
+ }, {
2521
+ type: "paragraph",
2522
+ ...op.expectedSecond
2523
+ })) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.nextBlockId} states other fields than expected.`);
2524
+ const trailingId = trailing.paraId ?? "";
2525
+ if (!isParaId(trailingId)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${trailingId} could not name the paragraph again.`);
2526
+ const depth = op.depth ?? 0;
2527
+ if (!isCount(depth)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
2528
+ const merged = joinedContent(op, joinContent(leading.content, trailing.content, depth), `between ${op.blockId} and ${op.nextBlockId}`);
2529
+ if (merged.isErr()) return Result.err(merged.error);
2530
+ const joined = {
2531
+ ...leading,
2532
+ content: merged.value.content
2533
+ };
2534
+ delete joined.pPrMark;
2535
+ if (trailing.sectionProperties !== void 0) joined.sectionProperties = trailing.sectionProperties;
2536
+ if (trailing.pPrMark !== void 0) joined.pPrMark = trailing.pPrMark;
2537
+ const length = paragraphLength(leading);
2538
+ const split = {
2539
+ type: DOCUMENT_OP_TYPES.SPLIT_BLOCK,
2540
+ at: {
2541
+ story: op.story,
2542
+ blockId: leading.paraId ?? op.blockId,
2543
+ offset: length,
2544
+ zeroWidthBefore: zeroWidthLeavesAt(leading.content, length).length
2545
+ },
2546
+ newBlockId: trailingId,
2547
+ newParagraph: splitFieldsOf(trailing)
2548
+ };
2549
+ if (leading.pPrMark !== void 0) split.firstMark = leading.pPrMark;
2550
+ if (namesIds(merged.value.retired)) split.newIds = merged.value.retired;
2551
+ const committed = commit({
2552
+ document,
2553
+ op,
2554
+ story: op.story,
2555
+ at: first.value,
2556
+ before: [leading, trailing],
2557
+ after: [joined],
2558
+ newIds: void 0
2559
+ });
2560
+ if (committed.isErr()) return Result.err(committed.error);
2561
+ return Result.ok({
2562
+ document: committed.value.document,
2563
+ inverse: [split],
2564
+ touched: committed.value.touched
2565
+ });
2566
+ };
2567
+ /**
2568
+ * Whether a replacement leaves every section break where it was: the replaced
2569
+ * paragraphs lie in one section (only the last may end it) and the
2570
+ * replacement ends it the same way. Anything else would change the sections
2571
+ * the body is divided into, which is a section operation.
2572
+ */
2573
+ const sameSectionBreaks = (before, after) => {
2574
+ const breaksInside = (paragraphs) => paragraphs.slice(0, -1).some(({ sectionProperties }) => sectionProperties !== void 0);
2575
+ return !breaksInside(before) && !breaksInside(after) && structurallyEqual(before.at(-1)?.sectionProperties, after.at(-1)?.sectionProperties);
2576
+ };
2577
+ const replaceBlocks = (document, op) => {
2578
+ const [firstExpected] = op.expected;
2579
+ if (firstExpected === void 0 || op.blocks.length === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "A replacement names the paragraphs it replaces and the ones it puts in their place.");
2580
+ const paragraphs = storyParagraphs(storyBody(document, op.story));
2581
+ const found = [];
2582
+ for (const expected of op.expected) {
2583
+ if (expected.paraId === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, "A replaced paragraph has no id.");
2584
+ const located = findParagraph(op, paragraphs, expected.paraId);
2585
+ if (located.isErr()) return Result.err(located.error);
2586
+ found.push(located.value);
2587
+ }
2588
+ const [start] = found;
2589
+ if (start === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "Nothing to replace.");
2590
+ if (!found.every((location, offset) => sameBlockList(location.list, start.list) && location.index === start.index + offset)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, "The replaced paragraphs are not adjacent.");
2591
+ if (found.some((location, offset) => !equalForStaleness(location.paragraph, op.expected[offset]))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The paragraphs to replace have changed.");
2592
+ if (op.blocks.some(({ paraId }) => paraId === void 0)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A replacement paragraph has no id.");
2593
+ if (op.blocks.some(({ content }) => holdsEmptyRecord(content))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "A replacement paragraph holds an empty run or text node.");
2594
+ const before = found.map(({ paragraph }) => paragraph);
2595
+ const kept = new Set(before.map(({ paraId }) => idKey(paraId ?? "")));
2596
+ const placed = new Set(op.blocks.map(({ paraId }) => idKey(paraId ?? "")));
2597
+ if ([...op.blocks.filter(({ paraId }) => !kept.has(idKey(paraId ?? ""))), ...before.filter(({ paraId }) => !placed.has(idKey(paraId ?? "")))].some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A paragraph the replacement adds or removes has no usable id.");
2598
+ if (!sameSectionBreaks(before, op.blocks)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, "A replacement keeps every section break where it is.");
2599
+ const remaining = countIds(packageParagraphIds(document.package));
2600
+ for (const id of paragraphIdsIn(before)) remaining.set(idKey(id), (remaining.get(idKey(id)) ?? 1) - 1);
2601
+ if (collides(remaining, paragraphIdsIn(op.blocks))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "A replacement paragraph id is already used in the package.");
2602
+ const outside = identitiesOutside(document, before);
2603
+ const incomingRecords = identityKeysIn(op.blocks);
2604
+ if (incomingRecords.some((key) => outside.has(key)) || new Set(incomingRecords).size !== incomingRecords.length) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "A replacement carries a revision or content-control id already used in the package.");
2605
+ return Result.ok({
2606
+ document: replaceParagraphs({
2607
+ document,
2608
+ story: op.story,
2609
+ at: start,
2610
+ count: before.length,
2611
+ replacement: op.blocks
2612
+ }),
2613
+ inverse: [{
2614
+ type: DOCUMENT_OP_TYPES.REPLACE_BLOCKS,
2615
+ story: op.story,
2616
+ expected: op.blocks,
2617
+ blocks: before
2618
+ }],
2619
+ touched: touchedBetween(before, op.blocks)
2620
+ });
2621
+ };
2622
+ const dispatch = (document, op) => {
2623
+ switch (op.type) {
2624
+ case DOCUMENT_OP_TYPES.INSERT_TEXT: return insertText(document, op);
2625
+ case DOCUMENT_OP_TYPES.INSERT_CONTENT: return insertContent(document, op);
2626
+ case DOCUMENT_OP_TYPES.DELETE_RANGE: return deleteRange(document, op);
2627
+ case DOCUMENT_OP_TYPES.SPLIT_INLINE: return splitInline(document, op);
2628
+ case DOCUMENT_OP_TYPES.JOIN_INLINE: return joinInline(document, op);
2629
+ case DOCUMENT_OP_TYPES.SET_RUN_PROPS: return setRunProps(document, op);
2630
+ case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS: return setParagraphProps(document, op);
2631
+ case DOCUMENT_OP_TYPES.SPLIT_BLOCK: return splitBlock(document, op);
2632
+ case DOCUMENT_OP_TYPES.JOIN_BLOCKS: return joinBlocks(document, op);
2633
+ case DOCUMENT_OP_TYPES.REPLACE_BLOCKS: return replaceBlocks(document, op);
2634
+ default: return op;
2635
+ }
2636
+ };
2637
+ /** Apply one operation to a document that meets the seed contract. */
2638
+ const applyDocumentOp = (document, op) => {
2639
+ const valid = validateOpsDocument(document);
2640
+ if (valid.isErr()) return refuse(op, valid.error.reason, valid.error.message);
2641
+ const applied = dispatch(document, op);
2642
+ if (applied.isOk()) meetsContract(applied.value.document);
2643
+ return applied;
2644
+ };
2645
+ const TOUCH_TRANSITIONS = {
2646
+ modified: {
2647
+ modified: "modified",
2648
+ inserted: "modified",
2649
+ removed: "removed"
2650
+ },
2651
+ inserted: {
2652
+ modified: "inserted",
2653
+ inserted: "inserted",
2654
+ removed: void 0
2655
+ },
2656
+ removed: {
2657
+ modified: "modified",
2658
+ inserted: "modified",
2659
+ removed: "removed"
2660
+ }
2661
+ };
2662
+ /**
2663
+ * Apply operations in order, atomically: the first refusal is returned and
2664
+ * the document is unchanged. The inverse undoes the whole list.
2665
+ */
2666
+ const applyDocumentOps = (document, ops) => {
2667
+ let current = document;
2668
+ const inverses = [];
2669
+ const touched = /* @__PURE__ */ new Map();
2670
+ for (const op of ops) {
2671
+ const applied = applyDocumentOp(current, op);
2672
+ if (applied.isErr()) return applied;
2673
+ current = applied.value.document;
2674
+ inverses.push(applied.value.inverse);
2675
+ for (const state of [
2676
+ "modified",
2677
+ "inserted",
2678
+ "removed"
2679
+ ]) for (const id of applied.value.touched[state]) {
2680
+ const previous = touched.get(id);
2681
+ const nextState = previous === void 0 ? state : TOUCH_TRANSITIONS[previous][state];
2682
+ if (nextState === void 0) touched.delete(id);
2683
+ else touched.set(id, nextState);
2684
+ }
2685
+ }
2686
+ const ids = (state) => [...touched].flatMap(([id, value]) => value === state ? [id] : []);
2687
+ return Result.ok({
2688
+ document: current,
2689
+ inverse: inverses.toReversed().flat(),
2690
+ touched: {
2691
+ modified: ids("modified"),
2692
+ inserted: ids("inserted"),
2693
+ removed: ids("removed")
2694
+ }
2695
+ });
2696
+ };
2697
+ //#endregion
2698
+ export { DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, applyDocumentOp, applyDocumentOps, normalizeForOps, paragraphLength, paragraphLogicalText, toOpEnvelope, validateOpsDocument };