@stll/docx-core 0.42.1 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { M as PARAGRAPH_ALIGNMENTS, et as isNumberingLevel, gt as finalizeParagraphFormatting, o as INSERTION_SEAM_POLICIES, rt as isNumberingReference, s as MAX_REVISION_ID, st as paragraphNumberingReference, t as COMMENT_PART_RELATIONSHIPS, vt as setDocumentBodyComments, yt as getSingularRunPropertyChange } from "../document-NtScxyHH.js";
1
+ import { Et as getSingularRunPropertyChange, M as PARAGRAPH_ALIGNMENTS, et as isNumberingLevel, gt as finalizeParagraphFormatting, o as INSERTION_SEAM_POLICIES, rt as isNumberingReference, s as MAX_REVISION_ID, st as paragraphNumberingReference, t as COMMENT_PART_RELATIONSHIPS, vt as setDocumentBodyComments } from "../document-CEMwM5On.js";
2
2
  import { a as hasIllegalXmlCharacters, t as sanitizeExternalUrl } from "../href-ogmJmncc.js";
3
3
  import { Result, TaggedError, panic } from "better-result";
4
4
  import { encodeUtf8 } from "@stll/utf8-boundaries";
@@ -149,6 +149,13 @@ const registerParagraphPropertySnapshot = ({ paragraph, snapshot }) => {
149
149
  snapshot
150
150
  });
151
151
  };
152
+ /**
153
+ * The registration a paragraph's snapshot stands on, as an opaque token: the
154
+ * same object while nothing registers or transfers another one for it. A pass
155
+ * that registered a snapshot can tell from it that registering again would
156
+ * change nothing.
157
+ */
158
+ const paragraphPropertySnapshotToken = (paragraph) => snapshots.get(paragraph);
152
159
  /** Retain paragraph-owned snapshot bindings through sanctioned model copies. */
153
160
  const transferParagraphPropertySnapshot = ({ source, target }) => {
154
161
  const registered = snapshots.get(source);
@@ -372,6 +379,7 @@ const DOCUMENT_OP_TYPES = Object.freeze({
372
379
  SET_PARAGRAPH_REVIEW: "setParagraphReview",
373
380
  REPLACE_INLINE: "replaceInline",
374
381
  RESOLVE_REVISION: "resolveRevision",
382
+ SET_REVISION_INFO: "setRevisionInfo",
375
383
  INSERT_TABLE: "insertTable",
376
384
  DELETE_TABLE: "deleteTable",
377
385
  SET_CONTAINER_BLOCKS: "setContainerBlocks",
@@ -589,6 +597,8 @@ const collectParagraphs = (blocks, list, out) => {
589
597
  case "preservedBlock":
590
598
  case "bookmarkStart":
591
599
  case "bookmarkEnd":
600
+ case "commentRangeStart":
601
+ case "commentRangeEnd":
592
602
  case "moveFromRangeStart":
593
603
  case "moveFromRangeEnd":
594
604
  case "moveToRangeStart":
@@ -1133,7 +1143,8 @@ const HYPERLINK_CHILD_TYPES = {
1133
1143
  moveToRangeStart: true,
1134
1144
  moveToRangeEnd: true,
1135
1145
  inlineWrapper: true,
1136
- preservedInline: true
1146
+ preservedInline: true,
1147
+ complexField: true
1137
1148
  };
1138
1149
  const TRACKED_CHILD_TYPES = {
1139
1150
  run: true,
@@ -1142,6 +1153,7 @@ const TRACKED_CHILD_TYPES = {
1142
1153
  bookmarkEnd: true,
1143
1154
  commentRangeStart: true,
1144
1155
  commentRangeEnd: true,
1156
+ commentReference: true,
1145
1157
  moveFromRangeStart: true,
1146
1158
  moveFromRangeEnd: true,
1147
1159
  moveToRangeStart: true,
@@ -1253,12 +1265,14 @@ const walk = ({ value, visit, context = {
1253
1265
  visit(entries, context);
1254
1266
  const type = fieldOf(entries, "type");
1255
1267
  const ownerType = typeof type === "string" ? type : void 0;
1268
+ const table = type === "table" ? value : context.table;
1256
1269
  for (const [heldBy, field] of entries) walk({
1257
1270
  value: field,
1258
1271
  visit,
1259
1272
  context: {
1260
1273
  heldBy,
1261
- ownerType
1274
+ ownerType,
1275
+ table
1262
1276
  }
1263
1277
  });
1264
1278
  };
@@ -1380,77 +1394,206 @@ const controlIdOf = (entries, { heldBy, ownerType }) => {
1380
1394
  return heldBy === "properties" && (ownerType === "inlineSdt" || ownerType === "blockSdt") || heldBy === CONTENT_CONTROL_STACK || typeof fieldOf(entries, "sdtType") === "string" ? id : void 0;
1381
1395
  };
1382
1396
  /**
1383
- * Every revision and content-control id in a value, as slot keys: tracked
1384
- * changes and property changes by their `info`, content controls by their
1385
- * properties.
1397
+ * The ids each record and list contributes, by the context it was walked in.
1398
+ *
1399
+ * A record's contribution depends only on its own fields, the field holding
1400
+ * it and its owner's type, so it is the same wherever an unchanged record is
1401
+ * shared: an edit replaces the records on the path to what it changed and
1402
+ * keeps the rest, and a census of the new version walks only those. A record
1403
+ * a census counts against others (a control stacked in a table's order is
1404
+ * counted once per table) is not shareable: it, and every record holding it,
1405
+ * are walked anew.
1386
1406
  */
1387
- const identityKeysIn = (value) => {
1388
- const out = [];
1389
- const stacked = /* @__PURE__ */ new Map();
1390
- walk({
1391
- value,
1392
- visit: (entries, { heldBy, ownerType }) => {
1393
- const revision = revisionIdOf(entries, heldBy);
1394
- if (revision !== void 0) out.push(slotKey({
1395
- space: IDENTITY_SPACES.REVISION,
1396
- id: revision
1397
- }));
1398
- const control = controlIdOf(entries, {
1407
+ const NO_KEYS = Object.freeze([]);
1408
+ const contextKey = ({ heldBy, ownerType }) => `${heldBy ?? ""}\u0000${ownerType ?? ""}`;
1409
+ const joined = (parts) => {
1410
+ const filled = parts.filter((part) => part.length > 0);
1411
+ if (filled.length === 0) return NO_KEYS;
1412
+ if (filled.length === 1) return filled[0] ?? NO_KEYS;
1413
+ return filled.flat();
1414
+ };
1415
+ const subtreeCensus = (ownKeys, sharing = "shared") => {
1416
+ const known = /* @__PURE__ */ new WeakMap();
1417
+ const remembered = (value, key, census) => {
1418
+ if (!census.shareable || sharing === "full") return census;
1419
+ const keys = census.keys.length === 0 ? NO_KEYS : Object.freeze([...census.keys]);
1420
+ let byContext = known.get(value);
1421
+ if (byContext === void 0) {
1422
+ byContext = /* @__PURE__ */ new Map();
1423
+ known.set(value, byContext);
1424
+ }
1425
+ byContext.set(key, keys);
1426
+ return {
1427
+ keys,
1428
+ shareable: true
1429
+ };
1430
+ };
1431
+ const censusOf = (value, context) => {
1432
+ if (typeof value !== "object" || value === null) return {
1433
+ keys: NO_KEYS,
1434
+ shareable: true
1435
+ };
1436
+ const isList = Array.isArray(value) || value instanceof Map;
1437
+ if (!isList && !isPlainRecord(value)) return {
1438
+ keys: NO_KEYS,
1439
+ shareable: true
1440
+ };
1441
+ const key = contextKey(context);
1442
+ const cached = known.get(value)?.get(key);
1443
+ if (cached !== void 0) return {
1444
+ keys: cached,
1445
+ shareable: true
1446
+ };
1447
+ if (isList) {
1448
+ const parts = (Array.isArray(value) ? value : [...value.values()]).map((item) => censusOf(item, context));
1449
+ return remembered(value, key, {
1450
+ keys: joined(parts.map((part) => part.keys)),
1451
+ shareable: parts.every((part) => part.shareable)
1452
+ });
1453
+ }
1454
+ const entries = Object.entries(value);
1455
+ const own = ownKeys(entries, context);
1456
+ let shareable = own.shareable;
1457
+ const type = fieldOf(entries, "type");
1458
+ const ownerType = typeof type === "string" ? type : void 0;
1459
+ const table = type === "table" ? value : context.table;
1460
+ const parts = [own.keys];
1461
+ for (const [heldBy, child] of entries) {
1462
+ const census = censusOf(child, {
1399
1463
  heldBy,
1400
- ownerType
1464
+ ownerType,
1465
+ table,
1466
+ stacked: context.stacked
1401
1467
  });
1402
- if (control === void 0) return;
1403
- if (heldBy === CONTENT_CONTROL_STACK) {
1404
- const record = Object.fromEntries(entries);
1405
- const seen = stacked.get(control) ?? [];
1406
- if (seen.some((other) => structurallyEqual(other, record))) return;
1407
- seen.push(record);
1408
- stacked.set(control, seen);
1409
- }
1410
- out.push(slotKey({
1411
- space: IDENTITY_SPACES.CONTROL,
1412
- id: control
1413
- }));
1468
+ parts.push(census.keys);
1469
+ if (!census.shareable) shareable = false;
1414
1470
  }
1471
+ return remembered(value, key, {
1472
+ keys: joined(parts),
1473
+ shareable
1474
+ });
1475
+ };
1476
+ return (value) => [...censusOf(value, {
1477
+ heldBy: void 0,
1478
+ ownerType: void 0,
1479
+ stacked: /* @__PURE__ */ new Map()
1480
+ }).keys];
1481
+ };
1482
+ const ownIdentityKeys = (entries, context) => {
1483
+ const { heldBy, ownerType, table } = context;
1484
+ const keys = [];
1485
+ let shareable = true;
1486
+ const revision = revisionIdOf(entries, heldBy);
1487
+ if (revision !== void 0) keys.push(slotKey({
1488
+ space: IDENTITY_SPACES.REVISION,
1489
+ id: revision
1490
+ }));
1491
+ const control = controlIdOf(entries, {
1492
+ heldBy,
1493
+ ownerType
1415
1494
  });
1416
- return out;
1495
+ if (control === void 0) return {
1496
+ keys,
1497
+ shareable
1498
+ };
1499
+ if (heldBy === CONTENT_CONTROL_STACK || heldBy === "properties" && ownerType === "sdt") {
1500
+ shareable = false;
1501
+ const record = Object.fromEntries(entries);
1502
+ const inTable = context.stacked.get(table) ?? /* @__PURE__ */ new Map();
1503
+ context.stacked.set(table, inTable);
1504
+ const seen = inTable.get(control) ?? [];
1505
+ if (seen.some((other) => structurallyEqual(other, record))) return {
1506
+ keys,
1507
+ shareable
1508
+ };
1509
+ seen.push(record);
1510
+ inTable.set(control, seen);
1511
+ }
1512
+ keys.push(slotKey({
1513
+ space: IDENTITY_SPACES.CONTROL,
1514
+ id: control
1515
+ }));
1516
+ return {
1517
+ keys,
1518
+ shareable
1519
+ };
1417
1520
  };
1521
+ /**
1522
+ * Every revision and content-control id in a value, as slot keys: tracked
1523
+ * changes and property changes by their `info`, content controls by their
1524
+ * properties. Every record is read anew: the value may belong to a caller
1525
+ * who changes it between calls.
1526
+ */
1527
+ const identityKeysIn = subtreeCensus(ownIdentityKeys, "full");
1528
+ /**
1529
+ * {@link identityKeysIn} reusing what it counted in records an earlier
1530
+ * census met. Only for packages, which no operation changes (see
1531
+ * {@link censusOnce}).
1532
+ */
1533
+ const sharedIdentityKeysIn = subtreeCensus(ownIdentityKeys);
1418
1534
  /** The field holding the stack of content controls a table row or cell sits inside. */
1419
1535
  const CONTENT_CONTROL_STACK = "contentControls";
1420
- /** Pending cut references reserve IDs without becoming physical model identities. */
1421
- const reservedIdentityKeysIn = (value) => {
1422
- const out = [];
1423
- walk({
1424
- value,
1425
- visit: (entries, { heldBy }) => {
1426
- if (heldBy === "deferredRemove") {
1427
- const blockers = fieldOf(entries, "blockers");
1428
- if (Array.isArray(blockers)) {
1429
- for (const id of blockers) if (typeof id === "number") out.push(slotKey({
1430
- space: IDENTITY_SPACES.REVISION,
1431
- id
1432
- }));
1433
- }
1434
- return;
1435
- }
1436
- if (heldBy !== "retainedAfter") return;
1437
- for (const field of ["source", "target"]) {
1438
- const slots = fieldOf(entries, field);
1439
- if (!Array.isArray(slots)) continue;
1440
- for (const slot of slots) {
1441
- if (typeof slot !== "object" || slot === null || !("space" in slot) || !("id" in slot)) continue;
1442
- if ((slot.space === IDENTITY_SPACES.REVISION || slot.space === IDENTITY_SPACES.CONTROL) && typeof slot.id === "number") out.push(slotKey({
1443
- space: slot.space,
1444
- id: slot.id
1445
- }));
1446
- }
1447
- }
1536
+ const ownReservedKeys = (entries, { heldBy }) => {
1537
+ const keys = [];
1538
+ if (heldBy === "deferredRemove") {
1539
+ const blockers = fieldOf(entries, "blockers");
1540
+ if (Array.isArray(blockers)) {
1541
+ for (const id of blockers) if (typeof id === "number") keys.push(slotKey({
1542
+ space: IDENTITY_SPACES.REVISION,
1543
+ id
1544
+ }));
1448
1545
  }
1449
- });
1450
- return out;
1546
+ return {
1547
+ keys,
1548
+ shareable: true
1549
+ };
1550
+ }
1551
+ if (heldBy !== "retainedAfter") return {
1552
+ keys,
1553
+ shareable: true
1554
+ };
1555
+ for (const field of ["source", "target"]) {
1556
+ const slots = fieldOf(entries, field);
1557
+ if (!Array.isArray(slots)) continue;
1558
+ for (const slot of slots) {
1559
+ if (typeof slot !== "object" || slot === null || !("space" in slot) || !("id" in slot)) continue;
1560
+ if ((slot.space === IDENTITY_SPACES.REVISION || slot.space === IDENTITY_SPACES.CONTROL) && typeof slot.id === "number") keys.push(slotKey({
1561
+ space: slot.space,
1562
+ id: slot.id
1563
+ }));
1564
+ }
1565
+ }
1566
+ return {
1567
+ keys,
1568
+ shareable: true
1569
+ };
1570
+ };
1571
+ /**
1572
+ * Pending cut references reserve IDs without becoming physical model
1573
+ * identities. Every record is read anew, as {@link identityKeysIn} does.
1574
+ */
1575
+ const reservedIdentityKeysIn = subtreeCensus(ownReservedKeys, "full");
1576
+ /** {@link reservedIdentityKeysIn} reusing earlier counts; only for packages. */
1577
+ const sharedReservedIdentityKeysIn = subtreeCensus(ownReservedKeys);
1578
+ /**
1579
+ * A census of a package, once per package object. Operations never change a
1580
+ * package they are given: each returns a new one, sharing what it left as it
1581
+ * was, so a package's ids are read once however often a plan asks.
1582
+ */
1583
+ const censusOnce = (census) => {
1584
+ const known = /* @__PURE__ */ new WeakMap();
1585
+ return (pkg) => {
1586
+ const cached = known.get(pkg);
1587
+ if (cached !== void 0) return cached;
1588
+ const keys = Object.freeze(census(pkg));
1589
+ known.set(pkg, keys);
1590
+ return keys;
1591
+ };
1451
1592
  };
1452
1593
  /** Every revision and content-control id of a package, each story walked once. */
1453
- const packageIdentityKeys = (pkg) => identityKeysIn(storiesOf(pkg));
1594
+ const packageIdentityKeys = censusOnce((pkg) => sharedIdentityKeysIn(storiesOf(pkg)));
1595
+ /** The ids a package's pending cut references reserve. */
1596
+ const packageReservedIdentityKeys = censusOnce((pkg) => sharedReservedIdentityKeysIn(pkg));
1454
1597
  // src/ops/slots.ts
1455
1598
  const revision$1 = (id) => ({
1456
1599
  space: IDENTITY_SPACES.REVISION,
@@ -2147,6 +2290,8 @@ const hasValidCopyOriginAncestorsInBlocks = (blocks) => blocks.every((block) =>
2147
2290
  case "table": return block.rows.every((row) => row.cells.every((cell) => hasValidCopyOriginAncestorsInBlocks(cell.content)));
2148
2291
  case "blockSdt":
2149
2292
  case "blockCustomXml": return hasValidCopyOriginAncestorsInBlocks(block.content);
2293
+ case "commentRangeStart":
2294
+ case "commentRangeEnd": return true;
2150
2295
  case "bookmarkStart":
2151
2296
  case "bookmarkEnd":
2152
2297
  case "moveFromRangeStart":
@@ -2188,6 +2333,8 @@ const copyOriginBoundaryKeysInBlocks = (blocks) => {
2188
2333
  if (key !== void 0) keys.add(key);
2189
2334
  break;
2190
2335
  }
2336
+ case "commentRangeStart":
2337
+ case "commentRangeEnd":
2191
2338
  case "preservedBlock": break;
2192
2339
  default: return block;
2193
2340
  }
@@ -2357,14 +2504,43 @@ const noteContentWithAutomaticMark = ({ note, customMark }) => {
2357
2504
  return updateBlockList(note.content, first.list, (blocks) => blocks.map((block, index) => index === first.index ? Object.assign({}, first.paragraph, { content: [marker, ...first.paragraph.content] }) : block));
2358
2505
  };
2359
2506
  const noteUsesCustomMark = (document, note) => documentStories(document).some((story) => storyParagraphs(storyBody(document, story)).some(({ paragraph }) => leafSpans(paragraph.content).some(({ node }) => (note.type === "footnote" && node.type === "footnoteRef" || note.type === "endnote" && node.type === "endnoteRef") && node.id === note.id && node.customMarkFollows === true)));
2360
- const referencedNoteKeys = (document) => {
2361
- const references = /* @__PURE__ */ new Set();
2362
- for (const story of documentStories(document)) for (const { paragraph } of storyParagraphs(storyBody(document, story))) for (const { node } of leafSpans(paragraph.content)) {
2363
- if (node.type === "footnoteRef") references.add(`footnote:${String(node.id)}`);
2364
- if (node.type === "endnoteRef") references.add(`endnote:${String(node.id)}`);
2507
+ /** The notes one paragraph references. */
2508
+ const paragraphNoteKeys = (paragraph) => {
2509
+ const keys = [];
2510
+ for (const { node } of leafSpans(paragraph.content)) {
2511
+ if (node.type === "footnoteRef") keys.push(`footnote:${String(node.id)}`);
2512
+ if (node.type === "endnoteRef") keys.push(`endnote:${String(node.id)}`);
2365
2513
  }
2514
+ return keys;
2515
+ };
2516
+ /**
2517
+ * The notes a document references, read once per document and per paragraph
2518
+ * object. Operations never change a record they are given, so a paragraph an
2519
+ * edit left as it was reads as it did, and only the paragraphs an edit
2520
+ * replaced are read again.
2521
+ */
2522
+ const PARAGRAPH_NOTE_KEYS = /* @__PURE__ */ new WeakMap();
2523
+ const DOCUMENT_NOTE_KEYS = /* @__PURE__ */ new WeakMap();
2524
+ const sharedParagraphNoteKeys = (paragraph) => {
2525
+ const known = PARAGRAPH_NOTE_KEYS.get(paragraph);
2526
+ if (known !== void 0) return known;
2527
+ const keys = Object.freeze(paragraphNoteKeys(paragraph));
2528
+ PARAGRAPH_NOTE_KEYS.set(paragraph, keys);
2529
+ return keys;
2530
+ };
2531
+ const noteKeysOf = (ofParagraph) => (document) => {
2532
+ const references = /* @__PURE__ */ new Set();
2533
+ for (const story of documentStories(document)) for (const { paragraph } of storyParagraphs(storyBody(document, story))) for (const key of ofParagraph(paragraph)) references.add(key);
2366
2534
  return references;
2367
2535
  };
2536
+ const readSharedNoteKeys = noteKeysOf(sharedParagraphNoteKeys);
2537
+ const referencedNoteKeys = (document) => {
2538
+ const known = DOCUMENT_NOTE_KEYS.get(document);
2539
+ if (known !== void 0) return known;
2540
+ const keys = readSharedNoteKeys(document);
2541
+ DOCUMENT_NOTE_KEYS.set(document, keys);
2542
+ return keys;
2543
+ };
2368
2544
  /** Note stories whose final live reference an edit removes. */
2369
2545
  const removedNoteStories = (before, after) => {
2370
2546
  const beforeReferences = referencedNoteKeys(before);
@@ -2418,6 +2594,8 @@ const blocksHaveMultiplePropertyChanges = (blocks) => {
2418
2594
  case "preservedBlock":
2419
2595
  case "bookmarkStart":
2420
2596
  case "bookmarkEnd":
2597
+ case "commentRangeStart":
2598
+ case "commentRangeEnd":
2421
2599
  case "moveFromRangeStart":
2422
2600
  case "moveFromRangeEnd":
2423
2601
  case "moveToRangeStart":
@@ -2551,6 +2729,8 @@ const normalizeBlocks = (blocks) => {
2551
2729
  case "preservedBlock":
2552
2730
  case "bookmarkStart":
2553
2731
  case "bookmarkEnd":
2732
+ case "commentRangeStart":
2733
+ case "commentRangeEnd":
2554
2734
  case "moveFromRangeStart":
2555
2735
  case "moveFromRangeEnd":
2556
2736
  case "moveToRangeStart":
@@ -2634,21 +2814,144 @@ const storyBodiesIncludingTextBoxes = (body) => {
2634
2814
  }
2635
2815
  return bodies;
2636
2816
  };
2637
- const anchorsIn = (document) => {
2817
+ /**
2818
+ * A story's comment anchors in document order. A range marker between blocks
2819
+ * is one of them, placed at the edge of the text beside it: a start at the
2820
+ * front of the next paragraph, an end at the back of the one before.
2821
+ */
2822
+ const storyAnchors = (story, body) => {
2638
2823
  const anchors = [];
2639
- for (const story of documentStories(document)) for (const body of storyBodiesIncludingTextBoxes(storyBody(document, story))) for (const { paragraph } of storyParagraphs(body)) for (const span of leafSpans(paragraph.content)) if (isCommentAnchor(span.node)) anchors.push({
2824
+ let waiting = [];
2825
+ let previous;
2826
+ const boundary = (node, blockId, gap) => ({
2827
+ node,
2828
+ ancestors: [],
2829
+ before: gap,
2830
+ after: gap,
2640
2831
  story,
2641
- blockId: paragraph.paraId ?? "",
2642
- ...span
2832
+ blockId,
2833
+ betweenBlocks: true
2643
2834
  });
2835
+ const walk = (blocks) => {
2836
+ for (const block of blocks) switch (block.type) {
2837
+ case "paragraph": {
2838
+ const blockId = block.paraId ?? "";
2839
+ const spans = leafSpans(block.content);
2840
+ const start = spans.at(0)?.before ?? {
2841
+ offset: 0,
2842
+ zeroWidthBefore: 0
2843
+ };
2844
+ for (const node of waiting) anchors.push(boundary(node, blockId, start));
2845
+ waiting = [];
2846
+ for (const span of spans) if (isCommentAnchor(span.node)) anchors.push({
2847
+ story,
2848
+ blockId,
2849
+ ...span
2850
+ });
2851
+ previous = {
2852
+ blockId,
2853
+ end: spans.at(-1)?.after ?? {
2854
+ offset: 0,
2855
+ zeroWidthBefore: 0
2856
+ }
2857
+ };
2858
+ break;
2859
+ }
2860
+ case "table":
2861
+ for (const row of block.rows) for (const cell of row.cells) walk(cell.content);
2862
+ break;
2863
+ case "blockSdt":
2864
+ case "blockCustomXml":
2865
+ walk(block.content);
2866
+ break;
2867
+ case "commentRangeStart":
2868
+ waiting.push(block);
2869
+ break;
2870
+ case "commentRangeEnd":
2871
+ if (previous === void 0) waiting.push(block);
2872
+ else anchors.push(boundary(block, previous.blockId, previous.end));
2873
+ break;
2874
+ case "preservedBlock":
2875
+ case "bookmarkStart":
2876
+ case "bookmarkEnd":
2877
+ case "moveFromRangeStart":
2878
+ case "moveFromRangeEnd":
2879
+ case "moveToRangeStart":
2880
+ case "moveToRangeEnd": break;
2881
+ default: return block;
2882
+ }
2883
+ };
2884
+ walk(body.content);
2885
+ for (const node of waiting) anchors.push(boundary(node, previous?.blockId ?? "", previous?.end ?? {
2886
+ offset: 0,
2887
+ zeroWidthBefore: 0
2888
+ }));
2889
+ return anchors;
2890
+ };
2891
+ const anchorsIn = (document) => {
2892
+ const anchors = [];
2893
+ for (const story of documentStories(document)) for (const body of storyBodiesIncludingTextBoxes(storyBody(document, story))) anchors.push(...storyAnchors(story, body));
2644
2894
  return anchors;
2645
2895
  };
2646
- /** Range coverage in source order; comment anchors themselves are only carriers. */
2896
+ /** A comment, the comments it replies to and the replies under it. */
2897
+ const threadIds = (document, id) => {
2898
+ const comments = document.package.document.comments ?? [];
2899
+ const parentOf = new Map(comments.map((comment) => [comment.id, comment.parentId]));
2900
+ let root = id;
2901
+ const seen = /* @__PURE__ */ new Set();
2902
+ while (!seen.has(root)) {
2903
+ seen.add(root);
2904
+ const parent = parentOf.get(root);
2905
+ if (parent === void 0 || !parentOf.has(parent)) break;
2906
+ root = parent;
2907
+ }
2908
+ const thread = [root];
2909
+ for (let index = 0; index < thread.length; index += 1) for (const comment of comments) if (comment.parentId === thread[index] && !thread.includes(comment.id)) thread.push(comment.id);
2910
+ return thread;
2911
+ };
2912
+ /**
2913
+ * Comments with a range marker between blocks. Removing or replying to one
2914
+ * would have to edit that block, which the comment operations do not do yet.
2915
+ */
2916
+ const blockAnchoredCommentIds = (document) => new Set(anchorsIn(document).filter(({ betweenBlocks }) => betweenBlocks === true).map(({ node }) => anchorId(node) ?? -1));
2917
+ /** Every leaf of a story with its comment range markers between blocks, in order. */
2918
+ const storyCoverageNodes = (body) => {
2919
+ const out = [];
2920
+ const walk = (blocks) => {
2921
+ for (const block of blocks) switch (block.type) {
2922
+ case "paragraph":
2923
+ out.push(...leafSpans(block.content));
2924
+ break;
2925
+ case "table":
2926
+ for (const row of block.rows) for (const cell of row.cells) walk(cell.content);
2927
+ break;
2928
+ case "blockSdt":
2929
+ case "blockCustomXml":
2930
+ walk(block.content);
2931
+ break;
2932
+ case "commentRangeStart":
2933
+ case "commentRangeEnd":
2934
+ out.push({ node: block });
2935
+ break;
2936
+ case "preservedBlock":
2937
+ case "bookmarkStart":
2938
+ case "bookmarkEnd":
2939
+ case "moveFromRangeStart":
2940
+ case "moveFromRangeEnd":
2941
+ case "moveToRangeStart":
2942
+ case "moveToRangeEnd": break;
2943
+ default: return block;
2944
+ }
2945
+ };
2946
+ walk(body.content);
2947
+ return out;
2948
+ };
2949
+ /** Range coverage in source order; comment anchors and range boundaries are only carriers. */
2647
2950
  const coveredCommentIds = (document) => {
2648
2951
  const covered = /* @__PURE__ */ new Set();
2649
2952
  for (const story of documentStories(document)) for (const body of storyBodiesIncludingTextBoxes(storyBody(document, story))) {
2650
2953
  const open = /* @__PURE__ */ new Set();
2651
- for (const { paragraph } of storyParagraphs(body)) for (const { node } of leafSpans(paragraph.content)) {
2954
+ for (const { node } of storyCoverageNodes(body)) {
2652
2955
  if (node.type === "commentRangeStart") {
2653
2956
  open.add(node.id);
2654
2957
  continue;
@@ -2657,7 +2960,7 @@ const coveredCommentIds = (document) => {
2657
2960
  open.delete(node.id);
2658
2961
  continue;
2659
2962
  }
2660
- if (isCommentAnchor(node)) continue;
2963
+ if (isCommentAnchor(node) || isParagraphContent(node) && isRangeBoundary(node)) continue;
2661
2964
  for (const id of open) covered.add(id);
2662
2965
  }
2663
2966
  }
@@ -3273,6 +3576,8 @@ const applyCommentOp = (document, op, applyOps) => {
3273
3576
  id: op.id
3274
3577
  }))) return fail(op, issue);
3275
3578
  const orphans = orphanRootCommentIds(document);
3579
+ const blockAnchored = blockAnchoredCommentIds(document);
3580
+ if (blockAnchored.size > 0 && (op.type === DOCUMENT_OP_TYPES.DELETE_COMMENT && threadIds(document, op.id).some((id) => blockAnchored.has(id)) || op.type === DOCUMENT_OP_TYPES.CREATE_COMMENT && op.anchor?.kind === "reply" && threadIds(document, op.anchor.parentId).some((id) => blockAnchored.has(id)))) return fail(op, "A comment whose range opens or closes between blocks cannot be removed or replied to yet.");
3276
3581
  if (op.type === DOCUMENT_OP_TYPES.CREATE_COMMENT) {
3277
3582
  if (op.anchor?.kind === "reply" && orphans.has(op.anchor.parentId)) return fail(op, "A comment without a source anchor is preserved read-only.");
3278
3583
  if (!op.comment || typeof op.comment.author !== "string" || !Array.isArray(op.comment.content) || !op.anchor || typeof op.anchor !== "object") return fail(op, "The comment creation payload is invalid.");
@@ -3349,7 +3654,7 @@ const applyCommentOp = (document, op, applyOps) => {
3349
3654
  };
3350
3655
  // src/ops/storyLifecycle.ts
3351
3656
  /** Explicit story lifecycle and section property edits, with exact JSON-safe inverses. */
3352
- const refuse$5 = (op, message) => Result.err(new DocumentOpRefusal({
3657
+ const refuse$6 = (op, message) => Result.err(new DocumentOpRefusal({
3353
3658
  opType: op.type,
3354
3659
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
3355
3660
  message
@@ -3688,7 +3993,7 @@ const undefinedFieldsIssue = (parts) => {
3688
3993
  const applyStoryLifecycle = (document, op) => {
3689
3994
  if (op.type === DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS) {
3690
3995
  const metadataIssue = undefinedFieldsIssue(op.parts);
3691
- if (metadataIssue) return refuse$5(op, metadataIssue);
3996
+ if (metadataIssue) return refuse$6(op, metadataIssue);
3692
3997
  if (!structurallyEqual(captureStoryParts(document, op.expected), op.expected)) return Result.err(new DocumentOpRefusal({
3693
3998
  opType: op.type,
3694
3999
  reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
@@ -3697,7 +4002,7 @@ const applyStoryLifecycle = (document, op) => {
3697
4002
  return storyLifecycleEdit(document, restoreParts(document, cloneModel(op.parts)), op);
3698
4003
  }
3699
4004
  const properties = sectionPropertiesAt(document, op.sectionIndex);
3700
- if (!properties) return refuse$5(op, "The section does not exist.");
4005
+ if (!properties) return refuse$6(op, "The section does not exist.");
3701
4006
  if (op.type === DOCUMENT_OP_TYPES.SET_SECTION_PROPS) {
3702
4007
  const nextProps = applyFormattingPatch(properties, op.patch) ?? {};
3703
4008
  let next = withSectionProperties(document, op.sectionIndex, nextProps);
@@ -3722,8 +4027,8 @@ const applyStoryLifecycle = (document, op) => {
3722
4027
  let nextRefs = [...refs ?? []];
3723
4028
  const nextProps = { ...properties };
3724
4029
  if (op.type === DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER) {
3725
- if (!op.story.rId || document.package.relationships?.has(op.story.rId) || document.package.headers?.has(op.story.rId) || document.package.footers?.has(op.story.rId) || refs?.some(({ type }) => type === op.referenceType)) return refuse$5(op, "The header/footer identity or section variant is already used.");
3726
- if (op.content.length === 0 || storyParagraphs({ content: op.content }).length === 0) return refuse$5(op, "A header/footer needs an addressable paragraph.");
4030
+ if (!op.story.rId || document.package.relationships?.has(op.story.rId) || document.package.headers?.has(op.story.rId) || document.package.footers?.has(op.story.rId) || refs?.some(({ type }) => type === op.referenceType)) return refuse$6(op, "The header/footer identity or section variant is already used.");
4031
+ if (op.content.length === 0 || storyParagraphs({ content: op.content }).length === 0) return refuse$6(op, "A header/footer needs an addressable paragraph.");
3727
4032
  const part = {
3728
4033
  type: kind,
3729
4034
  hdrFtrType: op.referenceType,
@@ -3737,7 +4042,7 @@ const applyStoryLifecycle = (document, op) => {
3737
4042
  if (op.referenceType === "first") nextProps.titlePg = true;
3738
4043
  if (op.referenceType === "even") nextProps.evenAndOddHeaders = true;
3739
4044
  } else {
3740
- if (!parts?.has(op.story.rId) || !refs?.some(({ type, rId }) => type === op.referenceType && rId === op.story.rId)) return refuse$5(op, "The section does not own this header/footer variant.");
4045
+ if (!parts?.has(op.story.rId) || !refs?.some(({ type, rId }) => type === op.referenceType && rId === op.story.rId)) return refuse$6(op, "The section does not own this header/footer variant.");
3741
4046
  nextRefs = nextRefs.filter(({ type }) => type !== op.referenceType);
3742
4047
  if (![...sectionEnds(document.package.document).map(({ properties: sectionProps }) => sectionProps), document.package.document.finalSectionProperties ?? {}].some((sectionProps, index) => index !== op.sectionIndex && (kind === "header" ? sectionProps.headerReferences : sectionProps.footerReferences)?.some(({ rId }) => rId === op.story.rId)) && !nextRefs.some(({ rId }) => rId === op.story.rId)) nextParts.delete(op.story.rId);
3743
4048
  }
@@ -3816,6 +4121,7 @@ const stampInfo = (stamp) => {
3816
4121
  date: stamp.date
3817
4122
  };
3818
4123
  if (stamp.initials !== void 0) info.initials = stamp.initials;
4124
+ if (stamp.suggestionId !== void 0) info.suggestionId = stamp.suggestionId;
3819
4125
  return info;
3820
4126
  };
3821
4127
  /** Whether a record's metadata is the stamp's, whatever its id. */
@@ -3912,6 +4218,7 @@ const foldedParagraphPropertyChange = ({ paragraph, formatting, stamp }) => {
3912
4218
  id: existing.info.id
3913
4219
  };
3914
4220
  if (stamp.initials === void 0) delete info.initials;
4221
+ if (stamp.suggestionId === void 0) delete info.suggestionId;
3915
4222
  delete info.utcDate;
3916
4223
  const change = {
3917
4224
  ...existing,
@@ -3992,10 +4299,10 @@ const mergeWithStampedNeighbour = (out, index, state) => {
3992
4299
  }
3993
4300
  }
3994
4301
  };
3995
- const trackedContent = (nodes, state) => {
4302
+ const trackedContent$1 = (nodes, state) => {
3996
4303
  const out = [];
3997
4304
  for (const node of nodes) {
3998
- if (!isParagraphContent(node) || !isTrackedChild(node)) {
4305
+ if (!isParagraphContent(node) || !isTrackedChild(node) || node.type === "commentReference") {
3999
4306
  state.refusal = DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE;
4000
4307
  return;
4001
4308
  }
@@ -4010,7 +4317,7 @@ const groupCovered = (entries, state) => {
4010
4317
  let stretch = [];
4011
4318
  const flush = () => {
4012
4319
  if (stretch.length === 0) return true;
4013
- let content = trackedContent(stretch.map(({ node }) => node), state);
4320
+ let content = trackedContent$1(stretch.map(({ node }) => node), state);
4014
4321
  if (content === void 0) return false;
4015
4322
  if (state.kind === WRAP_KINDS.INSERTION) {
4016
4323
  const adjusted = addCopyOriginAncestorsInNodes(content, state.copiedBoundaries);
@@ -4119,7 +4426,7 @@ const wrapList = (nodes, cursor, state) => {
4119
4426
  case "refuse":
4120
4427
  state.refusal = DOCUMENT_OP_REFUSAL_REASONS.INSIDE_TRACKED_DELETION;
4121
4428
  return;
4122
- case "keep":
4429
+ case "keep": {
4123
4430
  const retained = retainSameStampCopyOwner(node);
4124
4431
  if (retained === void 0) return void 0;
4125
4432
  entries.push({
@@ -4127,6 +4434,7 @@ const wrapList = (nodes, cursor, state) => {
4127
4434
  covered: false
4128
4435
  });
4129
4436
  break;
4437
+ }
4130
4438
  case "descend": {
4131
4439
  const end = { ...cursor };
4132
4440
  cursor.position = start.position;
@@ -4850,6 +5158,8 @@ const insertsInvertedRange = ({ body, paragraph, candidateContent, incomingConte
4850
5158
  case "blockCustomXml":
4851
5159
  visitBlocks(block.content);
4852
5160
  break;
5161
+ case "commentRangeStart":
5162
+ case "commentRangeEnd":
4853
5163
  case "preservedBlock": break;
4854
5164
  default: return block;
4855
5165
  }
@@ -5396,6 +5706,7 @@ const deleteBlocks = ({ document, op, applyOps }) => {
5396
5706
  };
5397
5707
  // src/ops/blockInsertion.ts
5398
5708
  /** Paragraph insertion, isolated from the inline and table operation implementations. */
5709
+ const sameFormatting = (left, right) => structurallyEqual(finalizeParagraphFormatting(left) ?? {}, finalizeParagraphFormatting(right) ?? {});
5399
5710
  const insertBlocks = ({ document, op, applyOps }) => {
5400
5711
  const refuse = (reason, message) => Result.err(new DocumentOpRefusal({
5401
5712
  reason,
@@ -5411,12 +5722,13 @@ const insertBlocks = ({ document, op, applyOps }) => {
5411
5722
  const following = blockListAt(body.content, location.list)[location.index + 1];
5412
5723
  const before = op.at.type === "before" || following?.type === "paragraph";
5413
5724
  const anchor = op.at.type === "after" && following?.type === "paragraph" ? following : location.paragraph;
5414
- if (op.revision !== void 0 && !before) return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Tracked insertion requires a following paragraph in the same block list.");
5415
- const replacement = (blocks) => ({
5725
+ const takesOverMark = op.revision !== void 0 && !before && following === void 0;
5726
+ if (takesOverMark && (location.paragraph.pPrMark !== void 0 || location.paragraph.reviewCarrier !== void 0 || (location.paragraph.propertyChanges?.length ?? 0) > 0)) return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "A tracked insertion after a paragraph no paragraph follows needs the anchor's mark free of review records.");
5727
+ const replacement = (blocks, replacedAnchor = anchor) => ({
5416
5728
  type: DOCUMENT_OP_TYPES.REPLACE_BLOCKS,
5417
5729
  story: op.story,
5418
5730
  expected: [anchor],
5419
- blocks: before ? [...blocks, anchor] : [anchor, ...blocks]
5731
+ blocks: before ? [...blocks, replacedAnchor] : [replacedAnchor, ...blocks]
5420
5732
  });
5421
5733
  const canonicalBlocks = op.blocks.map((paragraph) => {
5422
5734
  if (finalizeParagraphFormatting(paragraph.formatting) !== void 0) return paragraph;
@@ -5433,7 +5745,7 @@ const insertBlocks = ({ document, op, applyOps }) => {
5433
5745
  const insertedIds = new Set(canonicalBlocks.map(({ paraId }) => idKey(paraId ?? "")));
5434
5746
  if (storyParagraphs(storyBody(direct.value.document, op.story)).some((at) => insertedIds.has(idKey(at.paragraph.paraId ?? "")) && at.paragraph.pPrMark !== void 0 && endsItsContainer(storyBody(direct.value.document, op.story), at))) return refuse(DOCUMENT_OP_REFUSAL_REASONS.CONTAINER_FINAL_MARK, "Insertion would leave a tracked mark on a container-final paragraph.");
5435
5747
  const touched = {
5436
- modified: [],
5748
+ modified: takesOverMark && location.paragraph.paraId !== void 0 ? [location.paragraph.paraId] : [],
5437
5749
  inserted: op.blocks.flatMap(({ paraId }) => paraId === void 0 ? [] : [paraId]),
5438
5750
  removed: []
5439
5751
  };
@@ -5442,8 +5754,9 @@ const insertBlocks = ({ document, op, applyOps }) => {
5442
5754
  touched
5443
5755
  });
5444
5756
  if (identityKeysIn(op.blocks).length > 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Tracked insertion of identified review or content-control records is unsupported.");
5757
+ const revision = op.revision;
5445
5758
  const blocks = [];
5446
- for (const paragraph of canonicalBlocks) {
5759
+ for (const [index, paragraph] of canonicalBlocks.entries()) {
5447
5760
  const wrapped = wrapTracked({
5448
5761
  items: paragraph.content,
5449
5762
  from: {
@@ -5458,18 +5771,41 @@ const insertBlocks = ({ document, op, applyOps }) => {
5458
5771
  stamp: op.revision
5459
5772
  });
5460
5773
  if (wrapped.kind === "refused") return refuse(wrapped.reason, "The inserted content cannot be tracked.");
5774
+ const content = wrapped.kind === "wrapped" ? wrapped.content : paragraph.content;
5775
+ if (!takesOverMark || index < canonicalBlocks.length - 1) {
5776
+ blocks.push({
5777
+ ...paragraph,
5778
+ content,
5779
+ pPrMark: {
5780
+ kind: "ins",
5781
+ info: stampInfo(revision)
5782
+ }
5783
+ });
5784
+ continue;
5785
+ }
5786
+ const previous = location.paragraph.formatting;
5787
+ const current = finalizeParagraphFormatting(paragraph.formatting);
5461
5788
  blocks.push({
5462
5789
  ...paragraph,
5463
- content: wrapped.kind === "wrapped" ? wrapped.content : paragraph.content,
5464
- pPrMark: {
5465
- kind: "ins",
5466
- info: stampInfo(op.revision)
5467
- }
5790
+ content,
5791
+ ...sameFormatting(previous, current) ? {} : { propertyChanges: [{
5792
+ type: "paragraphPropertyChange",
5793
+ info: stampInfo(revision),
5794
+ ...previous === void 0 ? {} : { previousFormatting: previous }
5795
+ }] }
5468
5796
  });
5469
5797
  }
5798
+ const anchorBlocks = takesOverMark ? [{
5799
+ ...location.paragraph,
5800
+ pPrMark: {
5801
+ kind: "ins",
5802
+ info: stampInfo(revision),
5803
+ survivor: "first"
5804
+ }
5805
+ }] : [];
5470
5806
  const fresh = freshenIdentities({
5471
5807
  before: [],
5472
- after: blocks,
5808
+ after: [...anchorBlocks, ...blocks],
5473
5809
  newIds: op.newIds ?? {},
5474
5810
  usedElsewhere: () => new Set(packageIdentityKeys(document.package))
5475
5811
  });
@@ -5477,7 +5813,8 @@ const insertBlocks = ({ document, op, applyOps }) => {
5477
5813
  case "needsIds": return refuse(DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS, "Inserted paragraph review records need more revision ids.");
5478
5814
  case "invalidId": return refuse(DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, "An inserted review record has an invalid revision id.");
5479
5815
  case "fresh": {
5480
- const tracked = applyOps(document, [replacement(fresh.paragraphs)]);
5816
+ const [replacedAnchor, ...inserted] = takesOverMark ? fresh.paragraphs : [anchor, ...fresh.paragraphs];
5817
+ const tracked = applyOps(document, [replacement(inserted, replacedAnchor)]);
5481
5818
  return tracked.isErr() ? Result.err(new DocumentOpRefusal({
5482
5819
  reason: tracked.error.reason,
5483
5820
  message: tracked.error.message,
@@ -6772,7 +7109,6 @@ const tableGrid = (table, opType) => {
6772
7109
  if (!nonnegative(position) || !nonnegative(after)) return refuse();
6773
7110
  const cells = [];
6774
7111
  for (const [index, cell] of row.cells.entries()) {
6775
- if (cell.structuralChange?.type === "tableCellDeletion") continue;
6776
7112
  const span = cell.formatting?.gridSpan ?? 1;
6777
7113
  if (!nonnegative(span) || span === 0 || !nonnegative(position + span)) return refuse();
6778
7114
  const start = position;
@@ -6860,6 +7196,8 @@ const collectTables = (blocks, out) => {
6860
7196
  case "preservedBlock":
6861
7197
  case "bookmarkStart":
6862
7198
  case "bookmarkEnd":
7199
+ case "commentRangeStart":
7200
+ case "commentRangeEnd":
6863
7201
  case "moveFromRangeStart":
6864
7202
  case "moveFromRangeEnd":
6865
7203
  case "moveToRangeStart":
@@ -7758,7 +8096,8 @@ const carryResolutionState = (resolution, from, to) => {
7758
8096
  const occurrenceOf = (node, occurrence) => ({
7759
8097
  node,
7760
8098
  owner: occurrence?.owner,
7761
- ...occurrence?.lifted === true && { lifted: true }
8099
+ ...occurrence?.lifted === true && { lifted: true },
8100
+ ...occurrence?.payload === true && { payload: true }
7762
8101
  });
7763
8102
  const sourceOwnerRoot = (owner) => {
7764
8103
  let root = owner;
@@ -7822,11 +8161,12 @@ const resolveList = (nodes, resolution) => {
7822
8161
  const sourceEdges = /* @__PURE__ */ new Map();
7823
8162
  const pending = [...nodes];
7824
8163
  const sourceOwners = nodes.map(() => ({ state: { type: "source" } }));
7825
- const appendSource = (node, index, lifted = false) => {
8164
+ const appendSource = (node, index, lifted = false, payload = false) => {
7826
8165
  out.push({
7827
8166
  node,
7828
8167
  owner: sourceOwners.at(index) ?? panic("A source occurrence has an owner."),
7829
- ...lifted && { lifted: true }
8168
+ ...lifted && { lifted: true },
8169
+ ...payload && { payload: true }
7830
8170
  });
7831
8171
  };
7832
8172
  const appendUnowned = (items) => {
@@ -7838,6 +8178,8 @@ const resolveList = (nodes, resolution) => {
7838
8178
  const recordExactSeam = (index, depth) => {
7839
8179
  if (depth > 0) exactSeams.set(index, Math.max(exactSeams.get(index) ?? 0, depth));
7840
8180
  };
8181
+ /** Seams a removed revision recorded between the source pieces around it. */
8182
+ const removalSeams = /* @__PURE__ */ new Set();
7841
8183
  const recordSourceSeam = (index, depth) => {
7842
8184
  recordExactSeam(index, depth);
7843
8185
  if (depth > 0) sourceEdges.set(index, Math.max(sourceEdges.get(index) ?? 0, depth));
@@ -7883,10 +8225,15 @@ const resolveList = (nodes, resolution) => {
7883
8225
  resolution
7884
8226
  });
7885
8227
  const prepared = prepareDeferredRemovals(restored, resolution);
7886
- out.splice(0, out.length, ...prepared.slice(0, prefixLength).map((next, prefixIndex) => ({
7887
- node: next,
7888
- owner: (out.at(prefixIndex) ?? panic("Restoring source identities preserves every output occurrence.")).owner
7889
- })));
8228
+ out.splice(0, out.length, ...prepared.slice(0, prefixLength).map((next, prefixIndex) => {
8229
+ const previous = out.at(prefixIndex) ?? panic("Restoring source identities preserves every output occurrence.");
8230
+ const restoredOccurrence = {
8231
+ node: next,
8232
+ owner: previous.owner
8233
+ };
8234
+ if (previous.payload === true) restoredOccurrence.payload = true;
8235
+ return restoredOccurrence;
8236
+ }));
7890
8237
  pending.splice(index + 1, pending.length - index - 1, ...prepared.slice(prefixLength));
7891
8238
  }
7892
8239
  const removalContent = resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node) ? rejectCopyOriginAncestorsInNodes(node.content, 1) : node.content;
@@ -7905,10 +8252,15 @@ const resolveList = (nodes, resolution) => {
7905
8252
  after: sourceOwners.at(index + 1)
7906
8253
  });
7907
8254
  if (node.resolutionJoins === void 0) seams.push(out.length);
7908
- else recordSourceSeam(out.length, node.resolutionJoins.remove);
8255
+ else if ((node.resolutionJoins.plainSides?.length ?? 0) > 0) plainSeams.add(out.length);
8256
+ else {
8257
+ recordSourceSeam(out.length, node.resolutionJoins.remove);
8258
+ if (node.resolutionJoins.remove > 0) removalSeams.add(out.length);
8259
+ }
7909
8260
  continue;
7910
8261
  }
7911
8262
  if (node.resolutionJoins === void 0) seams.push(out.length);
8263
+ else if (node.resolutionJoins.plainSides?.includes("before") === true) plainSeams.add(out.length);
7912
8264
  else recordSourceSeam(out.length, node.resolutionJoins.before);
7913
8265
  const resolved = resolveList(node.content, resolution);
7914
8266
  const content = isAddedRevision(node) && resolution.decision === REVISION_DECISIONS.ACCEPT ? acceptCopyOriginAncestor(resolved.nodes) : resolved.nodes;
@@ -7923,9 +8275,11 @@ const resolveList = (nodes, resolution) => {
7923
8275
  plainSeams.add(out.length);
7924
8276
  plainSeams.add(out.length + content.length);
7925
8277
  }
7926
- for (const child of content) appendSource(child, index, true);
8278
+ const payload = isAddedRevision(node) && resolution.decision === REVISION_DECISIONS.ACCEPT;
8279
+ for (const child of content) appendSource(child, index, true, payload);
7927
8280
  if (resolved.edges?.last !== void 0) recordSourceSeam(out.length, resolved.edges.last);
7928
8281
  if (node.resolutionJoins === void 0) seams.push(out.length);
8282
+ else if (node.resolutionJoins.plainSides?.includes("after") === true) plainSeams.add(out.length);
7929
8283
  else recordSourceSeam(out.length, node.resolutionJoins.after);
7930
8284
  continue;
7931
8285
  }
@@ -8014,10 +8368,20 @@ const resolveList = (nodes, resolution) => {
8014
8368
  const lastDepth = sourceEdges.get(out.length);
8015
8369
  if (firstDepth !== void 0) edges.first = firstDepth;
8016
8370
  if (lastDepth !== void 0) edges.last = lastDepth;
8371
+ const pendingRemoval = (node) => node !== void 0 && (node.type === "deletion" || node.type === "moveFrom") && !resolution.ids.has(node.info.id) && node.resolutionJoins !== void 0;
8372
+ const acceptAsPlain = (index, facing) => {
8373
+ const occurrence = out[index];
8374
+ const node = occurrence?.node;
8375
+ if (occurrence === void 0 || node === void 0 || !isTrackedWrapper(node) || node.resolutionJoins === void 0) return;
8376
+ out[index] = occurrenceOf(Object.assign({}, node, { resolutionJoins: Object.assign({}, node.resolutionJoins, { plainSides: [.../* @__PURE__ */ new Set([...node.resolutionJoins.plainSides ?? [], facing])] }) }), occurrence);
8377
+ changed = true;
8378
+ };
8017
8379
  for (const seam of plainSeams) {
8018
8380
  const left = out.at(seam - 1)?.node;
8019
8381
  const right = out.at(seam)?.node;
8020
8382
  if (seam > 0 && left?.type === "run" && right?.type === "run" && runsMergeable(left, right)) seams.push(seam);
8383
+ else if (pendingRemoval(right)) acceptAsPlain(seam, "before");
8384
+ else if (seam > 0 && pendingRemoval(left)) acceptAsPlain(seam - 1, "after");
8021
8385
  }
8022
8386
  const merges = new Set(seams);
8023
8387
  for (const recorded of [.../* @__PURE__ */ new Set([
@@ -8071,8 +8435,38 @@ const resolveList = (nodes, resolution) => {
8071
8435
  if (left === void 0 || right === void 0) continue;
8072
8436
  let exactDepth = exactSeams.get(recorded);
8073
8437
  if (exactDepth !== void 0) exactDepth = Math.max(exactDepth, resolution.cutEdges.get(left)?.last ?? 0, resolution.cutEdges.get(right)?.first ?? 0);
8438
+ if (exactDepth !== void 0 && exactDepth > 0 && kept === void 0) {
8439
+ const blocking = (index) => {
8440
+ const node = out[index]?.node;
8441
+ return node !== void 0 && isAddedRevision(node) && isTrackedWrapper(node) && node.resolutionJoins !== void 0 && !resolution.ids.has(node.info.id);
8442
+ };
8443
+ let leftEnd = seam - 1;
8444
+ while (leftEnd >= 0 && blocking(leftEnd)) leftEnd -= 1;
8445
+ let rightStart = seam;
8446
+ while (rightStart < out.length && blocking(rightStart)) rightStart += 1;
8447
+ if ((leftEnd !== seam - 1 || rightStart !== seam) && leftEnd >= 0 && rightStart < out.length) {
8448
+ const blockerIndices = [...Array.from({ length: seam - 1 - leftEnd }, (_, offset) => leftEnd + 1 + offset), ...Array.from({ length: rightStart - seam }, (_, offset) => seam + offset)];
8449
+ const blockers = blockerIndices.flatMap((index) => {
8450
+ const node = out[index]?.node;
8451
+ return node !== void 0 && isTrackedWrapper(node) ? [node.info.id] : [];
8452
+ });
8453
+ for (const index of blockerIndices) {
8454
+ const occurrence = out[index];
8455
+ const node = occurrence?.node;
8456
+ if (occurrence === void 0 || node === void 0 || !isTrackedWrapper(node) || node.resolutionJoins === void 0) panic("A deferring seam blocker is a pending insertion.");
8457
+ const groups = [...node.resolutionJoins.deferredRemove ?? []];
8458
+ groups.push({
8459
+ depth: exactDepth,
8460
+ blockers
8461
+ });
8462
+ out[index] = occurrenceOf(Object.assign({}, node, { resolutionJoins: Object.assign({}, node.resolutionJoins, { deferredRemove: canonicalDeferredGroups(groups) }) }), occurrence);
8463
+ }
8464
+ continue;
8465
+ }
8466
+ }
8074
8467
  let met;
8075
- if (merges.has(recorded)) met = mergeAtSeam(left, right, resolution.emptied);
8468
+ const besidePayload = leftOccurrence?.payload === true || rightOccurrence?.payload === true;
8469
+ if (merges.has(recorded) || exactDepth !== void 0 && removalSeams.has(recorded) && besidePayload) met = besidePayload && alikeDepth(left, right) === 0 ? [left, right] : mergeAtSeam(left, right, resolution.emptied);
8076
8470
  else if (exactDepth === void 0) met = foldAtSeam(left, right, resolution.emptied);
8077
8471
  else {
8078
8472
  const folded = foldAtSeam(left, right, resolution.emptied);
@@ -8338,7 +8732,14 @@ const joinOps = (document, { op, story, paraId, added, depth }, ends, ranInto =
8338
8732
  ends.set(nextId, emptiedEndsOf(merged, emptied));
8339
8733
  const mergedContent = asParagraphContent(merged);
8340
8734
  const receivesSection = outcome.sectionDestination === "following";
8341
- const survivor = !receivesSection && structurallyEqual(mergedContent, next.content) ? next : {
8735
+ const { pPrMark: _rejectedMark, ...first } = paragraph;
8736
+ let survivor;
8737
+ if (paragraph.pPrMark?.survivor === "first") survivor = {
8738
+ ...first,
8739
+ content: mergedContent
8740
+ };
8741
+ else if (!receivesSection && structurallyEqual(mergedContent, next.content)) survivor = next;
8742
+ else survivor = {
8342
8743
  ...next,
8343
8744
  content: mergedContent,
8344
8745
  ...receivesSection ? { sectionProperties: paragraph.sectionProperties } : {}
@@ -8748,6 +9149,109 @@ const resolveRevision = (document, op, applyOps) => planRevisionResolution({
8748
9149
  op,
8749
9150
  applyOps
8750
9151
  }).map(({ edit }) => edit);
9152
+ // src/ops/revisionInfo.ts
9153
+ const refuse$5 = (reason, message) => Result.err(new DocumentOpRefusal({
9154
+ reason,
9155
+ message,
9156
+ opType: DOCUMENT_OP_TYPES.SET_REVISION_INFO
9157
+ }));
9158
+ const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9159
+ const revisionInfoOf = (value) => isRecord$2(value) && typeof value["id"] === "number" && typeof value["author"] === "string" ? value : void 0;
9160
+ /** Every paragraph id under a value. */
9161
+ const paragraphIdsIn$1 = (value, out) => {
9162
+ if (Array.isArray(value)) {
9163
+ for (const item of value) paragraphIdsIn$1(item, out);
9164
+ return;
9165
+ }
9166
+ if (!isRecord$2(value)) return;
9167
+ if (value["type"] === "paragraph" && typeof value["paraId"] === "string") out.add(value["paraId"]);
9168
+ for (const field of Object.values(value)) paragraphIdsIn$1(field, out);
9169
+ };
9170
+ /**
9171
+ * Write the info given for each revision id onto every record carrying that
9172
+ * id, in the story's blocks and its section view. Records keep their content
9173
+ * and their place; an unchanged subtree keeps its identity.
9174
+ */
9175
+ const setRevisionInfo = (document, op) => {
9176
+ const wanted = /* @__PURE__ */ new Map();
9177
+ for (const info of op.infos) {
9178
+ if (wanted.has(info.id)) return refuse$5(DOCUMENT_OP_REFUSAL_REASONS.INVALID_OPERATION, `Revision ${String(info.id)} is given two infos.`);
9179
+ wanted.set(info.id, info);
9180
+ }
9181
+ const previous = /* @__PURE__ */ new Map();
9182
+ let disagreeing;
9183
+ const modified = /* @__PURE__ */ new Set();
9184
+ const rebuilt = /* @__PURE__ */ new WeakMap();
9185
+ const rebuild = (value) => {
9186
+ if (typeof value !== "object" || value === null) return value;
9187
+ const known = rebuilt.get(value);
9188
+ if (known !== void 0) return known;
9189
+ let out = value;
9190
+ if (Array.isArray(value)) {
9191
+ const items = value.map(rebuild);
9192
+ if (items.some((item, index) => item !== value[index])) out = items;
9193
+ } else if (isRecord$2(value)) {
9194
+ let changed = false;
9195
+ let ownInfoChanged = false;
9196
+ const entries = [];
9197
+ for (const [key, field] of Object.entries(value)) {
9198
+ const info = key === "info" ? revisionInfoOf(field) : void 0;
9199
+ const replacement = info === void 0 ? void 0 : wanted.get(info.id);
9200
+ let next;
9201
+ if (info !== void 0 && replacement !== void 0) {
9202
+ const before = previous.get(info.id);
9203
+ if (before !== void 0 && !structurallyEqual(before, info)) disagreeing ??= info.id;
9204
+ previous.set(info.id, info);
9205
+ next = structurallyEqual(info, replacement) ? field : replacement;
9206
+ if (next !== field) ownInfoChanged = true;
9207
+ } else next = rebuild(field);
9208
+ if (next !== field) changed = true;
9209
+ entries.push([key, next]);
9210
+ }
9211
+ if (changed) {
9212
+ const copy = { ...value };
9213
+ for (const [key, field] of entries) copy[key] = field;
9214
+ transferParagraphPropertySnapshot({
9215
+ source: value,
9216
+ target: copy
9217
+ });
9218
+ out = copy;
9219
+ if (value["type"] === "paragraph" && typeof value["paraId"] === "string") modified.add(value["paraId"]);
9220
+ else if (ownInfoChanged) paragraphIdsIn$1(value, modified);
9221
+ }
9222
+ }
9223
+ rebuilt.set(value, out);
9224
+ return out;
9225
+ };
9226
+ const body = storyBody(document, op.story);
9227
+ const content = rebuild(body.content);
9228
+ const sections = body.sections === void 0 ? void 0 : rebuild(body.sections);
9229
+ const missing = [...wanted.keys()].find((id) => !previous.has(id));
9230
+ if (missing !== void 0) return refuse$5(DOCUMENT_OP_REFUSAL_REASONS.STALE, `No revision ${String(missing)} in the story.`);
9231
+ if (disagreeing !== void 0) return refuse$5(DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `The records of revision ${String(disagreeing)} carry different infos.`);
9232
+ if (content === body.content && sections === body.sections) return refuse$5(DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE, "The revisions already carry these infos.");
9233
+ return Result.ok({
9234
+ document: replaceStoryBody({
9235
+ document,
9236
+ story: op.story,
9237
+ body: {
9238
+ ...body,
9239
+ content,
9240
+ ...sections === void 0 ? {} : { sections }
9241
+ }
9242
+ }),
9243
+ inverse: [{
9244
+ type: DOCUMENT_OP_TYPES.SET_REVISION_INFO,
9245
+ story: op.story,
9246
+ infos: [...previous.values()]
9247
+ }],
9248
+ touched: {
9249
+ modified: [...modified],
9250
+ inserted: [],
9251
+ removed: []
9252
+ }
9253
+ });
9254
+ };
8751
9255
  // src/ops/tableEditBoundary.ts
8752
9256
  /** Validate untyped table edits before reading fields or revision stamps. */
8753
9257
  const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -8871,6 +9375,8 @@ const mapParagraphs = (blocks, replace) => blocks.map((block) => {
8871
9375
  case "preservedBlock":
8872
9376
  case "bookmarkStart":
8873
9377
  case "bookmarkEnd":
9378
+ case "commentRangeStart":
9379
+ case "commentRangeEnd":
8874
9380
  case "moveFromRangeStart":
8875
9381
  case "moveFromRangeEnd":
8876
9382
  case "moveToRangeStart":
@@ -8908,6 +9414,8 @@ const trackableBlocks = (blocks) => blocks.every((block) => {
8908
9414
  case "preservedBlock":
8909
9415
  case "bookmarkStart":
8910
9416
  case "bookmarkEnd":
9417
+ case "commentRangeStart":
9418
+ case "commentRangeEnd":
8911
9419
  case "moveFromRangeStart":
8912
9420
  case "moveFromRangeEnd":
8913
9421
  case "moveToRangeStart":
@@ -9132,6 +9640,8 @@ const stampedTableRevisionIds = ({ blocks, stamp, known }) => {
9132
9640
  case "preservedBlock":
9133
9641
  case "bookmarkStart":
9134
9642
  case "bookmarkEnd":
9643
+ case "commentRangeStart":
9644
+ case "commentRangeEnd":
9135
9645
  case "moveFromRangeStart":
9136
9646
  case "moveFromRangeEnd":
9137
9647
  case "moveToRangeStart":
@@ -9165,6 +9675,8 @@ const validStructure = (blocks) => blocks.every((block) => {
9165
9675
  case "preservedBlock":
9166
9676
  case "bookmarkStart":
9167
9677
  case "bookmarkEnd":
9678
+ case "commentRangeStart":
9679
+ case "commentRangeEnd":
9168
9680
  case "moveFromRangeStart":
9169
9681
  case "moveFromRangeEnd":
9170
9682
  case "moveToRangeStart":
@@ -9285,6 +9797,8 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
9285
9797
  case "preservedBlock":
9286
9798
  case "bookmarkStart":
9287
9799
  case "bookmarkEnd":
9800
+ case "commentRangeStart":
9801
+ case "commentRangeEnd":
9288
9802
  case "moveFromRangeStart":
9289
9803
  case "moveFromRangeEnd":
9290
9804
  case "moveToRangeStart":
@@ -9690,6 +10204,8 @@ const withOmission = (row, side, value) => {
9690
10204
  };
9691
10205
  const hasStructuralMarkup = (table) => table.preserved !== void 0 || table.bookmarks !== void 0 || table.carrierStack !== void 0 || table.rows.some((row) => row.preserved !== void 0 || row.carrierStack !== void 0 || row.contentControls !== void 0);
9692
10206
  const hasReview = (table) => table.formatting?.gridChange !== void 0 || table.propertyChanges !== void 0 || table.rows.some((row) => row.structuralChange !== void 0 || row.propertyChanges !== void 0 || row.cells.some((cell) => cell.structuralChange !== void 0 || cell.propertyChanges !== void 0));
10207
+ /** A review other than a pending cell deletion. */
10208
+ const hasReviewBesidesCellDeletions = (table) => table.formatting?.gridChange !== void 0 || table.propertyChanges !== void 0 || table.rows.some((row) => row.structuralChange !== void 0 || row.propertyChanges !== void 0 || row.cells.some((cell) => cell.structuralChange !== void 0 && cell.structuralChange.type !== "tableCellDeletion" || cell.propertyChanges !== void 0));
9693
10209
  /** Multiple physical review records always get distinct, explicitly supplied ids. */
9694
10210
  const stampsFor = (op, count) => {
9695
10211
  const revision = op.revision;
@@ -9722,7 +10238,7 @@ const columnEdit = ({ document, op, table, grid }) => {
9722
10238
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
9723
10239
  message: "Indexed table markup must be relocated before changing columns."
9724
10240
  });
9725
- if (hasReview(table)) return refuse$3({
10241
+ if (!insert && op.revision !== void 0 ? hasReviewBesidesCellDeletions(table) : hasReview(table)) return refuse$3({
9726
10242
  op,
9727
10243
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
9728
10244
  message: "Resolve table reviews before changing its columns."
@@ -9744,7 +10260,19 @@ const columnEdit = ({ document, op, table, grid }) => {
9744
10260
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
9745
10261
  message: "Tracked column edits require an explicit previous grid."
9746
10262
  });
9747
- const stamps = stampsFor(op, table.rows.length + 2);
10263
+ const trackedDeletion = !insert && op.revision !== void 0;
10264
+ const markedRows = /* @__PURE__ */ new Map();
10265
+ if (trackedDeletion) for (const [rowIndex, row] of table.rows.entries()) {
10266
+ const before = row.formatting?.gridBefore ?? 0;
10267
+ const after = grid.width - (row.formatting?.gridAfter ?? 0);
10268
+ if (op.column >= before && op.column < after) markedRows.set(rowIndex, markedRows.size);
10269
+ }
10270
+ if (trackedDeletion && markedRows.size === 0) return refuse$3({
10271
+ op,
10272
+ reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
10273
+ message: "A suggested column deletion needs a cell in the column to mark."
10274
+ });
10275
+ const stamps = stampsFor(op, trackedDeletion ? markedRows.size : table.rows.length + 2);
9748
10276
  if (stamps.isErr()) return Result.err(stamps.error);
9749
10277
  let freshIndex = 0;
9750
10278
  const rows = [];
@@ -9753,6 +10281,10 @@ const columnEdit = ({ document, op, table, grid }) => {
9753
10281
  if (entries === void 0) return mismatch(op, "The grid row is missing.");
9754
10282
  const before = row.formatting?.gridBefore ?? 0;
9755
10283
  const after = grid.width - (row.formatting?.gridAfter ?? 0);
10284
+ if (trackedDeletion && (op.column < before || op.column >= after)) {
10285
+ rows.push(row);
10286
+ continue;
10287
+ }
9756
10288
  if (op.column < before) {
9757
10289
  const next = withOmission(row, "gridBefore", before + (insert ? 1 : -1));
9758
10290
  const stamp = stamps.value[rowIndex];
@@ -9810,6 +10342,16 @@ const columnEdit = ({ document, op, table, grid }) => {
9810
10342
  reason: DOCUMENT_OP_REFUSAL_REASONS.DEPENDENT_RECORDS,
9811
10343
  message: "Resolve dependent anchors and review records before removing this cell."
9812
10344
  });
10345
+ if (trackedDeletion && entry.cell.structuralChange?.type === "tableCellDeletion") return refuse$3({
10346
+ op,
10347
+ reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
10348
+ message: "The column's cells are already suggested for deletion."
10349
+ });
10350
+ if (trackedDeletion && entry.end - entry.start > 1) return refuse$3({
10351
+ op,
10352
+ reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
10353
+ message: "A suggested column deletion cannot narrow a cell that spans other columns."
10354
+ });
9813
10355
  if (entry.end - entry.start > 1) {
9814
10356
  const next = withSpan(entry.cell, entry.end - entry.start - 1);
9815
10357
  const stamp = stamps.value[rowIndex];
@@ -9821,7 +10363,7 @@ const columnEdit = ({ document, op, table, grid }) => {
9821
10363
  cells.push(next);
9822
10364
  continue;
9823
10365
  }
9824
- const stamp = stamps.value[rowIndex];
10366
+ const stamp = stamps.value[trackedDeletion ? markedRows.get(rowIndex) ?? -1 : rowIndex];
9825
10367
  if (stamp !== void 0) cells.push({
9826
10368
  ...entry.cell,
9827
10369
  structuralChange: {
@@ -9855,6 +10397,10 @@ const columnEdit = ({ document, op, table, grid }) => {
9855
10397
  cells
9856
10398
  });
9857
10399
  }
10400
+ if (trackedDeletion) return Result.ok({
10401
+ ...table,
10402
+ rows
10403
+ });
9858
10404
  const columnWidths = table.columnWidths === void 0 ? void 0 : [...table.columnWidths];
9859
10405
  if (columnWidths !== void 0) {
9860
10406
  if (op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN) columnWidths.splice(op.column, 0, op.width);
@@ -10268,11 +10814,12 @@ const applyTableEdit = (document, op) => {
10268
10814
  "gridChange",
10269
10815
  "preserved"
10270
10816
  ].includes(key))) return mismatch(op, "Grid and source provenance require a grid operation.");
10271
- if (table.propertyChanges !== void 0) return refuse$3({
10817
+ if ((table.propertyChanges?.length ?? 0) > 1) return refuse$3({
10272
10818
  op,
10273
10819
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
10274
10820
  message: "Resolve the existing table property revision."
10275
10821
  });
10822
+ const pending = table.propertyChanges?.at(0);
10276
10823
  const next = { ...table };
10277
10824
  const formatting = applyFormattingPatch(table.formatting, op.patch);
10278
10825
  if (!patchChanges(table.formatting, op.patch)) return Result.ok({
@@ -10286,11 +10833,14 @@ const applyTableEdit = (document, op) => {
10286
10833
  });
10287
10834
  if (formatting === void 0) delete next.formatting;
10288
10835
  else next.formatting = authored(formatting);
10289
- if (op.revision !== void 0) next.propertyChanges = [{
10290
- type: "tablePropertyChange",
10291
- info: stampInfo(op.revision),
10292
- ...table.formatting === void 0 ? {} : { previousFormatting: table.formatting }
10293
- }];
10836
+ if (op.revision !== void 0) {
10837
+ const previousFormatting = pending === void 0 ? table.formatting : pending.previousFormatting;
10838
+ next.propertyChanges = [{
10839
+ type: "tablePropertyChange",
10840
+ info: stampInfo(op.revision),
10841
+ ...previousFormatting === void 0 ? {} : { previousFormatting }
10842
+ }];
10843
+ }
10294
10844
  changed = Result.ok(next);
10295
10845
  break;
10296
10846
  }
@@ -10303,11 +10853,12 @@ const applyTableEdit = (document, op) => {
10303
10853
  ].includes(key))) return mismatch(op, "Omitted grid slots require a topology operation.");
10304
10854
  const row = table.rows[location.rowIndex];
10305
10855
  if (!row) return mismatch(op, "The addressed row is absent.");
10306
- if (row.propertyChanges !== void 0) return refuse$3({
10856
+ if ((row.propertyChanges?.length ?? 0) > 1) return refuse$3({
10307
10857
  op,
10308
10858
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
10309
10859
  message: "Resolve the existing row property revision."
10310
10860
  });
10861
+ const pending = row.propertyChanges?.at(0);
10311
10862
  const next = { ...row };
10312
10863
  const formatting = applyFormattingPatch(row.formatting, op.patch);
10313
10864
  if (!patchChanges(row.formatting, op.patch)) return Result.ok({
@@ -10321,11 +10872,14 @@ const applyTableEdit = (document, op) => {
10321
10872
  });
10322
10873
  if (formatting === void 0) delete next.formatting;
10323
10874
  else next.formatting = authored(formatting);
10324
- if (op.revision !== void 0) next.propertyChanges = [{
10325
- type: "tableRowPropertyChange",
10326
- info: stampInfo(op.revision),
10327
- ...row.formatting === void 0 ? {} : { previousFormatting: row.formatting }
10328
- }];
10875
+ if (op.revision !== void 0) {
10876
+ const previousFormatting = pending === void 0 ? row.formatting : pending.previousFormatting;
10877
+ next.propertyChanges = [{
10878
+ type: "tableRowPropertyChange",
10879
+ info: stampInfo(op.revision),
10880
+ ...previousFormatting === void 0 ? {} : { previousFormatting }
10881
+ }];
10882
+ }
10329
10883
  const rows = [...table.rows];
10330
10884
  rows[location.rowIndex] = next;
10331
10885
  changed = Result.ok({
@@ -10344,11 +10898,12 @@ const applyTableEdit = (document, op) => {
10344
10898
  const row = table.rows[location.rowIndex];
10345
10899
  const cell = row?.cells[location.cellIndex];
10346
10900
  if (!row || !cell) return mismatch(op, "The addressed cell is absent.");
10347
- if (cell.propertyChanges !== void 0) return refuse$3({
10901
+ if ((cell.propertyChanges?.length ?? 0) > 1) return refuse$3({
10348
10902
  op,
10349
10903
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
10350
10904
  message: "Resolve the existing cell property revision."
10351
10905
  });
10906
+ const pending = cell.propertyChanges?.at(0);
10352
10907
  const next = { ...cell };
10353
10908
  const formatting = applyFormattingPatch(cell.formatting, op.patch);
10354
10909
  if (!patchChanges(cell.formatting, op.patch)) return Result.ok({
@@ -10362,11 +10917,14 @@ const applyTableEdit = (document, op) => {
10362
10917
  });
10363
10918
  if (formatting === void 0) delete next.formatting;
10364
10919
  else next.formatting = authored(formatting);
10365
- if (op.revision !== void 0) next.propertyChanges = [{
10366
- type: "tableCellPropertyChange",
10367
- info: stampInfo(op.revision),
10368
- ...cell.formatting === void 0 ? {} : { previousFormatting: cell.formatting }
10369
- }];
10920
+ if (op.revision !== void 0) {
10921
+ const previousFormatting = pending === void 0 ? cell.formatting : pending.previousFormatting;
10922
+ next.propertyChanges = [{
10923
+ type: "tableCellPropertyChange",
10924
+ info: stampInfo(op.revision),
10925
+ ...previousFormatting === void 0 ? {} : { previousFormatting }
10926
+ }];
10927
+ }
10370
10928
  const rows = [...table.rows];
10371
10929
  const cells = [...row.cells];
10372
10930
  cells[location.cellIndex] = next;
@@ -10814,7 +11372,7 @@ const withFreshIds = ({ document, op, before, after, newIds, inserted }) => {
10814
11372
  after,
10815
11373
  newIds: newIds ?? {},
10816
11374
  usedElsewhere: () => identitiesOutside(document, before),
10817
- reserved: new Set(reservedIdentityKeysIn(document.package)),
11375
+ reserved: new Set(packageReservedIdentityKeys(document.package)),
10818
11376
  ...inserted === void 0 ? {} : { inserted }
10819
11377
  });
10820
11378
  switch (freshened.kind) {
@@ -11963,6 +12521,7 @@ const dispatchCore = (document, op) => {
11963
12521
  case DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW: return setParagraphReview(document, op);
11964
12522
  case DOCUMENT_OP_TYPES.REPLACE_INLINE: return replaceInline(document, op);
11965
12523
  case DOCUMENT_OP_TYPES.RESOLVE_REVISION: return resolveRevision(document, op, applyDocumentOps);
12524
+ case DOCUMENT_OP_TYPES.SET_REVISION_INFO: return setRevisionInfo(document, op);
11966
12525
  case DOCUMENT_OP_TYPES.INSERT_TABLE:
11967
12526
  case DOCUMENT_OP_TYPES.DELETE_TABLE:
11968
12527
  case DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS: return applyTableOp(document, op);
@@ -12050,7 +12609,8 @@ const stampOf = (op) => {
12050
12609
  case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
12051
12610
  case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
12052
12611
  case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT:
12053
- case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES: return;
12612
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES:
12613
+ case DOCUMENT_OP_TYPES.SET_REVISION_INFO: return;
12054
12614
  default: return op;
12055
12615
  }
12056
12616
  };
@@ -12060,11 +12620,11 @@ const recordedRevisions = (before, edit, stamp) => {
12060
12620
  const paragraphs = documentStories(edit.document).flatMap((story) => storyParagraphs(storyBody(edit.document, story))).map(({ paragraph }) => paragraph).filter(({ paraId }) => paraId !== void 0 && touched.has(idKey(paraId)));
12061
12621
  const known = new Set(packageIdentityKeys(before.package));
12062
12622
  const revisions = paragraphs.flatMap((paragraph) => stampedRevisionIds([paragraph], stamp, known));
12063
- revisions.unshift(...documentStories(edit.document).map((story) => stampedTableRevisionIds({
12623
+ revisions.unshift(...documentStories(edit.document).flatMap((story) => stampedTableRevisionIds({
12064
12624
  blocks: storyBody(edit.document, story).content,
12065
12625
  stamp,
12066
12626
  known
12067
- })).flat());
12627
+ })));
12068
12628
  return revisions;
12069
12629
  };
12070
12630
  /** Content edits retain authored snapshots across immutable paragraph replacements. */
@@ -12180,6 +12740,82 @@ const applyDocumentOps = (document, ops) => {
12180
12740
  revisions
12181
12741
  });
12182
12742
  };
12743
+ // src/ops/suggestions.ts
12744
+ /**
12745
+ * The ids of the revisions in a value that belong to a pending suggestion:
12746
+ * tracked insertions and deletions, moves, property changes and paragraph
12747
+ * mark revisions, at any depth.
12748
+ */
12749
+ const suggestedRevisionIdsIn = (value, out) => {
12750
+ if (typeof value !== "object" || value === null) return;
12751
+ if (Array.isArray(value)) {
12752
+ for (const item of value) suggestedRevisionIdsIn(item, out);
12753
+ return;
12754
+ }
12755
+ const record = value;
12756
+ const info = record["info"];
12757
+ if (typeof info === "object" && info !== null && typeof info["suggestionId"] === "string" && typeof info["id"] === "number") out.add(info.id);
12758
+ for (const child of Object.values(record)) suggestedRevisionIdsIn(child, out);
12759
+ };
12760
+ /**
12761
+ * The document as a save writes it: every pending suggestion rejected. A
12762
+ * suggestion is a proposal the host holds, not a change in the file, so the
12763
+ * file reads as if it had never been made; ordinary tracked changes stay.
12764
+ */
12765
+ const withoutPendingSuggestions = (document) => {
12766
+ let current = document;
12767
+ for (const story of documentStories(document)) {
12768
+ const ids = /* @__PURE__ */ new Set();
12769
+ suggestedRevisionIdsIn(storyBody(current, story), ids);
12770
+ if (ids.size === 0) continue;
12771
+ const rejected = applyDocumentOp(current, {
12772
+ type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
12773
+ story,
12774
+ revisionIds: [...ids],
12775
+ decision: REVISION_DECISIONS.REJECT
12776
+ });
12777
+ if (rejected.isErr()) return Result.err(rejected.error);
12778
+ current = rejected.value.document;
12779
+ }
12780
+ return Result.ok(current);
12781
+ };
12782
+ /**
12783
+ * The revisions of one pending suggestion in a story, one info per revision
12784
+ * id, in document order.
12785
+ */
12786
+ const suggestionRevisionInfos = (document, story, suggestionId) => {
12787
+ const out = /* @__PURE__ */ new Map();
12788
+ const visit = (value) => {
12789
+ if (typeof value !== "object" || value === null) return;
12790
+ if (Array.isArray(value)) {
12791
+ for (const item of value) visit(item);
12792
+ return;
12793
+ }
12794
+ const record = value;
12795
+ const info = record["info"];
12796
+ if (typeof info === "object" && info !== null && info.suggestionId === suggestionId && typeof info.id === "number" && !out.has(info.id)) out.set(info.id, info);
12797
+ for (const child of Object.values(record)) visit(child);
12798
+ };
12799
+ visit(storyBody(document, story).content);
12800
+ return [...out.values()];
12801
+ };
12802
+ /** The ids of every pending suggestion in a document, in every story. */
12803
+ const pendingSuggestionIdsIn = (document) => {
12804
+ const out = /* @__PURE__ */ new Set();
12805
+ const visit = (value) => {
12806
+ if (typeof value !== "object" || value === null) return;
12807
+ if (Array.isArray(value)) {
12808
+ for (const item of value) visit(item);
12809
+ return;
12810
+ }
12811
+ const record = value;
12812
+ const info = record["info"];
12813
+ if (typeof info === "object" && info !== null && typeof info.suggestionId === "string") out.add(info.suggestionId);
12814
+ for (const child of Object.values(record)) visit(child);
12815
+ };
12816
+ for (const story of documentStories(document)) visit(storyBody(document, story).content);
12817
+ return out;
12818
+ };
12183
12819
  // src/ops/tocIntent.ts
12184
12820
  const refuse$1 = (message, reason = DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE) => Result.err(new DocumentOpRefusal({
12185
12821
  message,
@@ -12516,19 +13152,19 @@ const censusOf = (identities, paragraphs) => {
12516
13152
  stories: /* @__PURE__ */ new Map()
12517
13153
  };
12518
13154
  };
12519
- /** Cache immutable versions and update plain main stories without walking unchanged leaves. */
13155
+ /** Cache immutable versions and update a main story without walking the blocks an edit left. */
12520
13156
  const createCensusReader = () => {
12521
13157
  const versions = /* @__PURE__ */ new WeakMap();
12522
- const paragraphKeys = /* @__PURE__ */ new WeakMap();
13158
+ const blockKeys = /* @__PURE__ */ new WeakMap();
12523
13159
  let latest;
12524
- const keysOf = (paragraph) => {
12525
- let keys = paragraphKeys.get(paragraph);
13160
+ const keysOf = (block) => {
13161
+ let keys = blockKeys.get(block);
12526
13162
  if (keys === void 0) {
12527
13163
  keys = {
12528
- identities: identityKeysIn(paragraph).concat(reservedIdentityKeysIn(paragraph)),
12529
- paragraphs: paragraphIdsIn(paragraph).map(idKey)
13164
+ identities: identityKeysIn(block).concat(reservedIdentityKeysIn(block)),
13165
+ paragraphs: paragraphIdsIn(block).map(idKey)
12530
13166
  };
12531
- paragraphKeys.set(paragraph, keys);
13167
+ blockKeys.set(block, keys);
12532
13168
  }
12533
13169
  return keys;
12534
13170
  };
@@ -12543,15 +13179,15 @@ const createCensusReader = () => {
12543
13179
  const content = document.package.document.content;
12544
13180
  let identities;
12545
13181
  let paragraphs;
12546
- if (before !== void 0 && oldContent !== void 0 && oldContent.every((block) => block.type === "paragraph") && content.every((block) => block.type === "paragraph") && sameFieldsExcept(before.document.package, document.package, PACKAGE_CONTENT_FIELDS) && sameFieldsExcept(before.document.package.document, document.package.document, DOCUMENT_CONTENT_FIELDS)) {
13182
+ if (before !== void 0 && oldContent !== void 0 && sameFieldsExcept(before.document.package, document.package, PACKAGE_CONTENT_FIELDS) && sameFieldsExcept(before.document.package.document, document.package.document, DOCUMENT_CONTENT_FIELDS)) {
12547
13183
  identities = new Map(before.identities);
12548
13184
  paragraphs = new Map(before.paragraphs);
12549
13185
  const changed = /* @__PURE__ */ new Map();
12550
- for (const paragraph of oldContent) changed.set(paragraph, (changed.get(paragraph) ?? 0) - 1);
12551
- for (const paragraph of content) changed.set(paragraph, (changed.get(paragraph) ?? 0) + 1);
12552
- for (const [paragraph, delta] of changed) {
13186
+ for (const block of oldContent) changed.set(block, (changed.get(block) ?? 0) - 1);
13187
+ for (const block of content) changed.set(block, (changed.get(block) ?? 0) + 1);
13188
+ for (const [block, delta] of changed) {
12553
13189
  if (delta === 0) continue;
12554
- const keys = keysOf(paragraph);
13190
+ const keys = keysOf(block);
12555
13191
  adjustCounts({
12556
13192
  counts: identities,
12557
13193
  keys: keys.identities,
@@ -12564,7 +13200,7 @@ const createCensusReader = () => {
12564
13200
  });
12565
13201
  }
12566
13202
  } else {
12567
- identities = countKeys(packageIdentityKeys(document.package).concat(reservedIdentityKeysIn(document.package)));
13203
+ identities = countKeys(packageIdentityKeys(document.package).concat(packageReservedIdentityKeys(document.package)));
12568
13204
  paragraphs = countKeys(packageParagraphIds(document.package).map(idKey));
12569
13205
  }
12570
13206
  const version = {
@@ -12641,7 +13277,8 @@ const withNewIds = (op, newIds) => {
12641
13277
  case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
12642
13278
  case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
12643
13279
  case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT:
12644
- case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES: return op;
13280
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES:
13281
+ case DOCUMENT_OP_TYPES.SET_REVISION_INFO: return op;
12645
13282
  default: return op;
12646
13283
  }
12647
13284
  };
@@ -12833,8 +13470,23 @@ const outOfIds = () => Result.err(new DocumentOpRefusal({
12833
13470
  reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
12834
13471
  opType: DOCUMENT_OP_TYPES.DELETE_RANGE
12835
13472
  }));
13473
+ /** The story a planned piece edits. */
13474
+ const storyOf = (input) => {
13475
+ switch (input.type) {
13476
+ case DOCUMENT_OP_TYPES.DELETE_RANGE:
13477
+ case DOCUMENT_OP_TYPES.SET_RUN_PROPS: return input.from.story;
13478
+ case DOCUMENT_OP_TYPES.INSERT_CONTENT:
13479
+ case DOCUMENT_OP_TYPES.SPLIT_BLOCK: return input.at.story;
13480
+ case DOCUMENT_OP_TYPES.JOIN_BLOCKS:
13481
+ case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS:
13482
+ case DOCUMENT_OP_TYPES.REPLACE_INLINE: return input.story;
13483
+ default: return input;
13484
+ }
13485
+ };
13486
+ /** Whether an operation, its unused ids trimmed, still names a new id. */
13487
+ const takesNewIds = (op) => "newIds" in op && op.newIds !== void 0 && ((op.newIds.revision?.length ?? 0) > 0 || (op.newIds.control?.length ?? 0) > 0);
12836
13488
  /** Shared allocation and simulation for all pieces of one planned edit. */
12837
- const createTrackedPlan = ({ document, revision, newIds }) => {
13489
+ const createTrackedPlan = ({ document, revision, newIds, countEveryPiece = false }) => {
12838
13490
  const used = usedIds(document, IDENTITY_SPACES.REVISION);
12839
13491
  const pool = [...new Set(newIds?.revision ?? [])].filter((id) => !used.has(id) && id !== revision.id);
12840
13492
  let taken = 0;
@@ -12865,33 +13517,42 @@ const createTrackedPlan = ({ document, revision, newIds }) => {
12865
13517
  }
12866
13518
  };
12867
13519
  }
12868
- const demand = revisionIdDemand(current, op);
12869
- if (demand.isErr()) return Result.err(demand.error);
12870
- const ids = take(demand.value);
12871
- if (ids === void 0) return outOfIds();
12872
13520
  const controls = usedIds(current, IDENTITY_SPACES.CONTROL);
12873
- op = withNewIds(op, {
12874
- revision: ids,
12875
- control: (newIds?.control ?? []).filter((id) => !controls.has(id))
13521
+ const control = (newIds?.control ?? []).filter((id) => !controls.has(id));
13522
+ const story = storyOf(input);
13523
+ const unallocated = withNewIds(op, {
13524
+ revision: [],
13525
+ control
12876
13526
  });
12877
- const applied = applyDocumentOp(current, op);
13527
+ const attempt = countEveryPiece ? void 0 : applyDocumentOp(current, unallocated);
13528
+ let applied;
13529
+ let trimmed;
13530
+ if (attempt?.isOk() === true) {
13531
+ trimmed = trimAppliedNewIds({
13532
+ before: current,
13533
+ op: unallocated,
13534
+ applied: attempt.value,
13535
+ story
13536
+ });
13537
+ if (!takesNewIds(trimmed)) applied = attempt;
13538
+ }
13539
+ if (applied === void 0) {
13540
+ trimmed = void 0;
13541
+ const demand = revisionIdDemand(current, op);
13542
+ if (demand.isErr()) return Result.err(demand.error);
13543
+ const ids = take(demand.value);
13544
+ if (ids === void 0) return outOfIds();
13545
+ op = withNewIds(op, {
13546
+ revision: ids,
13547
+ control
13548
+ });
13549
+ applied = applyDocumentOp(current, op);
13550
+ } else op = unallocated;
12878
13551
  if (applied.isErr()) return Result.err(applied.error);
12879
13552
  stampUsed ||= stampOf(input) !== void 0 && applied.value.revisions.length > 0;
12880
13553
  const before = current;
12881
13554
  current = applied.value.document;
12882
- const story = (() => {
12883
- switch (input.type) {
12884
- case DOCUMENT_OP_TYPES.DELETE_RANGE:
12885
- case DOCUMENT_OP_TYPES.SET_RUN_PROPS: return input.from.story;
12886
- case DOCUMENT_OP_TYPES.INSERT_CONTENT:
12887
- case DOCUMENT_OP_TYPES.SPLIT_BLOCK: return input.at.story;
12888
- case DOCUMENT_OP_TYPES.JOIN_BLOCKS:
12889
- case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS:
12890
- case DOCUMENT_OP_TYPES.REPLACE_INLINE: return input.story;
12891
- default: return input;
12892
- }
12893
- })();
12894
- ops.push(trimAppliedNewIds({
13555
+ ops.push(trimmed ?? trimAppliedNewIds({
12895
13556
  before,
12896
13557
  op,
12897
13558
  applied: applied.value,
@@ -13119,18 +13780,32 @@ const refuse = (message, reason = DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE) => Re
13119
13780
  reason,
13120
13781
  opType: DOCUMENT_OP_TYPES.REPLACE_INLINE
13121
13782
  }));
13122
- /** Cutting these records cannot duplicate review identities or unmodeled wrappers. */
13783
+ /**
13784
+ * Records a link edit can cut. A run's pending formatting change and a
13785
+ * tracked change are cut with it, and the halves after the first take fresh
13786
+ * ids; wrappers it cannot model (controls, opaque captures) are not cut.
13787
+ */
13123
13788
  const editable = (items) => items.every((item) => {
13124
13789
  switch (item.type) {
13125
- case "run": return (item.propertyChanges?.length ?? 0) === 0;
13790
+ case "run": return true;
13791
+ case "insertion":
13792
+ case "deletion":
13793
+ case "moveFrom":
13794
+ case "moveTo": return editable(item.content);
13126
13795
  case "simpleField":
13127
13796
  case "complexField":
13128
13797
  case "bookmarkStart":
13129
- case "bookmarkEnd": return true;
13798
+ case "bookmarkEnd":
13799
+ case "commentRangeStart":
13800
+ case "commentRangeEnd":
13801
+ case "commentReference":
13802
+ case "preservedInline": return true;
13130
13803
  case "hyperlink": return editable(item.children);
13131
13804
  default: return false;
13132
13805
  }
13133
13806
  });
13807
+ /** Content rebuilt inside a tracked change, which admits every kind it held. */
13808
+ const trackedContent = (items) => items.map((item) => isTrackedChild(item) ? item : panic("A link edit put a record into a tracked change that it cannot hold."));
13134
13809
  const HYPERLINK_STYLE_ID = "Hyperlink";
13135
13810
  const styledRun = (run, intent) => {
13136
13811
  if (run.formatting === void 0) return run;
@@ -13154,8 +13829,21 @@ const linkedChildren = (items, intent) => {
13154
13829
  case "complexField":
13155
13830
  case "bookmarkStart":
13156
13831
  case "bookmarkEnd":
13832
+ case "commentRangeStart":
13833
+ case "commentRangeEnd":
13834
+ case "commentReference":
13835
+ case "preservedInline":
13157
13836
  children.push(item);
13158
13837
  break;
13838
+ case "insertion":
13839
+ case "deletion":
13840
+ case "moveFrom":
13841
+ case "moveTo":
13842
+ children.push({
13843
+ ...item,
13844
+ content: trackedContent(linkedChildren(item.content, intent))
13845
+ });
13846
+ break;
13159
13847
  case "hyperlink":
13160
13848
  if (item.children.length === 0) {
13161
13849
  children.push(item);
@@ -13192,10 +13880,46 @@ const wrapLinkedChildren = (intent, children) => {
13192
13880
  continue;
13193
13881
  }
13194
13882
  link = void 0;
13883
+ if (child.type === "insertion" || child.type === "deletion" || child.type === "moveFrom" || child.type === "moveTo") {
13884
+ result.push({
13885
+ ...child,
13886
+ content: trackedContent(wrapLinkedChildren(intent, child.content))
13887
+ });
13888
+ continue;
13889
+ }
13195
13890
  result.push(child);
13196
13891
  }
13197
13892
  return result;
13198
13893
  };
13894
+ /**
13895
+ * The edited paragraphs with fresh ids where a cut left two records sharing
13896
+ * one: a run's pending formatting change or a tracked change cut at a link's
13897
+ * edge keeps its id on the first half, and the halves after it take the
13898
+ * mode's new ids, as any cut does.
13899
+ */
13900
+ const freshenedParagraphs = (document, edited, mode) => {
13901
+ const before = edited.map(({ paragraph }) => paragraph);
13902
+ const freshened = freshenIdentities({
13903
+ before,
13904
+ after: edited.map(({ paragraph, content }) => ({
13905
+ ...paragraph,
13906
+ content
13907
+ })),
13908
+ newIds: mode.newIds ?? {},
13909
+ usedElsewhere: () => {
13910
+ const counts = countKeys(packageIdentityKeys(document.package));
13911
+ for (const key of identityKeysIn(before)) counts.set(key, (counts.get(key) ?? 1) - 1);
13912
+ return new Set([...counts].flatMap(([key, count]) => count > 0 ? [key] : []));
13913
+ },
13914
+ reserved: new Set(reservedIdentityKeysIn(document.package))
13915
+ });
13916
+ switch (freshened.kind) {
13917
+ case "fresh": return Result.ok(freshened.paragraphs);
13918
+ case "needsIds": return refuse(`The hyperlink edit needs ${String(freshened.missing)} additional revision ids.`, DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS);
13919
+ case "invalidId": return refuse(`Revision id ${String(freshened.id)} is not available.`, DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID);
13920
+ default: return freshened;
13921
+ }
13922
+ };
13199
13923
  /** Wrapper edits compile to exact-inverse content ops, never to a projection snapshot. */
13200
13924
  const compileHyperlinkIntent = (document, { intent: sourceIntent, mode, compileEmptyReplacement }) => {
13201
13925
  let intent = sourceIntent;
@@ -13212,7 +13936,7 @@ const compileHyperlinkIntent = (document, { intent: sourceIntent, mode, compileE
13212
13936
  const locations = selected.value.flat();
13213
13937
  const pieces = [];
13214
13938
  for (const { paragraph } of locations) {
13215
- if (!editable(paragraph.content)) return refuse("Hyperlink edits cannot cut pending review identities or unsupported inline wrappers.");
13939
+ if (!editable(paragraph.content)) return refuse("Hyperlink edits cannot cut a content control or markup folio does not model.");
13216
13940
  const blockId = paragraph.paraId ?? "";
13217
13941
  const from = idKey(blockId) === idKey(intent.from.blockId) ? intent.from : {
13218
13942
  story: intent.from.story,
@@ -13277,13 +14001,18 @@ const compileHyperlinkIntent = (document, { intent: sourceIntent, mode, compileE
13277
14001
  if (typeof gap !== "object") return refuse("Invalid hyperlink insertion gap.", gap);
13278
14002
  const [before = [], after = []] = partitionContent(paragraph.content, [gap]);
13279
14003
  const replacement = asParagraphContent(before).concat(content, asParagraphContent(after));
14004
+ const freshened = freshenedParagraphs(applied.value.document, [{
14005
+ paragraph,
14006
+ content: replacement
14007
+ }], mode);
14008
+ if (freshened.isErr()) return Result.err(freshened.error);
13280
14009
  return Result.ok({
13281
14010
  ops: deletion.value.ops.concat([{
13282
14011
  type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
13283
14012
  story: at.story,
13284
14013
  blockId: at.blockId,
13285
14014
  expected: paragraph.content,
13286
- content: replacement
14015
+ content: freshened.value[0]?.content ?? replacement
13287
14016
  }]),
13288
14017
  selection: {
13289
14018
  ...at,
@@ -13292,20 +14021,26 @@ const compileHyperlinkIntent = (document, { intent: sourceIntent, mode, compileE
13292
14021
  }
13293
14022
  });
13294
14023
  }
13295
- const ops = [];
14024
+ const edited = [];
13296
14025
  for (const piece of pieces) {
13297
14026
  if (piece.from.offset === piece.to.offset) continue;
13298
14027
  const children = linkedChildren(piece.middle, intent);
13299
14028
  const replacement = intent.type === "setHyperlink" ? wrapLinkedChildren(intent, children) : children;
13300
14029
  if (structurallyEqual(piece.middle, replacement)) continue;
13301
- ops.push({
13302
- type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
13303
- story: intent.from.story,
13304
- blockId: piece.from.blockId,
13305
- expected: piece.paragraph.content,
14030
+ edited.push({
14031
+ paragraph: piece.paragraph,
13306
14032
  content: piece.before.concat(replacement, piece.after)
13307
14033
  });
13308
14034
  }
14035
+ const freshened = freshenedParagraphs(document, edited, mode);
14036
+ if (freshened.isErr()) return Result.err(freshened.error);
14037
+ const ops = freshened.value.map((paragraph, index) => ({
14038
+ type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
14039
+ story: intent.from.story,
14040
+ blockId: paragraph.paraId ?? "",
14041
+ expected: edited[index]?.paragraph.content ?? panic("A freshened paragraph has no edited source."),
14042
+ content: paragraph.content
14043
+ }));
13309
14044
  return Result.ok({
13310
14045
  ops,
13311
14046
  selection: intent.to
@@ -13448,13 +14183,22 @@ const planTrackedReplace = (document, options) => {
13448
14183
  /** One editor intent, compiled to direct or tracked document operations. */
13449
14184
  const intentEndpoints = (intent) => {
13450
14185
  switch (intent.type) {
13451
- case "table": return {
14186
+ case "table":
14187
+ case "tableRow":
14188
+ case "tableBlock": return {
13452
14189
  story: intent.operation.story,
13453
14190
  fromId: intent.operation.blockId,
13454
14191
  toId: intent.operation.blockId,
13455
14192
  fromOffset: 0,
13456
14193
  toOffset: 0
13457
14194
  };
14195
+ case "insertParagraphs": return {
14196
+ story: intent.story,
14197
+ fromId: intent.at.blockId,
14198
+ toId: intent.at.blockId,
14199
+ fromOffset: 0,
14200
+ toOffset: 0
14201
+ };
13458
14202
  case "setHyperlink":
13459
14203
  case "removeHyperlink":
13460
14204
  case "insertHyperlink":
@@ -13556,6 +14300,27 @@ const createEditorIntentIdAllocator = () => {
13556
14300
  for (let id = 1; id <= 2147483647 && ids.length < count; id += 1) if (!occupied.has(id)) ids.push(id);
13557
14301
  return ids;
13558
14302
  };
14303
+ if (intent.type === "insertParagraphs") {
14304
+ demand = 3;
14305
+ for (const paragraph of intent.paragraphs) {
14306
+ demand += PARAGRAPH_REVISION_DEMAND;
14307
+ for (const span of leafSpans(paragraph.content)) demand += leafRevisionDemand(span.ancestors.length);
14308
+ }
14309
+ }
14310
+ if (intent.type === "tableBlock") {
14311
+ const op = intent.operation;
14312
+ const table = op.type === DOCUMENT_OP_TYPES.INSERT_TABLE ? op.table : locateTableRow(document, op).map(({ table: found }) => found).unwrapOr(void 0);
14313
+ if (table !== void 0) {
14314
+ demand = 2 + table.rows.length + PARAGRAPH_REVISION_DEMAND;
14315
+ for (const { paragraph } of storyParagraphs({ content: [{
14316
+ type: "table",
14317
+ rows: table.rows
14318
+ }] })) {
14319
+ demand += PARAGRAPH_REVISION_DEMAND;
14320
+ for (const span of leafSpans(paragraph.content)) demand += leafRevisionDemand(span.ancestors.length);
14321
+ }
14322
+ }
14323
+ }
13559
14324
  if (intent.type === "table") {
13560
14325
  const op = intent.operation;
13561
14326
  const located = locateTableRow(document, op);
@@ -13702,12 +14467,23 @@ const physicalPositionAtEditorOffset = (document, at) => {
13702
14467
  }
13703
14468
  return at;
13704
14469
  };
13705
- const replacementCaret = (at, text) => ({
14470
+ /**
14471
+ * The caret after typing `text` at `at`: directly after the typed text, before
14472
+ * any zero-width marker that follows it, so the next keystroke continues the
14473
+ * same run instead of landing on the far side of a comment, bookmark or
14474
+ * permission boundary.
14475
+ */
14476
+ const replacementCaret = (at, text) => text.length > 0 ? {
13706
14477
  story: at.story,
13707
14478
  blockId: at.blockId,
13708
14479
  offset: at.offset + text.length,
13709
- ...text.length === 0 && at.zeroWidthBefore !== void 0 ? { zeroWidthBefore: at.zeroWidthBefore } : {}
13710
- });
14480
+ zeroWidthBefore: 0
14481
+ } : {
14482
+ story: at.story,
14483
+ blockId: at.blockId,
14484
+ offset: at.offset,
14485
+ ...at.zeroWidthBefore === void 0 ? {} : { zeroWidthBefore: at.zeroWidthBefore }
14486
+ };
13711
14487
  const paragraphAt = (document, at) => storyParagraphs(storyBody(document, at.story)).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(at.blockId))?.paragraph;
13712
14488
  /** Zero-width markers and empty leaves never supply the formatting of typed content. */
13713
14489
  const visibleFormattingSpans = (paragraph) => leafSpans(paragraph.content).filter(({ ancestors, before, after }) => after.offset > before.offset && !ancestors.some(isRemovedRevisionNode));
@@ -13756,7 +14532,7 @@ const splitParagraphFields = (document, at) => {
13756
14532
  /** A compound intent consumes one identity pool across its sequential plans. */
13757
14533
  const modeAfterOps = (document, mode) => {
13758
14534
  if (mode.newIds === void 0) return mode;
13759
- const occupied = new Set(packageIdentityKeys(document.package).concat(reservedIdentityKeysIn(document.package)));
14535
+ const occupied = new Set(packageIdentityKeys(document.package).concat(packageReservedIdentityKeys(document.package)));
13760
14536
  const revisionIds = mode.newIds.revision?.filter((id) => !occupied.has(`${IDENTITY_SPACES.REVISION}:${id}`));
13761
14537
  const controlIds = mode.newIds.control?.filter((id) => !occupied.has(`${IDENTITY_SPACES.CONTROL}:${id}`));
13762
14538
  const newIds = {
@@ -13802,7 +14578,7 @@ const withoutMoveAnchors = (nodes) => {
13802
14578
  };
13803
14579
  const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId }) => {
13804
14580
  const copy = cloneModel([...paragraphs]);
13805
- const occupied = new Set(packageIdentityKeys(document.package).concat(reservedIdentityKeysIn(document.package)));
14581
+ const occupied = new Set(packageIdentityKeys(document.package).concat(packageReservedIdentityKeys(document.package)));
13806
14582
  for (const id of mode.newIds?.revision ?? []) occupied.add(`${IDENTITY_SPACES.REVISION}:${id}`);
13807
14583
  for (const id of mode.newIds?.control ?? []) occupied.add(`${IDENTITY_SPACES.CONTROL}:${id}`);
13808
14584
  if (mode.type === "suggesting") occupied.add(`${IDENTITY_SPACES.REVISION}:${mode.revision.id}`);
@@ -13898,19 +14674,20 @@ const joinParagraphPropertyAlignment = ({ document, current, intent, revision })
13898
14674
  const followingGroup = groups.find(({ paragraphs }) => paragraphs.some(({ paraId }) => idKey(paraId ?? "") === idKey(intent.nextBlockId)));
13899
14675
  if (!firstGroup || !followingGroup) panic("A valid canonical join must belong to paragraph groups.");
13900
14676
  const source = firstGroup.text.length === 0 ? followingGroup.paragraphs.at(-1) : firstGroup.paragraphs.at(-1);
14677
+ const survivorId = revision === void 0 && intent.survivor === "first" ? firstGroup.blockId : followingGroup.blockId;
13901
14678
  const survivor = paragraphAt(current, {
13902
14679
  story: intent.story,
13903
- blockId: followingGroup.blockId,
14680
+ blockId: survivorId,
13904
14681
  offset: 0
13905
14682
  });
13906
- if (!survivor) panic("A valid canonical join must retain its following group survivor.");
14683
+ if (!survivor) panic("A valid canonical join must retain its surviving group.");
13907
14684
  const desired = paragraphPropertiesOf(source?.formatting);
13908
14685
  const existing = paragraphPropertiesOf(survivor.formatting);
13909
14686
  if (structurallyEqual(existing, desired)) return void 0;
13910
14687
  return {
13911
14688
  type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS,
13912
14689
  story: intent.story,
13913
- blockId: followingGroup.blockId,
14690
+ blockId: survivorId,
13914
14691
  patch: Object.fromEntries([...Object.keys(existing ?? {}).map((key) => [key, null]), ...Object.entries(desired ?? {})]),
13915
14692
  whenEmpty: source?.formatting === void 0 ? EMPTY_PROPERTY_SETS.OMIT : EMPTY_PROPERTY_SETS.KEEP,
13916
14693
  ...revision === void 0 ? {} : { revision }
@@ -14474,17 +15251,14 @@ const compileEditorIntent = (document, { intent, mode, firstBlockId }) => {
14474
15251
  if (located.isErr()) return Result.err(located.error);
14475
15252
  const demand = tableEditParagraphDemand(located.value, operation);
14476
15253
  if (demand.isErr()) return Result.err(demand.error);
14477
- const occupied = new Set([...packageParagraphIds(document.package), ...mode.reservedBlockIds ?? []].map(idKey));
14478
- const newBlockIds = [];
14479
- for (let nextId = 1; newBlockIds.length < demand.value; nextId += 1) {
14480
- if (nextId >= 2147483648) return Result.err(new DocumentOpRefusal({
14481
- opType: operation.type,
14482
- reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
14483
- message: "The paragraph identity space is exhausted."
14484
- }));
14485
- const id = nextId.toString(16).padStart(8, "0").toUpperCase();
14486
- if (!occupied.has(idKey(id))) newBlockIds.push(id);
14487
- }
15254
+ const fresh = freshParagraphIds({
15255
+ document,
15256
+ reserved: mode.reservedBlockIds,
15257
+ count: demand.value,
15258
+ opType: operation.type
15259
+ });
15260
+ if (fresh.isErr()) return Result.err(fresh.error);
15261
+ const newBlockIds = fresh.value;
14488
15262
  let op;
14489
15263
  switch (operation.type) {
14490
15264
  case DOCUMENT_OP_TYPES.INSERT_COLUMN:
@@ -14535,6 +15309,216 @@ const compileEditorIntent = (document, { intent, mode, firstBlockId }) => {
14535
15309
  };
14536
15310
  break;
14537
15311
  }
15312
+ case "tableRow": {
15313
+ const operation = intent.operation;
15314
+ const located = locateTableRow(document, operation);
15315
+ if (located.isErr()) return Result.err(located.error);
15316
+ const { table, rowIndex, list } = located.value;
15317
+ let op;
15318
+ let blockId;
15319
+ if (operation.type === DOCUMENT_OP_TYPES.INSERT_ROW) {
15320
+ const fresh = freshParagraphIds({
15321
+ document,
15322
+ reserved: mode.reservedBlockIds,
15323
+ count: rowParagraphCount(operation.row),
15324
+ opType: operation.type
15325
+ });
15326
+ if (fresh.isErr()) return Result.err(fresh.error);
15327
+ const row = withFreshParagraphIds(operation.row, fresh.value);
15328
+ op = {
15329
+ ...operation,
15330
+ row,
15331
+ ...tracked
15332
+ };
15333
+ blockId = fresh.value[0];
15334
+ } else {
15335
+ op = {
15336
+ ...operation,
15337
+ ...tracked
15338
+ };
15339
+ blockId = tableRowAnchor(table.rows.filter((_row, index) => index !== rowIndex)) ?? storyParagraphs(storyBody(document, op.story)).find((paragraph) => sameBlockList(paragraph.list, list) && paragraph.paragraph.paraId !== void 0)?.paragraph.paraId;
15340
+ }
15341
+ if (blockId === void 0) return Result.err(new DocumentOpRefusal({
15342
+ opType: op.type,
15343
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
15344
+ message: "The row edit leaves no paragraph for the caret."
15345
+ }));
15346
+ const applied = applyDocumentOp(document, op);
15347
+ if (applied.isErr()) return Result.err(applied.error);
15348
+ ops = [trimAppliedNewIds({
15349
+ before: document,
15350
+ op,
15351
+ applied: applied.value,
15352
+ story: op.story
15353
+ })];
15354
+ selection = {
15355
+ story: op.story,
15356
+ blockId,
15357
+ offset: 0
15358
+ };
15359
+ break;
15360
+ }
15361
+ case "insertParagraphs": {
15362
+ const fresh = freshParagraphIds({
15363
+ document,
15364
+ reserved: mode.reservedBlockIds,
15365
+ count: intent.paragraphs.length,
15366
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
15367
+ });
15368
+ if (fresh.isErr()) return Result.err(fresh.error);
15369
+ const blocks = intent.paragraphs.map((paragraph, index) => ({
15370
+ ...paragraph,
15371
+ paraId: fresh.value[index] ?? panic("A fresh paragraph id is missing.")
15372
+ }));
15373
+ const first = blocks[0];
15374
+ if (first === void 0) return Result.err(new DocumentOpRefusal({
15375
+ reason: DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST,
15376
+ message: "No paragraphs to insert.",
15377
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
15378
+ }));
15379
+ return Result.ok({
15380
+ ops: [{
15381
+ type: DOCUMENT_OP_TYPES.INSERT_BLOCKS,
15382
+ story: intent.story,
15383
+ at: intent.at,
15384
+ blocks,
15385
+ ...tracked
15386
+ }],
15387
+ selection: {
15388
+ story: intent.story,
15389
+ blockId: first.paraId,
15390
+ offset: 0
15391
+ }
15392
+ });
15393
+ }
15394
+ case "tableBlock": {
15395
+ if (intent.operation.type === DOCUMENT_OP_TYPES.INSERT_TABLE) {
15396
+ const { story, blockId, table } = intent.operation;
15397
+ const fresh = freshParagraphIds({
15398
+ document,
15399
+ reserved: mode.reservedBlockIds,
15400
+ count: storyParagraphs({ content: [{
15401
+ type: "table",
15402
+ rows: table.rows
15403
+ }] }).length + (intent.operation.separated === true ? 2 : 1),
15404
+ opType: DOCUMENT_OP_TYPES.INSERT_TABLE
15405
+ });
15406
+ if (fresh.isErr()) return Result.err(fresh.error);
15407
+ const separated = intent.operation.separated === true;
15408
+ const leadingId = separated ? fresh.value[0] : void 0;
15409
+ const [paragraphId, ...tableIds] = separated ? fresh.value.slice(1) : fresh.value;
15410
+ if (paragraphId === void 0 || separated && leadingId === void 0) return panic("A fresh paragraph id is missing.");
15411
+ let next = 0;
15412
+ const rows = table.rows.map((row) => {
15413
+ const count = storyParagraphs({ content: [{
15414
+ type: "table",
15415
+ rows: [row]
15416
+ }] }).length;
15417
+ const ids = tableIds.slice(next, next + count);
15418
+ next += count;
15419
+ return withFreshParagraphIds(row, ids);
15420
+ });
15421
+ const before = intent.operation.side === "before";
15422
+ const sequence = [{
15423
+ type: DOCUMENT_OP_TYPES.INSERT_BLOCKS,
15424
+ story,
15425
+ at: {
15426
+ type: before ? "before" : "after",
15427
+ blockId
15428
+ },
15429
+ blocks: [...leadingId === void 0 ? [] : [{
15430
+ type: "paragraph",
15431
+ paraId: leadingId,
15432
+ content: []
15433
+ }], {
15434
+ type: "paragraph",
15435
+ paraId: paragraphId,
15436
+ content: []
15437
+ }],
15438
+ ...tracked
15439
+ }, {
15440
+ type: DOCUMENT_OP_TYPES.INSERT_TABLE,
15441
+ story,
15442
+ at: before ? {
15443
+ type: "before",
15444
+ blockId: paragraphId
15445
+ } : {
15446
+ type: "after",
15447
+ blockId
15448
+ },
15449
+ table: {
15450
+ ...table,
15451
+ rows
15452
+ },
15453
+ ...tracked
15454
+ }];
15455
+ let current = document;
15456
+ ops = [];
15457
+ let pool = mode.type === "suggesting" ? [mode.revision.id, ...mode.newIds?.revision ?? []] : [];
15458
+ for (const planned of sequence) {
15459
+ const [id, ...rest] = pool;
15460
+ const op = mode.type === "suggesting" && id !== void 0 ? {
15461
+ ...planned,
15462
+ revision: {
15463
+ ...mode.revision,
15464
+ id
15465
+ },
15466
+ newIds: {
15467
+ revision: rest,
15468
+ control: mode.newIds?.control ?? []
15469
+ }
15470
+ } : planned;
15471
+ const applied = applyDocumentOp(current, op);
15472
+ if (applied.isErr()) return Result.err(applied.error);
15473
+ const trimmed = trimAppliedNewIds({
15474
+ before: current,
15475
+ op,
15476
+ applied: applied.value,
15477
+ story
15478
+ });
15479
+ ops.push(trimmed);
15480
+ const used = new Set(applied.value.revisions ?? []);
15481
+ pool = pool.filter((candidate) => !used.has(candidate));
15482
+ current = applied.value.document;
15483
+ }
15484
+ const first = tableIds.at(0);
15485
+ if (first === void 0) return panic("The inserted table has no paragraph.");
15486
+ selection = {
15487
+ story,
15488
+ blockId: first,
15489
+ offset: 0
15490
+ };
15491
+ break;
15492
+ }
15493
+ const op = {
15494
+ ...intent.operation,
15495
+ ...tracked
15496
+ };
15497
+ const located = locateTableRow(document, op);
15498
+ if (located.isErr()) return Result.err(located.error);
15499
+ const { list } = located.value;
15500
+ const beside = storyParagraphs(storyBody(document, op.story)).filter(({ list: other, paragraph }) => sameBlockList(other, list) && paragraph.paraId !== void 0);
15501
+ const anchor = (beside[beside.findIndex(({ index }) => index > located.value.index)] ?? beside.at(-1))?.paragraph.paraId;
15502
+ if (anchor === void 0) return Result.err(new DocumentOpRefusal({
15503
+ opType: op.type,
15504
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
15505
+ message: "Removing the table leaves no paragraph for the caret."
15506
+ }));
15507
+ const applied = applyDocumentOp(document, op);
15508
+ if (applied.isErr()) return Result.err(applied.error);
15509
+ ops = [trimAppliedNewIds({
15510
+ before: document,
15511
+ op,
15512
+ applied: applied.value,
15513
+ story: op.story
15514
+ })];
15515
+ selection = {
15516
+ story: op.story,
15517
+ blockId: anchor,
15518
+ offset: 0
15519
+ };
15520
+ break;
15521
+ }
14538
15522
  case "setList": {
14539
15523
  const first = intent.items.at(0);
14540
15524
  if (first === void 0) return Result.err(new DocumentOpRefusal({
@@ -14759,6 +15743,23 @@ const compileEditorIntent = (document, { intent, mode, firstBlockId }) => {
14759
15743
  text
14760
15744
  }]
14761
15745
  }];
15746
+ const continuing = idKey(from.blockId) === idKey(to.blockId) && from.offset === to.offset && (from.zeroWidthBefore ?? 0) === (to.zeroWidthBefore ?? 0) && text !== "" ? continuedSlice(continuation(paragraph.content, from, to, { ...intent.inside === void 0 ? {} : { inside: intent.inside } }), content) : void 0;
15747
+ if (mode.type === "suggesting" && continuing !== void 0) {
15748
+ const at = {
15749
+ ...from,
15750
+ zeroWidthBefore: from.zeroWidthBefore ?? defaultInsertionGap(paragraph.content, from.offset).zeroWidthBefore
15751
+ };
15752
+ ops = [{
15753
+ type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
15754
+ at,
15755
+ slice: continuing,
15756
+ seamPolicy: INSERTION_SEAM_POLICIES.MERGE_PLAIN_RUNS,
15757
+ revision: mode.revision,
15758
+ ...mode.newIds === void 0 ? {} : { newIds: mode.newIds }
15759
+ }];
15760
+ selection = replacementCaret(at, text);
15761
+ break;
15762
+ }
14762
15763
  if (mode.type === "suggesting") {
14763
15764
  const planned = planTrackedReplace(document, {
14764
15765
  sourceContainerPolicy: "join",
@@ -14777,7 +15778,19 @@ const compileEditorIntent = (document, { intent, mode, firstBlockId }) => {
14777
15778
  }
14778
15779
  });
14779
15780
  if (planned.isErr()) return Result.err(planned.error);
14780
- ops = planned.value;
15781
+ const resumed = idKey(from.blockId) === idKey(to.blockId) && text !== "" ? continuation(paragraph.content, from, to, { ...intent.inside === void 0 ? {} : { inside: intent.inside } }) : void 0;
15782
+ ops = [];
15783
+ for (const op of planned.value) {
15784
+ if (resumed === void 0 || op.type !== DOCUMENT_OP_TYPES.INSERT_CONTENT || idKey(op.at.blockId) !== idKey(from.blockId) || op.slice.openStart !== 0 || op.slice.openEnd !== 0) {
15785
+ ops.push(op);
15786
+ continue;
15787
+ }
15788
+ const slice = continuedSlice(resumed, op.slice.content);
15789
+ ops.push(slice === void 0 ? op : {
15790
+ ...op,
15791
+ slice
15792
+ });
15793
+ }
14781
15794
  selection = {
14782
15795
  ...from,
14783
15796
  offset: from.offset + text.length
@@ -14881,7 +15894,7 @@ const compileEditorIntent = (document, { intent, mode, firstBlockId }) => {
14881
15894
  if (text !== "") ops.push({
14882
15895
  type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
14883
15896
  at,
14884
- slice: {
15897
+ slice: (idKey(from.blockId) === idKey(to.blockId) ? continuedSlice(continuation(paragraph.content, from, to, { ...intent.inside === void 0 ? {} : { inside: intent.inside } }), content) : void 0) ?? {
14885
15898
  openStart: 0,
14886
15899
  openEnd: 0,
14887
15900
  content
@@ -15000,6 +16013,7 @@ const compileEditorIntent = (document, { intent, mode, firstBlockId }) => {
15000
16013
  blockId: intent.blockId,
15001
16014
  nextBlockId: intent.nextBlockId,
15002
16015
  sectionBoundary: SECTION_BOUNDARY_POLICIES.REMOVE,
16016
+ ...mode.type === "editing" && intent.survivor !== void 0 ? { survivor: intent.survivor } : {},
15003
16017
  ...ownInsertedMark ? {} : tracked
15004
16018
  };
15005
16019
  if (mode.type === "suggesting") {
@@ -15150,6 +16164,124 @@ const compileEditorIntent = (document, { intent, mode, firstBlockId }) => {
15150
16164
  selection
15151
16165
  });
15152
16166
  };
16167
+ /** The lowest paragraph identities neither the package nor the batch holds. */
16168
+ const freshParagraphIds = ({ document, reserved, count, opType }) => {
16169
+ const occupied = new Set([...packageParagraphIds(document.package), ...reserved ?? []].map(idKey));
16170
+ const ids = [];
16171
+ for (let nextId = 1; ids.length < count; nextId += 1) {
16172
+ if (nextId >= 2147483648) return Result.err(new DocumentOpRefusal({
16173
+ opType,
16174
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
16175
+ message: "The paragraph identity space is exhausted."
16176
+ }));
16177
+ const id = nextId.toString(16).padStart(8, "0").toUpperCase();
16178
+ if (!occupied.has(idKey(id))) ids.push(id);
16179
+ }
16180
+ return Result.ok(ids);
16181
+ };
16182
+ const rowParagraphCount = (row) => storyParagraphs({ content: [{
16183
+ type: "table",
16184
+ rows: [row]
16185
+ }] }).length;
16186
+ /** The row with each paragraph, in document order, given the next fresh id. */
16187
+ const withFreshParagraphIds = (row, ids) => {
16188
+ let next = 0;
16189
+ const blocks = (content) => content.map((block) => {
16190
+ switch (block.type) {
16191
+ case "paragraph": {
16192
+ const paraId = ids[next] ?? panic("A fresh paragraph id is missing.");
16193
+ next += 1;
16194
+ const { textId: _textId, ...rest } = block;
16195
+ return {
16196
+ ...rest,
16197
+ paraId
16198
+ };
16199
+ }
16200
+ case "table": return {
16201
+ ...block,
16202
+ rows: block.rows.map((each) => ({
16203
+ ...each,
16204
+ cells: each.cells.map((cell) => ({
16205
+ ...cell,
16206
+ content: blocks(cell.content)
16207
+ }))
16208
+ }))
16209
+ };
16210
+ case "blockSdt":
16211
+ case "blockCustomXml": return {
16212
+ ...block,
16213
+ content: blocks(block.content)
16214
+ };
16215
+ default: return block;
16216
+ }
16217
+ });
16218
+ return {
16219
+ ...row,
16220
+ cells: row.cells.map((cell) => ({
16221
+ ...cell,
16222
+ content: blocks(cell.content)
16223
+ }))
16224
+ };
16225
+ };
16226
+ /** Containers typed text continues when it lands between their own leaves. */
16227
+ const CONTINUED_CONTAINERS = /* @__PURE__ */ new Set(["inlineSdt", "inlineWrapper"]);
16228
+ /**
16229
+ * What text typed over the range from `from` to `to` continues: every
16230
+ * content control and wrapper that holds the leaves on both sides,
16231
+ * so typing within one extends it rather than cutting it in two. At an edge
16232
+ * only one side is inside, and the text stays outside, as a mark that does not
16233
+ * extend past its end, unless the caret stood just inside that edge.
16234
+ */
16235
+ const continuation = (items, from, to, { inside = {} } = {}) => {
16236
+ const spans = leafSpans(items);
16237
+ const start = {
16238
+ offset: from.offset,
16239
+ zeroWidthBefore: from.zeroWidthBefore ?? 0
16240
+ };
16241
+ const end = {
16242
+ offset: to.offset,
16243
+ zeroWidthBefore: to.zeroWidthBefore ?? 0
16244
+ };
16245
+ const outerLeft = spans.findLast(({ before }) => compareGaps(before, start) < 0);
16246
+ const outerRight = spans.find(({ after }) => compareGaps(after, end) > 0);
16247
+ const left = inside.start ? spans.find(({ after }) => compareGaps(after, start) > 0) : outerLeft;
16248
+ const right = inside.end ? spans.findLast(({ before }) => compareGaps(before, end) < 0) : outerRight;
16249
+ const containers = [];
16250
+ for (const [depth, ancestor] of (left?.ancestors ?? []).entries()) {
16251
+ if (right?.ancestors[depth] !== ancestor || !CONTINUED_CONTAINERS.has(ancestor.type)) break;
16252
+ containers.push(ancestor);
16253
+ }
16254
+ const continued = (side) => {
16255
+ let depth = 0;
16256
+ while (depth < containers.length && side?.ancestors[depth] === containers[depth]) depth += 1;
16257
+ return depth;
16258
+ };
16259
+ return {
16260
+ containers,
16261
+ openStart: continued(outerLeft),
16262
+ openEnd: continued(outerRight)
16263
+ };
16264
+ };
16265
+ /** `content` inside copies of the continued containers; `undefined` when there are none. */
16266
+ const continuedSlice = ({ containers, openStart, openEnd }, content) => {
16267
+ if (containers.length === 0) return void 0;
16268
+ let wrapped = content.slice();
16269
+ for (const container of containers.toReversed()) switch (container.type) {
16270
+ case "inlineSdt":
16271
+ case "inlineWrapper":
16272
+ wrapped = [{
16273
+ ...container,
16274
+ content: wrapped
16275
+ }];
16276
+ break;
16277
+ default: return;
16278
+ }
16279
+ return {
16280
+ openStart,
16281
+ openEnd,
16282
+ content: wrapped
16283
+ };
16284
+ };
15153
16285
  // src/ops/sequencing/address.ts
15154
16286
  const DECLARED_STORIES = Object.values(OP_STORIES);
15155
16287
  /** Compare story identities without depending on their representation. */
@@ -15269,7 +16401,8 @@ const revision = optional(object({
15269
16401
  id: natural,
15270
16402
  author: string,
15271
16403
  date: string,
15272
- initials: optional(string)
16404
+ initials: optional(string),
16405
+ suggestionId: optional(string)
15273
16406
  }));
15274
16407
  const newIds = optional(object({
15275
16408
  revision: optional(array(natural)),
@@ -15479,7 +16612,8 @@ const operationFields = {
15479
16612
  setCellProps: void 0,
15480
16613
  setRowProps: void 0,
15481
16614
  setTableProps: void 0,
15482
- setTable: void 0
16615
+ setTable: void 0,
16616
+ setRevisionInfo: void 0
15483
16617
  };
15484
16618
  const BATCH_WIRE_OP_TYPES = Object.freeze(Object.entries(operationFields).filter(([, fields]) => fields !== void 0).map(([type]) => type));
15485
16619
  const isDocumentOp = (value) => {
@@ -15664,6 +16798,7 @@ const operationStory = (op) => {
15664
16798
  case DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW:
15665
16799
  case DOCUMENT_OP_TYPES.REPLACE_INLINE:
15666
16800
  case DOCUMENT_OP_TYPES.RESOLVE_REVISION:
16801
+ case DOCUMENT_OP_TYPES.SET_REVISION_INFO:
15667
16802
  case DOCUMENT_OP_TYPES.INSERT_TABLE:
15668
16803
  case DOCUMENT_OP_TYPES.DELETE_TABLE:
15669
16804
  case DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS:
@@ -16060,7 +17195,18 @@ const createSequencer = (document) => {
16060
17195
  const results = /* @__PURE__ */ new Map();
16061
17196
  const submit = (batch) => {
16062
17197
  const previous = results.get(batch.opId);
16063
- if (previous !== void 0) return previous;
17198
+ if (previous !== void 0) {
17199
+ if (previous.actor === batch.actor) return previous.outcome;
17200
+ return {
17201
+ type: SUBMISSION_TYPES.REJECT,
17202
+ opId: batch.opId,
17203
+ reason: new BatchRejection({
17204
+ reason: BATCH_REJECTION_REASONS.CONFLICT,
17205
+ message: "The operation id was already submitted by another actor."
17206
+ }),
17207
+ headRev: journal.length
17208
+ };
17209
+ }
16064
17210
  const reject = (reason) => {
16065
17211
  const outcome = {
16066
17212
  type: SUBMISSION_TYPES.REJECT,
@@ -16068,7 +17214,10 @@ const createSequencer = (document) => {
16068
17214
  reason,
16069
17215
  headRev: journal.length
16070
17216
  };
16071
- results.set(batch.opId, outcome);
17217
+ results.set(batch.opId, {
17218
+ actor: batch.actor,
17219
+ outcome
17220
+ });
16072
17221
  return outcome;
16073
17222
  };
16074
17223
  const validated = validateDocumentBatch(batch);
@@ -16118,7 +17267,10 @@ const createSequencer = (document) => {
16118
17267
  opId: batch.opId,
16119
17268
  rev: revision
16120
17269
  };
16121
- results.set(batch.opId, ack);
17270
+ results.set(batch.opId, {
17271
+ actor: batch.actor,
17272
+ outcome: ack
17273
+ });
16122
17274
  return ack;
16123
17275
  };
16124
17276
  return {
@@ -16341,6 +17493,11 @@ const createClient = (document) => {
16341
17493
  reason: BATCH_REJECTION_REASONS.INVALID_OPERATION,
16342
17494
  message: applied.error.message
16343
17495
  }));
17496
+ const local = entries.find(({ batch: pendingBatch }) => pendingBatch.opId === next.opId);
17497
+ if (local !== void 0 && local.batch.actor !== next.actor) return Result.err(new BatchRejection({
17498
+ reason: BATCH_REJECTION_REASONS.CONFLICT,
17499
+ message: "A broadcast reuses a pending operation id under another actor."
17500
+ }));
16344
17501
  if (localIds.has(next.opId)) {
16345
17502
  entries = entries.filter(({ batch: pendingBatch }) => pendingBatch.opId !== next.opId);
16346
17503
  if (inFlight === next.opId) inFlight = void 0;
@@ -16519,4 +17676,4 @@ const groupInsertionRuns = (operations, insertionPositionOf, keepsGap = () => fa
16519
17676
  }
16520
17677
  return groups;
16521
17678
  };
16522
- export { BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, acceptCopyOriginAncestors, addCopyOriginAncestor, allocateCommentAnchorIds, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, commentDocumentIssue, compareBatchOrder, compareGaps, compileEditorIntent, contentRank, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, deletionRemovesBlock, documentStories, editorParagraphGroups, editorPositionAtPhysicalPosition, findStoryBody, formattingEquals, freshCommentId, groupInsertionRuns, idKey, inlineLeafSpans, isCommentAnchorCarrierType, isCommentExhausted, isCopyOriginAncestors, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, orderAddressingBeforeRemoval, orderBatchOperations, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, paragraphIdsIn, paragraphLength, paragraphLogicalText, paragraphMarkOutcome, paragraphRemains, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, planWellFormedRanges, reconcileDocumentPartRelationships, registerParagraphPropertySnapshot, rejectCopyOriginAncestors, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, shiftCopyOriginAncestors, storyBody, survivingComments, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withoutCommentThreads, zeroWidthLeavesAt };
17679
+ export { BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, acceptCopyOriginAncestors, addCopyOriginAncestor, allocateCommentAnchorIds, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, commentDocumentIssue, compareBatchOrder, compareGaps, compileEditorIntent, contentRank, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, deletionRemovesBlock, documentStories, editorParagraphGroups, editorPositionAtPhysicalPosition, findStoryBody, formattingEquals, freshCommentId, groupInsertionRuns, idKey, inlineLeafSpans, isCommentAnchorCarrierType, isCommentExhausted, isCopyOriginAncestors, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, orderAddressingBeforeRemoval, orderBatchOperations, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, paragraphIdsIn, paragraphLength, paragraphLogicalText, paragraphMarkOutcome, paragraphPropertySnapshotToken, paragraphRemains, paragraphVisibleText, parseDocumentBatch, pendingSuggestionIdsIn, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, planWellFormedRanges, reconcileDocumentPartRelationships, registerParagraphPropertySnapshot, rejectCopyOriginAncestors, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, shiftCopyOriginAncestors, storyBody, suggestionRevisionInfos, survivingComments, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withoutCommentThreads, withoutPendingSuggestions, zeroWidthLeavesAt };