@stll/docx-core 0.44.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -512,6 +512,20 @@ const sharedIdentityCensus = censusWalker(ownIdentityKeys, "shared");
512
512
  const CONTENT_CONTROL_STACK = "contentControls";
513
513
  const ownReservedKeys = (entries, { heldBy }) => {
514
514
  const keys = [];
515
+ if (heldBy === "keptCut") {
516
+ const holders = fieldOf(entries, "holders");
517
+ if (typeof holders === "object" && holders !== null) for (const side of ["before", "after"]) {
518
+ const id = Reflect.get(holders, side);
519
+ if (typeof id === "number") keys.push(slotKey({
520
+ space: IDENTITY_SPACES.REVISION,
521
+ id
522
+ }));
523
+ }
524
+ return {
525
+ keys,
526
+ shareable: true
527
+ };
528
+ }
515
529
  if (heldBy === "deferredRemove") {
516
530
  const blockers = fieldOf(entries, "blockers");
517
531
  if (Array.isArray(blockers)) {
@@ -5301,39 +5315,102 @@ const wellFormedRanges = ({ contents, order, relocated }) => {
5301
5315
  return changed;
5302
5316
  };
5303
5317
  // src/ops/keptCut.ts
5318
+ /**
5319
+ * The cut a kept range marker stands in (`KeptCut`): review state a
5320
+ * resolution records on a marker it kept from removed content and could not
5321
+ * place inside a piece of the record that content cut.
5322
+ */
5304
5323
  const carriesKeptCut = (node) => isBoundary(node);
5324
+ const isKeptCutPiece = (value) => value === "before" || value === "after" || value === "both";
5325
+ const keptCutHolders = ({ before, after }) => {
5326
+ if (before === void 0) return after === void 0 ? void 0 : { after };
5327
+ return after === void 0 ? { before } : {
5328
+ before,
5329
+ after
5330
+ };
5331
+ };
5332
+ /** The side `holders` name. */
5333
+ const pieceOf = (holders) => {
5334
+ if (holders === void 0) return void 0;
5335
+ if (holders.scope === "seam" || holders.before !== void 0 && holders.after !== void 0) return "both";
5336
+ return holders.before === void 0 ? "after" : "before";
5337
+ };
5338
+ /** Retain the seam scope when its pending holders change. */
5339
+ const withHolderScope = (holders, scope) => holders === void 0 || scope === void 0 ? holders : {
5340
+ ...holders,
5341
+ scope
5342
+ };
5343
+ /** `cut` with `holders`, or with none. */
5344
+ const cutHeldBy = (cut, holders) => holders === void 0 ? { keptFrom: cut.keptFrom } : {
5345
+ keptFrom: cut.keptFrom,
5346
+ holders
5347
+ };
5305
5348
  /**
5306
5349
  * `node` marked as standing in `cut`, when it is a range marker. A marker
5307
5350
  * already standing in a cut keeps the revision it was first kept from and
5308
- * the piece first named for it: whichever order kept it and then floated it
5309
- * with another removal's seam, it records the same cut.
5351
+ * the holders first named for it: whichever order kept it and then floated
5352
+ * it with another removal's seam, it records the same cut.
5310
5353
  */
5311
5354
  const withKeptCut = (node, cut) => {
5312
5355
  if (!carriesKeptCut(node)) return node;
5313
5356
  const known = node.keptCut;
5314
5357
  if (known === void 0) return Object.assign({}, node, { keptCut: cut });
5315
- if (known.piece !== void 0 || cut.piece === void 0) return node;
5316
- return Object.assign({}, node, { keptCut: {
5317
- ...known,
5318
- piece: cut.piece
5319
- } });
5358
+ if (known.holders !== void 0 || cut.holders === void 0) return node;
5359
+ return Object.assign({}, node, { keptCut: cutHeldBy(known, cut.holders) });
5320
5360
  };
5321
5361
  /**
5322
- * `node` with every marked range marker it stands for naming `piece` as the
5323
- * side whose record is a piece of its cut, keeping what the resolution
5324
- * recorded per marker. An unmarked marker stays unmarked, and one already
5325
- * naming a piece keeps it.
5362
+ * `node` with every marked range marker it stands for naming `holders` as
5363
+ * the pending changes beside it holding a piece of its cut, keeping what the
5364
+ * resolution recorded per marker. An unmarked marker stays unmarked, and one
5365
+ * already naming holders keeps them.
5326
5366
  */
5327
- const withKeptCutPieceRecorded = (node, piece, known) => changeStandingMarkers(node, keepingRecord((marker) => carriesKeptCut(marker) && marker.keptCut !== void 0 ? withKeptCut(marker, {
5328
- ...marker.keptCut,
5329
- piece
5330
- }) : marker, known));
5331
- /** `node` with every marker it stands for naming no side as its cut's piece. */
5367
+ const withKeptCutHoldersRecorded = (node, holders, known) => changeStandingMarkers(node, keepingRecord((marker) => carriesKeptCut(marker) && marker.keptCut !== void 0 ? withKeptCut(marker, cutHeldBy(marker.keptCut, holders)) : marker, known));
5368
+ /** Whether all markers in this record name the revision on the given side. */
5369
+ const keptCutHeldBy = (node, { side, id }) => {
5370
+ if (node.type === "deletion") return node.content.length > 0 && node.content.every((child) => keptCutHeldBy(child, {
5371
+ side,
5372
+ id
5373
+ }));
5374
+ return carriesKeptCut(node) && node.keptCut?.holders?.[side] === id;
5375
+ };
5376
+ /** Move a cut's holder to the revision taking its join. */
5377
+ const withKeptCutHolderHandedOver = (node, { side, from, to }, known) => changeStandingMarkers(node, keepingRecord((marker) => {
5378
+ if (!carriesKeptCut(marker)) return marker;
5379
+ const cut = marker.keptCut;
5380
+ const holders = cut?.holders;
5381
+ if (cut === void 0 || holders?.[side] !== from) return marker;
5382
+ const next = side === "before" ? {
5383
+ ...holders,
5384
+ before: to
5385
+ } : {
5386
+ ...holders,
5387
+ after: to
5388
+ };
5389
+ return Object.assign({}, marker, { keptCut: cutHeldBy(cut, next) });
5390
+ }, known));
5391
+ /** `node` with every marker it stands for naming no holder of its cut. */
5332
5392
  const withKeptCutPieceConsumed = (node, known) => changeStandingMarkers(node, keepingRecord((marker) => {
5333
- if (!carriesKeptCut(marker) || marker.keptCut?.piece === void 0) return marker;
5334
- const { piece: _consumed, ...cut } = marker.keptCut;
5335
- return Object.assign({}, marker, { keptCut: cut });
5393
+ if (!carriesKeptCut(marker) || marker.keptCut?.holders === void 0) return marker;
5394
+ return Object.assign({}, marker, { keptCut: cutHeldBy(marker.keptCut, void 0) });
5336
5395
  }, known));
5396
+ /** Point a cut at the copies or successors of its holders. */
5397
+ const remapKeptCutHolders = (cut, successor) => {
5398
+ const holders = cut.holders;
5399
+ if (holders === void 0) return cut;
5400
+ const before = holders.before === void 0 ? void 0 : successor(holders.before);
5401
+ const after = holders.after === void 0 ? void 0 : successor(holders.after);
5402
+ if (before === holders.before && after === holders.after) return cut;
5403
+ return cutHeldBy(cut, withHolderScope(keptCutHolders({
5404
+ before,
5405
+ after
5406
+ }), holders.scope));
5407
+ };
5408
+ /** Redirect holder references on a marker when its revisions are reminted. */
5409
+ const withKeptCutHoldersRenamed = (node, successor) => {
5410
+ if (!carriesKeptCut(node) || node.keptCut === void 0) return node;
5411
+ const cut = remapKeptCutHolders(node.keptCut, successor);
5412
+ return cut === node.keptCut ? node : Object.assign({}, node, { keptCut: cut });
5413
+ };
5337
5414
  /** The earliest revision a marker `node` stands for was kept from. */
5338
5415
  const keptCutFrom = (node) => {
5339
5416
  if (node.type === "deletion") return node.content.flatMap((child) => keptCutFrom(child) ?? []).toSorted().at(0);
@@ -5348,7 +5425,7 @@ const keptCutPiece = (node) => {
5348
5425
  const pieces = new Set(node.content.map(keptCutPiece));
5349
5426
  return pieces.size === 1 ? pieces.values().next().value : void 0;
5350
5427
  }
5351
- return carriesKeptCut(node) ? node.keptCut?.piece : void 0;
5428
+ return carriesKeptCut(node) ? pieceOf(node.keptCut?.holders) : void 0;
5352
5429
  };
5353
5430
  /**
5354
5431
  * Whether `node` stands in a kept cut: a marked range marker, or a pending
@@ -5413,7 +5490,7 @@ const withKeptCutsFromChanges = (nodes, writtenOnChange) => {
5413
5490
  const marked = withKeptCutsFromChanges(children, writtenOnChange);
5414
5491
  return marked === children ? node : rebuildNode(node, [...marked]);
5415
5492
  });
5416
- const mark = (from, step, { keptFrom, count }, piece) => {
5493
+ const mark = (from, step, { keptFrom, count }, holders) => {
5417
5494
  let boundaries = 0;
5418
5495
  for (let index = from;; index += step) {
5419
5496
  const node = out[index];
@@ -5422,21 +5499,21 @@ const withKeptCutsFromChanges = (nodes, writtenOnChange) => {
5422
5499
  if (boundaries > count) return;
5423
5500
  out[index] = withKeptCuts(node, {
5424
5501
  keptFrom,
5425
- piece
5502
+ holders
5426
5503
  });
5427
5504
  }
5428
5505
  };
5429
5506
  for (const [index, node] of nodes.entries()) {
5430
5507
  const joins = isTrackedWrapper(node) ? node.resolutionJoins : void 0;
5431
5508
  const kept = joins === void 0 ? void 0 : writtenOnChange(joins)?.change;
5432
- if (joins === void 0 || kept === void 0) continue;
5509
+ if (joins === void 0 || kept === void 0 || !isTrackedWrapper(node)) continue;
5433
5510
  const count = kept.keptCount ?? Number.POSITIVE_INFINITY;
5434
5511
  const named = {
5435
5512
  keptFrom: kept.keptFrom,
5436
5513
  count
5437
5514
  };
5438
- if (joins.before > 0) mark(index - 1, -1, named, "after");
5439
- if (joins.after > 0) mark(index + 1, 1, named, "before");
5515
+ if (joins.before > 0) mark(index - 1, -1, named, { after: node.info.id });
5516
+ if (joins.after > 0) mark(index + 1, 1, named, { before: node.info.id });
5440
5517
  }
5441
5518
  const keptGroups = (node) => {
5442
5519
  const joins = node !== void 0 && isTrackedWrapper(node) ? node.resolutionJoins : void 0;
@@ -5466,40 +5543,57 @@ const withKeptCutsFromChanges = (nodes, writtenOnChange) => {
5466
5543
  const afterSeams = new Set(after.map(seamOf));
5467
5544
  const across = before.find((group) => afterSeams.has(seamOf(group)));
5468
5545
  const group = across ?? after.at(0) ?? before.at(0);
5546
+ const beforeId = changeAtEdge(start === 0 ? void 0 : out[start - 1], "end");
5547
+ const afterId = changeAtEdge(out[end], "start");
5469
5548
  if (group !== void 0) {
5470
- let piece = "before";
5471
- if (across !== void 0) piece = "both";
5472
- else if (after.includes(group)) piece = "after";
5473
5549
  const cut = {
5474
5550
  keptFrom: group.keptFrom,
5475
5551
  count: group.keptCount ?? Number.POSITIVE_INFINITY
5476
5552
  };
5477
- if (piece === "after") mark(end - 1, -1, cut, piece);
5478
- else mark(start, 1, cut, piece);
5553
+ if (across !== void 0 && beforeId !== void 0 && afterId !== void 0) mark(start, 1, cut, {
5554
+ before: beforeId,
5555
+ after: afterId
5556
+ });
5557
+ else if (after.includes(group) && afterId !== void 0) mark(end - 1, -1, cut, { after: afterId });
5558
+ else if (beforeId !== void 0) mark(start, 1, cut, { before: beforeId });
5479
5559
  }
5480
5560
  start = end;
5481
5561
  }
5482
5562
  return out.every((node, index) => node === nodes[index]) ? nodes : out;
5483
5563
  };
5484
5564
  /** {@link withKeptCutsFromChanges} over a paragraph's content. */
5485
- const paragraphKeptCutsFromChanges = (content, writtenOnChange) => asParagraphContent(withKeptCutsFromChanges(content, writtenOnChange));
5565
+ const paragraphKeptCutsFromChanges = (content, writtenOnChange, legacyPiece) => {
5566
+ const cuts = withKeptCutsFromChanges(content, writtenOnChange);
5567
+ return asParagraphContent(legacyPiece === void 0 ? cuts : settleKeptCuts(cuts, { legacyPiece }));
5568
+ };
5486
5569
  /** How many range boundaries a kept marker `node` stands for. */
5487
5570
  const keptBoundaryCount$1 = (node) => node.type === "deletion" ? node.content.reduce((sum, child) => sum + keptBoundaryCount$1(child), 0) : 1;
5488
- const KEPT_CUT_PIECES = {
5571
+ const KEPT_CUT_HOLDER_FIELDS = {
5489
5572
  before: true,
5490
5573
  after: true,
5491
- both: true
5574
+ scope: true
5492
5575
  };
5493
5576
  const KEPT_CUT_FIELDS = {
5494
5577
  keptFrom: true,
5495
- piece: true
5578
+ holders: true
5579
+ };
5580
+ const isRevisionId = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2147483647;
5581
+ /** Whether `holders` names a revision on one side of a marker, or both. */
5582
+ const isKeptCutHolders = (holders) => {
5583
+ if (typeof holders !== "object" || holders === null || Array.isArray(holders)) return false;
5584
+ const keys = Object.keys(holders);
5585
+ return (Object.hasOwn(holders, "before") || Object.hasOwn(holders, "after")) && keys.every((key) => {
5586
+ if (!Object.hasOwn(KEPT_CUT_HOLDER_FIELDS, key)) return false;
5587
+ const value = Reflect.get(holders, key);
5588
+ return key === "scope" ? value === "seam" : isRevisionId(value);
5589
+ });
5496
5590
  };
5497
5591
  /**
5498
5592
  * Whether `cut` is a well-formed kept cut: exactly its fields, kept from a
5499
- * dated revision, naming one side as its piece if any. The contract and the
5500
- * review history reader share it.
5593
+ * dated revision, naming the revisions holding its piece if any. The
5594
+ * contract and the review history reader share it.
5501
5595
  */
5502
- const isKeptCut = (cut) => typeof cut === "object" && cut !== null && !Array.isArray(cut) && Object.keys(cut).every((key) => Object.hasOwn(KEPT_CUT_FIELDS, key)) && "keptFrom" in cut && typeof cut.keptFrom === "string" && (!("piece" in cut) || typeof cut.piece === "string" && Object.hasOwn(KEPT_CUT_PIECES, cut.piece));
5596
+ const isKeptCut = (cut) => typeof cut === "object" && cut !== null && !Array.isArray(cut) && Object.keys(cut).every((key) => Object.hasOwn(KEPT_CUT_FIELDS, key)) && "keptFrom" in cut && typeof cut.keptFrom === "string" && (!("holders" in cut) || isKeptCutHolders(cut.holders));
5503
5597
  const hasValidKeptCuts = (nodes) => nodes.every((node) => {
5504
5598
  if (carriesKeptCut(node) && node.keptCut !== void 0) return isKeptCut(node.keptCut);
5505
5599
  return hasValidKeptCuts(childNodes(node) ?? []);
@@ -5517,29 +5611,29 @@ const hasValidKeptCutsInBlocks = (blocks) => blocks.every((block) => {
5517
5611
  default: return !("keptCut" in block);
5518
5612
  }
5519
5613
  });
5520
- /**
5521
- * `node` with every marker it stands for naming a side as its cut's piece
5522
- * keeping that name only where `facing` says the change that took its seam
5523
- * still stands, keeping what the resolution recorded per marker.
5524
- */
5525
- const withKeptCutPiecesFacing = (node, facing, known) => changeStandingMarkers(node, keepingRecord((marker) => {
5526
- if (!carriesKeptCut(marker) || marker.keptCut?.piece === void 0) return marker;
5527
- if (facing[marker.keptCut.piece]) return marker;
5528
- const { piece: _consumed, ...cut } = marker.keptCut;
5529
- return Object.assign({}, marker, { keptCut: cut });
5530
- }, known));
5531
- /**
5532
- * Whether a pending change stands at `node`'s `edge`: the node itself, or
5533
- * one at that edge of the records it holds, whose resolution can still let
5534
- * the pieces across from it meet.
5535
- */
5536
- const pendingAtEdge = (node, edge) => {
5537
- if (node === void 0) return false;
5538
- if (isTrackedWrapper(node)) return true;
5614
+ /** The id of the pending change at a record edge. */
5615
+ const changeAtEdge = (node, edge) => {
5616
+ if (node === void 0) return void 0;
5617
+ if (isTrackedWrapper(node)) return node.info.id;
5539
5618
  const children = childNodes(node);
5540
- if (children === void 0) return false;
5541
- return pendingAtEdge(edge === "start" ? children.at(0) : children.at(-1), edge);
5542
- };
5619
+ return changeAtEdge(edge === "start" ? children?.at(0) : children?.at(-1), edge);
5620
+ };
5621
+ /** Keep each holder only while that revision is still at the facing edge. */
5622
+ const withFacingHolders = (node, facing, known) => changeStandingMarkers(node, keepingRecord((marker) => {
5623
+ if (!carriesKeptCut(marker)) return marker;
5624
+ const cut = marker.keptCut;
5625
+ const holders = cut?.holders;
5626
+ if (cut === void 0 || holders === void 0) return marker;
5627
+ const keep = (side) => facing[side] === KEPT_CUT_EDGES.UNSETTLED || facing[side] === holders[side];
5628
+ const before = keep("before") ? holders.before : void 0;
5629
+ const after = keep("after") ? holders.after : void 0;
5630
+ if (before === holders.before && after === holders.after) return marker;
5631
+ const facingHolders = withHolderScope(keptCutHolders({
5632
+ before,
5633
+ after
5634
+ }), holders.scope);
5635
+ return Object.assign({}, marker, { keptCut: cutHeldBy(cut, facingHolders) });
5636
+ }, known));
5543
5637
  /** Whether the piece a marker names goes with the records on the sides `gone`. */
5544
5638
  const pieceGoes = (piece, gone) => {
5545
5639
  switch (piece) {
@@ -5557,9 +5651,9 @@ const pieceGoes = (piece, gone) => {
5557
5651
  * leaves them.
5558
5652
  */
5559
5653
  const withKeptCutBesideRemoved = (node, { gone, known }) => changeStandingMarkers(node, keepingRecord((marker) => {
5560
- if (!carriesKeptCut(marker) || marker.keptCut?.piece === void 0) return marker;
5561
- const { piece, ...cut } = marker.keptCut;
5562
- return pieceGoes(piece, gone) ? Object.assign({}, marker, { keptCut: cut }) : marker;
5654
+ if (!carriesKeptCut(marker) || marker.keptCut === void 0) return marker;
5655
+ const piece = pieceOf(marker.keptCut.holders);
5656
+ return piece !== void 0 && pieceGoes(piece, gone) ? Object.assign({}, marker, { keptCut: cutHeldBy(marker.keptCut, void 0) }) : marker;
5563
5657
  }, known));
5564
5658
  /** What meets a list's edge from outside, as kept cuts at that edge read it. */
5565
5659
  const KEPT_CUT_EDGES = Object.freeze({
@@ -5571,33 +5665,12 @@ const KEPT_CUT_EDGES = Object.freeze({
5571
5665
  * seam, so it holds no piece a marker names.
5572
5666
  */
5573
5667
  PENDING_MARK: "pendingMark",
5574
- /** A pending tracked change, which can hold a piece a marker names. */
5575
- PENDING_CHANGE: "pendingChange",
5576
5668
  /**
5577
5669
  * Not known yet: the edge of a nested list, which the paragraph's own
5578
5670
  * settlement reads once the joins stand. Its markers keep what they have.
5579
5671
  */
5580
5672
  UNSETTLED: "unsettled"
5581
5673
  });
5582
- /** Whether a cut at an edge waits there, and whether a piece named there stands. */
5583
- const EDGE_READING = {
5584
- nothing: {
5585
- waits: false,
5586
- holdsPiece: false
5587
- },
5588
- pendingMark: {
5589
- waits: true,
5590
- holdsPiece: false
5591
- },
5592
- pendingChange: {
5593
- waits: true,
5594
- holdsPiece: true
5595
- },
5596
- unsettled: {
5597
- waits: true,
5598
- holdsPiece: true
5599
- }
5600
- };
5601
5674
  /**
5602
5675
  * `nodes` with the kept cuts that wait on nothing cleared, at every depth: a
5603
5676
  * run of kept markers records its cut only while a pending change stands
@@ -5606,12 +5679,12 @@ const EDGE_READING = {
5606
5679
  * holding the run is no such change; resolving it keeps them again.
5607
5680
  * Whichever order resolved the rest, no cut outlives that change.
5608
5681
  */
5609
- const settleKeptCuts = (nodes, { known = /* @__PURE__ */ new WeakMap(), rebuilt, outside = {
5682
+ const settleKeptCuts = (nodes, { known = /* @__PURE__ */ new WeakMap(), legacyPiece, rebuilt, outside = {
5610
5683
  start: KEPT_CUT_EDGES.NOTHING,
5611
5684
  end: KEPT_CUT_EDGES.NOTHING
5612
5685
  } } = {}) => {
5613
5686
  let out;
5614
- const edgeOf = (node, edge) => pendingAtEdge(node, edge) ? KEPT_CUT_EDGES.PENDING_CHANGE : KEPT_CUT_EDGES.NOTHING;
5687
+ const edgeOf = (node, edge) => changeAtEdge(node, edge) ?? KEPT_CUT_EDGES.NOTHING;
5615
5688
  const pendingBefore = (index) => index === 0 ? outside.start : edgeOf(nodes[index - 1], "end");
5616
5689
  const pendingAfter = (index) => index === nodes.length - 1 ? outside.end : edgeOf(nodes[index + 1], "start");
5617
5690
  let start = 0;
@@ -5622,6 +5695,7 @@ const settleKeptCuts = (nodes, { known = /* @__PURE__ */ new WeakMap(), rebuilt,
5622
5695
  const children = childNodes(first);
5623
5696
  const settled = children === void 0 ? children : settleKeptCuts(children, {
5624
5697
  known,
5698
+ ...legacyPiece === void 0 ? {} : { legacyPiece },
5625
5699
  ...rebuilt === void 0 ? {} : { rebuilt },
5626
5700
  outside: {
5627
5701
  start: pendingBefore(start),
@@ -5643,16 +5717,25 @@ const settleKeptCuts = (nodes, { known = /* @__PURE__ */ new WeakMap(), rebuilt,
5643
5717
  if (node === void 0 || !isKeptBoundaryCarrier(node)) break;
5644
5718
  }
5645
5719
  const run = nodes.slice(start, end);
5646
- const before = EDGE_READING[pendingBefore(start)];
5647
- const after = EDGE_READING[pendingAfter(end - 1)];
5648
- const waiting = run.some((node) => node.type === "deletion") || before.waits || after.waits;
5649
- const facing = {
5650
- before: before.holdsPiece,
5651
- after: after.holdsPiece,
5652
- both: before.holdsPiece || after.holdsPiece
5653
- };
5720
+ const before = pendingBefore(start);
5721
+ const after = pendingAfter(end - 1);
5722
+ const waiting = run.some((node) => node.type === "deletion") || before !== KEPT_CUT_EDGES.NOTHING || after !== KEPT_CUT_EDGES.NOTHING;
5654
5723
  for (const [offset, node] of run.entries()) {
5655
- const settled = waiting ? withKeptCutPiecesFacing(node, facing, known) : withoutKeptCutsRecorded(node, known);
5724
+ let settled;
5725
+ if (legacyPiece === void 0) settled = waiting ? withFacingHolders(node, {
5726
+ before,
5727
+ after
5728
+ }, known) : withoutKeptCutsRecorded(node, known);
5729
+ else settled = changeStandingMarkers(node, (marker) => {
5730
+ if (!carriesKeptCut(marker) || marker.keptCut === void 0) return marker;
5731
+ const piece = legacyPiece(marker.keptCut);
5732
+ if (piece === void 0) return marker;
5733
+ const holders = keptCutHolders({
5734
+ before: piece !== "after" && typeof before === "number" ? before : void 0,
5735
+ after: piece !== "before" && typeof after === "number" ? after : void 0
5736
+ });
5737
+ return withKeptCut(marker, cutHeldBy(marker.keptCut, withHolderScope(holders, piece === "both" ? "seam" : void 0)));
5738
+ });
5656
5739
  if (settled === node) continue;
5657
5740
  out ??= [...nodes];
5658
5741
  out[start + offset] = settled;
@@ -7170,18 +7253,44 @@ const coveredCommentIds = (document) => {
7170
7253
  }
7171
7254
  return covered;
7172
7255
  };
7256
+ /** Read coverage once per anchor kind for the requested roots in a document. */
7257
+ const commentExhaustionIn = (document) => {
7258
+ let covered;
7259
+ let anchored;
7260
+ return ({ anchorKind, id, parentId }) => {
7261
+ if (parentId !== void 0) return false;
7262
+ switch (anchorKind) {
7263
+ case "range":
7264
+ covered ??= coveredCommentIds(document);
7265
+ return !covered.has(id);
7266
+ case "point":
7267
+ anchored ??= sourceCommentAnchorIds(document);
7268
+ return !anchored.has(id);
7269
+ default: return false;
7270
+ }
7271
+ };
7272
+ };
7173
7273
  /** Whether a known range lost its content or a known point lost its anchor. */
7174
7274
  const isCommentExhausted = (input) => {
7175
7275
  if (input.type === "coverage") return input.anchorKind === "range" && !input.survivingNonCarrierContent;
7176
7276
  const { document, id } = input;
7177
7277
  const comment = document.package.document.comments?.find((entry) => entry.id === id);
7178
- if (comment === void 0 || comment.parentId !== void 0) return false;
7179
- if (comment.anchorKind === "point") return !sourceCommentAnchorIds(document).has(id);
7180
- return isCommentExhausted({
7181
- type: "coverage",
7182
- anchorKind: comment.anchorKind,
7183
- survivingNonCarrierContent: coveredCommentIds(document).has(id)
7184
- });
7278
+ return comment !== void 0 && commentExhaustionIn(document)(comment);
7279
+ };
7280
+ /** Root comment threads that still had coverage before an edit consumed it. */
7281
+ const newlyExhaustedCommentIds = (before, after) => {
7282
+ const previous = before.package.document.comments ?? [];
7283
+ if (previous.length === 0) return [];
7284
+ const current = new Map((after.package.document.comments ?? []).map((comment) => [comment.id, comment]));
7285
+ const wasExhausted = commentExhaustionIn(before);
7286
+ const isExhausted = commentExhaustionIn(after);
7287
+ const exhausted = [];
7288
+ for (const source of previous) {
7289
+ if (source.parentId !== void 0) continue;
7290
+ const target = current.get(source.id);
7291
+ if (target !== void 0 && isExhausted(target) && !wasExhausted(source)) exhausted.push(source.id);
7292
+ }
7293
+ return exhausted;
7185
7294
  };
7186
7295
  /**
7187
7296
  * Hyperlinks that held nothing but markers of the threads a retirement
@@ -8665,7 +8774,7 @@ const freshenIdentities = ({ before, after, newIds, usedElsewhere, inserted = /*
8665
8774
  kind: "fresh",
8666
8775
  paragraphs: bindDeferredIdentities({
8667
8776
  before: after,
8668
- after: rebindPropertyChangeOwners({
8777
+ after: rebindParagraphMarkReferences({
8669
8778
  source: before,
8670
8779
  draft: after,
8671
8780
  freshened: rebindRetainedIdentities({
@@ -8681,24 +8790,51 @@ const freshenIdentities = ({ before, after, newIds, usedElsewhere, inserted = /*
8681
8790
  };
8682
8791
  };
8683
8792
  /**
8684
- * A property change that belongs to a paragraph-mark deletion
8685
- * (`resolvesWith`) follows that deletion to the id freshening gave it.
8793
+ * Review provenance that refers to a paragraph mark follows its freshened
8794
+ * identity when the referring record is copied with it.
8686
8795
  */
8687
- const rebindPropertyChangeOwners = ({ source, draft, freshened, elsewhere }) => {
8796
+ const rebindParagraphMarkReferences = ({ source, draft, freshened, elsewhere }) => {
8688
8797
  const ownerInfo = ({ pPrMark }) => pPrMark?.kind === "del" ? pPrMark.info : pPrMark?.deletion?.info;
8689
8798
  const kept = /* @__PURE__ */ new Set();
8690
8799
  const moved = /* @__PURE__ */ new Map();
8800
+ const movedMarks = /* @__PURE__ */ new Map();
8801
+ const keptMarks = /* @__PURE__ */ new Set();
8691
8802
  for (const [index, paragraph] of draft.entries()) {
8803
+ const fresh = freshened.at(index) ?? panic("Freshening preserves each paragraph.");
8804
+ const oldId = paragraph.pPrMark?.info.id;
8805
+ const freshId = fresh.pPrMark?.info.id;
8806
+ if (oldId !== void 0 && freshId !== void 0) {
8807
+ if (oldId === freshId) keptMarks.add(oldId);
8808
+ else movedMarks.set(oldId, freshId);
8809
+ }
8692
8810
  const old = ownerInfo(paragraph);
8693
- const next = ownerInfo(freshened.at(index) ?? panic("Freshening preserves each paragraph."));
8811
+ const next = ownerInfo(fresh);
8694
8812
  if (old === void 0 || next === void 0) continue;
8695
8813
  if (old.id === next.id) kept.add(old.id);
8696
8814
  else moved.set(old.id, next.id);
8697
8815
  }
8698
- if (moved.size === 0) return freshened;
8816
+ if (moved.size === 0 && movedMarks.size === 0) return freshened;
8699
8817
  const previousOwners = /* @__PURE__ */ new Map();
8700
- for (const paragraph of source) for (const { info, resolvesWith } of paragraph.propertyChanges ?? []) if (resolvesWith !== void 0) previousOwners.set(info.id, resolvesWith);
8701
- return freshened.map((paragraph) => {
8818
+ const previousTakeovers = /* @__PURE__ */ new Map();
8819
+ for (const paragraph of source) {
8820
+ const mark = paragraph.pPrMark;
8821
+ if (mark?.takenOverMark !== void 0) previousTakeovers.set(mark.info.id, mark.takenOverMark);
8822
+ for (const { info, resolvesWith } of paragraph.propertyChanges ?? []) if (resolvesWith !== void 0) previousOwners.set(info.id, resolvesWith);
8823
+ }
8824
+ return freshened.map((fresh) => {
8825
+ const mark = fresh.pPrMark;
8826
+ const target = mark?.takenOverMark;
8827
+ const targetId = target === void 0 ? void 0 : movedMarks.get(target);
8828
+ const paragraph = mark === void 0 || target === void 0 || targetId === void 0 || previousTakeovers.get(mark.info.id) === target && (keptMarks.has(target) || elsewhere.has(slotKey({
8829
+ space: IDENTITY_SPACES.REVISION,
8830
+ id: target
8831
+ }))) ? fresh : {
8832
+ ...fresh,
8833
+ pPrMark: {
8834
+ ...mark,
8835
+ takenOverMark: targetId
8836
+ }
8837
+ };
8702
8838
  if (paragraph.propertyChanges === void 0) return paragraph;
8703
8839
  let changed = false;
8704
8840
  const propertyChanges = paragraph.propertyChanges.map((change) => {
@@ -9120,15 +9256,7 @@ const paragraphMarkOutcome = ({ follows, holdsContent, markWasAdded, containerSt
9120
9256
  * that still covered something `before` it.
9121
9257
  */
9122
9258
  const withExhaustedCommentsRetired = ({ before, edit, applyOps }) => {
9123
- const exhaustedCommentIds = (before.package.document.comments ?? []).flatMap(({ id, parentId }) => parentId === void 0 && !isCommentExhausted({
9124
- type: "document",
9125
- document: before,
9126
- id
9127
- }) && isCommentExhausted({
9128
- type: "document",
9129
- document: edit.document,
9130
- id
9131
- }) ? [id] : []);
9259
+ const exhaustedCommentIds = newlyExhaustedCommentIds(before, edit.document);
9132
9260
  if (exhaustedCommentIds.length === 0) return Result.ok({
9133
9261
  edit,
9134
9262
  modified: []
@@ -9193,6 +9321,19 @@ const breakRetiredBefore = (list, index) => {
9193
9321
  return candidate !== index - 1 && list[candidate]?.type === "paragraph" ? candidate : index - 1;
9194
9322
  };
9195
9323
  /**
9324
+ * A table pending deletion still blocks a tracked paragraph join, but it
9325
+ * does not supply properties to the closing paragraph. Look past such
9326
+ * tables for the paragraph that supplies them in the accepted document.
9327
+ */
9328
+ const terminalPropertySource = (list, index) => {
9329
+ let candidate = index;
9330
+ for (;;) {
9331
+ const block = list[candidate];
9332
+ if (block?.type !== "table" || block.rows.length === 0 || !block.rows.every((row) => row.structuralChange?.type === "tableRowDeletion")) return candidate;
9333
+ candidate = breakRetiredBefore(list, candidate);
9334
+ }
9335
+ };
9336
+ /**
9196
9337
  * Whether accepting leaves nothing of `blocks`, a container's last blocks:
9197
9338
  * paragraphs that keep no content once accepted, each before the last with
9198
9339
  * its break pending deletion, and no section break among them.
@@ -9219,6 +9360,61 @@ const unchanged$3 = (document) => Result.ok({
9219
9360
  removed: []
9220
9361
  }
9221
9362
  });
9363
+ /**
9364
+ * The container's last paragraph, right after `last`, when its pending
9365
+ * deletion took `last`'s mark, along with the property change that belongs
9366
+ * to that mark's deletion.
9367
+ */
9368
+ const finalDeletionTakenFrom = ({ list, following, followerIndex, last }) => {
9369
+ const mark = last.pPrMark;
9370
+ if (following?.type !== "paragraph" || mark?.kind !== "del" || blockFollower(list, followerIndex).block !== void 0 || paragraphHoldsContentOnceAccepted(following)) return void 0;
9371
+ const change = following.propertyChanges?.find(({ resolvesWith }) => resolvesWith === mark.info.id);
9372
+ return change === void 0 ? void 0 : {
9373
+ final: following,
9374
+ change
9375
+ };
9376
+ };
9377
+ /**
9378
+ * The tracked deletion of `op`'s paragraphs and `final` together, once the
9379
+ * property change `final`'s deletion gave it is rejected. The records the
9380
+ * earlier deletion made on the marks and words stay as they are. A
9381
+ * suggestion takes back no change of another suggestion or an ordinary one,
9382
+ * as it folds into none.
9383
+ */
9384
+ const withFinalDeletionTakenBack = ({ document, op, applyOps, revision, final, change }) => {
9385
+ const refuse = (reason, message) => Result.err(new DocumentOpRefusal({
9386
+ reason,
9387
+ message,
9388
+ opType: op.type
9389
+ }));
9390
+ if (final.paraId === void 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "The last paragraph has no id to delete it by.");
9391
+ if (takesOverOtherSuggestion(change, revision)) return refuse(DOCUMENT_OP_REFUSAL_REASONS.PENDING_PARAGRAPH_PROPERTY_CHANGE, "A suggestion cannot take back another pending paragraph property change.");
9392
+ const takenBack = applyOps(document, [{
9393
+ type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
9394
+ story: op.story,
9395
+ revisionIds: [change.info.id],
9396
+ decision: REVISION_DECISIONS.REJECT
9397
+ }]);
9398
+ if (takenBack.isErr()) return refuse(takenBack.error.reason, takenBack.error.message);
9399
+ const deleted = deleteBlocks({
9400
+ document: takenBack.value.document,
9401
+ op: {
9402
+ ...op,
9403
+ blockIds: [...op.blockIds, final.paraId]
9404
+ },
9405
+ applyOps
9406
+ });
9407
+ if (deleted.isErr()) return deleted;
9408
+ const { touched } = deleted.value;
9409
+ return Result.ok({
9410
+ ...deleted.value,
9411
+ inverse: [...deleted.value.inverse, ...takenBack.value.inverse],
9412
+ touched: {
9413
+ ...touched,
9414
+ modified: [.../* @__PURE__ */ new Set([...touched.modified, ...takenBack.value.touched.modified])]
9415
+ }
9416
+ });
9417
+ };
9222
9418
  const deleteBlocks = ({ document, op, applyOps }) => {
9223
9419
  const refuse = (reason, message) => Result.err(new DocumentOpRefusal({
9224
9420
  reason,
@@ -9285,14 +9481,15 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9285
9481
  }
9286
9482
  });
9287
9483
  }
9288
- const broken = list[first.index - 1];
9289
- const takenOver = owner !== void 0 && terminal && op.move !== true && broken?.type === "paragraph" ? takenOverBreakRecords({
9484
+ const blockBefore = list[first.index - 1];
9485
+ const broken = blockBefore?.type === "paragraph" ? blockBefore : void 0;
9486
+ const takenOver = owner !== void 0 && terminal && op.move !== true && broken !== void 0 ? takenOverBreakRecords({
9290
9487
  broken,
9291
9488
  paragraphs: found.map(({ paragraph }) => paragraph),
9292
9489
  owner,
9293
9490
  held
9294
9491
  }) : void 0;
9295
- if (takenOver !== void 0) {
9492
+ if (takenOver !== void 0 && broken !== void 0) {
9296
9493
  const rejected = applyOps(document, [{
9297
9494
  type: DOCUMENT_OP_TYPES.RESOLVE_REVISION,
9298
9495
  story: op.story,
@@ -9301,12 +9498,44 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9301
9498
  }]);
9302
9499
  if (rejected.isErr()) return refuse(rejected.error.reason, rejected.error.message);
9303
9500
  const { document: retracted, inverse, touched } = rejected.value;
9304
- return Result.ok({
9501
+ if ((broken.propertyChanges?.length ?? 0) === 0) return Result.ok({
9305
9502
  document: retracted,
9306
9503
  inverse,
9307
9504
  touched
9308
9505
  });
9506
+ const survivor = storyParagraphs(storyBody$1(retracted, op.story)).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(broken.paraId ?? ""))?.paragraph ?? panic("A taken-back insertion lost the paragraph it broke.");
9507
+ const { pPrMark: _addedMark, ...restyle } = reviewFieldsOf(broken);
9508
+ const kept = applyOps(retracted, [{
9509
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
9510
+ story: op.story,
9511
+ blockId: survivor.paraId ?? "",
9512
+ expected: reviewFieldsOf(survivor),
9513
+ review: survivor.pPrMark === void 0 ? restyle : {
9514
+ ...restyle,
9515
+ pPrMark: survivor.pPrMark
9516
+ }
9517
+ }]);
9518
+ if (kept.isErr()) return refuse(kept.error.reason, kept.error.message);
9519
+ return Result.ok({
9520
+ document: kept.value.document,
9521
+ inverse: [...kept.value.inverse, ...inverse],
9522
+ touched
9523
+ });
9309
9524
  }
9525
+ const takenFinal = finalDeletionTakenFrom({
9526
+ list,
9527
+ following,
9528
+ followerIndex,
9529
+ last: last.paragraph
9530
+ });
9531
+ const retiresBreakBefore = list[breakRetiredBefore(list, first.index)]?.type === "paragraph";
9532
+ if (op.revision !== void 0 && op.move !== true && takenFinal !== void 0 && retiresBreakBefore) return withFinalDeletionTakenBack({
9533
+ document,
9534
+ op,
9535
+ applyOps,
9536
+ revision: op.revision,
9537
+ ...takenFinal
9538
+ });
9310
9539
  const tableBoundary = following?.type === "table" ? paragraphTableRunInBoundary(last.paragraph, following) : void 0;
9311
9540
  const emptiedBeforeBlockedTable = tableBoundary?.type === "blocked" && (tableBoundary.reason === "review" || tableBoundary.reason === "section") && (endsWithParagraph || blockListEndsInParagraph(list));
9312
9541
  const trackedBeforeTable = op.revision !== void 0 && tableBoundary !== void 0 && (markBeforeTableResolves({
@@ -9368,8 +9597,10 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9368
9597
  ...sectionBoundaries
9369
9598
  };
9370
9599
  const finalReview = reviewFieldsOf(last.paragraph);
9371
- if (previous !== void 0 && givesProperties(list, previousIndex)) {
9372
- const formatting = withMarkFormatting(paragraphPropertiesOf(previous.formatting), last.paragraph.formatting);
9600
+ const formattingSourceIndex = terminal && op.revision !== void 0 ? terminalPropertySource(list, previousIndex) : previousIndex;
9601
+ const formattingSource = list[formattingSourceIndex];
9602
+ if (terminal && formattingSource?.type === "paragraph" && givesProperties(list, formattingSourceIndex)) {
9603
+ const formatting = withMarkFormatting(paragraphPropertiesOf(formattingSource.formatting), last.paragraph.formatting);
9373
9604
  delete finalReview.formatting;
9374
9605
  if (formatting !== void 0) finalReview.formatting = formatting;
9375
9606
  }
@@ -9454,11 +9685,13 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9454
9685
  const retired = retiredIndex === void 0 ? void 0 : list[retiredIndex];
9455
9686
  const trailing = [];
9456
9687
  let endFormatting = survivor.formatting;
9688
+ let propertySource = previous;
9457
9689
  let reviewed = affected;
9458
9690
  if (retiredIndex !== void 0 && retired?.type === "paragraph") {
9459
9691
  const ending = lastBlockPastBoundaries(list);
9460
- if (ending?.type === "paragraph" && givesProperties(list, retiredIndex) && !sameParagraphProperties(retired.formatting, ending.formatting)) {
9692
+ if (ending?.type === "paragraph" && (ending.propertyChanges?.length ?? 0) === 0 && givesProperties(list, retiredIndex) && !sameParagraphProperties(retired.formatting, ending.formatting)) {
9461
9693
  trailing.push(...paragraphsIn$5(list.slice(last.index + 1)));
9694
+ propertySource = retired;
9462
9695
  endFormatting = withMarkFormatting(paragraphPropertiesOf(retired.formatting), ending.formatting);
9463
9696
  }
9464
9697
  reviewed = [
@@ -9471,11 +9704,10 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9471
9704
  const endsContainer = trailing.at(-1) ?? (terminal ? last.paragraph : null);
9472
9705
  const losesMark = (paragraph) => paragraph !== endsContainer && !trailing.includes(paragraph);
9473
9706
  const joinsNext = new Set(reviewed.filter((paragraph) => losesMark(paragraph) && paragraph.sectionProperties === void 0 && (paragraph !== last.paragraph || following?.type === "paragraph") && (paragraph.pPrMark?.kind === "ins" || paragraph.pPrMark?.kind === "moveTo") && isOwnRecord(paragraph.pPrMark.info, revision)));
9474
- const finalTakeover = following?.type === "paragraph" && blockFollower(list, followerIndex).block === void 0 && paragraphHoldsContent(following) && !paragraphHoldsContentOnceAccepted(following) && (following.propertyChanges?.length ?? 0) > 0 && sameParagraphProperties(paragraphPropertiesOf(following.formatting), paragraphPropertiesOf(last.paragraph.formatting));
9475
- const keepsDeletedMark = (paragraph) => (markPendingDeletion(paragraph) || paragraph.pPrMark?.deletion !== void 0) && !(op.move === true && selected.includes(paragraph)) && !(finalTakeover && paragraph === last.paragraph);
9707
+ const keepsDeletedMark = (paragraph) => (markPendingDeletion(paragraph) || paragraph.pPrMark?.deletion !== void 0) && !(op.move === true && selected.includes(paragraph));
9476
9708
  const before = list[first.index - 1];
9477
9709
  const beforeInsertedTable = !(before?.type === "paragraph" && markGoes(before)) && following?.type === "table" && following.rows.length > 0 && following.rows.every((row) => row.structuralChange?.type === "tableRowInsertion");
9478
- const deletesAddedMark = (paragraph) => op.move !== true && losesMark(paragraph) && !joinsNext.has(paragraph) && (paragraph.pPrMark?.kind === "ins" || paragraph.pPrMark?.kind === "moveTo") && paragraph.pPrMark.deletion === void 0 && (!isOwnRecord(paragraph.pPrMark.info, revision) || paragraph.sectionProperties !== void 0 || beforeInsertedTable && paragraph === last.paragraph) && !(finalTakeover && paragraph === last.paragraph);
9710
+ const deletesAddedMark = (paragraph) => op.move !== true && losesMark(paragraph) && !joinsNext.has(paragraph) && (paragraph.pPrMark?.kind === "ins" || paragraph.pPrMark?.kind === "moveTo") && paragraph.pPrMark.deletion === void 0 && (!isOwnRecord(paragraph.pPrMark.info, revision) || paragraph.sectionProperties !== void 0 || beforeInsertedTable && paragraph === last.paragraph);
9479
9711
  const overwrittenMark = reviewed.find((paragraph) => paragraph.pPrMark !== void 0 && !trailing.includes(paragraph) && !joinsNext.has(paragraph) && !keepsDeletedMark(paragraph) && !deletesAddedMark(paragraph))?.pPrMark;
9480
9712
  if (overwrittenMark !== void 0) return refuse(pendingParagraphMarkReason(overwrittenMark), "Deletion would overwrite a paragraph review record.");
9481
9713
  const selectedSet = new Set(selected);
@@ -9517,7 +9749,7 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9517
9749
  review.propertyChanges = [foldedParagraphPropertyChange({
9518
9750
  paragraph,
9519
9751
  formatting: endFormatting,
9520
- stamp: op.revision
9752
+ stamp: revision
9521
9753
  })];
9522
9754
  next = withReviewFields(next, review);
9523
9755
  }
@@ -9536,6 +9768,9 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9536
9768
  case "invalidId": return refuse(DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, "Paragraph deletion received an invalid revision id.");
9537
9769
  case "fresh": {
9538
9770
  const next = following?.type === "paragraph" && trailing.length === 0 ? [following] : [];
9771
+ const sourceMark = fresh.paragraphs.find((_, index) => reviewed[index] === propertySource)?.pPrMark;
9772
+ const ownerId = sourceMark?.kind === "del" ? sourceMark.info.id : sourceMark?.deletion?.info.id;
9773
+ const newOwner = ownerId !== void 0 && propertySource !== void 0 && !markGoes(propertySource) ? ownerId : void 0;
9539
9774
  const marked = [...fresh.paragraphs, ...next];
9540
9775
  const original = [...reviewed, ...next];
9541
9776
  const changed = [...tracked, ...next];
@@ -9545,8 +9780,16 @@ const deleteBlocks = ({ document, op, applyOps }) => {
9545
9780
  const modified = /* @__PURE__ */ new Set();
9546
9781
  let carried;
9547
9782
  let joining = [];
9548
- for (const [index, paragraph] of marked.entries()) {
9783
+ for (const [index, markedParagraph] of marked.entries()) {
9549
9784
  const source = original[index];
9785
+ const change = markedParagraph.propertyChanges?.at(0);
9786
+ const paragraph = newOwner !== void 0 && source === endsContainer && !source.propertyChanges?.length && change !== void 0 ? {
9787
+ ...markedParagraph,
9788
+ propertyChanges: [{
9789
+ ...change,
9790
+ resolvesWith: newOwner
9791
+ }]
9792
+ } : markedParagraph;
9550
9793
  if (source === following && standing.length > 0) {
9551
9794
  if (carried === void 0) blocks.push(...standing);
9552
9795
  else carried.push(...standing);
@@ -10160,6 +10403,19 @@ const storyLifecycleTouched = ({ before, after }) => {
10160
10403
  removed: [...oldIds].filter((id) => !newIds.has(id))
10161
10404
  };
10162
10405
  };
10406
+ /**
10407
+ * The operation that turns `before`'s story parts (body, sections, headers,
10408
+ * footers, notes and settings) into `after`'s, for an edit computed on the
10409
+ * whole document; it is stale-checked against `before`.
10410
+ */
10411
+ const storyPartsOpOf = ({ before, after }) => {
10412
+ const prior = changedParts(before, after, true);
10413
+ return {
10414
+ type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
10415
+ expected: cloneModel(prior),
10416
+ parts: cloneModel(captureStoryParts(after, prior))
10417
+ };
10418
+ };
10163
10419
  const storyLifecycleEdit = (before, after, op, semantic = false) => {
10164
10420
  const invalid = contractViolation(after);
10165
10421
  if (invalid) return Result.err(new DocumentOpRefusal({
@@ -10549,6 +10805,71 @@ const setContentControl = (document, op) => {
10549
10805
  }
10550
10806
  });
10551
10807
  };
10808
+ // src/ops/firstSurvivor.ts
10809
+ /**
10810
+ * The fields of a new mark that keeps the paragraph before it, the paragraph
10811
+ * after it taking over `former`, the mark the paragraph had: the tracked
10812
+ * mark at the end of a chain of such takeovers, none when it is no tracked
10813
+ * change.
10814
+ */
10815
+ const firstSurvivorFields = (former) => {
10816
+ const takenOverMark = former?.survivor === "first" ? former.takenOverMark : former?.info.id;
10817
+ return takenOverMark === void 0 ? { survivor: "first" } : {
10818
+ survivor: "first",
10819
+ takenOverMark
10820
+ };
10821
+ };
10822
+ /** The ids of the marks on `paragraphs`. */
10823
+ const markIdsOf = (paragraphs) => new Set(paragraphs.flatMap(({ pPrMark }) => pPrMark ? [pPrMark.info.id] : []));
10824
+ const located = (body, ids) => ids.flatMap((id) => {
10825
+ const at = findStoryParagraph(body, id);
10826
+ return at === void 0 ? [] : [at.paragraph];
10827
+ });
10828
+ /** Removing a break retires the keep-first rule that depended on it. */
10829
+ const storyReleases = ({ before, after, story, touched }) => {
10830
+ const holders = located(before, [...touched.modified, ...touched.removed]);
10831
+ if (holders.every(({ pPrMark }) => pPrMark === void 0)) return [];
10832
+ const kept = markIdsOf(located(after, [...touched.modified, ...touched.inserted]));
10833
+ const retired = /* @__PURE__ */ new Set();
10834
+ for (const holder of holders) {
10835
+ const id = holder.pPrMark?.info.id;
10836
+ if (id === void 0 || kept.has(id)) continue;
10837
+ retired.add(id);
10838
+ }
10839
+ if (retired.size === 0) return [];
10840
+ const releases = [];
10841
+ for (const { paragraph } of storyParagraphs(after)) {
10842
+ const mark = paragraph.pPrMark;
10843
+ const named = mark?.takenOverMark;
10844
+ if (mark === void 0 || named === void 0 || paragraph.paraId === void 0) continue;
10845
+ if (!retired.has(named)) continue;
10846
+ const { survivor: _survivor, takenOverMark: _named, ...rest } = mark;
10847
+ const expected = reviewFieldsOf(paragraph);
10848
+ releases.push({
10849
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
10850
+ story,
10851
+ blockId: paragraph.paraId,
10852
+ expected,
10853
+ review: {
10854
+ ...expected,
10855
+ pPrMark: rest
10856
+ }
10857
+ });
10858
+ }
10859
+ return releases;
10860
+ };
10861
+ /** Retire references to marks removed by an edit in its addressed story. */
10862
+ const takenOverMarkReleases = ({ before, after, touched, story }) => {
10863
+ if (story === void 0 || touched.modified.length === 0 && touched.removed.length === 0) return [];
10864
+ const was = findStoryBody$1(before, story);
10865
+ const is = findStoryBody$1(after, story);
10866
+ return was === void 0 || is === void 0 || was === is ? [] : storyReleases({
10867
+ before: was,
10868
+ after: is,
10869
+ story,
10870
+ touched
10871
+ });
10872
+ };
10552
10873
  // src/ops/paragraphPrimitive.ts
10553
10874
  const refusal$5 = (op, reason, message) => new DocumentOpRefusal({
10554
10875
  message,
@@ -10945,12 +11266,14 @@ const trackedParagraphReplacement = ({ op, revision, source, anchor, takesOverMa
10945
11266
  }));
10946
11267
  if (identityKeysIn(op.blocks).length > 0) return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Tracked insertion of identified review or content-control records is unsupported.");
10947
11268
  const markKind = op.move === true ? "moveTo" : "ins";
11269
+ const former = takesOverMark ? source.pPrMark : void 0;
11270
+ const survivor = firstSurvivorFields(former);
10948
11271
  const marks = takenOverMarks({
10949
- mark: takesOverMark ? source.pPrMark : void 0,
11272
+ mark: former,
10950
11273
  added: {
10951
11274
  kind: markKind,
10952
11275
  info: stampInfo(revision),
10953
- survivor: "first"
11276
+ ...survivor
10954
11277
  }
10955
11278
  });
10956
11279
  if (marks.isErr()) return marks;
@@ -10970,7 +11293,7 @@ const trackedParagraphReplacement = ({ op, revision, source, anchor, takesOverMa
10970
11293
  pPrMark: {
10971
11294
  kind: markKind,
10972
11295
  info: stampInfo(revision),
10973
- ...takesOverMark ? { survivor: "first" } : {}
11296
+ ...takesOverMark ? survivor : {}
10974
11297
  }
10975
11298
  });
10976
11299
  continue;
@@ -11242,7 +11565,8 @@ const insertBlocks = ({ document, op, applyOps, validateBlockReplacement }) => {
11242
11565
  const following = list[location.index + 1];
11243
11566
  const before = op.at.type === "before" || following?.type === "paragraph";
11244
11567
  const anchor = op.at.type === "after" && following?.type === "paragraph" ? following : location.paragraph;
11245
- const takesOverMark = op.revision !== void 0 && !before && (following?.type !== "table" || !insertedMarkResolvesBeforeTable({
11568
+ const opensNextSection = !before && following !== void 0 && location.paragraph.sectionProperties !== void 0;
11569
+ const takesOverMark = op.revision !== void 0 && !before && !opensNextSection && (following?.type !== "table" || !insertedMarkResolvesBeforeTable({
11246
11570
  blocks: list,
11247
11571
  source: location.paragraph,
11248
11572
  index: location.index + 1,
@@ -11259,9 +11583,10 @@ const insertBlocks = ({ document, op, applyOps, validateBlockReplacement }) => {
11259
11583
  });
11260
11584
  const canonicalBlocks = op.blocks.map(canonicalizeInsertedParagraph);
11261
11585
  if (op.revision === void 0 && op.at.type === "after" && following?.type === "paragraph" && location.paragraph.pPrMark?.survivor === "first") return refuse(DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "Insertion after a pending paragraph mark needs its former formatting snapshot and revision ids.");
11586
+ const sectionBoundaries = opensNextSection ? { sectionBoundaries: SECTION_BOUNDARY_POLICIES.REPLACE } : {};
11262
11587
  const draft = {
11263
11588
  ...replacement(canonicalBlocks),
11264
- ...op.revision === void 0 && !before && following !== void 0 && anchor.sectionProperties !== void 0 ? { sectionBoundaries: SECTION_BOUNDARY_POLICIES.REPLACE } : {}
11589
+ ...sectionBoundaries
11265
11590
  };
11266
11591
  const direct = op.revision !== void 0 && op.story === OP_STORIES.MAIN && location.list.length === 0 && anchor.paraId !== void 0 && isParaId(anchor.paraId) && canSpliceMainBodyWithoutSectionRepair(body) && (document.package.footnotes?.length ?? 0) === 0 && (document.package.endnotes?.length ?? 0) === 0 && canonicalBlocks.every(({ pPrMark, propertyChanges, reviewCarrier, content }) => pPrMark === void 0 && propertyChanges === void 0 && reviewCarrier === void 0 && content.every((node) => node.type === "run" && node.content.every((leaf) => leaf.type === "text"))) ? validateBlockReplacement({
11267
11592
  document,
@@ -11298,7 +11623,10 @@ const insertBlocks = ({ document, op, applyOps, validateBlockReplacement }) => {
11298
11623
  usedElsewhere: () => packageIdentityKeyIndex(document.package)
11299
11624
  });
11300
11625
  if (prepared.isErr()) return prepared;
11301
- const tracked = applyOps(document, [prepared.value]);
11626
+ const tracked = applyOps(document, [{
11627
+ ...prepared.value,
11628
+ ...sectionBoundaries
11629
+ }]);
11302
11630
  return tracked.isErr() ? Result.err(new DocumentOpRefusal({
11303
11631
  reason: tracked.error.reason,
11304
11632
  message: tracked.error.message,
@@ -13417,6 +13745,108 @@ const withoutRepeatedMoveRangesIn = (document, contents) => {
13417
13745
  };
13418
13746
  /** {@link withoutRepeatedMoveRangesIn} of one content. */
13419
13747
  const withoutRepeatedMoveRanges = (document, content) => withoutRepeatedMoveRangesIn(document, [content]).at(0) ?? content;
13748
+ // src/ops/contiguousResolutionJoins.ts
13749
+ const plainFields = /* @__PURE__ */ new Set([
13750
+ "type",
13751
+ "paraId",
13752
+ "textId",
13753
+ "content",
13754
+ "pPrMark"
13755
+ ]);
13756
+ const isPlainTextContent = (paragraph) => {
13757
+ if (paragraph.content.length === 0) return true;
13758
+ const run = paragraph.content.at(0);
13759
+ if (paragraph.content.length !== 1 || run?.type !== "run" || Object.keys(run).some((key) => key !== "type" && key !== "content") || run.content.length !== 1) return false;
13760
+ const text = run.content.at(0);
13761
+ return text?.type === "text" && Object.keys(text).every((key) => key === "type" || key === "text");
13762
+ };
13763
+ const isPlainJoinParagraph = (paragraph) => paragraph.paraId !== void 0 && isParaId(paragraph.paraId) && isPlainTextContent(paragraph) && Object.keys(paragraph).every((key) => plainFields.has(key));
13764
+ /**
13765
+ * Each rejected inserted mark joins its paragraph into the already settled
13766
+ * suffix of its contiguous run. In a section-free pair with at most one plain
13767
+ * text payload, only those two paragraphs can affect the ordinary join plan.
13768
+ */
13769
+ const planContiguousResolutionJoins = ({ document, story, paragraphCount, indexOf, paragraphAt, joins, planPair }) => {
13770
+ const firstJoin = joins.at(0);
13771
+ const start = firstJoin === void 0 ? void 0 : indexOf(firstJoin.paraId);
13772
+ if (start === void 0) return {
13773
+ type: "fallback",
13774
+ reason: "joinShape"
13775
+ };
13776
+ const end = start + joins.length + 1;
13777
+ let survivor = paragraphAt(end - 1);
13778
+ if (story !== "main" || end > paragraphCount || survivor === void 0 || survivor.pPrMark !== void 0 || !isPlainJoinParagraph(survivor)) return {
13779
+ type: "fallback",
13780
+ reason: "joinShape"
13781
+ };
13782
+ const effects = [];
13783
+ const receiverEffects = [];
13784
+ for (let i = joins.length - 1; i >= 0; i--) {
13785
+ const first = paragraphAt(start + i);
13786
+ const join = joins[i];
13787
+ if (first === void 0 || !isPlainJoinParagraph(first) || first.content.length > 0 && survivor.content.length > 0 || join === void 0 || join.story !== story || join.op.decision !== REVISION_DECISIONS.REJECT || !join.added || join.depth !== void 0 || join.paraId !== first.paraId || first.pPrMark?.kind !== "ins" || first.pPrMark.info.id !== join.revisionId || first.pPrMark.deletion !== void 0 || first.pPrMark.resolutionJoin !== void 0) return {
13788
+ type: "fallback",
13789
+ reason: "joinShape"
13790
+ };
13791
+ const second = survivor;
13792
+ const planned = planPair({
13793
+ join,
13794
+ first,
13795
+ second
13796
+ });
13797
+ if (planned.isErr()) return {
13798
+ type: "fallback",
13799
+ reason: "joinPlan"
13800
+ };
13801
+ const plan = planned.value;
13802
+ const op = plan.ops.at(0);
13803
+ const receiver = plan.receiverEffects.at(0);
13804
+ if (plan.endsControl !== void 0 || plan.ops.length !== 1 || op?.type !== DOCUMENT_OP_TYPES.REPLACE_BLOCKS || op.story !== story || op.sectionView !== void 0 || op.sectionBoundaries !== void 0 || op.expected.length !== 2 || op.expected[0] !== first || op.expected[1] !== second || op.blocks.length !== 1 || plan.receiverEffects.length !== 1 || receiver?.type !== "paragraph-join" || receiver.receiver !== second) return {
13805
+ type: "fallback",
13806
+ reason: "joinPlan"
13807
+ };
13808
+ const next = op.blocks[0];
13809
+ if (next === void 0 || next.pPrMark !== void 0 || !isPlainJoinParagraph(next) || !structurallyEqual(next.content, first.content.length === 0 ? second.content : first.content) || next.paraId !== first.paraId && next.paraId !== second.paraId) return {
13810
+ type: "fallback",
13811
+ reason: "joinPlan"
13812
+ };
13813
+ if (validateBlockReplacement({
13814
+ document,
13815
+ op,
13816
+ before: op.expected
13817
+ }).isErr()) return {
13818
+ type: "fallback",
13819
+ reason: "joinValidation"
13820
+ };
13821
+ const survivorId = next.paraId;
13822
+ const source = next.paraId === first.paraId ? first : second;
13823
+ if (next !== source) transferParagraphPropertySnapshot({
13824
+ source,
13825
+ target: next
13826
+ });
13827
+ const effect = nonemptyBlockReplacementEffects(op, op.expected);
13828
+ effects.push({
13829
+ inverse: effect.inverse.map(captureDocumentOp),
13830
+ touched: {
13831
+ ...effect.touched,
13832
+ absorbed: effect.touched.removed.map((absorbed) => ({
13833
+ absorbed,
13834
+ survivor: survivorId
13835
+ }))
13836
+ }
13837
+ });
13838
+ receiverEffects.push(receiver);
13839
+ survivor = next;
13840
+ }
13841
+ return {
13842
+ type: "planned",
13843
+ start,
13844
+ end,
13845
+ survivor,
13846
+ effects,
13847
+ receiverEffects
13848
+ };
13849
+ };
13420
13850
  // src/ops/keptJoins.ts
13421
13851
  /**
13422
13852
  * The joins a pending tracked change takes over from a resolved piece that
@@ -13477,6 +13907,138 @@ const withJoinRetired = (node, side, depth) => {
13477
13907
  if (joins[side] <= depth) return node;
13478
13908
  return Object.assign({}, node, { resolutionJoins: Object.assign({}, joins, side === "before" ? { before: depth } : { after: depth }) });
13479
13909
  };
13910
+ /**
13911
+ * `node`, a pending tracked change, with its join on `side` `depth` levels
13912
+ * deep and closed to records there (`plainSides`): it meets no record of the
13913
+ * cut on that side and takes only the kept markers naming its side.
13914
+ */
13915
+ const withJoinClosed = (node, side, depth) => {
13916
+ if (!isTrackedWrapper(node) || node.resolutionJoins === void 0) return panic("A facing insertion is a pending change with joins.");
13917
+ const joins = node.resolutionJoins;
13918
+ const plainSides = joins.plainSides ?? [];
13919
+ return Object.assign({}, node, { resolutionJoins: Object.assign({}, joins, side === "before" ? { before: depth } : { after: depth }, { plainSides: plainSides.includes(side) ? plainSides : [...plainSides, side] }) });
13920
+ };
13921
+ // src/ops/resolutionMaterialization.ts
13922
+ const MAX_INLINE_RESOLUTION_SPAN = 16384;
13923
+ const fallback$1 = (reason) => ({
13924
+ type: "fallback",
13925
+ reason
13926
+ });
13927
+ const isTextRun$1 = (node) => node.type === "run" && node.content.every(({ type }) => type === "text");
13928
+ const isLocalText = (node) => isTextRun$1(node) || (node.type === "insertion" || node.type === "deletion") && node.content.every(isTextRun$1);
13929
+ const hasCanonicalTrailingSection = (body) => {
13930
+ if (body.sections === void 0) return true;
13931
+ if (body.sections?.length !== 1 || body.finalSectionProperties === void 0) return false;
13932
+ const section = body.sections.at(0);
13933
+ return section !== void 0 && section.properties === body.finalSectionProperties && Object.keys(section).length === 2 && Object.hasOwn(section, "properties") && Object.hasOwn(section, "content") && section.content.length === body.content.length && body.content.every((block, index) => block === section.content[index]);
13934
+ };
13935
+ /**
13936
+ * The ordinary primitive validators prepare each paragraph in journal order.
13937
+ * They can read the original package here because each edit only retires IDs.
13938
+ * Section, note, range and other container interactions stay in the ordinary
13939
+ * sequential planner. A failed proof lets that planner determine the refusal.
13940
+ */
13941
+ const tryMaterializeResolution = ({ document, story, locations, inline, join, noteReferences, receiverEffects }) => {
13942
+ if (story !== OP_STORIES.MAIN) return fallback$1("story");
13943
+ const body = document.package.document;
13944
+ if ((document.package.footnotes?.length ?? 0) > 0 || (document.package.endnotes?.length ?? 0) > 0 || (body.comments?.length ?? 0) > 0) return fallback$1("packageDependencies");
13945
+ if (noteReferences.length > 0 || receiverEffects.length > 0) return fallback$1("referenceEffects");
13946
+ const originals = body.content;
13947
+ if (join.type === "plan" && locations.some(({ paragraph }) => paragraph.pPrMark?.takenOverMark !== void 0)) return fallback$1("survivorProvenance");
13948
+ if (!originals.every((block) => block.type === "paragraph") || locations.length !== originals.length) return fallback$1("paragraphList");
13949
+ if (originals.some(({ sectionProperties }) => sectionProperties !== void 0) || !hasCanonicalTrailingSection(body)) return fallback$1("sectionView");
13950
+ if (validateOpsDocument(document).isErr()) return fallback$1("inputContract");
13951
+ const byId = /* @__PURE__ */ new Map();
13952
+ for (const at of locations) {
13953
+ const { paraId } = at.paragraph;
13954
+ if (at.list.length > 0 || originals.at(at.index) !== at.paragraph || paraId === void 0 || !isParaId(paraId)) return fallback$1("paragraphList");
13955
+ byId.set(idKey(paraId), at);
13956
+ }
13957
+ const replacements = /* @__PURE__ */ new Map();
13958
+ const effects = [];
13959
+ let first = originals.length;
13960
+ let end = 0;
13961
+ for (const op of inline) {
13962
+ const at = byId.get(idKey(op.blockId));
13963
+ const paragraph = at === void 0 ? void 0 : replacements.get(at.index) ?? originals.at(at.index);
13964
+ if (op.story !== story || at === void 0 || paragraph === void 0 || !paragraph.content.every(isLocalText)) return fallback$1("primitiveShape");
13965
+ if (op.type === DOCUMENT_OP_TYPES.REPLACE_INLINE) {
13966
+ if (!op.content.every(isTextRun$1)) return fallback$1("primitiveShape");
13967
+ } else if (op.review.propertyChanges !== void 0 || op.review.pPrMark !== void 0) return fallback$1("primitiveShape");
13968
+ const prepared = prepareResolutionParagraphOp({
13969
+ document,
13970
+ op,
13971
+ at: {
13972
+ ...at,
13973
+ paragraph
13974
+ }
13975
+ });
13976
+ if (prepared.isErr()) return fallback$1("primitiveValidation");
13977
+ if (prepared.value.type === "unchanged") continue;
13978
+ const next = prepared.value;
13979
+ if (next.incomingParagraphIds.length > 0 || next.incomingIdentityKeys.length > 0) return fallback$1("identityIntroduction");
13980
+ if (!structurallyEqual(next.paragraph.formatting, paragraph.formatting)) return fallback$1("primitiveShape");
13981
+ transferParagraphPropertySnapshot({
13982
+ source: paragraph,
13983
+ target: next.paragraph
13984
+ });
13985
+ replacements.set(at.index, next.paragraph);
13986
+ first = Math.min(first, at.index);
13987
+ end = Math.max(end, at.index + 1);
13988
+ effects.push({
13989
+ inverse: [captureDocumentOp(next.inverse)],
13990
+ touched: next.touched
13991
+ });
13992
+ }
13993
+ if (effects.length === 0 && join.type === "noJoins") return {
13994
+ type: "materialized",
13995
+ edit: combineEditEffects(document, []),
13996
+ receiverEffects: []
13997
+ };
13998
+ const combinedInline = combineEditEffects(document, effects);
13999
+ const joined = join.type === "plan" ? join.prepare({
14000
+ paragraphCount: originals.length,
14001
+ indexOf: (id) => byId.get(idKey(id))?.index,
14002
+ paragraphAt: (index) => replacements.get(index) ?? originals.at(index)
14003
+ }) : void 0;
14004
+ if (joined?.type === "fallback") return joined;
14005
+ const start = joined === void 0 ? first : Math.min(first, joined.start);
14006
+ const stop = joined === void 0 ? end : Math.max(end, joined.end);
14007
+ const removed = joined === void 0 ? 0 : joined.end - joined.start - 1;
14008
+ if (stop - start - removed > MAX_INLINE_RESOLUTION_SPAN) return fallback$1("wideSpan");
14009
+ let replacement;
14010
+ if (joined === void 0) {
14011
+ replacement = originals.slice(start, stop);
14012
+ for (const [index, paragraph] of replacements) replacement[index - start] = paragraph;
14013
+ } else {
14014
+ replacement = [];
14015
+ for (let index = start; index < stop; index++) if (index === joined.start) {
14016
+ replacement.push(joined.survivor);
14017
+ index = joined.end - 1;
14018
+ } else {
14019
+ const current = replacements.get(index) ?? originals.at(index);
14020
+ if (current === void 0) return fallback$1("paragraphList");
14021
+ replacement.push(current);
14022
+ }
14023
+ }
14024
+ const final = replaceParagraphs({
14025
+ document,
14026
+ story,
14027
+ at: {
14028
+ list: [],
14029
+ index: start
14030
+ },
14031
+ count: stop - start,
14032
+ replacement
14033
+ });
14034
+ if (final.isErr() || hasMultipleParagraphPropertyChanges(final.value) || repeatedParagraphId(final.value) !== void 0) return fallback$1("materialization");
14035
+ meetsContract(final.value);
14036
+ return {
14037
+ type: "materialized",
14038
+ edit: combineEditEffects(final.value, [combinedInline, ...joined?.effects ?? []]),
14039
+ receiverEffects: joined?.receiverEffects ?? []
14040
+ };
14041
+ };
13480
14042
  // src/ops/resolvedEdges.ts
13481
14043
  /**
13482
14044
  * The records at an edge of an inline record, as a resolution reads them
@@ -13724,9 +14286,44 @@ const withMergesHandedOn = (table, rowIndex) => {
13724
14286
  cells
13725
14287
  } : void 0;
13726
14288
  };
13727
- /** The table's rows without row `rowIndex`, the merges it starts handed on. */
14289
+ /**
14290
+ * The row before `rowIndex` once that row is removed, when the removed row
14291
+ * holds the only continuation of a vertical merge the row before starts: the
14292
+ * merge no row continues is no merge, and the cell starting it states none.
14293
+ * `undefined` when the removed row ends no such merge.
14294
+ */
14295
+ const withMergesEnded = (table, rowIndex) => {
14296
+ const grid = tableGrid(table, DOCUMENT_OP_TYPES.DELETE_ROW);
14297
+ if (grid.isErr()) return void 0;
14298
+ const previousRow = table.rows[rowIndex - 1];
14299
+ if (previousRow === void 0) return void 0;
14300
+ const removed = grid.value.rows[rowIndex] ?? [];
14301
+ const following = grid.value.rows[rowIndex + 1] ?? [];
14302
+ const ended = new Set(removed.filter((slot) => slot.ownerRow === rowIndex - 1 && !following.some((entry) => entry.ownerRow === slot.ownerRow && entry.ownerIndex === slot.ownerIndex)).map((slot) => slot.ownerIndex));
14303
+ if (ended.size === 0) return void 0;
14304
+ const cells = previousRow.cells.map((cell, index) => {
14305
+ if (!ended.has(index)) return cell;
14306
+ const { vMerge: _vMerge, sourceXml: _sourceXml, ...formatting } = cell.formatting ?? {};
14307
+ if (Object.keys(formatting).length > 0) return {
14308
+ ...cell,
14309
+ formatting
14310
+ };
14311
+ const { formatting: _formatting, ...plain } = cell;
14312
+ return plain;
14313
+ });
14314
+ return {
14315
+ ...previousRow,
14316
+ cells
14317
+ };
14318
+ };
14319
+ /**
14320
+ * The table's rows without row `rowIndex`: the merges it starts handed on,
14321
+ * and those it alone continues ended.
14322
+ */
13728
14323
  const rowsWithoutRow = (table, rowIndex) => {
13729
14324
  const rows = [...table.rows];
14325
+ const ended = withMergesEnded(table, rowIndex);
14326
+ if (ended !== void 0) rows[rowIndex - 1] = ended;
13730
14327
  const next = withMergesHandedOn(table, rowIndex);
13731
14328
  if (next === void 0) rows.splice(rowIndex, 1);
13732
14329
  else rows.splice(rowIndex, 2, next);
@@ -14206,21 +14803,38 @@ const marksInRemovedStructure = (document, op) => {
14206
14803
  if (op.decision === REVISION_DECISIONS.REJECT) return change.type === "tableRowInsertion" || change.type === "tableCellInsertion";
14207
14804
  return change.type === "tableRowDeletion" || change.type === "tableCellDeletion";
14208
14805
  };
14806
+ const handedOn = (table) => {
14807
+ const grid = tableGrid(table, DOCUMENT_OP_TYPES.SET_TABLE_ROWS);
14808
+ if (grid.isErr()) return /* @__PURE__ */ new Set();
14809
+ const kept = /* @__PURE__ */ new Set();
14810
+ for (const [rowIndex, slots] of grid.value.rows.entries()) {
14811
+ if (removes(table.rows[rowIndex]?.structuralChange)) continue;
14812
+ for (const slot of slots) {
14813
+ if (slot.ownerRow === rowIndex) continue;
14814
+ const owner = table.rows[slot.ownerRow]?.cells[slot.ownerIndex];
14815
+ if (owner !== void 0) kept.add(owner);
14816
+ }
14817
+ }
14818
+ return kept;
14819
+ };
14209
14820
  const settled = /* @__PURE__ */ new Map();
14210
- for (const table of tablesIn(document, op.story)) for (const row of table.rows) for (const cell of row.cells) {
14211
- if (!removes(row.structuralChange) && !removes(cell.structuralChange)) continue;
14212
- for (const { paragraph } of storyParagraphs({ content: cell.content })) {
14213
- const { paraId } = paragraph;
14214
- if (paragraph.pPrMark === void 0 || paraId === void 0 || settled.has(paraId)) continue;
14215
- const review = reviewFieldsOf(paragraph);
14216
- delete review.pPrMark;
14217
- settled.set(paraId, {
14218
- type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
14219
- story: op.story,
14220
- blockId: paraId,
14221
- expected: reviewFieldsOf(paragraph),
14222
- review
14223
- });
14821
+ for (const table of tablesIn(document, op.story)) {
14822
+ const kept = handedOn(table);
14823
+ for (const row of table.rows) for (const cell of row.cells) {
14824
+ if (!(removes(cell.structuralChange) || removes(row.structuralChange) && !kept.has(cell))) continue;
14825
+ for (const { paragraph } of storyParagraphs({ content: cell.content })) {
14826
+ const { paraId } = paragraph;
14827
+ if (paragraph.pPrMark === void 0 || paraId === void 0 || settled.has(paraId)) continue;
14828
+ const review = reviewFieldsOf(paragraph);
14829
+ delete review.pPrMark;
14830
+ settled.set(paraId, {
14831
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
14832
+ story: op.story,
14833
+ blockId: paraId,
14834
+ expected: reviewFieldsOf(paragraph),
14835
+ review
14836
+ });
14837
+ }
14224
14838
  }
14225
14839
  }
14226
14840
  return [...settled.values()];
@@ -14353,6 +14967,35 @@ const reachableOnTable = (table) => /* @__PURE__ */ new Set([
14353
14967
  ...row.cells.flatMap((cell) => [...propertyIds(cell.propertyChanges), ...cellStructuralIds(cell)])
14354
14968
  ])
14355
14969
  ]);
14970
+ /**
14971
+ * The table once every pending record of its grid, its properties, its rows'
14972
+ * properties and its cells is accepted or rejected, as resolving them does;
14973
+ * the rows' own insertions and deletions stay pending. `unsupported` where
14974
+ * resolving them refuses.
14975
+ */
14976
+ const withTableRecordsResolved = (table, reject) => {
14977
+ const rowIds = new Set(table.rows.flatMap(({ structuralChange }) => structuralChange === void 0 ? [] : [structuralChange.info.id]));
14978
+ const ids = new Set([...reachableOnTable(table)].filter((id) => !rowIds.has(id)));
14979
+ if (ids.size === 0) return Result.ok(table);
14980
+ if (removesEveryCell({
14981
+ table,
14982
+ ids,
14983
+ reject
14984
+ })) return Result.err("unsupported");
14985
+ const cells = resolveCellChanges({
14986
+ table,
14987
+ ids,
14988
+ reject,
14989
+ selectedGridChange: table.formatting?.gridChange !== void 0 && ids.has(table.formatting.gridChange.id)
14990
+ });
14991
+ if (cells.isErr()) return Result.err(cells.error);
14992
+ return propertyTable({
14993
+ table: cells.value.table,
14994
+ keepsGrid: cells.value.holdsRemovedColumns,
14995
+ ids,
14996
+ reject
14997
+ });
14998
+ };
14356
14999
  // src/ops/sectionReview.ts
14357
15000
  /**
14358
15001
  * Rejected section properties: the stored old sectPr wholesale, preserving
@@ -14855,7 +15498,13 @@ const restoreRetainedIdentities = ({ nodes, transfers, resolution }) => {
14855
15498
  next = Object.assign({}, node, { resolutionJoins: joins });
14856
15499
  }
14857
15500
  const children = childNodes(next);
14858
- return children === void 0 ? next : rebuildNode(next, children.map(rebase));
15501
+ return children === void 0 ? withKeptCutHoldersRenamed(next, (id) => {
15502
+ const restored = references.get(slotKey({
15503
+ space: IDENTITY_SPACES.REVISION,
15504
+ id
15505
+ }));
15506
+ return restored?.space === IDENTITY_SPACES.REVISION ? restored.id : id;
15507
+ }) : rebuildNode(next, children.map(rebase));
14859
15508
  };
14860
15509
  return {
14861
15510
  nodes: out.map(rebase),
@@ -15056,13 +15705,29 @@ const consumeSeamNames = (out, { blockers }, known) => {
15056
15705
  if (!isTrackedWrapper(node) || !blockers.includes(node.info.id)) continue;
15057
15706
  for (const step of [-1, 1]) {
15058
15707
  const run = [];
15708
+ const toward = step === -1 ? "before" : "after";
15709
+ const ownSide = step === -1 ? "after" : "before";
15710
+ const takesOwn = (node.resolutionJoins?.[toward] ?? 0) > 0;
15711
+ const ownRun = [];
15059
15712
  let beyond;
15060
15713
  for (let at = index + step; at >= 0; at += step) {
15061
15714
  beyond = out[at];
15062
- if (beyond === void 0 || !standsInKeptCut(beyond) || keptCutPiece(beyond) !== "both") break;
15063
- run.push(at);
15715
+ if (beyond === void 0 || !keptCutHeldBy(beyond, {
15716
+ side: ownSide,
15717
+ id: node.info.id
15718
+ })) break;
15719
+ const named = keptCutPiece(beyond);
15720
+ if (named === ownSide && !takesOwn) ownRun.push(at);
15721
+ else if (named !== "both") break;
15722
+ else run.push(at);
15064
15723
  beyond = void 0;
15065
15724
  }
15725
+ for (const at of ownRun) {
15726
+ const marker = out[at];
15727
+ if (marker === void 0) continue;
15728
+ out[at] = withKeptCutPieceConsumed(marker, known);
15729
+ changed = true;
15730
+ }
15066
15731
  if (beyond !== void 0 && isTrackedWrapper(beyond) && waitedOn.has(beyond.info.id)) continue;
15067
15732
  for (const at of run) {
15068
15733
  const marker = out[at];
@@ -15198,6 +15863,41 @@ const settleDeferredRemovals = (nodes, options) => {
15198
15863
  return changed ? out : nodes;
15199
15864
  };
15200
15865
  /**
15866
+ * Kept markers at the edge of an accepted removal away from its seam, naming
15867
+ * its side as their cut's piece: the removal held that piece, and once its
15868
+ * content goes they meet the piece across the seam, which continues the
15869
+ * record the cut split. They go into it at its facing edge, as deep as the
15870
+ * seam, as they do when the removal goes with the change holding it. `out`
15871
+ * is changed in place; whether it changed.
15872
+ */
15873
+ const placeKeptAcrossRemovedPiece = ({ out, index, group, fateOf, known }) => {
15874
+ const holder = out[index];
15875
+ if (holder === void 0 || holder.type !== "deletion" && holder.type !== "moveFrom" || group.edge === void 0) return false;
15876
+ const atEnd = group.edge === "end";
15877
+ const step = atEnd ? -1 : 1;
15878
+ const named = atEnd ? "after" : "before";
15879
+ let records = 0;
15880
+ for (let at = index + step;; at += step) {
15881
+ const node = at < 0 ? void 0 : out[at];
15882
+ if (node === void 0 || !standsInKeptCut(node) || keptCutPiece(node) !== named || !keptCutHeldBy(node, {
15883
+ side: named,
15884
+ id: holder.info.id
15885
+ })) break;
15886
+ records += 1;
15887
+ }
15888
+ if (records === 0) return false;
15889
+ const pieceAt = index - step;
15890
+ const piece = pieceAt < 0 ? void 0 : out[pieceAt];
15891
+ const edgeRecord = atEnd ? holder.content.at(-1) : holder.content.at(0);
15892
+ if (piece === void 0 || edgeRecord === void 0 || isTrackedWrapper(piece) || isStandingBoundary(piece) || emptiedBy(piece, fateOf) || !sameOwnFields(edgeRecord, piece)) return false;
15893
+ const start = atEnd ? index - records : index + 1;
15894
+ const placed = withBoundariesAtEdge(piece, out.slice(start, start + records).map((node) => withKeptCutPieceConsumed(node, known)), group.depth, atEnd ? "start" : "end");
15895
+ if (placed === void 0) return false;
15896
+ out.splice(start, records);
15897
+ out[atEnd ? pieceAt - records : pieceAt] = placed;
15898
+ return true;
15899
+ };
15900
+ /**
15201
15901
  * Kept markers beside a pending removal that holds a piece of the cut they
15202
15902
  * stand in, naming its side as their cut's piece, once the removal is
15203
15903
  * accepted: that piece goes, and they go into the piece across from them at
@@ -15215,10 +15915,19 @@ const placeKeptBesideRemovedPiece = ({ out, index, group, fateOf, known }) => {
15215
15915
  for (let at = index + step;; at += step) {
15216
15916
  const node = at < 0 ? void 0 : out[at];
15217
15917
  const piece = node === void 0 ? void 0 : keptCutPiece(node);
15218
- if (node === void 0 || !standsInKeptCut(node) || piece !== named && piece !== "both") break;
15918
+ if (node === void 0 || !standsInKeptCut(node) || piece !== named && piece !== "both" || !keptCutHeldBy(node, {
15919
+ side: named,
15920
+ id: holder.info.id
15921
+ })) break;
15219
15922
  records += 1;
15220
15923
  }
15221
- if (records === 0) return false;
15924
+ if (records === 0) return placeKeptAcrossRemovedPiece({
15925
+ out,
15926
+ index,
15927
+ group,
15928
+ fateOf,
15929
+ known
15930
+ });
15222
15931
  const pieceAt = index + step * (records + 1);
15223
15932
  const piece = pieceAt < 0 ? void 0 : out[pieceAt];
15224
15933
  const edgeRecord = atEnd ? holder.content.at(-1) : holder.content.at(0);
@@ -15574,6 +16283,7 @@ const withRejoinedBlockers = ({ nodes, retired, resolution }) => {
15574
16283
  next = Object.assign({}, next, { resolutionJoins: joins });
15575
16284
  }
15576
16285
  }
16286
+ if (children === void 0) next = withKeptCutHoldersRenamed(next, successor);
15577
16287
  if (next !== node) carryResolutionState(resolution, node, next);
15578
16288
  return next;
15579
16289
  };
@@ -15836,6 +16546,14 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
15836
16546
  ...payload && { payload: true }
15837
16547
  });
15838
16548
  };
16549
+ /** A cut at a paragraph edge can end inside the one insertion it split. */
16550
+ const cutsEdgeOfRemovedInsertion = (node, index) => {
16551
+ const cut = node.resolutionJoins;
16552
+ if (cut?.remove !== 1 || cut.before !== 0 || cut.after !== 0) return false;
16553
+ if (index !== 0 && index !== pending.length - 1) return false;
16554
+ const piece = pending[index === 0 ? 1 : index - 1];
16555
+ return piece !== void 0 && isAddedRevision(piece) && isTrackedWrapper(piece) && resolution.ids.has(piece.info.id) && removesContent(piece, resolution.decision) && (piece.info.date ?? "") < (node.info.date ?? "") && piece.resolutionJoins?.before === 0 && piece.resolutionJoins.after === 0 && piece.resolutionJoins.remove === 0;
16556
+ };
15839
16557
  /**
15840
16558
  * How many levels of the cut `node` recorded for its removal remain once
15841
16559
  * this resolution is done, read against the records either side of it as
@@ -15850,6 +16568,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
15850
16568
  const joins = node.resolutionJoins;
15851
16569
  const depth = joins?.remove ?? 0;
15852
16570
  if (depth === 0) return 0;
16571
+ if (cutsEdgeOfRemovedInsertion(node, index)) return 0;
15853
16572
  const reachesPast = resolution.ids.has(node.info.id) && removesContent(node, resolution.decision) && joins?.before === 0 && joins.after === 0;
15854
16573
  const goes = (candidate) => reachesPast && candidate !== void 0 && isTrackedWrapper(candidate) && resolution.ids.has(candidate.info.id) && removesContent(candidate, resolution.decision);
15855
16574
  const removed = resolution.ids.has(node.info.id);
@@ -15868,6 +16587,12 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
15868
16587
  const takesCut = (candidate) => candidate !== void 0 && isAddedRevision(candidate) && resolution.ids.has(candidate.info.id) && removesContent(candidate, resolution.decision) && (candidate.info.date ?? "") < (node.info.date ?? "");
15869
16588
  if (before === void 0 || after === void 0) return !removed && (takesCut(before) || takesCut(after)) ? 0 : depth;
15870
16589
  if (takesCut(before) || takesCut(after)) return 0;
16590
+ const laterGoing = (candidate) => removed && candidate !== void 0 && isAddedRevision(candidate) && resolution.ids.has(candidate.info.id) && removesContent(candidate, resolution.decision) && (candidate.info.date ?? "") > (node.info.date ?? "");
16591
+ let takerBefore = beforeIndex;
16592
+ while (takerBefore >= 0 && laterGoing(pending.at(takerBefore))) takerBefore -= 1;
16593
+ let takerAfter = afterIndex;
16594
+ while (takerAfter < pending.length && laterGoing(pending.at(takerAfter))) takerAfter += 1;
16595
+ if (takerBefore >= 0 && takesCut(pending.at(takerBefore)) || takesCut(pending.at(takerAfter))) return 0;
15871
16596
  const joinedToNothing = (candidate) => candidate !== void 0 && isTrackedWrapper(candidate) && isAddedRevision(candidate) && resolution.ids.has(candidate.info.id) && removesContent(candidate, resolution.decision) && candidate.resolutionJoins !== void 0 && candidate.resolutionJoins.before === 0 && candidate.resolutionJoins.after === 0 && candidate.resolutionJoins.remove === 0;
15872
16597
  let pastBefore = beforeIndex;
15873
16598
  while (pastBefore >= 0 && joinedToNothing(pending.at(pastBefore))) pastBefore -= 1;
@@ -15992,12 +16717,13 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
15992
16717
  * their seam. A marker already naming a piece keeps it: the first change
15993
16718
  * to take its seam holds it. Whether any marker took the name.
15994
16719
  */
15995
- const nameKeptPiece = (start, end, piece) => {
16720
+ const nameKeptPiece = (start, end, holders) => {
16721
+ if (holders === void 0) return false;
15996
16722
  let named = false;
15997
16723
  for (let index = start; index < end; index += 1) {
15998
16724
  const occurrence = out[index];
15999
16725
  if (occurrence === void 0) continue;
16000
- const next = withKeptCutPieceRecorded(occurrence.node, piece, resolution.relocated.nodes);
16726
+ const next = withKeptCutHoldersRecorded(occurrence.node, holders, resolution.relocated.nodes);
16001
16727
  if (next === occurrence.node) continue;
16002
16728
  out[index] = occurrenceOf(next, occurrence);
16003
16729
  named = true;
@@ -16005,6 +16731,29 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16005
16731
  return named;
16006
16732
  };
16007
16733
  /**
16734
+ * Whether the rejected insertion at `index` meets, on `side`, a join an
16735
+ * earlier change still holds toward it: an insertion made before it, or a
16736
+ * removal, pending or given back by this rejection. The boundaries the
16737
+ * rejection keeps stay at its seam then, naming no piece and going into
16738
+ * none, whichever of them is resolved first: resolving that change hands
16739
+ * its join to the rejected content's place.
16740
+ */
16741
+ const heldAcross = (index, side) => {
16742
+ const node = pending[index];
16743
+ if (node === void 0 || !isTrackedWrapper(node)) return false;
16744
+ const date = node.info.date ?? "";
16745
+ const step = side === "before" ? -1 : 1;
16746
+ let at = index + step;
16747
+ for (let beside = pending[at]; beside !== void 0 && standsInKeptCut(beside); beside = pending[at]) at += step;
16748
+ const across = at < 0 ? void 0 : pending[at];
16749
+ if (across === void 0 || !isTrackedWrapper(across)) return false;
16750
+ const facing = side === "before" ? "after" : "before";
16751
+ if ((across.resolutionJoins?.[facing] ?? 0) === 0) return false;
16752
+ const resolved = resolution.ids.has(across.info.id);
16753
+ if (isAddedRevision(across)) return !resolved && (across.info.date ?? "") < date;
16754
+ return isRemovedRevisionNode(across) && (!resolved || resolution.decision === REVISION_DECISIONS.REJECT);
16755
+ };
16756
+ /**
16008
16757
  * The boundaries a removed one-sided insertion kept, moved into the source
16009
16758
  * piece its join names: the record after it, not yet resolved, or the one
16010
16759
  * `out` holds before them. They stay standing where that record is a
@@ -16012,28 +16761,43 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16012
16761
  * held boundaries only has no edge record to differ from it. Their cuts go
16013
16762
  * with them, naming no piece: settling the list keeps a cut only while a
16014
16763
  * pending change still stands beside them, as placing them by accepting
16015
- * that piece later does.
16764
+ * that piece later does. Whether they moved.
16016
16765
  */
16017
16766
  const placeOneSidedKept = ({ index, piece, depth, kept, inside, edge }) => {
16767
+ if (heldAcross(index, piece === "after" ? "before" : "after")) return false;
16018
16768
  const standsInside = (record) => record !== void 0 && !isTrackedWrapper(record) && childNodes(record) !== void 0 && (edge === void 0 || sameOwnFields(edge, record));
16019
16769
  const first = out.length - kept;
16020
16770
  const boundaries = out.slice(piece === "after" ? out.length - inside : first, piece === "after" ? out.length : first + inside).map(({ node }) => withKeptCutPieceConsumed(node, resolution.relocated.nodes));
16021
16771
  if (piece === "after") {
16022
16772
  const next = pending.at(index + 1);
16023
- if (next === void 0 || !standsInside(next)) return;
16773
+ if (next === void 0 || !standsInside(next)) return false;
16024
16774
  const placed = withBoundariesAtEdge(next, boundaries, depth, "start");
16025
- if (placed === void 0) return;
16775
+ if (placed === void 0) return false;
16026
16776
  pending[index + 1] = placed;
16027
16777
  out.splice(out.length - inside, inside);
16028
- } else {
16029
- const previous = itemBefore(out, first);
16030
- if (previous === void 0 || !standsInside(previous.node)) return;
16031
- const placed = withBoundariesAtEdge(previous.node, boundaries, depth, "end");
16032
- if (placed === void 0) return;
16033
- carryResolutionState(resolution, previous.node, placed);
16034
- out[first - 1] = occurrenceOf(placed, previous);
16035
- out.splice(first, inside);
16778
+ return true;
16036
16779
  }
16780
+ const previous = itemBefore(out, first);
16781
+ if (previous === void 0 || !standsInside(previous.node)) return false;
16782
+ const placed = withBoundariesAtEdge(previous.node, boundaries, depth, "end");
16783
+ if (placed === void 0) return false;
16784
+ carryResolutionState(resolution, previous.node, placed);
16785
+ out[first - 1] = occurrenceOf(placed, previous);
16786
+ out.splice(first, inside);
16787
+ return true;
16788
+ };
16789
+ /**
16790
+ * What pending change, if any, is the one-sided `piece` of the insertion
16791
+ * at `index` this rejection removes, `kept` boundaries kept from it last
16792
+ * in `out`: an insertion, or a removal not resolved with it. A cut the
16793
+ * insertion records across its place leaves no one-sided piece.
16794
+ */
16795
+ const pendingOneSidedPiece = ({ index, piece, joins, kept }) => {
16796
+ if (piece === void 0 || (joins?.remove ?? 0) > 0) return void 0;
16797
+ const record = piece === "after" ? pending[index + 1] : itemBefore(out, out.length - kept)?.node;
16798
+ if (record === void 0 || !isTrackedWrapper(record)) return void 0;
16799
+ if (isAddedRevision(record)) return "insertion";
16800
+ return isRemovedRevisionNode(record) && !resolution.ids.has(record.info.id) ? "removal" : void 0;
16037
16801
  };
16038
16802
  /**
16039
16803
  * Boundaries a rejection kept from new content joined to nothing, standing
@@ -16053,15 +16817,19 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16053
16817
  const handKeptToFacingJoins = ({ index, kept, standing, inEdgeRecords, boundariesOnly, cuts }) => {
16054
16818
  const previousAt = out.length - standing - 1;
16055
16819
  const facing = (node, side) => {
16056
- if (node === void 0 || !isTrackedWrapper(node) || !isAddedRevision(node) || resolution.ids.has(node.info.id)) return void 0;
16820
+ if (node === void 0 || !isTrackedWrapper(node) || !isAddedRevision(node) || resolution.ids.has(node.info.id) && side === "after") return void 0;
16057
16821
  const join = node.resolutionJoins?.[side] ?? 0;
16058
16822
  const date = node.info.date ?? "";
16059
16823
  if (join === 0 || holdsSeamJoin(node, side)) return void 0;
16060
- if (date < kept.from) return cuts ? void 0 : {
16061
- join,
16062
- kept,
16063
- made: "earlier"
16064
- };
16824
+ if (date < kept.from) {
16825
+ const edgeRecord = side === "before" ? node.content.at(0) : node.content.at(-1);
16826
+ if (cuts || edgeRecord !== void 0 && isRemovedRevisionNode(edgeRecord)) return void 0;
16827
+ return {
16828
+ join,
16829
+ kept,
16830
+ made: "earlier"
16831
+ };
16832
+ }
16065
16833
  if (date === kept.from) return void 0;
16066
16834
  const acrossNode = side === "before" ? out[previousAt]?.node : pending[index + 1];
16067
16835
  const facingSide = side === "before" ? "after" : "before";
@@ -16073,6 +16841,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16073
16841
  date: ""
16074
16842
  };
16075
16843
  if (acrossJoin.depth > 0 && acrossJoin.date < kept.from) return void 0;
16844
+ if (heldAcross(index, side)) return void 0;
16076
16845
  const count = acrossJoin.depth > 1 ? 0 : inEdgeRecords[side === "before" ? "last" : "first"];
16077
16846
  if (cuts && count === 0) return void 0;
16078
16847
  return {
@@ -16116,7 +16885,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16116
16885
  side: "before",
16117
16886
  depth: nextFacing.join
16118
16887
  }).takesKept) {
16119
- nameKeptPiece(out.length - recordsFrom(out.length - 1, -1, nextFacing.kept.count), out.length, "after");
16888
+ nameKeptPiece(out.length - recordsFrom(out.length - 1, -1, nextFacing.kept.count), out.length, keptCutHolders({ after: changeAtEdge(next, "start") }));
16120
16889
  if (nextFacing.made === "later") pending[index + 1] = closedToward(next, "before", nextFacing.kept.count);
16121
16890
  }
16122
16891
  if (previous !== void 0 && previousFacing !== void 0 && handJoin({
@@ -16124,7 +16893,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16124
16893
  side: "after",
16125
16894
  depth: previousFacing.join
16126
16895
  }).takesKept) {
16127
- nameKeptPiece(previousAt + 1, previousAt + 1 + recordsFrom(previousAt + 1, 1, previousFacing.kept.count), "before");
16896
+ nameKeptPiece(previousAt + 1, previousAt + 1 + recordsFrom(previousAt + 1, 1, previousFacing.kept.count), keptCutHolders({ before: changeAtEdge(previous.node, "end") }));
16128
16897
  if (previousFacing.made === "later") {
16129
16898
  const closed = closedToward(previous.node, "after", previousFacing.kept.count);
16130
16899
  carryResolutionState(resolution, previous.node, closed);
@@ -16141,12 +16910,41 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16141
16910
  const nameKeptWaitedOn = (groups, kept, index) => {
16142
16911
  const first = out.length - kept;
16143
16912
  const waitedOn = (node, facing) => node !== void 0 && isTrackedWrapper(node) && isAddedRevision(node) && node.resolutionJoins?.[facing] === 0 && groups.some(({ blockers }) => blockers.includes(node.info.id));
16144
- const before = waitedOn(itemBefore(out, first)?.node, "after");
16145
- const after = waitedOn(pending[index + 1], "before");
16146
- if (!before && !after) return;
16147
- let piece = before ? "before" : "after";
16148
- if (before && after) piece = "both";
16149
- nameKeptPiece(first, out.length, piece);
16913
+ const left = itemBefore(out, first)?.node;
16914
+ const right = pending[index + 1];
16915
+ nameKeptPiece(first, out.length, keptCutHolders({
16916
+ before: waitedOn(left, "after") ? changeAtEdge(left, "end") : void 0,
16917
+ after: waitedOn(right, "before") ? changeAtEdge(right, "start") : void 0
16918
+ }));
16919
+ };
16920
+ /** Update markers beside a revision when its edge passes to another. */
16921
+ const handKeptBeside = ({ index, side, from, to }) => {
16922
+ const markerSide = side === "before" ? "after" : "before";
16923
+ const transfer = {
16924
+ side: markerSide,
16925
+ from,
16926
+ to
16927
+ };
16928
+ if (side === "before") {
16929
+ for (let at = out.length - 1; at >= 0; at -= 1) {
16930
+ const occurrence = out[at];
16931
+ if (occurrence === void 0 || !keptCutHeldBy(occurrence.node, {
16932
+ side: markerSide,
16933
+ id: from
16934
+ })) break;
16935
+ const next = withKeptCutHolderHandedOver(occurrence.node, transfer, resolution.relocated.nodes);
16936
+ out[at] = occurrenceOf(next, occurrence);
16937
+ }
16938
+ return;
16939
+ }
16940
+ for (let at = index + 1; at < pending.length; at += 1) {
16941
+ const marker = pending[at];
16942
+ if (marker === void 0 || !keptCutHeldBy(marker, {
16943
+ side: markerSide,
16944
+ id: from
16945
+ })) break;
16946
+ pending[at] = withKeptCutHolderHandedOver(marker, transfer, resolution.relocated.nodes);
16947
+ }
16150
16948
  };
16151
16949
  /**
16152
16950
  * Rejecting an insertion cancels a pending insertion's join facing it:
@@ -16171,15 +16969,196 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16171
16969
  const own = side === "after" ? joins?.before : joins?.after;
16172
16970
  return neighbourDate < date && (own ?? 0) > 0;
16173
16971
  };
16174
- const beyond = (neighbour, side) => made === "later" ? Math.min((neighbour.resolutionJoins?.[side] ?? 0) - 1, joins === void 0 ? 0 : recordJoin(joins, side)) : 0;
16175
- const previous = out.at(-1);
16972
+ const joinedFromBeyond = (side) => {
16973
+ const across = side === "before" ? out.at(-1)?.node : pending[index + 1];
16974
+ const facing = side === "before" ? "after" : "before";
16975
+ return across !== void 0 && isTrackedWrapper(across) && isAddedRevision(across) && !resolution.ids.has(across.info.id) ? recordJoin(across.resolutionJoins ?? {
16976
+ before: 0,
16977
+ after: 0,
16978
+ remove: 0
16979
+ }, facing) : 0;
16980
+ };
16981
+ const fromBeyond = {
16982
+ before: joinedFromBeyond("before"),
16983
+ after: joinedFromBeyond("after")
16984
+ };
16985
+ const beyond = (neighbour, side) => made === "later" ? Math.min((neighbour.resolutionJoins?.[side] ?? 0) - 1, Math.max(joins === void 0 ? 0 : recordJoin(joins, side), fromBeyond[side])) : 0;
16986
+ const handed = {
16987
+ before: false,
16988
+ after: false
16989
+ };
16990
+ const retiredFacing = (neighbour, side) => {
16991
+ const depth = made === "later" && joins !== void 0 && namesSide(index, side) ? Math.min((neighbour.resolutionJoins?.[side] ?? 0) - 1, joins[side]) : 0;
16992
+ if (depth <= 0) return withJoinRetired(neighbour, side, beyond(neighbour, side));
16993
+ handKeptBeside({
16994
+ index,
16995
+ side,
16996
+ from: node.info.id,
16997
+ to: neighbour.info.id
16998
+ });
16999
+ handed[side] = true;
17000
+ return withJoinClosed(neighbour, side, depth);
17001
+ };
17002
+ let before = out.length - 1;
17003
+ let after = index + 1;
17004
+ if (made === "later") {
17005
+ for (let marker = out[before]?.node; marker !== void 0 && keptCutHeldBy(marker, {
17006
+ side: "after",
17007
+ id: node.info.id
17008
+ }); marker = out[before]?.node) before -= 1;
17009
+ for (let marker = pending[after]; marker !== void 0 && keptCutHeldBy(marker, {
17010
+ side: "before",
17011
+ id: node.info.id
17012
+ }); marker = pending[after]) after += 1;
17013
+ }
17014
+ const previous = out[before];
16176
17015
  if (facesNode(previous?.node, "after")) {
16177
- const retired = withJoinRetired(previous.node, "after", beyond(previous.node, "after"));
17016
+ const retired = retiredFacing(previous.node, "after");
16178
17017
  carryResolutionState(resolution, previous.node, retired);
16179
- out[out.length - 1] = occurrenceOf(retired, previous);
17018
+ out[before] = occurrenceOf(retired, previous);
16180
17019
  }
17020
+ const next = pending[after];
17021
+ if (facesNode(next, "before")) pending[after] = retiredFacing(next, "before");
17022
+ return handed;
17023
+ };
17024
+ /**
17025
+ * Whether the removed insertion at `index` holds, by its join on `side`
17026
+ * closed to records, the piece of the kept markers standing there: they
17027
+ * name its side.
17028
+ */
17029
+ const namesSide = (index, side) => {
17030
+ const node = pending[index];
17031
+ if (node === void 0 || !isTrackedWrapper(node)) return false;
17032
+ const joins = node.resolutionJoins;
17033
+ if (joins === void 0 || joins[side] === 0 || joins.plainSides?.includes(side) !== true) return false;
17034
+ const marker = side === "before" ? out.at(-1)?.node : pending[index + 1];
17035
+ return marker !== void 0 && standsInKeptCut(marker) && keptCutPiece(marker) === (side === "before" ? "after" : "before") && keptCutHeldBy(marker, {
17036
+ side: side === "before" ? "after" : "before",
17037
+ id: node.info.id
17038
+ });
17039
+ };
17040
+ /**
17041
+ * The kept markers whose piece the rejected insertion at `index` holds by
17042
+ * its join on one side, closed to records, moved into the record standing
17043
+ * across it that its join on the other side reaches, as deep as both
17044
+ * joins go: that record holds a piece of their cut too. Rejecting the
17045
+ * insertion before that record's own insertion was accepted hands their
17046
+ * name to it (see {@link retireFacingJoins}), and accepting it then
17047
+ * places them there. The sides whose markers moved.
17048
+ */
17049
+ const placeNamedKeptAcross = (index) => {
17050
+ const placed = {
17051
+ before: false,
17052
+ after: false
17053
+ };
17054
+ const node = pending[index];
17055
+ if (node === void 0 || !isTrackedWrapper(node)) return placed;
17056
+ const joins = node.resolutionJoins;
17057
+ if (joins === void 0) return placed;
17058
+ const names = (marker, piece) => marker !== void 0 && standsInKeptCut(marker) && keptCutPiece(marker) === piece && keptCutHeldBy(marker, {
17059
+ side: piece,
17060
+ id: node.info.id
17061
+ });
17062
+ const holds = (record) => record !== void 0 && !isTrackedWrapper(record) && !isStandingBoundary(record) && childNodes(record) !== void 0;
17063
+ const consumed = (markers) => markers.map((marker) => withKeptCutPieceConsumed(marker, resolution.relocated.nodes));
17064
+ if (namesSide(index, "before") && recordJoin(joins, "after") > 0) {
17065
+ const record = pending[index + 1];
17066
+ let start = out.length;
17067
+ while (names(out[start - 1]?.node, "after")) start -= 1;
17068
+ const into = holds(record) ? withBoundariesAtEdge(record, consumed(out.slice(start).map(({ node: marker }) => marker)), Math.min(joins.before, joins.after), "start") : void 0;
17069
+ if (into !== void 0) {
17070
+ pending[index + 1] = into;
17071
+ out.splice(start);
17072
+ placed.before = true;
17073
+ }
17074
+ }
17075
+ const joinedBefore = Math.max(recordJoin(joins, "before"), exactSeams.get(out.length) ?? 0);
17076
+ if (namesSide(index, "after") && joinedBefore > 0) {
17077
+ const previous = out.at(-1);
17078
+ const record = previous?.node;
17079
+ let end = index + 1;
17080
+ while (names(pending[end], "before")) end += 1;
17081
+ const into = holds(record) ? withBoundariesAtEdge(record, consumed(pending.slice(index + 1, end)), Math.min(joinedBefore, joins.after), "end") : void 0;
17082
+ if (previous !== void 0 && into !== void 0) {
17083
+ carryResolutionState(resolution, previous.node, into);
17084
+ out[out.length - 1] = occurrenceOf(into, previous);
17085
+ for (let at = index + 1; at < end; at += 1) placedInside.add(at);
17086
+ placed.after = true;
17087
+ }
17088
+ }
17089
+ return placed;
17090
+ };
17091
+ /**
17092
+ * The pending insertion at `index`, emptied by this resolution of the
17093
+ * changes it held while it stays pending, hands its joins on as accepting
17094
+ * it does: a pending insertion beside it, of the record it was made in,
17095
+ * takes its join toward the other side, a level less deep for its own
17096
+ * wrapper, where something there joins it.
17097
+ */
17098
+ const handEmptiedJoin = (index) => {
17099
+ const node = pending[index];
17100
+ const joins = node !== void 0 && isTrackedWrapper(node) ? node.resolutionJoins : void 0;
17101
+ if (joins === void 0) return;
17102
+ const takes = (beside) => beside !== void 0 && isTrackedWrapper(beside) && isAddedRevision(beside) && beside.resolutionJoins !== void 0 && !resolution.ids.has(beside.info.id);
16181
17103
  const next = pending[index + 1];
16182
- if (facesNode(next, "before")) pending[index + 1] = withJoinRetired(next, "before", beyond(next, "before"));
17104
+ const throughAfter = Math.min(recordJoin(joins, "before"), joins.after - 1);
17105
+ if (takes(next) && throughAfter > 0) pending[index + 1] = handJoin({
17106
+ node: next,
17107
+ side: "before",
17108
+ depth: throughAfter
17109
+ }).node;
17110
+ const previous = out.at(-1);
17111
+ const throughBefore = Math.min(recordJoin(joins, "after"), joins.before - 1);
17112
+ if (previous !== void 0 && takes(previous.node) && throughBefore > 0) {
17113
+ const handed = handJoin({
17114
+ node: previous.node,
17115
+ side: "after",
17116
+ depth: throughBefore
17117
+ }).node;
17118
+ carryResolutionState(resolution, previous.node, handed);
17119
+ out[out.length - 1] = occurrenceOf(handed, previous);
17120
+ }
17121
+ };
17122
+ /**
17123
+ * The sides of the removed deletion at `index` whose kept markers name it
17124
+ * as their cut's piece and face, across its place, a pending insertion
17125
+ * joined toward its content: that insertion holds a piece of the record
17126
+ * the deleted content was, and keeps their name, as it does when the
17127
+ * deletion goes with the insertion holding it.
17128
+ */
17129
+ const namedKeptFacedAcross = (index) => {
17130
+ const faced = {
17131
+ before: false,
17132
+ after: false
17133
+ };
17134
+ const node = pending[index];
17135
+ if (node === void 0 || !isTrackedWrapper(node)) return faced;
17136
+ const joinedToward = (across, side) => across !== void 0 && isTrackedWrapper(across) && isAddedRevision(across) && !resolution.ids.has(across.info.id) && (across.resolutionJoins?.[side] ?? 0) > 0;
17137
+ const names = (marker, side) => marker !== void 0 && keptCutPiece(marker) === side && keptCutHeldBy(marker, {
17138
+ side,
17139
+ id: node.info.id
17140
+ });
17141
+ const before = out.at(-1)?.node;
17142
+ const after = pending[index + 1];
17143
+ if (names(before, "after") && joinedToward(after, "before")) {
17144
+ handKeptBeside({
17145
+ index,
17146
+ side: "before",
17147
+ from: node.info.id,
17148
+ to: after.info.id
17149
+ });
17150
+ faced.before = true;
17151
+ }
17152
+ if (names(after, "before") && joinedToward(before, "after")) {
17153
+ handKeptBeside({
17154
+ index,
17155
+ side: "after",
17156
+ from: node.info.id,
17157
+ to: before.info.id
17158
+ });
17159
+ faced.after = true;
17160
+ }
17161
+ return faced;
16183
17162
  };
16184
17163
  const recordExactSeam = (index, depth) => {
16185
17164
  if (depth > 0) exactSeams.set(index, Math.max(exactSeams.get(index) ?? 0, depth));
@@ -16243,12 +17222,15 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16243
17222
  * name `piece` as the side taking them: the earliest revision they were
16244
17223
  * kept from and how many boundaries they stand for.
16245
17224
  */
16246
- const keptByPiece = (at, from, step, piece) => {
17225
+ const keptByPiece = (at, from, step, { side, id }) => {
16247
17226
  const dates = [];
16248
17227
  let count = 0;
16249
17228
  for (let index = from;; index += step) {
16250
17229
  const node = at(index);
16251
- if (node === void 0 || !standsInKeptCut(node) || keptCutPiece(node) !== piece) break;
17230
+ if (node === void 0 || !standsInKeptCut(node) || keptCutPiece(node) !== side || !keptCutHeldBy(node, {
17231
+ side,
17232
+ id
17233
+ })) break;
16252
17234
  const date = keptCutFrom(node);
16253
17235
  if (date !== void 0) dates.push(date);
16254
17236
  count += keptBoundaryCount([node]);
@@ -16264,9 +17246,12 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16264
17246
  * its side, or both sides, as their cut's piece: those `out` holds before
16265
17247
  * `before` and those after it in `pending`. Its removal consumes the name;
16266
17248
  * the earliest revision they were kept from and how many boundaries they
16267
- * stand for.
17249
+ * stand for. Those on a side whose name content made inside the change
17250
+ * took over (`handed`) keep it.
16268
17251
  */
16269
- const takeKeptBeside = (index, before, takesSeam) => {
17252
+ const takeKeptBeside = ({ index, before, takesSeam, handed }) => {
17253
+ const holder = pending[index];
17254
+ if (holder === void 0 || !isTrackedWrapper(holder)) return void 0;
16270
17255
  const dates = [];
16271
17256
  let count = 0;
16272
17257
  const take = (at, from, step, piece, put) => {
@@ -16274,6 +17259,10 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16274
17259
  const node = at(position);
16275
17260
  if (node === void 0 || !standsInKeptCut(node)) return;
16276
17261
  const named = keptCutPiece(node);
17262
+ if (!keptCutHeldBy(node, {
17263
+ side: piece,
17264
+ id: holder.info.id
17265
+ })) return;
16277
17266
  if (named !== piece && (named !== "both" || !takesSeam)) return;
16278
17267
  const date = keptCutFrom(node);
16279
17268
  if (date !== void 0) dates.push(date);
@@ -16281,11 +17270,11 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16281
17270
  put(position, withKeptCutPieceConsumed(node, resolution.relocated.nodes));
16282
17271
  }
16283
17272
  };
16284
- take((position) => out[position]?.node, before - 1, -1, "after", (position, node) => {
17273
+ if (!handed.before) take((position) => out[position]?.node, before - 1, -1, "after", (position, node) => {
16285
17274
  const occurrence = out[position];
16286
17275
  if (occurrence !== void 0) out[position] = occurrenceOf(node, occurrence);
16287
17276
  });
16288
- take((position) => pending[position], index + 1, 1, "before", (position, node) => {
17277
+ if (!handed.after) take((position) => pending[position], index + 1, 1, "before", (position, node) => {
16289
17278
  pending[position] = node;
16290
17279
  });
16291
17280
  const earliest = dates.toSorted().at(0);
@@ -16365,19 +17354,24 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16365
17354
  * standing beside it that its join takes inside its own record, on a side
16366
17355
  * that join meets no record on: those naming its side, as deep as the join.
16367
17356
  */
16368
- const withNamedKept = (content, joins, index) => {
17357
+ const withNamedKept = (content, source, index) => {
17358
+ const { info: { id }, resolutionJoins: joins } = source;
16369
17359
  if (joins === void 0) return content;
16370
17360
  const takenInto = (record, markers, side) => {
16371
17361
  const placed = record === void 0 || isTrackedWrapper(record) ? void 0 : withBoundariesAtEdge(record, markers.map((marker) => withKeptCutPieceConsumed(marker, resolution.relocated.nodes)), joins[side], side === "before" ? "start" : "end");
16372
17362
  if (record !== void 0 && placed !== void 0) carryResolutionState(resolution, record, placed);
16373
17363
  return placed;
16374
17364
  };
16375
- const names = (node, piece) => node !== void 0 && standsInKeptCut(node) && keptCutPiece(node) === piece;
17365
+ const names = (node, piece) => node !== void 0 && standsInKeptCut(node) && keptCutPiece(node) === piece && keptCutHeldBy(node, {
17366
+ side: piece,
17367
+ id
17368
+ });
16376
17369
  let taking = [...content];
16377
17370
  if (joins.plainSides?.includes("before") === true) {
16378
17371
  let start = out.length;
16379
17372
  while (names(itemBefore(out, start)?.node, "after")) start -= 1;
16380
- const placed = takenInto(taking.at(0), out.slice(start).map(({ node }) => node), "before");
17373
+ const first = taking.at(0);
17374
+ const placed = takenInto(first, out.slice(start).map(({ node }) => node), "before");
16381
17375
  const seamAmong = [
16382
17376
  ...exactSeams.keys(),
16383
17377
  ...seams,
@@ -16386,16 +17380,27 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16386
17380
  if (placed !== void 0 && !seamAmong) {
16387
17381
  out.splice(start);
16388
17382
  taking = [placed, ...taking.slice(1)];
16389
- }
17383
+ } else if (first !== void 0 && isTrackedWrapper(first)) handKeptBeside({
17384
+ index,
17385
+ side: "before",
17386
+ from: id,
17387
+ to: first.info.id
17388
+ });
16390
17389
  }
16391
17390
  if (joins.plainSides?.includes("after") === true) {
16392
17391
  let end = index + 1;
16393
17392
  while (names(pending[end], "before")) end += 1;
16394
- const placed = takenInto(taking.at(-1), pending.slice(index + 1, end), "after");
17393
+ const last = taking.at(-1);
17394
+ const placed = takenInto(last, pending.slice(index + 1, end), "after");
16395
17395
  if (placed !== void 0) {
16396
17396
  for (let at = index + 1; at < end; at += 1) placedInside.add(at);
16397
17397
  taking = [...taking.slice(0, -1), placed];
16398
- }
17398
+ } else if (last !== void 0 && isTrackedWrapper(last)) handKeptBeside({
17399
+ index,
17400
+ side: "after",
17401
+ from: id,
17402
+ to: last.info.id
17403
+ });
16399
17404
  }
16400
17405
  return taking;
16401
17406
  };
@@ -16505,7 +17510,10 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16505
17510
  });
16506
17511
  const cut = { keptFrom: node.info.date ?? "" };
16507
17512
  const kept = keptOf(removalContent).map((boundary) => isKeptBoundaryCarrier(boundary) ? withKeptCutsRecorded(boundary, cut, resolution.relocated.nodes) : boundary);
16508
- if (resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node)) retireFacingJoins(index, node, kept.length === 0 ? "later" : "laterInWrapper");
17513
+ const handedKept = resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node) ? retireFacingJoins(index, node, kept.length === 0 ? "later" : "laterInWrapper") : {
17514
+ before: false,
17515
+ after: false
17516
+ };
16509
17517
  const keptStart = out.length;
16510
17518
  appendUnowned(kept);
16511
17519
  const piece = resolution.decision === REVISION_DECISIONS.REJECT && joins !== void 0 && !resolution.deferredOnlyRemovals.has(joins) ? oneSidedKeptPiece(joins) : void 0;
@@ -16524,7 +17532,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16524
17532
  const at = piece === "before" ? out.length - (kept.length - inside) : out.length;
16525
17533
  const enclosingCut = enclosingRecordCut(node, index);
16526
17534
  const closedOn = (side) => node.resolutionJoins?.plainSides?.includes(side) === true;
16527
- const cutGoes = piece === void 0 && enclosingCut === void 0 && madeInNewContent(node, index) && cutLevelsOnceResolved(node, index) === 0;
17535
+ const cutGoes = piece === void 0 && enclosingCut === void 0 && (madeInNewContent(node, index) || cutsEdgeOfRemovedInsertion(node, index)) && cutLevelsOnceResolved(node, index) === 0;
16528
17536
  const depth = Math.max(node.resolutionJoins?.remove ?? 0, enclosingCut?.depth ?? 0, piece === void 0 || joins === void 0 ? 0 : recordJoin(joins, piece));
16529
17537
  if (!cutGoes) floating.set(at, {
16530
17538
  count: inside,
@@ -16538,7 +17546,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16538
17546
  ...joins !== void 0 && resolution.deferredOnlyRemovals.has(joins) && { cut: "deferred" }
16539
17547
  });
16540
17548
  }
16541
- if (inside > 0 && piece !== void 0 && (joins?.remove ?? 0) === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node)) placeOneSidedKept({
17549
+ const placedOneSided = inside > 0 && piece !== void 0 && (joins?.remove ?? 0) === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node) && placeOneSidedKept({
16542
17550
  index,
16543
17551
  piece,
16544
17552
  depth: piece === "after" ? joins?.after ?? 0 : joins?.before ?? 0,
@@ -16546,7 +17554,23 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16546
17554
  inside,
16547
17555
  edge: removalContent[(piece === "after" ? lastRecord : firstRecord) ?? -1]
16548
17556
  });
16549
- if (kept.length > 0 && joins !== void 0 && joins.before === 0 && joins.after === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node)) handKeptToFacingJoins({
17557
+ const pendingPiece = placedOneSided ? void 0 : pendingOneSidedPiece({
17558
+ index,
17559
+ piece,
17560
+ joins,
17561
+ kept: kept.length
17562
+ });
17563
+ if (inside > 0 && piece !== void 0 && pendingPiece === "removal" && isAddedRevision(node) && (joins?.deferredRemove ?? []).length === 0 && !heldAcross(index, piece === "after" ? "before" : "after")) {
17564
+ const first = out.length - kept.length;
17565
+ if (piece === "before") {
17566
+ const before = changeAtEdge(itemBefore(out, first)?.node, "end");
17567
+ nameKeptPiece(first, first + inside, keptCutHolders({ before }));
17568
+ } else {
17569
+ const after = changeAtEdge(pending[index + 1], "start");
17570
+ nameKeptPiece(out.length - inside, out.length, keptCutHolders({ after }));
17571
+ }
17572
+ }
17573
+ if (kept.length > 0 && joins !== void 0 && !placedOneSided && (joins.before === 0 && joins.after === 0 || pendingPiece === "insertion") && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node)) handKeptToFacingJoins({
16550
17574
  index,
16551
17575
  kept: {
16552
17576
  from: node.info.date ?? "",
@@ -16570,14 +17594,34 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16570
17594
  spanning: trackedWithin(node.content),
16571
17595
  piece: far
16572
17596
  });
17597
+ const facedAcross = kept.length === 0 && !isAddedRevision(node) ? namedKeptFacedAcross(index) : {
17598
+ before: false,
17599
+ after: false
17600
+ };
16573
17601
  if (node.resolutionJoins === void 0) seams.push(out.length);
16574
17602
  else if ((node.resolutionJoins.plainSides?.length ?? 0) > 0 && !resolution.deferredOnlyRemovals.has(node.resolutionJoins)) {
16575
17603
  plainSeams.add(out.length);
16576
17604
  for (let at = out.length - kept.length; at <= out.length; at += 1) if (floating.has(at)) folds.push(at);
16577
- takeKeptBeside(index, keptStart, false);
17605
+ const placedAcross = kept.length === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node) ? placeNamedKeptAcross(index) : {
17606
+ before: false,
17607
+ after: false
17608
+ };
17609
+ takeKeptBeside({
17610
+ index,
17611
+ before: keptStart,
17612
+ takesSeam: false,
17613
+ handed: {
17614
+ before: handedKept.before || placedAcross.before || facedAcross.before,
17615
+ after: handedKept.after || placedAcross.after || facedAcross.after
17616
+ }
17617
+ });
16578
17618
  } else {
16579
17619
  const around = floating.has(out.length) ? enclosingRecordCut(node, index) : void 0;
16580
- const removalCut = Math.max(cutLevelsOnceResolved(node, index), around?.side === void 0 ? around?.depth ?? 0 : 0);
17620
+ const after = pending.at(index + 1);
17621
+ const before = itemBefore(out, keptStart)?.node;
17622
+ const crossesKeptCut = before !== void 0 && standsInKeptCut(before) || after !== void 0 && standsInKeptCut(after);
17623
+ const carriedJoin = (path.length > 0 && before === void 0 !== (after === void 0) || crossesKeptCut) && joins !== void 0 && joins.remove === 0 && kept.length === 0 && resolution.decision === REVISION_DECISIONS.REJECT && isAddedRevision(node) ? Math.min(recordJoin(joins, "before"), recordJoin(joins, "after")) : 0;
17624
+ const removalCut = Math.max(cutLevelsOnceResolved(node, index), carriedJoin, around?.side === void 0 ? around?.depth ?? 0 : 0);
16581
17625
  if (around?.side !== void 0) folds.push(out.length);
16582
17626
  recordSourceSeam(out.length, removalCut);
16583
17627
  if (removalCut > 0) removalSeams.add(out.length);
@@ -16588,10 +17632,23 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16588
17632
  if (known === void 0 || made < known) removalDates.set(out.length, made);
16589
17633
  if (joins !== void 0) removalJoins.set(out.length, {
16590
17634
  before: recordJoin(joins, "before"),
16591
- after: recordJoin(joins, "after")
17635
+ after: recordJoin(joins, "after"),
17636
+ type: carriedJoin > 0 ? "carriedJoin" : "cut"
16592
17637
  });
16593
17638
  }
16594
- const beside = takeKeptBeside(index, keptStart, removalCut > 0);
17639
+ const faced = removalCut === 0 ? facedAcross : {
17640
+ before: false,
17641
+ after: false
17642
+ };
17643
+ const beside = takeKeptBeside({
17644
+ index,
17645
+ before: keptStart,
17646
+ takesSeam: removalCut > 0,
17647
+ handed: {
17648
+ before: handedKept.before || faced.before,
17649
+ after: handedKept.after || faced.after
17650
+ }
17651
+ });
16595
17652
  if (removalCut > 0 && beside !== void 0) exactKept.set(out.length, beside);
16596
17653
  if (removalCut === 0 && kept.length === 0 && isRemovedRevisionNode(node)) placeBetweenRemovedPieces(node, index);
16597
17654
  }
@@ -16622,8 +17679,12 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16622
17679
  resolution,
16623
17680
  path: [...path, index]
16624
17681
  });
16625
- const content = isAddedRevision(node) && resolution.decision === REVISION_DECISIONS.ACCEPT ? withNamedKept(withPayloadEdgesClosed(acceptCopyOriginAncestor(resolved.nodes), node.resolutionJoins, resolution), node.resolutionJoins, index) : resolved.nodes;
17682
+ const content = isAddedRevision(node) && resolution.decision === REVISION_DECISIONS.ACCEPT ? withNamedKept(withPayloadEdgesClosed(acceptCopyOriginAncestor(resolved.nodes), node.resolutionJoins, resolution), node, index) : resolved.nodes;
16626
17683
  if (content.length === 0 && node.content.length > 0) {
17684
+ if (isAddedRevision(node)) {
17685
+ placeNamedKeptAcross(index);
17686
+ namedKeptFacedAcross(index);
17687
+ }
16627
17688
  folds.push(out.length);
16628
17689
  if ((node.resolutionJoins?.plainSides?.length ?? 0) > 0) plainSeams.add(out.length);
16629
17690
  continue;
@@ -16637,7 +17698,10 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16637
17698
  recordKeptJoin(out.length, node);
16638
17699
  if (isRemovedRevisionNode(node)) ownContentAfter.add(out.length);
16639
17700
  }
16640
- const keptBefore = joined > 0 ? keptByPiece((at) => out[at]?.node, out.length - 1, -1, "after") : void 0;
17701
+ const keptBefore = joined > 0 ? keptByPiece((at) => out[at]?.node, out.length - 1, -1, {
17702
+ side: "after",
17703
+ id: node.info.id
17704
+ }) : void 0;
16641
17705
  if (keptBefore !== void 0) exactKept.set(out.length, {
16642
17706
  ...keptBefore,
16643
17707
  piece: "after"
@@ -16677,7 +17741,10 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16677
17741
  recordKeptJoin(out.length, node);
16678
17742
  if (isRemovedRevisionNode(node)) ownContentBefore.add(out.length);
16679
17743
  }
16680
- const keptAfter = joined > 0 ? keptByPiece((at) => pending[at], index + 1, 1, "before") : void 0;
17744
+ const keptAfter = joined > 0 ? keptByPiece((at) => pending[at], index + 1, 1, {
17745
+ side: "before",
17746
+ id: node.info.id
17747
+ }) : void 0;
16681
17748
  if (keptAfter !== void 0) exactKept.set(out.length, {
16682
17749
  ...keptAfter,
16683
17750
  piece: "before"
@@ -16732,6 +17799,11 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
16732
17799
  changed = true;
16733
17800
  const keepsEmptiedControl = node.type === "inlineSdt" && children.some((child) => isTrackedWrapper(child) && child.resolutionJoins?.holdsControlText === true);
16734
17801
  if ((isTrackedWrapper(node) || resolution.decision === REVISION_DECISIONS.ACCEPT && !keepsEmptiedControl || children.some((child) => isAddedRevision(child) && child.resolutionJoins?.emptiedHolder === true)) && inner.nodes.length === 0 && children.length > 0) {
17802
+ if (isAddedRevision(node)) {
17803
+ placeNamedKeptAcross(index);
17804
+ if (resolution.decision === REVISION_DECISIONS.ACCEPT) namedKeptFacedAcross(index);
17805
+ handEmptiedJoin(index);
17806
+ }
16735
17807
  folds.push(out.length);
16736
17808
  if (!isTrackedWrapper(node)) closeCutsAtEmptiedPiece({
16737
17809
  first: node,
@@ -17104,7 +18176,8 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
17104
18176
  const pieceOnly = kept?.piece !== void 0 && (kept.piece === "after" ? right : left) !== void 0;
17105
18177
  if (count === 0 || (left === void 0 || right === void 0) && !pieceOnly) continue;
17106
18178
  if (kept === void 0 && resolution.decision === REVISION_DECISIONS.ACCEPT && keptJoinSeams.has(recorded) && passesJoinOn(seam, seam - count - 1, depth)) continue;
17107
- if (kept === void 0 && (left === void 0 || right === void 0 || !sameOwnFields(left.node, right.node))) continue;
18179
+ const carriedJoinMeetsPiece = removalJoins.get(recorded)?.type === "carriedJoin" && alikeDepth(recordAt(left?.node, "end"), recordAt(right?.node, "start")) > 0;
18180
+ if (kept === void 0 && (left === void 0 || right === void 0 || !sameOwnFields(left.node, right.node) && !carriedJoinMeetsPiece)) continue;
17108
18181
  exactSeams.delete(recorded);
17109
18182
  exactSeams.set(seam, Math.max(exactSeams.get(seam) ?? 0, depth));
17110
18183
  if (floating.has(seam)) continue;
@@ -17323,7 +18396,7 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
17323
18396
  if (standingKept > 0 && keptFrom !== void 0 && takesKept && !yieldsKept) {
17324
18397
  const receiverBefore = side === "after";
17325
18398
  const records = keptRecordsFacing(index, receiverBefore ? "before" : "after");
17326
- tookKept = nameKeptPiece(receiverBefore ? first : seam - records, receiverBefore ? first + records : seam, receiverBefore ? "before" : "after");
18399
+ tookKept = nameKeptPiece(receiverBefore ? first : seam - records, receiverBefore ? first + records : seam, keptCutHolders(receiverBefore ? { before: changeAtEdge(node, "end") } : { after: changeAtEdge(node, "start") }));
17327
18400
  }
17328
18401
  if (node === occurrence.node && !tookKept) return;
17329
18402
  out[index] = occurrenceOf(node, occurrence);
@@ -17414,8 +18487,17 @@ const resolveList = ({ nodes: listed, resolution, path }) => {
17414
18487
  const facingAt = blockedBefore ? keptEnd : seam;
17415
18488
  const facingSide = blockedBefore ? "before" : "after";
17416
18489
  const inside = blockedSide !== "both" && facingJoinAt(facingAt, blockedBefore ? "after" : "before") > 0 ? keptRecordsFacing(facingAt, facingSide) : standingKept;
17417
- nameKeptPiece(blockedBefore ? first : seam - inside, blockedBefore ? first + inside : seam, blockedSide);
17418
- nameKeptPiece(first, seam, "both");
18490
+ const insideStart = blockedBefore ? first : seam - inside;
18491
+ const insideEnd = blockedBefore ? first + inside : seam;
18492
+ const holders = keptCutHolders({
18493
+ before: blockedBefore ? changeAtEdge(out[keptEnd]?.node, "end") : void 0,
18494
+ after: blockedAfter ? changeAtEdge(out[seam]?.node, "start") : void 0
18495
+ });
18496
+ nameKeptPiece(insideStart, insideEnd, holders);
18497
+ if (holders !== void 0 && inside < standingKept) nameKeptPiece(first, seam, {
18498
+ ...holders,
18499
+ scope: "seam"
18500
+ });
17419
18501
  continue;
17420
18502
  }
17421
18503
  if (handedOver.size > 0) continue;
@@ -17660,16 +18742,18 @@ const deferSplitSeam = ({ left, right, depth }) => {
17660
18742
  while (keptFrom >= 0 && standingInKeptCut(left.at(keptFrom))) keptFrom -= 1;
17661
18743
  let keptTo = rightStart;
17662
18744
  while (standingInKeptCut(right.at(keptTo))) keptTo += 1;
17663
- const named = (node, piece) => withKeptCutPieceRecorded(node, piece, /* @__PURE__ */ new WeakMap());
18745
+ const known = /* @__PURE__ */ new WeakMap();
18746
+ const leftHolder = keptCutHolders({ after: changeAtEdge(left[leftEnd + 1] ?? (rightStart > 0 ? right.at(0) : void 0), "start") });
18747
+ const rightHolder = keptCutHolders({ before: changeAtEdge(right[rightStart - 1] ?? (leftEnd < left.length - 1 ? left.at(-1) : void 0), "end") });
17664
18748
  const leftRow = left.slice(leftEnd + 1).toReversed();
17665
18749
  const rightRow = right.slice(0, rightStart);
17666
18750
  const atLeft = (node, index) => {
17667
18751
  if (index > leftEnd) return deferred(node, "after", leftRow);
17668
- return index > keptFrom ? named(node, "after") : node;
18752
+ return index > keptFrom && leftHolder !== void 0 ? withKeptCutHoldersRecorded(node, leftHolder, known) : node;
17669
18753
  };
17670
18754
  const atRight = (node, index) => {
17671
18755
  if (index < rightStart) return deferred(node, "before", rightRow);
17672
- return index < keptTo ? named(node, "before") : node;
18756
+ return index < keptTo && rightHolder !== void 0 ? withKeptCutHoldersRecorded(node, rightHolder, known) : node;
17673
18757
  };
17674
18758
  return {
17675
18759
  left: left.map(atLeft),
@@ -17683,7 +18767,7 @@ const deferSplitSeam = ({ left, right, depth }) => {
17683
18767
  };
17684
18768
  /**
17685
18769
  * Whether the paragraph stands only for its pending insertions: rejecting
17686
- * its added mark, which ended a block content control, left it in place.
18770
+ * its added mark left it in place until its content is resolved.
17687
18771
  */
17688
18772
  const standsForInsertions = (paragraph) => paragraph.content.some((node) => node.type === "insertion" && node.resolutionJoins?.holdsParagraph !== void 0);
17689
18773
  /**
@@ -17837,6 +18921,17 @@ const cutGoesOn = ({ mark, depth, onto }) => {
17837
18921
  const laterAt = splitDateOf(onto);
17838
18922
  return madeAt !== void 0 && laterAt !== void 0 && laterAt > madeAt && depth !== void 0 && depth > (onto.resolutionJoin ?? 0);
17839
18923
  };
18924
+ /**
18925
+ * An added paragraph that opens a section before trailing range boundaries
18926
+ * can disappear on rejection. The original section break and the trailing
18927
+ * boundaries keep the same placement.
18928
+ */
18929
+ const opensSectionBeforeTrailingBoundaries = (blocks, index) => {
18930
+ const follower = blockFollower(blocks, index);
18931
+ if (follower.block !== void 0 || follower.standing.length === 0) return false;
18932
+ const before = blocks.findLast((block, at) => at < index && !isBlockBoundary(block));
18933
+ return before?.type === "paragraph" && before.sectionProperties !== void 0;
18934
+ };
17840
18935
  const joinOps = (document, { op, story, paraId, revisionId, added, depth, holders }, ends, ranInto = /* @__PURE__ */ new Set(), joinsBefore = /* @__PURE__ */ new Set(), rejoined = /* @__PURE__ */ new Map()) => {
17841
18936
  const body = storyBody$1(document, story);
17842
18937
  const location = findStoryParagraph(body, paraId);
@@ -17984,6 +19079,7 @@ const joinOps = (document, { op, story, paraId, revisionId, added, depth, holder
17984
19079
  }));
17985
19080
  const followsBlock = isOpaqueFollower(next);
17986
19081
  const containerFinal = endsItsContainer(body, location);
19082
+ const endsBeforeBoundaries = added && next === void 0 && standing.length > 0 && opensSectionBeforeTrailingBoundaries(blocks, location.index);
17987
19083
  const tableBoundary = next?.type === "table" ? paragraphTableRunInBoundary(paragraph, next) : void 0;
17988
19084
  const tableTarget = tableBoundary?.type === "receiver" ? tableBoundary.target : void 0;
17989
19085
  const blockTarget = next !== void 0 && followsBlock ? paragraphBlockRunInTarget(paragraph, next) : void 0;
@@ -18012,7 +19108,7 @@ const joinOps = (document, { op, story, paraId, revisionId, added, depth, holder
18012
19108
  follows,
18013
19109
  holdsContent: paragraphHoldsContent(chained),
18014
19110
  markWasAdded: added,
18015
- containerStillEndsWithParagraph: follows !== "nothing" ? follows === "table" && blockListEndsInParagraph(blocks) || goesBeforeBlock || lastBlockPastBoundaries(blocks)?.type === "paragraph" : containerFinal && itemBefore(blocks, location.index)?.type === "paragraph" || endsControl && standsAfterBlock,
19111
+ containerStillEndsWithParagraph: follows !== "nothing" ? follows === "table" && blockListEndsInParagraph(blocks) || goesBeforeBlock || lastBlockPastBoundaries(blocks)?.type === "paragraph" : containerFinal && itemBefore(blocks, location.index)?.type === "paragraph" || endsBeforeBoundaries || endsControl && standsAfterBlock,
18016
19112
  followingTableCanReceiveRunIn: tableTarget !== void 0,
18017
19113
  holdsContentOnceAccepted: paragraphHoldsContentOnceAccepted(chained),
18018
19114
  followingBlockCanReceiveRunIn: blockTarget !== void 0,
@@ -18123,7 +19219,7 @@ const joinOps = (document, { op, story, paraId, revisionId, added, depth, holder
18123
19219
  expected: reviewFieldsOf(paragraph),
18124
19220
  review
18125
19221
  }];
18126
- const leavesHolder = added && op.decision === REVISION_DECISIONS.REJECT && (endsControl && standsAfterBlock || goesBeforeBlock);
19222
+ const leavesHolder = added && op.decision === REVISION_DECISIONS.REJECT && (endsControl && standsAfterBlock || goesBeforeBlock || endsBeforeBoundaries);
18127
19223
  const held = leavesHolder ? holdingParagraph(paragraph.content) : void 0;
18128
19224
  if (held !== void 0) markOps.push({
18129
19225
  type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
@@ -18189,7 +19285,8 @@ const absorbControlFollower = ({ document, story, paraId, applyOps }) => {
18189
19285
  * them, as rejecting its mark with them at once does: only while it still
18190
19286
  * ends its block content control short of the container's end, with a block
18191
19287
  * before it, so the control keeps ending with that block, or still stands
18192
- * before a block in a list that ends with a paragraph.
19288
+ * before a block in a list that ends with a paragraph, or opens a section
19289
+ * before trailing range boundaries.
18193
19290
  */
18194
19291
  const removeEmptiedHolder = ({ document, story, paraId, applyOps }) => {
18195
19292
  const body = storyBody$1(document, story);
@@ -18201,7 +19298,7 @@ const removeEmptiedHolder = ({ document, story, paraId, applyOps }) => {
18201
19298
  const anchor = blocks.find((block, position) => position !== index && block.type === "paragraph");
18202
19299
  const endsControl = index > 0 && index === blocks.length - 1 && list.at(-1)?.kind === "blockSdt" && !endsItsContainer(body, location);
18203
19300
  const standsBeforeBlock = anchor !== void 0 && isOpaqueFollower(blockFollower(blocks, index).block) && blockListEndsInParagraph(blocks.filter((block) => !isBlockBoundary(block)));
18204
- if (!endsControl && !standsBeforeBlock) return Result.ok(void 0);
19301
+ if (!endsControl && !standsBeforeBlock && !opensSectionBeforeTrailingBoundaries(blocks, index)) return Result.ok(void 0);
18205
19302
  const removed = applyOps(document, [anchor === void 0 ? {
18206
19303
  type: DOCUMENT_OP_TYPES.REPLACE_BLOCKS,
18207
19304
  story,
@@ -18359,6 +19456,7 @@ const removedPieceBoundary = ({ nodes, edge, resolution }) => {
18359
19456
  const settleTwoRecordMarks = (paragraphs, op) => {
18360
19457
  const ids = new Set(op.revisionIds);
18361
19458
  const ops = [];
19459
+ const replacementMarks = /* @__PURE__ */ new Map();
18362
19460
  for (const { paragraph } of paragraphs) {
18363
19461
  const mark = paragraph.pPrMark;
18364
19462
  if (mark?.deletion === void 0) continue;
@@ -18375,6 +19473,7 @@ const settleTwoRecordMarks = (paragraphs, op) => {
18375
19473
  ...mark.info.date === void 0 ? {} : { splitDate: mark.info.date }
18376
19474
  }
18377
19475
  };
19476
+ replacementMarks.set(insertion, deletion);
18378
19477
  ids.delete(insertion);
18379
19478
  } else {
18380
19479
  const { deletion: _deleted, ...added } = mark;
@@ -18389,6 +19488,33 @@ const settleTwoRecordMarks = (paragraphs, op) => {
18389
19488
  review
18390
19489
  });
18391
19490
  }
19491
+ if (replacementMarks.size > 0) {
19492
+ const planned = new Map(ops.map((edit) => [edit.blockId, edit]));
19493
+ for (const { paragraph } of paragraphs) {
19494
+ const blockId = paragraph.paraId ?? "";
19495
+ const existing = planned.get(blockId);
19496
+ const mark = existing === void 0 ? paragraph.pPrMark : existing.review.pPrMark;
19497
+ const target = mark?.takenOverMark;
19498
+ const replacement = target === void 0 ? void 0 : replacementMarks.get(target);
19499
+ if (mark === void 0 || replacement === void 0) continue;
19500
+ const expected = reviewFieldsOf(paragraph);
19501
+ const review = {
19502
+ ...existing?.review ?? expected,
19503
+ pPrMark: {
19504
+ ...mark,
19505
+ takenOverMark: replacement
19506
+ }
19507
+ };
19508
+ if (existing === void 0) ops.push({
19509
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
19510
+ story: op.story,
19511
+ blockId,
19512
+ expected,
19513
+ review
19514
+ });
19515
+ else existing.review = review;
19516
+ }
19517
+ }
18392
19518
  return {
18393
19519
  ops,
18394
19520
  ids: op.revisionIds.filter((id) => ids.has(id))
@@ -18850,6 +19976,8 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
18850
19976
  if (chainCut > depth) depth = Math.min(chainCut, trailing ?? chainCut);
18851
19977
  if (depth !== mark.resolutionJoin) retiredCutDepths.set(idKey(paragraph.paraId ?? ""), depth);
18852
19978
  }
19979
+ const keptBreaks = /* @__PURE__ */ new Set();
19980
+ for (const { paragraph: { pPrMark: mark } } of paragraphs) if (mark !== void 0 && ids.has(mark.info.id) && markWasAdded(mark.kind) === (op.decision === REVISION_DECISIONS.ACCEPT)) keptBreaks.add(mark.info.id);
18853
19981
  for (const location of paragraphs) {
18854
19982
  const { paragraph } = location;
18855
19983
  const paraId = paragraph.paraId ?? "";
@@ -18874,6 +20002,11 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
18874
20002
  });
18875
20003
  }
18876
20004
  let review = resolveParagraphReview(paragraph, resolution, keepsBreak);
20005
+ if (mark?.takenOverMark !== void 0 && keptBreaks.has(mark.takenOverMark) && !keepsBreak) {
20006
+ const { takenOverMark: _takenOverMark, ...positional } = mark;
20007
+ review ??= reviewFieldsOf(paragraph);
20008
+ review.pPrMark = positional;
20009
+ }
18877
20010
  const retiredDepth = retiredCutDepths.get(idKey(paraId));
18878
20011
  if (retiredDepth !== void 0) {
18879
20012
  const remainingMark = review === void 0 ? paragraph.pPrMark : review.pPrMark;
@@ -18890,6 +20023,31 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
18890
20023
  review
18891
20024
  });
18892
20025
  }
20026
+ const materialized = tryMaterializeResolution({
20027
+ document,
20028
+ story: op.story,
20029
+ locations: paragraphs,
20030
+ inline,
20031
+ join: joins.length === 0 ? { type: "noJoins" } : {
20032
+ type: "plan",
20033
+ prepare: (view) => {
20034
+ const ends = new Map(emptiedEnds);
20035
+ return planContiguousResolutionJoins({
20036
+ document,
20037
+ story: op.story,
20038
+ ...view,
20039
+ joins,
20040
+ planPair: ({ join, first, second }) => joinOps({ package: { document: { content: [first, second] } } }, join, ends)
20041
+ });
20042
+ }
20043
+ },
20044
+ noteReferences,
20045
+ receiverEffects
20046
+ });
20047
+ if (materialized.type === "materialized") return Result.ok({
20048
+ edit: materialized.edit,
20049
+ receiverEffects: materialized.receiverEffects
20050
+ });
18893
20051
  const staged = applyOps(document, inline);
18894
20052
  if (staged.isErr()) return Result.err(staged.error);
18895
20053
  const rows = resolveTableRows({
@@ -19033,17 +20191,9 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
19033
20191
  current = restored.value.document;
19034
20192
  }
19035
20193
  }
19036
- const exhausted = (document.package.document.comments ?? []).filter(({ id, parentId }) => parentId === void 0 && !isCommentExhausted({
19037
- type: "document",
19038
- document,
19039
- id
19040
- }) && isCommentExhausted({
19041
- type: "document",
19042
- document: current,
19043
- id
19044
- }));
20194
+ const exhausted = newlyExhaustedCommentIds(document, current);
19045
20195
  const beforeRetirement = current;
19046
- for (const { id } of exhausted) {
20196
+ for (const id of exhausted) {
19047
20197
  const retired = applyOps(current, [{
19048
20198
  type: DOCUMENT_OP_TYPES.DELETE_COMMENT,
19049
20199
  id,
@@ -19057,7 +20207,7 @@ const planSingleRecordResolution = ({ document, op, applyOps }, paragraphs) => {
19057
20207
  before: beforeRetirement,
19058
20208
  after: current,
19059
20209
  story: op.story,
19060
- retired: new Set(exhausted.map(({ id }) => id))
20210
+ retired: new Set(exhausted)
19061
20211
  });
19062
20212
  if (emptiedLinks.length > 0) {
19063
20213
  const removed = applyOps(current, emptiedLinks);
@@ -20387,10 +21537,12 @@ const withSpan = (cell, span) => {
20387
21537
  const formatting = authored({ ...cell.formatting });
20388
21538
  if (span === 1) delete formatting.gridSpan;
20389
21539
  else formatting.gridSpan = span;
20390
- return {
21540
+ if (Object.keys(formatting).length > 0) return {
20391
21541
  ...cell,
20392
21542
  formatting
20393
21543
  };
21544
+ const { formatting: _formatting, ...plain } = cell;
21545
+ return plain;
20394
21546
  };
20395
21547
  const dividedWidth = (width, parts) => {
20396
21548
  if (width === void 0) return void 0;
@@ -20524,6 +21676,58 @@ const restatedCell = (before, after, fields) => {
20524
21676
  fields
20525
21677
  }).map((propertyChanges) => propertyChanges === void 0 ? after : Object.assign({}, after, { propertyChanges }));
20526
21678
  };
21679
+ /**
21680
+ * A new cell a direct edit makes from `source`, taking its properties, with
21681
+ * `source`'s pending property changes restated over them as records of its
21682
+ * own: rejecting them takes the other properties off the new cell as it
21683
+ * does off `source`.
21684
+ */
21685
+ const copiedPropertyChanges = ({ source, cell, ids }) => {
21686
+ const restated = restatedCell(source, cell, CELL_GRID_FIELDS);
21687
+ if (restated.isErr() || restated.value.propertyChanges === void 0) return restated;
21688
+ const propertyChanges = [];
21689
+ for (const change of restated.value.propertyChanges) {
21690
+ const next = ids.next();
21691
+ if (next.done === true) panic("A copied property change has no revision id.");
21692
+ propertyChanges.push({
21693
+ ...change,
21694
+ info: {
21695
+ ...change.info,
21696
+ id: next.value
21697
+ }
21698
+ });
21699
+ }
21700
+ return Result.ok(Object.assign({}, restated.value, { propertyChanges }));
21701
+ };
21702
+ /**
21703
+ * The revision ids a direct edit gives the records it adds beside pending
21704
+ * ones, such as a new cell's copy of its source's property change: the first
21705
+ * `count` ids of `newIds.revision` no record in the package holds.
21706
+ */
21707
+ const directRevisionIds = ({ document, op, count }) => {
21708
+ if (count === 0) return Result.ok([]);
21709
+ const held = packageIdentityKeyIndex(document.package);
21710
+ const ids = [];
21711
+ for (const id of op.newIds?.revision ?? []) {
21712
+ if (ids.length === count) break;
21713
+ if (!Number.isInteger(id) || id < 0 || id > 2147483647) return refuse$3({
21714
+ op,
21715
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
21716
+ message: "Revision ids must be nonnegative 31-bit integers."
21717
+ });
21718
+ if (ids.includes(id) || held.has(slotKey({
21719
+ space: IDENTITY_SPACES.REVISION,
21720
+ id
21721
+ }))) continue;
21722
+ ids.push(id);
21723
+ }
21724
+ if (ids.length < count) return refuse$3({
21725
+ op,
21726
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
21727
+ message: `This table change keeps pending records under ${count} new revision ids.`
21728
+ });
21729
+ return Result.ok(ids);
21730
+ };
20527
21731
  /** `after`, the direct edit of `before`, with `before`'s pending property changes restated. */
20528
21732
  const restatedRow = (before, after) => restateChanges({
20529
21733
  changes: before.propertyChanges,
@@ -20589,15 +21793,13 @@ const rowExtent = (table, grid, row) => {
20589
21793
  * A grid column stands in the earlier grid unless a pending insertion takes
20590
21794
  * it whole.
20591
21795
  */
20592
- const columnReviews = ({ op, table, grid, leavesRow }) => {
21796
+ const columnReviews = ({ op, table, grid }) => {
20593
21797
  const conflict = (message) => refuse$3({
20594
21798
  op,
20595
21799
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
20596
21800
  message
20597
21801
  });
20598
- const columns = reviewColumns(grid);
20599
- if (columns === void 0) return conflict("Resolve the pending cell insertions and deletions that take part of a column before changing its columns.");
20600
- if (table.rows.some((row, rowIndex) => !leavesRow(rowIndex) && (!statesOwnGrid(row.propertyChanges, row.formatting, ROW_GRID_FIELDS) || row.cells.some((cell) => !statesOwnGrid(cell.propertyChanges, cell.formatting, CELL_SPAN_FIELDS))))) return conflict("Resolve the pending span changes of the rows the column crosses before changing its columns.");
21802
+ const columns = reviewColumns(grid) ?? panic("A column edit across partial records reads both decisions.");
20601
21803
  const gridChange = table.formatting?.gridChange;
20602
21804
  if (gridChange === void 0) return Result.ok(void 0);
20603
21805
  if (gridChange.columnWidths.length !== grid.width - columns.inserted.size) return conflict("Resolve the pending grid change before changing the table's columns.");
@@ -20612,6 +21814,365 @@ const columnReviews = ({ op, table, grid, leavesRow }) => {
20612
21814
  columnWidths
20613
21815
  });
20614
21816
  };
21817
+ /**
21818
+ * Whether a pending record places a column differently once it is accepted
21819
+ * than once it is rejected: a cell insertion or deletion that takes only part
21820
+ * of a column, or a row or cell property change recording other spans or
21821
+ * omissions.
21822
+ */
21823
+ const recordsPlaceColumnsApart = (table, grid) => reviewColumns(grid) === void 0 || table.rows.some((row) => !statesOwnGrid(row.propertyChanges, row.formatting, ROW_GRID_FIELDS) || row.cells.some((cell) => !statesOwnGrid(cell.propertyChanges, cell.formatting, CELL_SPAN_FIELDS)));
21824
+ /** A cell's first paragraph id, which names it in every decision's table. */
21825
+ const cellKey = (cell) => storyParagraphs({ content: cell.content }).at(0)?.paragraph.paraId;
21826
+ /** The rows of the table every cell and property record of which is decided. */
21827
+ const decidedRows = (table, reject, op) => {
21828
+ const decided = withTableRecordsResolved(table, reject);
21829
+ if (decided.isErr() || decided.value.rows.length !== table.rows.length) return void 0;
21830
+ const grid = tableGrid(decided.value, op.type);
21831
+ if (grid.isErr()) return void 0;
21832
+ const rows = [];
21833
+ for (const [index, row] of decided.value.rows.entries()) {
21834
+ const { before, end } = rowExtent(decided.value, grid.value, index);
21835
+ const cells = [];
21836
+ for (const { cell, start, end: cellEnd } of grid.value.rows[index] ?? []) {
21837
+ const key = cellKey(cell);
21838
+ if (key === void 0) return void 0;
21839
+ cells.push({
21840
+ key,
21841
+ start,
21842
+ end: cellEnd
21843
+ });
21844
+ }
21845
+ rows.push({
21846
+ before,
21847
+ end,
21848
+ after: row.formatting?.gridAfter ?? 0,
21849
+ cells
21850
+ });
21851
+ }
21852
+ return rows;
21853
+ };
21854
+ const columnPlace = (row, op) => {
21855
+ const insert = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN;
21856
+ const column = op.column;
21857
+ if (column < row.before) return { type: "before" };
21858
+ if (insert ? column > row.end + row.after : column >= row.end + row.after) return { type: "leaves" };
21859
+ if (insert ? column > row.end : column >= row.end) return { type: "after" };
21860
+ const spanning = row.cells.find(({ start, end }) => insert ? start < column && column < end : start <= column && column < end);
21861
+ if (spanning !== void 0) return {
21862
+ type: "within",
21863
+ cell: spanning.key,
21864
+ span: spanning.end - spanning.start
21865
+ };
21866
+ return {
21867
+ type: "between",
21868
+ after: row.cells.find(({ end }) => end === column)?.key
21869
+ };
21870
+ };
21871
+ /**
21872
+ * One row's part of a direct column edit, so that accepting every record
21873
+ * gives the edit of the accepted row, and rejecting them that of the
21874
+ * rejected row. `undefined` where no one change of the row does both.
21875
+ */
21876
+ const rowColumnPlan = ({ entries, accepted, rejected, op }) => {
21877
+ const inAccepted = accepted.cells.map(({ key }) => key);
21878
+ const inRejected = rejected.cells.map(({ key }) => key);
21879
+ const placeA = columnPlace(accepted, op);
21880
+ const placeR = columnPlace(rejected, op);
21881
+ if (placeA.type === "leaves" && placeR.type === "leaves") return { type: "unchanged" };
21882
+ if (placeA.type === "before" || placeA.type === "after") {
21883
+ if (placeR.type !== placeA.type) return void 0;
21884
+ return {
21885
+ type: "omission",
21886
+ side: placeA.type === "before" ? "gridBefore" : "gridAfter"
21887
+ };
21888
+ }
21889
+ if (placeR.type === "before" || placeR.type === "after") return void 0;
21890
+ const keys = entries.map(({ cell }) => cellKey(cell));
21891
+ const insert = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN;
21892
+ const count = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.count ?? 1 : 1;
21893
+ const spans = /* @__PURE__ */ new Map();
21894
+ const removed = /* @__PURE__ */ new Set();
21895
+ const occupant = insert ? void 0 : entries.findIndex(({ start, end }) => start <= op.column && op.column < end);
21896
+ for (const [index, key] of keys.entries()) {
21897
+ if (key === void 0) return void 0;
21898
+ const presentA = inAccepted.includes(key);
21899
+ const presentR = inRejected.includes(key);
21900
+ const hitA = placeA.type === "within" && placeA.cell === key;
21901
+ const hitR = placeR.type === "within" && placeR.cell === key;
21902
+ if (!insert) {
21903
+ const goesA = hitA && placeA.span === 1;
21904
+ const goesR = hitR && placeR.span === 1;
21905
+ if (presentA && presentR && goesA !== goesR) return void 0;
21906
+ if (goesA || goesR) {
21907
+ removed.add(index);
21908
+ continue;
21909
+ }
21910
+ }
21911
+ const delta = insert ? count : -1;
21912
+ const current = hitA && (insert ? placeR.type !== "between" : occupant === void 0 || occupant === index) ? delta : 0;
21913
+ const earlier = hitR ? delta : 0;
21914
+ if (current === 0 && earlier === 0) continue;
21915
+ const recorded = ((entries[index]?.cell)?.propertyChanges?.length ?? 0) > 0;
21916
+ if (!recorded && presentA && presentR && current !== earlier) return void 0;
21917
+ spans.set(index, recorded ? {
21918
+ current,
21919
+ earlier
21920
+ } : {
21921
+ current: presentA ? current : earlier,
21922
+ earlier: 0
21923
+ });
21924
+ }
21925
+ if (!insert) return {
21926
+ type: "cells",
21927
+ added: void 0,
21928
+ spans,
21929
+ removed
21930
+ };
21931
+ const range = (place, present) => {
21932
+ if (place.type !== "between") return void 0;
21933
+ const lower = place.after === void 0 ? 0 : keys.indexOf(place.after) + 1;
21934
+ const next = keys.findIndex((key, index) => index >= lower && key !== void 0 && present.includes(key));
21935
+ return {
21936
+ lower,
21937
+ upper: next === -1 ? keys.length : next
21938
+ };
21939
+ };
21940
+ const rangeA = range(placeA, inAccepted);
21941
+ const rangeR = range(placeR, inRejected);
21942
+ const ranges = [rangeA, rangeR].filter((each) => each !== void 0);
21943
+ if (ranges.length === 0) return {
21944
+ type: "cells",
21945
+ added: void 0,
21946
+ spans,
21947
+ removed
21948
+ };
21949
+ const at = maxOf(ranges.map(({ lower }) => lower), 0);
21950
+ if (ranges.some(({ lower, upper }) => lower < 0 || at > upper)) return void 0;
21951
+ let kept = "both";
21952
+ if (rangeA === void 0) kept = "reject";
21953
+ else if (rangeR === void 0) kept = "accept";
21954
+ return {
21955
+ type: "cells",
21956
+ added: {
21957
+ at,
21958
+ kept
21959
+ },
21960
+ spans,
21961
+ removed
21962
+ };
21963
+ };
21964
+ /** Every row's part of a direct column edit across records that place it apart. */
21965
+ const columnPlanAcrossRecords = ({ table, grid, op }) => {
21966
+ if (table.formatting?.gridChange !== void 0) return void 0;
21967
+ const accepted = decidedRows(table, false, op);
21968
+ const rejected = decidedRows(table, true, op);
21969
+ if (accepted === void 0 || rejected === void 0) return void 0;
21970
+ const plans = [];
21971
+ for (const index of table.rows.keys()) {
21972
+ const acceptedRow = accepted[index];
21973
+ const rejectedRow = rejected[index];
21974
+ const entries = grid.rows[index];
21975
+ if (acceptedRow === void 0 || rejectedRow === void 0 || entries === void 0) return void 0;
21976
+ const plan = rowColumnPlan({
21977
+ entries,
21978
+ accepted: acceptedRow,
21979
+ rejected: rejectedRow,
21980
+ op
21981
+ });
21982
+ if (plan === void 0) return void 0;
21983
+ plans.push(plan);
21984
+ }
21985
+ return plans;
21986
+ };
21987
+ /** The span field of cell formatting, moved by `delta` columns. */
21988
+ const respanned = (formatting, delta) => {
21989
+ if (delta === 0) return formatting;
21990
+ const next = authored({ ...formatting });
21991
+ const span = (formatting?.gridSpan ?? 1) + delta;
21992
+ if (span === 1) delete next.gridSpan;
21993
+ else next.gridSpan = span;
21994
+ return next;
21995
+ };
21996
+ /** The omission field of row formatting, moved by `delta` columns. */
21997
+ const reomitted = (formatting, side, delta) => {
21998
+ const next = authored({ ...formatting });
21999
+ const value = (formatting?.[side] ?? 0) + delta;
22000
+ if (side === "gridBefore") {
22001
+ if (value === 0) delete next.gridBefore;
22002
+ else next.gridBefore = value;
22003
+ } else if (value === 0) delete next.gridAfter;
22004
+ else next.gridAfter = value;
22005
+ return next;
22006
+ };
22007
+ /**
22008
+ * A direct column edit beside records that place the column apart once
22009
+ * accepted and once rejected. Each row takes the edit as both decisions read
22010
+ * it: a new cell only one of them keeps is recorded as that decision's cell
22011
+ * insertion or deletion, under the author of the row's record, and a span
22012
+ * only one of them changes is changed in the properties that decision gives
22013
+ * the cell. Accepting every record gives the edit of the accepted table, and
22014
+ * rejecting them that of the rejected one; where no table does both, the
22015
+ * edit refuses.
22016
+ */
22017
+ const columnEditAcrossRecords = ({ document, op, table, grid, conflict }) => {
22018
+ const refused = () => conflict("Resolve the pending cell insertions, deletions and span changes that place the column apart before changing its columns.");
22019
+ const plans = columnPlanAcrossRecords({
22020
+ table,
22021
+ grid,
22022
+ op
22023
+ });
22024
+ if (plans === void 0) return refused();
22025
+ const count = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.count ?? 1 : 1;
22026
+ const addedRows = plans.filter((plan) => plan.type === "cells" && plan.added !== void 0);
22027
+ const fresh = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? freshCells({
22028
+ document,
22029
+ op,
22030
+ ids: op.newBlockIds,
22031
+ count: addedRows.length * count
22032
+ }) : Result.ok([]);
22033
+ if (fresh.isErr()) return Result.err(fresh.error);
22034
+ const recorded = addedRows.filter((plan) => plan.type === "cells" && plan.added?.kept !== "both").length;
22035
+ const ids = directRevisionIds({
22036
+ document,
22037
+ op,
22038
+ count: recorded * count
22039
+ });
22040
+ if (ids.isErr()) return Result.err(ids.error);
22041
+ const freshIds = ids.value.values();
22042
+ const freshCellsLeft = fresh.value.values();
22043
+ const removedCells = [];
22044
+ const rows = [];
22045
+ for (const [rowIndex, row] of table.rows.entries()) {
22046
+ const plan = plans[rowIndex] ?? panic("A row has no plan.");
22047
+ const entries = grid.rows[rowIndex] ?? panic("A row has no grid.");
22048
+ const delta = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? count : -1;
22049
+ switch (plan.type) {
22050
+ case "unchanged":
22051
+ rows.push(row);
22052
+ continue;
22053
+ case "omission": {
22054
+ const next = {
22055
+ ...row,
22056
+ formatting: reomitted(row.formatting, plan.side, delta)
22057
+ };
22058
+ if (row.propertyChanges !== void 0) next.propertyChanges = row.propertyChanges.map((change) => ({
22059
+ ...change,
22060
+ previousFormatting: reomitted(change.previousFormatting, plan.side, delta)
22061
+ }));
22062
+ rows.push(next);
22063
+ continue;
22064
+ }
22065
+ case "cells": break;
22066
+ default: return plan;
22067
+ }
22068
+ const source = row.cells.find((cell) => cell.structuralChange !== void 0)?.structuralChange?.info ?? row.cells.find((cell) => cell.propertyChanges !== void 0)?.propertyChanges?.at(0)?.info ?? row.propertyChanges?.at(0)?.info;
22069
+ const recordInfo = (id) => {
22070
+ if (source === void 0) return panic("A new cell has no record.");
22071
+ const { author, date, initials, suggestionId } = source;
22072
+ return {
22073
+ id,
22074
+ author,
22075
+ ...date === void 0 ? {} : { date },
22076
+ ...initials === void 0 ? {} : { initials },
22077
+ ...suggestionId === void 0 ? {} : { suggestionId }
22078
+ };
22079
+ };
22080
+ const cells = [];
22081
+ const added = () => {
22082
+ const out = [];
22083
+ for (let column = 0; column < count; column += 1) {
22084
+ const next = freshCellsLeft.next();
22085
+ if (next.done === true) panic("A new cell has no paragraph id.");
22086
+ const kept = plan.added?.kept;
22087
+ if (kept === void 0 || kept === "both") {
22088
+ out.push(next.value);
22089
+ continue;
22090
+ }
22091
+ const id = freshIds.next();
22092
+ if (id.done === true) panic("A new cell has no revision id.");
22093
+ out.push({
22094
+ ...next.value,
22095
+ structuralChange: {
22096
+ type: kept === "accept" ? "tableCellInsertion" : "tableCellDeletion",
22097
+ info: recordInfo(id.value)
22098
+ }
22099
+ });
22100
+ }
22101
+ return out;
22102
+ };
22103
+ for (const [index, { cell }] of entries.entries()) {
22104
+ if (plan.added?.at === index) cells.push(...added());
22105
+ if (plan.removed.has(index)) {
22106
+ removedCells.push(cell);
22107
+ continue;
22108
+ }
22109
+ const span = plan.spans.get(index);
22110
+ if (span === void 0) {
22111
+ cells.push(cell);
22112
+ continue;
22113
+ }
22114
+ const next = { ...cell };
22115
+ const formatting = respanned(cell.formatting, span.current);
22116
+ if (formatting === void 0) delete next.formatting;
22117
+ else next.formatting = formatting;
22118
+ const [first, ...rest] = cell.propertyChanges ?? [];
22119
+ const earlier = respanned(first?.previousFormatting ?? {}, span.earlier);
22120
+ if (first !== void 0 && span.earlier !== 0) next.propertyChanges = [{
22121
+ ...first,
22122
+ ...earlier === void 0 ? {} : { previousFormatting: earlier }
22123
+ }, ...rest];
22124
+ cells.push(next);
22125
+ }
22126
+ if (plan.added !== void 0 && plan.added.at >= entries.length) cells.push(...added());
22127
+ if (editRemovesRow({
22128
+ before: row.cells,
22129
+ after: cells
22130
+ })) continue;
22131
+ rows.push({
22132
+ ...row,
22133
+ cells
22134
+ });
22135
+ }
22136
+ if (removedCells.some(reachesPastRemovedCell) || strandsABookmark(removedCells)) return refuse$3({
22137
+ op,
22138
+ reason: DOCUMENT_OP_REFUSAL_REASONS.DEPENDENT_RECORDS,
22139
+ message: "Resolve comments, moves and bookmarks reaching past the column before removing it."
22140
+ });
22141
+ const columnWidths = table.columnWidths === void 0 ? void 0 : [...table.columnWidths];
22142
+ if (columnWidths !== void 0) {
22143
+ if (op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN) columnWidths.splice(op.column, 0, ...Array.from({ length: count }, () => op.width));
22144
+ else columnWidths.splice(op.column, 1);
22145
+ }
22146
+ const edited = {
22147
+ ...table,
22148
+ rows
22149
+ };
22150
+ if (columnWidths !== void 0) edited.columnWidths = columnWidths;
22151
+ const newIds = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.newBlockIds : [];
22152
+ const unnamed = (value) => {
22153
+ let text = JSON.stringify(value);
22154
+ for (const id of newIds) text = text.replaceAll(`"${id}"`, `"new"`);
22155
+ return JSON.parse(text);
22156
+ };
22157
+ for (const reject of [false, true]) {
22158
+ const decided = withTableRecordsResolved(table, reject);
22159
+ const editedDecided = withTableRecordsResolved(edited, reject);
22160
+ if (decided.isErr() || editedDecided.isErr()) return refused();
22161
+ const decidedGrid = statedGrid(decided.value, op);
22162
+ if (decidedGrid.isErr()) return refused();
22163
+ const want = columnEdit({
22164
+ document,
22165
+ op: op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? {
22166
+ ...op,
22167
+ newBlockIds: newIds.slice(0, plans.filter((plan) => plan.type === "cells" && plan.added !== void 0 && plan.added.kept !== (reject ? "accept" : "reject")).length * count)
22168
+ } : op,
22169
+ table: decided.value,
22170
+ grid: decidedGrid.value
22171
+ });
22172
+ if (want.isErr() || !structurallyEqual(unnamed(editedDecided.value), unnamed(want.value))) return refused();
22173
+ }
22174
+ return Result.ok(edited);
22175
+ };
20615
22176
  const columnEdit = ({ document, op, table, grid }) => {
20616
22177
  const insert = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN;
20617
22178
  const count = op.type === DOCUMENT_OP_TYPES.INSERT_COLUMN ? op.count ?? 1 : 1;
@@ -20635,6 +22196,17 @@ const columnEdit = ({ document, op, table, grid }) => {
20635
22196
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
20636
22197
  message: "Resolve table reviews before changing its columns."
20637
22198
  });
22199
+ if (op.revision === void 0 && recordsPlaceColumnsApart(table, grid)) return columnEditAcrossRecords({
22200
+ document,
22201
+ op,
22202
+ table,
22203
+ grid,
22204
+ conflict: (message) => refuse$3({
22205
+ op,
22206
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
22207
+ message
22208
+ })
22209
+ });
20638
22210
  const removedCells = insert ? [] : grid.rows.flatMap((entries) => entries.filter((entry) => entry.start <= op.column && op.column < entry.end && entry.end - entry.start === 1).map((entry) => entry.cell));
20639
22211
  if (removedCells.some(reachesPastRemovedCell) || strandsABookmark(removedCells)) return refuse$3({
20640
22212
  op,
@@ -20663,8 +22235,7 @@ const columnEdit = ({ document, op, table, grid }) => {
20663
22235
  const earlierGrid = op.revision === void 0 ? columnReviews({
20664
22236
  op,
20665
22237
  table,
20666
- grid,
20667
- leavesRow
22238
+ grid
20668
22239
  }) : Result.ok(void 0);
20669
22240
  if (earlierGrid.isErr()) return Result.err(earlierGrid.error);
20670
22241
  const stampedRows = /* @__PURE__ */ new Map();
@@ -20881,6 +22452,35 @@ const closingRows = ({ before, after }) => new Set(after.flatMap((row, index) =>
20881
22452
  after: row.cells
20882
22453
  }) ? [index] : []));
20883
22454
  /**
22455
+ * The table without the rows a merge closes, each taken out as removing a
22456
+ * row does: a merge none of the rows left continues is no merge.
22457
+ */
22458
+ const withoutRows = (table, closing) => {
22459
+ let rows = table.rows;
22460
+ for (const index of [...closing].toSorted((left, right) => right - left)) rows = rowsWithoutRow({
22461
+ ...table,
22462
+ rows
22463
+ }, index);
22464
+ return {
22465
+ ...table,
22466
+ rows
22467
+ };
22468
+ };
22469
+ /**
22470
+ * A direct merge's rows that close go into its first row, which then holds
22471
+ * their words. Under a pending insertion or deletion of its own, the first
22472
+ * row would take them with it when that change removes it.
22473
+ */
22474
+ const closesOtherRows = ({ op, table, closing }) => {
22475
+ const first = table.rows[op.top]?.structuralChange;
22476
+ if (first === void 0 || [...closing].every((index) => structurallyEqual(table.rows[index]?.structuralChange, first))) return Result.ok(void 0);
22477
+ return refuse$3({
22478
+ op,
22479
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
22480
+ message: "Resolve the pending insertion or deletion of the merge's first row before merging rows it would take whole."
22481
+ });
22482
+ };
22483
+ /**
20884
22484
  * A suggested merge's rows, with the deletion of each row it closes
20885
22485
  * recorded beside its cell's merge record: accepting removes the row, as the
20886
22486
  * direct merge does, and rejecting keeps it as it was.
@@ -20916,25 +22516,240 @@ const trackedClosingRows = ({ document, op, table, merged, closing, used }) => {
20916
22516
  return Result.ok(rows);
20917
22517
  };
20918
22518
  /**
20919
- * Whether a direct merge keeps the table's pending records. The merged rows
20920
- * stand or go together: one pending insertion or deletion takes them all, or
20921
- * none does. A merged cell is under no pending insertion, deletion or merge of
20922
- * its own, and a cell the merge takes in records no other span, merge or
20923
- * width than it has.
22519
+ * Whether a direct merge keeps the table's pending records. A merged cell is
22520
+ * under no pending insertion, deletion or merge of its own, and a cell the
22521
+ * merge takes in records no other span, merge or width than it has. The
22522
+ * merged rows' own insertions and deletions stay on their words
22523
+ * (`reviewedMergeContent`).
20924
22524
  */
20925
- const mergeReviews = ({ op, table, selected, verticalOnly }) => {
22525
+ const mergeReviews = ({ op, selected, verticalOnly }) => {
20926
22526
  const conflict = (message) => refuse$3({
20927
22527
  op,
20928
22528
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
20929
22529
  message
20930
22530
  });
20931
- const rows = table.rows.slice(op.top, op.bottom);
20932
- if (rows.some((row) => !structurallyEqual(row.structuralChange, rows.at(0)?.structuralChange))) return conflict("Resolve the pending row insertions and deletions the merge crosses before merging.");
20933
22531
  const cells = selected.flat();
20934
22532
  if (cells.some(({ cell }) => cell.structuralChange !== void 0)) return conflict("Resolve the pending insertions, deletions and merges of the merged cells before merging.");
20935
22533
  if ((verticalOnly ? [] : cells.slice(1)).some(({ cell }) => !statesOwnGrid(cell.propertyChanges, cell.formatting, CELL_GRID_FIELDS))) return conflict("Resolve the pending span and width changes of the merged cells before merging.");
20936
22534
  return Result.ok(void 0);
20937
22535
  };
22536
+ /** The row change each kind of record goes with. */
22537
+ const ROW_CHANGE_TYPES = {
22538
+ [WRAP_KINDS.INSERTION]: "tableRowInsertion",
22539
+ [WRAP_KINDS.DELETION]: "tableRowDeletion"
22540
+ };
22541
+ const MARK_KINDS = {
22542
+ [WRAP_KINDS.INSERTION]: "ins",
22543
+ [WRAP_KINDS.DELETION]: "del"
22544
+ };
22545
+ /**
22546
+ * The paragraph's content recorded as the kind of change: words a pending
22547
+ * insertion already holds stay as they are, as a deletion keeps the words a
22548
+ * pending deletion holds.
22549
+ */
22550
+ const recordedContent = (paragraph, removal) => {
22551
+ const wrap = (items) => {
22552
+ if (items.length === 0) return Result.ok([]);
22553
+ const wrapped = wrapTracked({
22554
+ items,
22555
+ from: {
22556
+ offset: 0,
22557
+ zeroWidthBefore: 0
22558
+ },
22559
+ to: {
22560
+ offset: paragraphLength({
22561
+ type: "paragraph",
22562
+ content: [...items]
22563
+ }),
22564
+ zeroWidthBefore: Number.MAX_SAFE_INTEGER
22565
+ },
22566
+ kind: removal.kind,
22567
+ stamp: removal.stamp,
22568
+ ...removal.kind === WRAP_KINDS.DELETION ? { commentAnchors: "stand" } : {}
22569
+ });
22570
+ switch (wrapped.kind) {
22571
+ case "refused": return Result.err(wrapped.reason);
22572
+ case "unchanged": return Result.ok([...items]);
22573
+ case "wrapped": return Result.ok(wrapped.content);
22574
+ default: return wrapped;
22575
+ }
22576
+ };
22577
+ if (removal.kind === WRAP_KINDS.DELETION) return wrap(paragraph.content);
22578
+ const content = [];
22579
+ let stretch = [];
22580
+ for (const item of [...paragraph.content, void 0]) {
22581
+ if (item !== void 0 && item.type !== "insertion") {
22582
+ stretch.push(item);
22583
+ continue;
22584
+ }
22585
+ const wrapped = wrap(stretch);
22586
+ if (wrapped.isErr()) return wrapped;
22587
+ content.push(...wrapped.value);
22588
+ stretch = [];
22589
+ if (item !== void 0) content.push(item);
22590
+ }
22591
+ return Result.ok(content);
22592
+ };
22593
+ /**
22594
+ * A direct merge's cell content, across rows with different pending
22595
+ * insertions and deletions. The words of a row pending insertion keep that
22596
+ * insertion as records of their own, and those of a row pending deletion
22597
+ * that deletion, under its author, date and suggestion: rejecting the rows'
22598
+ * changes removes the inserted rows' words and keeps the deleted rows' in
22599
+ * place, and accepting them does the reverse. A paragraph mark between such
22600
+ * words and the next ones records the change too, so the words go with their
22601
+ * paragraphs. When the merged cell ends with words one decision removes,
22602
+ * the last paragraph that stays takes the cell's final mark as a paragraph
22603
+ * insertion or deletion at a container's end does.
22604
+ */
22605
+ const reviewedMergeContent = ({ document, op, changes, words }) => {
22606
+ if (changes.every((change) => structurallyEqual(change, changes.at(0)))) return Result.ok(words.flatMap(({ blocks }) => blocks));
22607
+ const conflict = (message) => refuse$3({
22608
+ op,
22609
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
22610
+ message
22611
+ });
22612
+ const merged = [];
22613
+ for (const { blocks: held, change } of words) for (const block of held) {
22614
+ if (change === void 0 && block.type === "paragraph") {
22615
+ merged.push({
22616
+ paragraph: block,
22617
+ removal: void 0
22618
+ });
22619
+ continue;
22620
+ }
22621
+ if (block.type !== "paragraph" || change?.type !== "tableRowInsertion" && change?.type !== "tableRowDeletion") return conflict("Resolve the pending row changes the merge crosses before merging cells that hold tables or content controls.");
22622
+ const { id, author, date, initials, suggestionId } = change.info;
22623
+ if (date === void 0) return conflict("Resolve the undated pending row changes the merge crosses before merging.");
22624
+ const stamp = {
22625
+ id,
22626
+ author,
22627
+ date,
22628
+ ...initials === void 0 ? {} : { initials },
22629
+ ...suggestionId === void 0 ? {} : { suggestionId }
22630
+ };
22631
+ merged.push({
22632
+ paragraph: block,
22633
+ removal: change.type === "tableRowInsertion" ? {
22634
+ kind: WRAP_KINDS.INSERTION,
22635
+ stamp
22636
+ } : {
22637
+ kind: WRAP_KINDS.DELETION,
22638
+ stamp
22639
+ }
22640
+ });
22641
+ }
22642
+ const lastStanding = (kind) => merged.findLastIndex(({ removal }) => removal?.kind !== kind);
22643
+ const rowStands = (kind) => changes.some((change) => change?.type !== ROW_CHANGE_TYPES[kind]);
22644
+ if ([WRAP_KINDS.INSERTION, WRAP_KINDS.DELETION].some((kind) => rowStands(kind) && lastStanding(kind) === -1)) return conflict("Resolve the pending row changes the merge crosses before merging cells whose words would all go with them.");
22645
+ const final = merged.length - 1;
22646
+ const after = [];
22647
+ for (const [index, { paragraph, removal }] of merged.entries()) {
22648
+ if (removal === void 0) {
22649
+ after.push(paragraph);
22650
+ continue;
22651
+ }
22652
+ const recorded = recordedContent(paragraph, removal);
22653
+ if (recorded.isErr()) return refuse$3({
22654
+ op,
22655
+ reason: recorded.error,
22656
+ message: "The merged rows' words cannot record their pending change."
22657
+ });
22658
+ const mark = MARK_KINDS[removal.kind];
22659
+ const existing = paragraph.pPrMark;
22660
+ if (existing !== void 0 && (existing.kind !== mark || existing.deletion !== void 0)) return conflict("Resolve the pending paragraph mark changes of the merged rows before merging.");
22661
+ const next = {
22662
+ ...paragraph,
22663
+ content: recorded.value
22664
+ };
22665
+ if (index === final) delete next.pPrMark;
22666
+ else if (existing === void 0) next.pPrMark = {
22667
+ kind: mark,
22668
+ info: stampInfo(removal.stamp)
22669
+ };
22670
+ after.push(next);
22671
+ }
22672
+ const ending = merged.at(final)?.removal;
22673
+ const standing = ending === void 0 ? -1 : lastStanding(ending.kind);
22674
+ if (ending !== void 0 && standing !== -1) {
22675
+ const survivor = after[standing] ?? panic("A merged paragraph is missing.");
22676
+ const last = after[final] ?? panic("A merged paragraph is missing.");
22677
+ if (survivor.pPrMark !== void 0 || survivor.propertyChanges !== void 0 || last.propertyChanges !== void 0) return conflict("Resolve the pending paragraph changes at the end of the merged cell before merging.");
22678
+ const info = stampInfo(ending.stamp);
22679
+ if (ending.kind === WRAP_KINDS.INSERTION) {
22680
+ after[standing] = {
22681
+ ...survivor,
22682
+ pPrMark: {
22683
+ kind: "ins",
22684
+ info,
22685
+ survivor: "first"
22686
+ }
22687
+ };
22688
+ for (let index = standing + 1; index < final; index += 1) {
22689
+ const paragraph = after[index] ?? panic("A merged paragraph is missing.");
22690
+ if (paragraph.pPrMark?.kind === "ins") after[index] = {
22691
+ ...paragraph,
22692
+ pPrMark: {
22693
+ ...paragraph.pPrMark,
22694
+ survivor: "first"
22695
+ }
22696
+ };
22697
+ }
22698
+ if (!structurallyEqual(finalizeParagraphFormatting(survivor.formatting) ?? {}, finalizeParagraphFormatting(last.formatting) ?? {})) after[final] = {
22699
+ ...last,
22700
+ propertyChanges: [{
22701
+ type: "paragraphPropertyChange",
22702
+ info,
22703
+ ...survivor.formatting === void 0 ? {} : { previousFormatting: survivor.formatting }
22704
+ }]
22705
+ };
22706
+ } else {
22707
+ after[standing] = {
22708
+ ...survivor,
22709
+ pPrMark: {
22710
+ kind: "del",
22711
+ info
22712
+ }
22713
+ };
22714
+ const formatting = finalizeParagraphFormatting(survivor.formatting);
22715
+ if (!structurallyEqual(formatting ?? {}, finalizeParagraphFormatting(last.formatting) ?? {})) {
22716
+ const review = reviewFieldsOf(last);
22717
+ delete review.formatting;
22718
+ if (formatting !== void 0) review.formatting = formatting;
22719
+ review.propertyChanges = [foldedParagraphPropertyChange({
22720
+ paragraph: last,
22721
+ formatting,
22722
+ stamp: ending.stamp
22723
+ })];
22724
+ after[final] = withReviewFields(last, review);
22725
+ }
22726
+ }
22727
+ }
22728
+ const before = merged.map(({ paragraph }) => paragraph);
22729
+ const held = packageIdentityKeyIndex(document.package);
22730
+ const own = /* @__PURE__ */ new Map();
22731
+ for (const key of identityKeysOf(before)) own.set(key, (own.get(key) ?? 0) + 1);
22732
+ const fresh = freshenIdentities({
22733
+ before,
22734
+ after,
22735
+ newIds: op.newIds ?? {},
22736
+ usedElsewhere: () => ({ has: (key) => held.count(key) > (own.get(key) ?? 0) })
22737
+ });
22738
+ switch (fresh.kind) {
22739
+ case "needsIds": return refuse$3({
22740
+ op,
22741
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
22742
+ message: `The merged rows' words need ${fresh.missing} more revision ids.`
22743
+ });
22744
+ case "invalidId": return refuse$3({
22745
+ op,
22746
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
22747
+ message: `${fresh.id} cannot be a new revision id.`
22748
+ });
22749
+ case "fresh": return Result.ok(fresh.paragraphs);
22750
+ default: return fresh;
22751
+ }
22752
+ };
20938
22753
  const merge = ({ document, op, table, grid }) => {
20939
22754
  if (hasStructuralMarkup(table)) return refuse$3({
20940
22755
  op,
@@ -20960,7 +22775,6 @@ const merge = ({ document, op, table, grid }) => {
20960
22775
  if (op.revision === void 0) {
20961
22776
  const kept = mergeReviews({
20962
22777
  op,
20963
- table,
20964
22778
  selected,
20965
22779
  verticalOnly
20966
22780
  });
@@ -21025,10 +22839,14 @@ const merge = ({ document, op, table, grid }) => {
21025
22839
  ...table,
21026
22840
  rows
21027
22841
  });
21028
- if (op.revision === void 0) return Result.ok({
22842
+ if (op.revision === void 0) return closesOtherRows({
22843
+ op,
22844
+ table,
22845
+ closing
22846
+ }).map(() => withoutRows({
21029
22847
  ...table,
21030
- rows: rows.filter((_row, index) => !closing.has(index))
21031
- });
22848
+ rows
22849
+ }, closing));
21032
22850
  return trackedClosingRows({
21033
22851
  document,
21034
22852
  op,
@@ -21052,8 +22870,20 @@ const merge = ({ document, op, table, grid }) => {
21052
22870
  if (fresh.isErr()) return Result.err(fresh.error);
21053
22871
  const first = selected.at(0)?.at(0);
21054
22872
  if (first === void 0) return mismatch(op, "No cells are selected.");
21055
- const holding = selected.flatMap((row) => row.map(({ cell }) => cell)).filter((cell) => !isEmptyCell(cell));
21056
- const content = (holding.length === 0 ? [first.cell] : holding).flatMap((cell) => cell.content);
22873
+ const changes = table.rows.slice(op.top, op.bottom).map(({ structuralChange }) => structuralChange);
22874
+ const holds = selected.some((row) => row.some(({ cell }) => !isEmptyCell(cell)));
22875
+ const words = selected.flatMap((row, offset) => row.filter(({ cell }) => holds ? !isEmptyCell(cell) : cell === first.cell).map(({ cell }) => ({
22876
+ blocks: cell.content,
22877
+ change: changes[offset]
22878
+ })));
22879
+ const reviewed = reviewedMergeContent({
22880
+ document,
22881
+ op,
22882
+ changes,
22883
+ words
22884
+ });
22885
+ if (reviewed.isErr()) return Result.err(reviewed.error);
22886
+ const content = reviewed.value;
21057
22887
  const mergedCellWidth = mergedWidth(selected.at(0)?.map(({ cell }) => cell) ?? []);
21058
22888
  if (mergedCellWidth.isErr()) return mismatch(op, "Selected cell widths must be nonnegative safe integer units.");
21059
22889
  const width = mergedCellWidth.value;
@@ -21096,10 +22926,14 @@ const merge = ({ document, op, table, grid }) => {
21096
22926
  before: table.rows,
21097
22927
  after: rows
21098
22928
  });
21099
- return Result.ok({
22929
+ return closesOtherRows({
22930
+ op,
22931
+ table,
22932
+ closing
22933
+ }).map(() => withoutRows({
21100
22934
  ...table,
21101
- rows: rows.filter((_row, index) => !closing.has(index))
21102
- });
22935
+ rows
22936
+ }, closing));
21103
22937
  };
21104
22938
  const split = ({ document, op, table, grid, location }) => {
21105
22939
  const target = grid.rows[location.rowIndex]?.find((entry) => entry.index === location.cellIndex);
@@ -21127,11 +22961,13 @@ const split = ({ document, op, table, grid, location }) => {
21127
22961
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
21128
22962
  message: "Resolve the pending insertions, deletions and merges of the split cell before splitting it."
21129
22963
  });
21130
- if (op.revision === void 0 && span > 1 && group.some(({ cell }) => cell.propertyChanges !== void 0)) return refuse$3({
22964
+ const copiedChanges = op.revision === void 0 ? directRevisionIds({
22965
+ document,
21131
22966
  op,
21132
- reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
21133
- message: "Resolve the pending property changes of the split cell before splitting its columns."
21134
- });
22967
+ count: group.reduce((sum, { cell }) => sum + (cell.propertyChanges?.length ?? 0) * (span - 1), 0)
22968
+ }) : Result.ok([]);
22969
+ if (copiedChanges.isErr()) return Result.err(copiedChanges.error);
22970
+ const copiedIds = copiedChanges.value.values();
21135
22971
  if (group.some(({ cell }) => {
21136
22972
  const width = cell.formatting?.width;
21137
22973
  return width !== void 0 && (width.type === "dxa" || width.type === "pct") && (!Number.isSafeInteger(width.value) || width.value < 0);
@@ -21203,7 +23039,17 @@ const split = ({ document, op, table, grid, location }) => {
21203
23039
  type: "tableCellInsertion",
21204
23040
  info: stampInfo(cellStamp)
21205
23041
  };
21206
- replacement.push(next);
23042
+ const copied = copiedPropertyChanges({
23043
+ source: entry.cell,
23044
+ cell: next,
23045
+ ids: copiedIds
23046
+ });
23047
+ if (copied.isErr()) return refuse$3({
23048
+ op,
23049
+ reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
23050
+ message: "A pending change records another span than the split changes."
23051
+ });
23052
+ replacement.push(copied.value);
21207
23053
  }
21208
23054
  }
21209
23055
  cells.splice(entry.index, 1, ...replacement);
@@ -21234,11 +23080,22 @@ const tableEditParagraphDemand = (location, op) => {
21234
23080
  const grid = statedGrid(table, op);
21235
23081
  if (grid.isErr()) return Result.err(grid.error);
21236
23082
  switch (op.type) {
21237
- case DOCUMENT_OP_TYPES.INSERT_COLUMN: return Result.ok(grid.value.rows.filter((cells, row) => {
21238
- const before = table.rows[row]?.formatting?.gridBefore ?? 0;
21239
- const { end } = rowExtent(table, grid.value, row);
21240
- return op.column >= before && op.column <= end && !cells.some((cell) => cell.start < op.column && op.column < cell.end);
21241
- }).length * (op.count ?? 1));
23083
+ case DOCUMENT_OP_TYPES.INSERT_COLUMN: {
23084
+ const plans = recordsPlaceColumnsApart(table, grid.value) ? columnPlanAcrossRecords({
23085
+ table,
23086
+ grid: grid.value,
23087
+ op: {
23088
+ ...op,
23089
+ newBlockIds: []
23090
+ }
23091
+ }) : void 0;
23092
+ if (plans !== void 0) return Result.ok(plans.filter((plan) => plan.type === "cells" && plan.added !== void 0).length * (op.count ?? 1));
23093
+ return Result.ok(grid.value.rows.filter((cells, row) => {
23094
+ const before = table.rows[row]?.formatting?.gridBefore ?? 0;
23095
+ const { end } = rowExtent(table, grid.value, row);
23096
+ return op.column >= before && op.column <= end && !cells.some((cell) => cell.start < op.column && op.column < cell.end);
23097
+ }).length * (op.count ?? 1));
23098
+ }
21242
23099
  case DOCUMENT_OP_TYPES.MERGE_CELLS: {
21243
23100
  const selection = mergeSelection({
21244
23101
  table,
@@ -21461,7 +23318,8 @@ const applyTableEdit = (document, op) => {
21461
23318
  });
21462
23319
  break;
21463
23320
  case DOCUMENT_OP_TYPES.SET_TABLE_GRID: {
21464
- if (op.columnWidths.length !== grid.value.width || op.columnWidths.some((width) => !Number.isSafeInteger(width) || width <= 0)) return mismatch(op, "Column widths must match the grid and be positive twip counts.");
23321
+ const unmeasured = op.columnWidths.length === 0;
23322
+ if (!unmeasured && op.columnWidths.length !== grid.value.width || op.columnWidths.some((width) => !Number.isSafeInteger(width) || width <= 0)) return mismatch(op, "Column widths must match the grid and be positive twip counts, or be none.");
21465
23323
  if (table.formatting?.gridChange !== void 0) return refuse$3({
21466
23324
  op,
21467
23325
  reason: DOCUMENT_OP_REFUSAL_REASONS.PENDING_TABLE_CHANGE,
@@ -21479,8 +23337,9 @@ const applyTableEdit = (document, op) => {
21479
23337
  });
21480
23338
  const stamps = stampsFor(op, 2);
21481
23339
  if (stamps.isErr()) return Result.err(stamps.error);
21482
- const next = {
21483
- ...table,
23340
+ const { columnWidths: _previous, ...rest } = table;
23341
+ const next = unmeasured ? rest : {
23342
+ ...rest,
21484
23343
  columnWidths: [...op.columnWidths]
21485
23344
  };
21486
23345
  const gridStamp = stamps.value.at(0);
@@ -22686,7 +24545,7 @@ const trackSplit = ({ op, stamp, paragraph, first, made, madeSecond, resolutionJ
22686
24545
  kind: "ins",
22687
24546
  info: stampInfo(stamp),
22688
24547
  resolutionJoin,
22689
- ...madeSecond ? { survivor: "first" } : {}
24548
+ ...madeSecond ? firstSurvivorFields(paragraph.pPrMark) : {}
22690
24549
  };
22691
24550
  if (!sameParagraphProperties(made.formatting, paragraph.formatting)) {
22692
24551
  const conflict = madeSecond ? paragraphPropertyFoldConflict(paragraph, stamp) : void 0;
@@ -23641,7 +25500,7 @@ const applyAddressedOp = ({ document, op, purpose, boxes }) => {
23641
25500
  purpose
23642
25501
  });
23643
25502
  if (applied.isErr()) return Result.err(applied.error);
23644
- const edit = applied.value;
25503
+ let edit = applied.value;
23645
25504
  const beforeSections = document.package.document.sections;
23646
25505
  const afterSections = edit.document.package.document.sections;
23647
25506
  const structural = op.type === DOCUMENT_OP_TYPES.SPLIT_BLOCK || op.type === DOCUMENT_OP_TYPES.JOIN_BLOCKS || op.type === DOCUMENT_OP_TYPES.REPLACE_BLOCKS;
@@ -23695,6 +25554,21 @@ const applyAddressedOp = ({ document, op, purpose, boxes }) => {
23695
25554
  }]
23696
25555
  };
23697
25556
  }
25557
+ const releases = op.type === DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW || op.type === DOCUMENT_OP_TYPES.RESOLVE_REVISION || edit.touched.removed.length === 0 ? [] : takenOverMarkReleases({
25558
+ before: document,
25559
+ after: edit.document,
25560
+ touched: edit.touched,
25561
+ story: addressedStory(op)
25562
+ });
25563
+ if (releases.length > 0) {
25564
+ const released = applyDocumentOpsForPurpose({
25565
+ document: edit.document,
25566
+ ops: releases,
25567
+ purpose
25568
+ });
25569
+ if (released.isErr()) return released;
25570
+ edit = combineEditEffects(released.value.document, [edit, released.value]);
25571
+ }
23698
25572
  return Result.ok({
23699
25573
  ...edit,
23700
25574
  inverse: edit.inverse.map(captureDocumentOp),
@@ -24552,6 +26426,13 @@ const filterNewIds = (op, keep) => {
24552
26426
  if (control !== void 0) newIds.control = control.filter((id) => keep(IDENTITY_SPACES.CONTROL, id));
24553
26427
  return withNewIds(op, newIds);
24554
26428
  };
26429
+ /** The table edits that may keep pending records on new rows and cells. */
26430
+ const DIRECT_TABLE_EDITS = /* @__PURE__ */ new Set([
26431
+ DOCUMENT_OP_TYPES.INSERT_COLUMN,
26432
+ DOCUMENT_OP_TYPES.DELETE_COLUMN,
26433
+ DOCUMENT_OP_TYPES.MERGE_CELLS,
26434
+ DOCUMENT_OP_TYPES.SPLIT_CELL
26435
+ ]);
24555
26436
  /** Keep only supplied ids that the successful operation put in changed paragraphs. */
24556
26437
  const trimAppliedNewIds = ({ before, op, applied, story }) => {
24557
26438
  if (!("newIds" in op) || op.newIds === void 0) return op;
@@ -24561,9 +26442,9 @@ const trimAppliedNewIds = ({ before, op, applied, story }) => {
24561
26442
  const location = findStoryParagraph(body, key);
24562
26443
  return location === void 0 ? [] : [location.paragraph];
24563
26444
  });
24564
- const identities = new Set(identityKeysIn(paragraphs));
24565
- const revisions = new Set(applied.revisions);
24566
26445
  const known = packageIdentityKeyIndex(before.package);
26446
+ const identities = new Set(DIRECT_TABLE_EDITS.has(op.type) && stampOf(op) === void 0 ? known.introducedIn(applied.document.package) : identityKeysIn(paragraphs));
26447
+ const revisions = new Set(applied.revisions);
24567
26448
  return filterNewIds(op, (space, id) => {
24568
26449
  const key = `${space}:${id}`;
24569
26450
  return !known.has(key) && (identities.has(key) || space === IDENTITY_SPACES.REVISION && revisions.has(id));
@@ -24714,8 +26595,10 @@ const leafPlan = ({ node, ancestors }, owner) => {
24714
26595
  const laterGap = (left, right) => compareGaps(left, right) >= 0 ? left : right;
24715
26596
  const earlierGap = (left, right) => compareGaps(left, right) <= 0 ? left : right;
24716
26597
  const replacementDeletionSegments = ({ spans, from, to, mode }) => {
24717
- const keepsLoneEmptyContainers = mode.type === "editing" && mode.keepsLoneEmptyContainers === true;
26598
+ const keepsLoneEmptyContainers = mode.type === "suggesting" || mode.keepsLoneEmptyContainers === true;
24718
26599
  const out = [];
26600
+ const recordingRegions = /* @__PURE__ */ new Set();
26601
+ let region = 0;
24719
26602
  let open;
24720
26603
  for (const span of spans) {
24721
26604
  const start = laterGap(span.before, from);
@@ -24723,6 +26606,7 @@ const replacementDeletionSegments = ({ spans, from, to, mode }) => {
24723
26606
  if (compareGaps(start, end) >= 0) continue;
24724
26607
  if (isParagraphContent(span.node) && isRangeBoundary(span.node)) {
24725
26608
  open = void 0;
26609
+ region += 1;
24726
26610
  continue;
24727
26611
  }
24728
26612
  let plan = isCommentAnchor(span.node) ? "anchor" : "direct";
@@ -24730,24 +26614,35 @@ const replacementDeletionSegments = ({ spans, from, to, mode }) => {
24730
26614
  else if (span.ancestors.some(isRemovedRevisionNode)) plan = "untouched";
24731
26615
  if (plan === "anchor") {
24732
26616
  open = void 0;
26617
+ region += 1;
24733
26618
  continue;
24734
26619
  }
24735
26620
  const segmentPlan = plan === "untouched" ? "tracked" : plan;
24736
- const records = plan !== "untouched" && !((mode.type === "suggesting" || keepsLoneEmptyContainers) && isEmptyContainer(span.node));
26621
+ const empty = plan !== "untouched" && keepsLoneEmptyContainers && isEmptyContainer(span.node);
26622
+ const records = plan !== "untouched" && !empty;
26623
+ if (records) recordingRegions.add(region);
24737
26624
  if (open !== void 0 && open.plan === segmentPlan && compareGaps(open.to, start) === 0) {
24738
26625
  open.to = end;
24739
26626
  open.records ||= records;
26627
+ open.empties ||= empty;
24740
26628
  continue;
24741
26629
  }
24742
26630
  open = {
24743
26631
  plan: segmentPlan,
24744
26632
  from: start,
24745
26633
  to: end,
24746
- records
26634
+ records,
26635
+ region,
26636
+ empties: empty
24747
26637
  };
24748
26638
  out.push(open);
24749
26639
  }
24750
- return out.filter(({ records }) => records);
26640
+ return out.flatMap((stretch) => stretch.records || mode.type === "editing" && stretch.empties && recordingRegions.has(stretch.region) ? [{
26641
+ plan: stretch.plan,
26642
+ from: stretch.from,
26643
+ to: stretch.to,
26644
+ records: true
26645
+ }] : []);
24751
26646
  };
24752
26647
  /**
24753
26648
  * The leaves of a range that its direct deletion leaves standing, in
@@ -25753,6 +27648,212 @@ const compileHyperlinkIntent = (document, { intent: sourceIntent, mode, compileI
25753
27648
  selection: intent.to
25754
27649
  });
25755
27650
  };
27651
+ // src/ops/pasteAnchors.ts
27652
+ const PLACEHOLDER_STEM = "_folioPasteAnchor";
27653
+ /** Where placeholder ids start; an id a bookmark already holds is skipped. */
27654
+ const PLACEHOLDER_FIRST_ID = 2130706432;
27655
+ /**
27656
+ * A placeholder name prefix no bookmark the destination or the paste holds
27657
+ * begins with, so that only this paste's placeholders carry it.
27658
+ */
27659
+ const freePrefix = (names) => {
27660
+ let serial = 0;
27661
+ for (;;) {
27662
+ const prefix = `${PLACEHOLDER_STEM}${String(serial)}_`;
27663
+ if (![...names].some((name) => name.startsWith(prefix))) return prefix;
27664
+ serial += 1;
27665
+ }
27666
+ };
27667
+ const PLACEHOLDER_INDEX = /^(?:0|[1-9]\d*)$/u;
27668
+ const placeholderIndex = (prefix, name) => {
27669
+ if (!name.startsWith(prefix)) return void 0;
27670
+ const suffix = name.slice(prefix.length);
27671
+ return PLACEHOLDER_INDEX.test(suffix) ? Number(suffix) : void 0;
27672
+ };
27673
+ /** `value` with every placeholder bookmark in it removed. */
27674
+ const withoutPasteAnchors = (value, ids) => {
27675
+ const isPlaceholder = (item) => {
27676
+ if (typeof item !== "object" || item === null) return false;
27677
+ const type = Reflect.get(item, "type");
27678
+ const id = Reflect.get(item, "id");
27679
+ return (type === "bookmarkStart" || type === "bookmarkEnd") && typeof id === "number" && ids.has(id);
27680
+ };
27681
+ const strip = (node) => {
27682
+ if (Array.isArray(node)) {
27683
+ for (let index = node.length - 1; index >= 0; index -= 1) if (isPlaceholder(node[index])) node.splice(index, 1);
27684
+ for (const item of node) strip(item);
27685
+ return;
27686
+ }
27687
+ if (typeof node !== "object" || node === null) return;
27688
+ for (const field of Object.values(node)) strip(field);
27689
+ };
27690
+ const copy = cloneModel(value);
27691
+ strip(copy);
27692
+ return copy;
27693
+ };
27694
+ /**
27695
+ * The blocks with each note reference and comment marker a placeholder, named
27696
+ * and numbered apart from every bookmark in `destination` and in the blocks.
27697
+ */
27698
+ const withPasteAnchors = (blocks, destination = {
27699
+ names: /* @__PURE__ */ new Set(),
27700
+ ids: /* @__PURE__ */ new Set()
27701
+ }) => {
27702
+ const pasted = bookmarksIn(blocks);
27703
+ const prefix = freePrefix(/* @__PURE__ */ new Set([...destination.names, ...pasted.names]));
27704
+ const taken = /* @__PURE__ */ new Set([...destination.ids, ...pasted.ids]);
27705
+ const ids = /* @__PURE__ */ new Set();
27706
+ let nextId = PLACEHOLDER_FIRST_ID;
27707
+ const anchors = [];
27708
+ const placeholder = (anchor) => {
27709
+ const index = anchors.length;
27710
+ anchors.push(anchor);
27711
+ while (taken.has(nextId)) nextId += 1;
27712
+ const id = nextId;
27713
+ nextId += 1;
27714
+ ids.add(id);
27715
+ return [{
27716
+ type: "bookmarkStart",
27717
+ id,
27718
+ name: `${prefix}${String(index)}`
27719
+ }, {
27720
+ type: "bookmarkEnd",
27721
+ id
27722
+ }];
27723
+ };
27724
+ const inline = (content) => {
27725
+ const out = [];
27726
+ for (const item of content) {
27727
+ if (item.type === "commentRangeStart" || item.type === "commentRangeEnd" || item.type === "commentReference") {
27728
+ out.push(...placeholder({
27729
+ kind: item.type,
27730
+ id: item.id
27731
+ }));
27732
+ continue;
27733
+ }
27734
+ if (item.type === "run") {
27735
+ if (!item.content.some((piece) => piece.type === "footnoteRef" || piece.type === "endnoteRef")) {
27736
+ out.push(item);
27737
+ continue;
27738
+ }
27739
+ let pending = [];
27740
+ const flush = () => {
27741
+ if (pending.length > 0) out.push({
27742
+ ...item,
27743
+ content: pending
27744
+ });
27745
+ pending = [];
27746
+ };
27747
+ for (const piece of item.content) {
27748
+ if (piece.type !== "footnoteRef" && piece.type !== "endnoteRef") {
27749
+ pending.push(piece);
27750
+ continue;
27751
+ }
27752
+ flush();
27753
+ out.push(...placeholder({
27754
+ kind: "note",
27755
+ note: piece.type === "footnoteRef" ? "footnote" : "endnote",
27756
+ id: piece.id
27757
+ }));
27758
+ }
27759
+ flush();
27760
+ continue;
27761
+ }
27762
+ out.push(isInlineContainer(item) ? withChildren(item, inline(childrenOf(item))) : item);
27763
+ }
27764
+ return out;
27765
+ };
27766
+ const block = (each) => each.type === "paragraph" ? {
27767
+ ...each,
27768
+ content: inline(each.content)
27769
+ } : {
27770
+ ...each,
27771
+ rows: each.rows.map((row) => ({
27772
+ ...row,
27773
+ cells: row.cells.map((cell) => ({
27774
+ ...cell,
27775
+ content: cell.content.map((inner) => inner.type === "paragraph" || inner.type === "table" ? block(inner) : inner)
27776
+ }))
27777
+ }))
27778
+ };
27779
+ const anchoredBlocks = blocks.map(block);
27780
+ return {
27781
+ prefix,
27782
+ ids,
27783
+ blocks: anchoredBlocks,
27784
+ plain: withoutPasteAnchors(anchoredBlocks, ids),
27785
+ anchors
27786
+ };
27787
+ };
27788
+ /** The names and ids of every bookmark `value` holds, at any depth. */
27789
+ const bookmarksIn = (value) => {
27790
+ const names = /* @__PURE__ */ new Set();
27791
+ const ids = /* @__PURE__ */ new Set();
27792
+ const visit = (node) => {
27793
+ if (Array.isArray(node)) {
27794
+ for (const item of node) visit(item);
27795
+ return;
27796
+ }
27797
+ if (node instanceof Map) {
27798
+ for (const item of node.values()) visit(item);
27799
+ return;
27800
+ }
27801
+ if (typeof node !== "object" || node === null) return;
27802
+ const type = Reflect.get(node, "type");
27803
+ const name = Reflect.get(node, "name");
27804
+ const id = Reflect.get(node, "id");
27805
+ if (type === "bookmarkStart" && typeof name === "string") names.add(name);
27806
+ if ((type === "bookmarkStart" || type === "bookmarkEnd") && typeof id === "number") ids.add(id);
27807
+ for (const field of Object.values(node)) visit(field);
27808
+ };
27809
+ visit(value);
27810
+ return {
27811
+ names,
27812
+ ids
27813
+ };
27814
+ };
27815
+ /** Whether `paragraph` holds this paste's placeholders and nothing else. */
27816
+ const holdsOnlyPasteAnchors = (paragraph, ids) => paragraph.content.length > 0 && paragraph.content.every((item) => (item.type === "bookmarkStart" || item.type === "bookmarkEnd") && ids.has(item.id));
27817
+ /**
27818
+ * Each of this paste's placeholders' place among `paragraphs`, by anchor
27819
+ * index; undefined when one is missing or found twice, since then no place
27820
+ * is the placeholder's own.
27821
+ */
27822
+ const placedPasteAnchors = ({ paragraphs, prefix, count }) => {
27823
+ const placed = /* @__PURE__ */ new Map();
27824
+ const seen = [];
27825
+ const visit = (items, at) => {
27826
+ let offset = at.start;
27827
+ for (const item of items) {
27828
+ if (item.type === "bookmarkStart") {
27829
+ const index = placeholderIndex(prefix, item.name);
27830
+ if (index !== void 0 && index < count) {
27831
+ seen.push(index);
27832
+ placed.set(index, {
27833
+ blockId: at.blockId,
27834
+ offset,
27835
+ order: at.order
27836
+ });
27837
+ }
27838
+ }
27839
+ if (isInlineContainer(item)) visit(childrenOf(item), {
27840
+ ...at,
27841
+ start: offset
27842
+ });
27843
+ offset += contentWidth([item]);
27844
+ }
27845
+ };
27846
+ for (const [order, paragraph] of paragraphs.entries()) {
27847
+ const blockId = paragraph.paraId;
27848
+ if (blockId === void 0) continue;
27849
+ visit(paragraph.content, {
27850
+ blockId,
27851
+ order,
27852
+ start: 0
27853
+ });
27854
+ }
27855
+ return seen.length !== count || placed.size !== count ? void 0 : placed;
27856
+ };
25756
27857
  // src/ops/rangeReplacement.ts
25757
27858
  /** Tracked replacement fragments share deletion's validation and physical-id pool. */
25758
27859
  const rangeParagraph = (body, blockId) => blockId === "" ? storyParagraphs(body).find(({ paragraph }) => (paragraph.paraId ?? "") === "") : findStoryParagraph(body, blockId);
@@ -26007,6 +28108,11 @@ const planTrackedReplacement = (document, options) => {
26007
28108
  });
26008
28109
  if (inserted.isErr()) return Result.err(inserted.error);
26009
28110
  }
28111
+ if (plan.ops.some((op) => op.type === DOCUMENT_OP_TYPES.DELETE_RANGE && op.revision === void 0)) for (const id of newlyExhaustedCommentIds(document, plan.document())) plan.ops.push({
28112
+ type: DOCUMENT_OP_TYPES.DELETE_COMMENT,
28113
+ id,
28114
+ scope: "thread"
28115
+ });
26010
28116
  return Result.ok(plan.ops);
26011
28117
  };
26012
28118
  /** Plan a same-list range deletion followed by tracked replacement insertions. */
@@ -26281,6 +28387,7 @@ const intentEndpoints = (intent) => {
26281
28387
  case "removeHyperlink":
26282
28388
  case "insertHyperlink":
26283
28389
  case "replaceFragment":
28390
+ case "pasteBlocks":
26284
28391
  case "moveFragment":
26285
28392
  case "replaceText":
26286
28393
  case "insertAtom":
@@ -26412,6 +28519,30 @@ const createEditorIntentIdAllocator = ({ reservedBlockIds } = {}) => {
26412
28519
  for (const span of leafSpans(paragraph.content)) demand += 4 * (1 + span.ancestors.length);
26413
28520
  }
26414
28521
  if (incoming.length > 0) demand += 8;
28522
+ if (intent.type === "pasteBlocks") {
28523
+ demand += 11;
28524
+ for (const block of intent.blocks) {
28525
+ const paragraphs = block.type === "table" ? storyParagraphs({ content: [block] }).map(({ paragraph }) => paragraph) : [block];
28526
+ if (block.type === "table") demand += 2 + block.rows.length;
28527
+ for (const paragraph of paragraphs) {
28528
+ demand += PARAGRAPH_REVISION_DEMAND;
28529
+ for (const span of leafSpans(paragraph.content)) demand += leafRevisionDemand(span.ancestors.length);
28530
+ }
28531
+ }
28532
+ for (const anchor of withPasteAnchors(intent.blocks).anchors) {
28533
+ if (anchor.kind !== "note") {
28534
+ demand += 4;
28535
+ continue;
28536
+ }
28537
+ const note = intent.annotations?.notes.find(({ type, id }) => type === anchor.note && id === anchor.id);
28538
+ demand += 4;
28539
+ for (const block of note?.content ?? []) {
28540
+ if (block.type !== "paragraph") continue;
28541
+ demand += PARAGRAPH_REVISION_DEMAND;
28542
+ for (const span of leafSpans(block.content)) demand += leafRevisionDemand(span.ancestors.length);
28543
+ }
28544
+ }
28545
+ }
26415
28546
  if (intent.type === "setHyperlink" || intent.type === "removeHyperlink" || intent.type === "insertHyperlink") demand = 2 * demand + 8;
26416
28547
  if (intent.type === "generateTOC") demand += 8 + (intent.headings.length + 1) * (PARAGRAPH_REVISION_DEMAND + 4 * leafRevisionDemand(3));
26417
28548
  if (intent.type === "moveFragment") {
@@ -26495,8 +28626,8 @@ const createEditorIntentIdAllocator = ({ reservedBlockIds } = {}) => {
26495
28626
  break;
26496
28627
  }
26497
28628
  case DOCUMENT_OP_TYPES.MERGE_CELLS:
26498
- demand = (op.bottom - op.top + 1) * 2;
26499
- for (const row of located.value.table.rows.slice(op.top + 1, op.bottom)) {
28629
+ demand = (op.bottom - op.top + 1) * 2 + 2;
28630
+ for (const row of located.value.table.rows.slice(op.top, op.bottom)) {
26500
28631
  demand += 1;
26501
28632
  for (const { paragraph } of storyParagraphs({ content: [{
26502
28633
  type: "table",
@@ -26679,6 +28810,543 @@ const adjacentJoinRefusal = (document, join) => {
26679
28810
  });
26680
28811
  };
26681
28812
  const paragraphAt = (document, at) => findStoryParagraph(storyBody$1(document, at.story), at.blockId)?.paragraph;
28813
+ /**
28814
+ * Whether `paragraph` holds content in `[from, to)` once its changes are
28815
+ * accepted, by the one paragraph-content rule: range markers, comment
28816
+ * references and what accepting takes away hold none. A paste keeps a
28817
+ * paragraph for the text beside it only when this holds, in either mode, so
28818
+ * accepting a suggested paste leaves the paragraphs the direct paste does.
28819
+ */
28820
+ const holdsContentWithin = ({ paragraph, from, to }) => {
28821
+ const clip = (items, start) => {
28822
+ const content = [];
28823
+ let offset = start;
28824
+ for (const item of items) {
28825
+ const end = offset + contentWidth([item]);
28826
+ if (end > from && offset < to) content.push(isInlineContainer(item) ? withChildren(item, clip(childrenOf(item), offset)) : item);
28827
+ offset = end;
28828
+ }
28829
+ return content;
28830
+ };
28831
+ return paragraphHoldsContentOnceAccepted({
28832
+ ...paragraph,
28833
+ content: clip(paragraph.content, 0)
28834
+ });
28835
+ };
28836
+ /** Bookmark ids the content's starts and ends carry, containers included. */
28837
+ const bookmarkIdsIn = (items) => items.flatMap((item) => {
28838
+ if (item.type === "bookmarkStart" || item.type === "bookmarkEnd") return [item.id];
28839
+ return isInlineContainer(item) ? bookmarkIdsIn(childrenOf(item)) : [];
28840
+ });
28841
+ /** Whether a pasted table, or one nested in it, holds bookmarks or records of its own. */
28842
+ const holdsTableLevelIdentities = (block) => {
28843
+ if (block.type !== "table") return false;
28844
+ if ((block.bookmarks?.length ?? 0) > 0 || (block.propertyChanges?.length ?? 0) > 0 || (block.carrierStack?.length ?? 0) > 0) return true;
28845
+ return block.rows.some((row) => (row.bookmarks?.length ?? 0) > 0 || (row.propertyChanges?.length ?? 0) > 0 || (row.carrierStack?.length ?? 0) > 0 || row.cells.some((cell) => (cell.propertyChanges?.length ?? 0) > 0 || (cell.carrierStack?.length ?? 0) > 0 || cell.content.some((inner) => (inner.type === "paragraph" || inner.type === "table") && holdsTableLevelIdentities(inner))));
28846
+ };
28847
+ /** A pasted block's paragraphs in document order, a table's cells' among them. */
28848
+ const blockParagraphs = (block) => block.type === "paragraph" ? [block] : block.rows.flatMap((row) => row.cells.flatMap((cell) => cell.content.flatMap((inner) => inner.type === "paragraph" || inner.type === "table" ? blockParagraphs(inner) : [])));
28849
+ /**
28850
+ * Clipboard blocks placed: once with their placeholders, to find where each
28851
+ * lands, and once without, for the operations and the document they leave.
28852
+ * Placeholders are zero width and hold no content, so both place the blocks
28853
+ * alike; a found place the plain document does not hold refuses. An open
28854
+ * fragment holding only placeholders places nothing: the range is cleared and
28855
+ * every placeholder lands at the caret. A closed paragraph is placed as one.
28856
+ */
28857
+ const placeAnchoredBlocks = (document, { intent, plain, prefix, ids, count, mode, firstBlockId }) => {
28858
+ const story = intent.from.story;
28859
+ const paragraphsOf = (from) => storyParagraphs(storyBody$1(from, story)).map(({ paragraph }) => paragraph);
28860
+ const only = intent.blocks.length === 1 ? intent.blocks[0] : void 0;
28861
+ if (only?.type === "paragraph" && intent.openStart === 1 && intent.openEnd === 1 && holdsOnlyPasteAnchors(only, ids)) {
28862
+ const cleared = idKey(intent.from.blockId) === idKey(intent.to.blockId) && intent.from.offset === intent.to.offset && (intent.from.zeroWidthBefore ?? 0) === (intent.to.zeroWidthBefore ?? 0) ? Result.ok({
28863
+ ops: [],
28864
+ selection: intent.from
28865
+ }) : compileEditorIntent(document, {
28866
+ intent: {
28867
+ type: "replaceText",
28868
+ from: intent.from,
28869
+ to: intent.to,
28870
+ text: ""
28871
+ },
28872
+ mode,
28873
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
28874
+ });
28875
+ if (cleared.isErr()) return Result.err(cleared.error);
28876
+ const applied = applyDocumentOps(document, cleared.value.ops);
28877
+ if (applied.isErr()) return Result.err(applied.error);
28878
+ const caret = cleared.value.selection;
28879
+ const order = paragraphsOf(applied.value.document).findIndex(({ paraId }) => paraId === caret.blockId);
28880
+ const at = {
28881
+ blockId: caret.blockId,
28882
+ offset: caret.offset,
28883
+ order
28884
+ };
28885
+ return Result.ok({
28886
+ ops: [...cleared.value.ops],
28887
+ document: applied.value.document,
28888
+ caret,
28889
+ places: () => at
28890
+ });
28891
+ }
28892
+ const placed = compileBlockPlacement(document, {
28893
+ intent,
28894
+ mode,
28895
+ firstBlockId
28896
+ });
28897
+ if (placed.isErr()) return Result.err(placed.error);
28898
+ const marked = placed.value.applied === void 0 ? applyDocumentOps(document, placed.value.ops) : Result.ok(placed.value.applied);
28899
+ if (marked.isErr()) return Result.err(marked.error);
28900
+ const lost = () => Result.err(new DocumentOpRefusal({
28901
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
28902
+ message: "A pasted note or comment lost its place in the paste.",
28903
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
28904
+ }));
28905
+ const found = placedPasteAnchors({
28906
+ paragraphs: paragraphsOf(marked.value.document),
28907
+ prefix,
28908
+ count
28909
+ });
28910
+ if (found === void 0) return lost();
28911
+ const unmarkedPlacement = compileBlockPlacement(document, {
28912
+ intent: {
28913
+ ...intent,
28914
+ blocks: plain
28915
+ },
28916
+ mode,
28917
+ firstBlockId
28918
+ });
28919
+ if (unmarkedPlacement.isErr()) return Result.err(unmarkedPlacement.error);
28920
+ const unmarked = unmarkedPlacement.value.applied === void 0 ? applyDocumentOps(document, unmarkedPlacement.value.ops) : Result.ok(unmarkedPlacement.value.applied);
28921
+ if (unmarked.isErr()) return Result.err(unmarked.error);
28922
+ const lengths = new Map(paragraphsOf(unmarked.value.document).map((paragraph) => [paragraph.paraId, paragraphLength(paragraph)]));
28923
+ for (const { blockId, offset } of found.values()) {
28924
+ const length = lengths.get(blockId);
28925
+ if (length === void 0 || offset > length) return lost();
28926
+ }
28927
+ return Result.ok({
28928
+ ops: [...unmarkedPlacement.value.ops],
28929
+ document: unmarked.value.document,
28930
+ caret: unmarkedPlacement.value.selection,
28931
+ places: (index) => found.get(index)
28932
+ });
28933
+ };
28934
+ /**
28935
+ * Clipboard blocks whose note references and comment markers name notes and
28936
+ * comments: the blocks are placed with a placeholder for each, then each note
28937
+ * and comment is copied under a fresh id where its placeholder landed, the
28938
+ * latest place first so that no copy moves the place of another. A comment
28939
+ * whose range the clipboard holds only part of is copied as a point.
28940
+ */
28941
+ const compileBlockPaste = (document, { intent, mode, firstBlockId }) => {
28942
+ const { annotations, ...placement } = intent;
28943
+ const anchored = withPasteAnchors(intent.blocks, bookmarksIn(document.package));
28944
+ if (anchored.anchors.length === 0) return compileBlockPlacement(document, {
28945
+ intent: placement,
28946
+ mode,
28947
+ firstBlockId
28948
+ });
28949
+ const refuse = (message) => Result.err(new DocumentOpRefusal({
28950
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_OPERATION,
28951
+ message,
28952
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
28953
+ }));
28954
+ const story = intent.from.story;
28955
+ const notes = [];
28956
+ for (const anchor of anchored.anchors) {
28957
+ if (anchor.kind !== "note") {
28958
+ if (!annotations?.comments.some(({ id }) => id === anchor.id)) return refuse("A pasted comment marker names no copied comment.");
28959
+ notes.push(void 0);
28960
+ continue;
28961
+ }
28962
+ const note = annotations?.notes.find(({ type, id }) => type === anchor.note && id === anchor.id);
28963
+ if (note === void 0) return refuse("A pasted note reference names no copied note.");
28964
+ if (story !== OP_STORIES.MAIN) return refuse("Notes are pasted only into the document body.");
28965
+ if (note.content.some((block) => block.type !== "paragraph")) return refuse("A pasted note holds only paragraphs.");
28966
+ notes.push(note);
28967
+ }
28968
+ const placed = placeAnchoredBlocks(document, {
28969
+ intent: {
28970
+ ...placement,
28971
+ blocks: anchored.blocks
28972
+ },
28973
+ plain: anchored.plain,
28974
+ prefix: anchored.prefix,
28975
+ ids: anchored.ids,
28976
+ count: anchored.anchors.length,
28977
+ mode,
28978
+ firstBlockId
28979
+ });
28980
+ if (placed.isErr()) return placed;
28981
+ const { ops, places, caret } = placed.value;
28982
+ let current = placed.value.document;
28983
+ const copies = [];
28984
+ const ranges = /* @__PURE__ */ new Map();
28985
+ for (const [index, anchor] of anchored.anchors.entries()) {
28986
+ const at = places(index);
28987
+ if (at === void 0) continue;
28988
+ const note = notes[index];
28989
+ if (anchor.kind === "note") {
28990
+ if (note !== void 0) copies.push({
28991
+ kind: "note",
28992
+ at,
28993
+ note,
28994
+ rank: index
28995
+ });
28996
+ continue;
28997
+ }
28998
+ const range = ranges.get(anchor.id) ?? {};
28999
+ const ranked = {
29000
+ at,
29001
+ rank: index
29002
+ };
29003
+ if (anchor.kind === "commentRangeStart") range.start = ranked;
29004
+ else if (anchor.kind === "commentRangeEnd") range.end = ranked;
29005
+ else range.reference = ranked;
29006
+ ranges.set(anchor.id, range);
29007
+ }
29008
+ for (const [id, { start, end, reference }] of ranges) {
29009
+ const comment = annotations?.comments.find((each) => each.id === id) ?? panic("A pasted comment was checked against the copied comments.");
29010
+ const ranged = start !== void 0 && end !== void 0;
29011
+ const last = ranged ? end : reference ?? end ?? start;
29012
+ if (last === void 0) continue;
29013
+ copies.push({
29014
+ kind: "comment",
29015
+ from: ranged ? start.at : void 0,
29016
+ at: last.at,
29017
+ comment,
29018
+ rank: last.rank
29019
+ });
29020
+ }
29021
+ copies.sort((left, right) => right.at.order - left.at.order || right.at.offset - left.at.offset || right.rank - left.rank);
29022
+ const position = ({ blockId, offset }) => ({
29023
+ story,
29024
+ blockId,
29025
+ offset
29026
+ });
29027
+ const nextId = (ids) => maxOf((ids ?? []).map(({ id }) => id), 0) + 1;
29028
+ const freshContent = ({ content, opType, reserved }) => {
29029
+ const identified = identifyClipboardParagraphs({
29030
+ document: current,
29031
+ paragraphs: content,
29032
+ mode: {
29033
+ ...mode,
29034
+ newIds: {
29035
+ ...mode.newIds,
29036
+ revision: [...mode.newIds?.revision ?? [], ...reserved]
29037
+ }
29038
+ },
29039
+ firstBlockId: void 0
29040
+ });
29041
+ if (identified.isErr()) return Result.err(identified.error);
29042
+ const fresh = freshParagraphIds({
29043
+ document: current,
29044
+ reserved: mode.reservedBlockIds,
29045
+ lease: mode.idLease,
29046
+ count: content.length,
29047
+ opType
29048
+ });
29049
+ if (fresh.isErr()) return Result.err(fresh.error);
29050
+ for (const [index, paragraph] of identified.value.entries()) paragraph.paraId = fresh.value[index] ?? panic("A fresh paragraph id is missing.");
29051
+ return Result.ok(identified.value);
29052
+ };
29053
+ const freeRevisionIds = () => {
29054
+ const occupied = packageIdOccupancy(current.package).revisions;
29055
+ const commented = new Set((current.package.document.comments ?? []).map(({ id }) => id));
29056
+ return [...mode.type === "suggesting" ? [mode.revision.id] : [], ...mode.newIds?.revision ?? []].filter((candidate) => !occupied.has(candidate) && !commented.has(candidate));
29057
+ };
29058
+ const out = [...ops];
29059
+ for (const copy of copies) {
29060
+ let op;
29061
+ if (copy.kind === "note") {
29062
+ const content = freshContent({
29063
+ content: copy.note.content.filter((block) => block.type === "paragraph"),
29064
+ opType: DOCUMENT_OP_TYPES.ADD_NOTE,
29065
+ reserved: []
29066
+ });
29067
+ if (content.isErr()) return Result.err(content.error);
29068
+ const note = copy.note.type === "footnote" ? {
29069
+ ...cloneModel(copy.note),
29070
+ id: nextId(current.package.footnotes),
29071
+ content: content.value
29072
+ } : {
29073
+ ...cloneModel(copy.note),
29074
+ id: nextId(current.package.endnotes),
29075
+ content: content.value
29076
+ };
29077
+ let stamp = {};
29078
+ if (mode.type === "suggesting") {
29079
+ const [id, ...rest] = freeRevisionIds();
29080
+ if (id === void 0) return Result.err(new DocumentOpRefusal({
29081
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
29082
+ message: "The pasted notes need more revision ids.",
29083
+ opType: DOCUMENT_OP_TYPES.ADD_NOTE
29084
+ }));
29085
+ stamp = {
29086
+ revision: {
29087
+ ...mode.revision,
29088
+ id
29089
+ },
29090
+ newIds: {
29091
+ revision: rest,
29092
+ control: mode.newIds.control ?? []
29093
+ }
29094
+ };
29095
+ }
29096
+ op = {
29097
+ type: DOCUMENT_OP_TYPES.ADD_NOTE,
29098
+ at: position(copy.at),
29099
+ note,
29100
+ ...stamp
29101
+ };
29102
+ } else {
29103
+ const fresh = freshCommentId(current, mode.idLease);
29104
+ if (fresh.isErr()) return Result.err(fresh.error);
29105
+ const commentId = fresh.value;
29106
+ const content = freshContent({
29107
+ content: copy.comment.content,
29108
+ opType: DOCUMENT_OP_TYPES.CREATE_COMMENT,
29109
+ reserved: [commentId]
29110
+ });
29111
+ if (content.isErr()) return Result.err(content.error);
29112
+ const { parentId: _parent, suggestionId: _suggestion, ...source } = cloneModel(copy.comment);
29113
+ const proposed = mode.type === "suggesting" ? mode.revision.suggestionId : void 0;
29114
+ op = {
29115
+ type: DOCUMENT_OP_TYPES.CREATE_COMMENT,
29116
+ newIds: {
29117
+ revision: freeRevisionIds().filter((id) => id !== commentId),
29118
+ control: mode.newIds?.control ?? []
29119
+ },
29120
+ comment: {
29121
+ ...source,
29122
+ id: commentId,
29123
+ content: content.value,
29124
+ anchorKind: copy.from === void 0 ? "point" : "range",
29125
+ ...proposed === void 0 ? {} : { suggestionId: proposed }
29126
+ },
29127
+ anchor: copy.from === void 0 ? {
29128
+ kind: "point",
29129
+ at: position(copy.at)
29130
+ } : {
29131
+ kind: "range",
29132
+ from: position(copy.from),
29133
+ to: position(copy.at)
29134
+ }
29135
+ };
29136
+ }
29137
+ const applied = applyDocumentOp(current, op);
29138
+ if (applied.isErr()) return Result.err(applied.error);
29139
+ out.push(trimAppliedNewIds({
29140
+ before: current,
29141
+ op,
29142
+ applied: applied.value,
29143
+ story
29144
+ }));
29145
+ current = applied.value.document;
29146
+ }
29147
+ const passed = copies.filter(({ at }) => at.blockId === caret.blockId && at.offset <= caret.offset).length;
29148
+ return Result.ok({
29149
+ ops: out,
29150
+ selection: {
29151
+ ...caret,
29152
+ offset: caret.offset + passed
29153
+ }
29154
+ });
29155
+ };
29156
+ /**
29157
+ * Clipboard blocks with tables: one step after another, each compiled against
29158
+ * the document the last left and, suggesting, taking the revision ids the
29159
+ * steps before it left unused.
29160
+ */
29161
+ const compileBlockPlacement = (document, { intent, mode, firstBlockId }) => {
29162
+ const { from, to, openStart, openEnd } = intent;
29163
+ const paragraphs = intent.blocks.filter((block) => block.type === "paragraph");
29164
+ if (paragraphs.length === intent.blocks.length) return compileEditorIntent(document, {
29165
+ intent: {
29166
+ type: "replaceFragment",
29167
+ from,
29168
+ to,
29169
+ paragraphs,
29170
+ openStart,
29171
+ openEnd
29172
+ },
29173
+ mode,
29174
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
29175
+ });
29176
+ const identified = identifyClipboardParagraphs({
29177
+ document,
29178
+ paragraphs: intent.blocks.flatMap(blockParagraphs),
29179
+ mode,
29180
+ firstBlockId
29181
+ });
29182
+ if (identified.isErr()) return Result.err(identified.error);
29183
+ let next = 0;
29184
+ const take = () => identified.value[next++] ?? panic("An identified clipboard paragraph is missing.");
29185
+ const rebuilt = (block) => block.type === "paragraph" ? take() : {
29186
+ ...block,
29187
+ rows: block.rows.map((row) => ({
29188
+ ...row,
29189
+ cells: row.cells.map((cell) => ({
29190
+ ...cell,
29191
+ content: cell.content.map((inner) => inner.type === "paragraph" || inner.type === "table" ? rebuilt(inner) : inner)
29192
+ }))
29193
+ }))
29194
+ };
29195
+ const blocks = intent.blocks.map(rebuilt);
29196
+ const refuseIdentities = (message) => Result.err(new DocumentOpRefusal({
29197
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_OPERATION,
29198
+ message,
29199
+ opType: DOCUMENT_OP_TYPES.INSERT_TABLE
29200
+ }));
29201
+ if (blocks.some(holdsTableLevelIdentities)) return refuseIdentities("A pasted table's own bookmarks and tracked records need fresh identities.");
29202
+ const joinedBlocks = /* @__PURE__ */ new Set();
29203
+ if (openStart === 1 && blocks.at(0)?.type === "paragraph") joinedBlocks.add(0);
29204
+ if (openEnd === 1 && blocks.at(-1)?.type === "paragraph") joinedBlocks.add(blocks.length - 1);
29205
+ const bookmarkBlocks = /* @__PURE__ */ new Map();
29206
+ for (const [index, block] of blocks.entries()) for (const paragraph of blockParagraphs(block)) for (const id of bookmarkIdsIn(paragraph.content)) {
29207
+ const holders = bookmarkBlocks.get(id) ?? /* @__PURE__ */ new Set();
29208
+ holders.add(index);
29209
+ bookmarkBlocks.set(id, holders);
29210
+ }
29211
+ for (const holders of bookmarkBlocks.values()) if (holders.size > 1 && [...holders].some((index) => joinedBlocks.has(index))) return refuseIdentities("A pasted bookmark spanning a joined paragraph and a table needs one identity.");
29212
+ const ops = [];
29213
+ let current = document;
29214
+ let pool = mode.type === "suggesting" ? [mode.revision.id, ...mode.newIds.revision ?? []] : [];
29215
+ const step = (stepIntent) => {
29216
+ let stepMode = mode;
29217
+ if (mode.type === "suggesting") {
29218
+ const [id, ...rest] = pool;
29219
+ if (id === void 0) return Result.err(new DocumentOpRefusal({
29220
+ reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
29221
+ message: "The pasted blocks need more revision ids.",
29222
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
29223
+ }));
29224
+ stepMode = {
29225
+ ...mode,
29226
+ revision: {
29227
+ ...mode.revision,
29228
+ id
29229
+ },
29230
+ newIds: {
29231
+ ...mode.newIds,
29232
+ revision: rest
29233
+ }
29234
+ };
29235
+ }
29236
+ const compiled = compileEditorIntent(current, {
29237
+ intent: stepIntent,
29238
+ mode: stepMode,
29239
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
29240
+ });
29241
+ if (compiled.isErr()) return Result.err(compiled.error);
29242
+ const applied = compiled.value.applied === void 0 ? applyDocumentOps(current, compiled.value.ops) : Result.ok(compiled.value.applied);
29243
+ if (applied.isErr()) return Result.err(applied.error);
29244
+ ops.push(...compiled.value.ops);
29245
+ current = applied.value.document;
29246
+ const occupied = packageIdOccupancy(current.package).revisions;
29247
+ pool = pool.filter((candidate) => !occupied.has(candidate));
29248
+ return Result.ok(compiled.value.selection);
29249
+ };
29250
+ let caret = from;
29251
+ if (from.blockId !== to.blockId || from.offset !== to.offset) {
29252
+ const cleared = step({
29253
+ type: "replaceText",
29254
+ from,
29255
+ to,
29256
+ text: ""
29257
+ });
29258
+ if (cleared.isErr()) return Result.err(cleared.error);
29259
+ caret = cleared.value;
29260
+ }
29261
+ const head = blocks.at(0);
29262
+ if (openStart === 1 && head?.type === "paragraph") {
29263
+ blocks.shift();
29264
+ const joined = step({
29265
+ type: "replaceFragment",
29266
+ from: caret,
29267
+ to: caret,
29268
+ paragraphs: [head],
29269
+ openStart: 1,
29270
+ openEnd: 1
29271
+ });
29272
+ if (joined.isErr()) return Result.err(joined.error);
29273
+ caret = joined.value;
29274
+ }
29275
+ const last = blocks.at(-1);
29276
+ const tail = openEnd === 1 && last?.type === "paragraph" ? last : void 0;
29277
+ if (tail !== void 0) blocks.pop();
29278
+ const destination = paragraphAt(current, caret);
29279
+ if (destination === void 0) return Result.err(new DocumentOpRefusal({
29280
+ reason: DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND,
29281
+ message: "The clipboard destination paragraph does not exist.",
29282
+ opType: DOCUMENT_OP_TYPES.INSERT_BLOCKS
29283
+ }));
29284
+ if (holdsContentWithin({
29285
+ paragraph: destination,
29286
+ from: 0,
29287
+ to: caret.offset
29288
+ })) {
29289
+ const fresh = freshParagraphIds({
29290
+ document: current,
29291
+ reserved: mode.reservedBlockIds,
29292
+ lease: mode.idLease,
29293
+ count: 1,
29294
+ opType: DOCUMENT_OP_TYPES.SPLIT_BLOCK
29295
+ });
29296
+ if (fresh.isErr()) return Result.err(fresh.error);
29297
+ const newBlockId = fresh.value[0] ?? panic("A fresh paragraph id is missing.");
29298
+ const split = step({
29299
+ type: "splitParagraph",
29300
+ at: caret,
29301
+ newBlockId
29302
+ });
29303
+ if (split.isErr()) return Result.err(split.error);
29304
+ }
29305
+ const anchor = caret.blockId;
29306
+ for (const block of blocks) {
29307
+ const placed = step(block.type === "paragraph" ? {
29308
+ type: "insertParagraphs",
29309
+ story: caret.story,
29310
+ at: {
29311
+ type: "before",
29312
+ blockId: anchor
29313
+ },
29314
+ paragraphs: [block]
29315
+ } : {
29316
+ type: "tableBlock",
29317
+ operation: {
29318
+ type: DOCUMENT_OP_TYPES.INSERT_TABLE,
29319
+ story: caret.story,
29320
+ blockId: anchor,
29321
+ table: block,
29322
+ side: "before",
29323
+ paragraphAfter: "none"
29324
+ }
29325
+ });
29326
+ if (placed.isErr()) return Result.err(placed.error);
29327
+ }
29328
+ let selection = {
29329
+ story: caret.story,
29330
+ blockId: anchor,
29331
+ offset: 0
29332
+ };
29333
+ if (tail !== void 0) {
29334
+ const joined = step({
29335
+ type: "replaceFragment",
29336
+ from: selection,
29337
+ to: selection,
29338
+ paragraphs: [tail],
29339
+ openStart: 1,
29340
+ openEnd: 1
29341
+ });
29342
+ if (joined.isErr()) return Result.err(joined.error);
29343
+ selection = joined.value;
29344
+ }
29345
+ return Result.ok({
29346
+ ops,
29347
+ selection
29348
+ });
29349
+ };
26682
29350
  /** The first paragraph of the cell a merge made, which keeps its place. */
26683
29351
  const mergedCellParagraph = ({ document, op, located }) => {
26684
29352
  const leading = tableGrid(located.table, op.type).map(({ rows }) => rows[op.top]?.find(({ start }) => start === op.left)).unwrapOr(void 0);
@@ -26986,7 +29654,9 @@ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId
26986
29654
  return id;
26987
29655
  };
26988
29656
  const remintedControls = /* @__PURE__ */ new WeakSet();
29657
+ const keptMarkers = [];
26989
29658
  visit(copy, (value) => {
29659
+ if ("keptCut" in value) keptMarkers.push(value);
26990
29660
  if ("type" in value && value.type === "inlineSdt" && "properties" in value && typeof value.properties === "object" && value.properties !== null && "id" in value.properties && typeof value.properties.id === "number") {
26991
29661
  value.properties.id = freshId(IDENTITY_SPACES.CONTROL, value.properties.id);
26992
29662
  remintedControls.add(value.properties);
@@ -26999,6 +29669,14 @@ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId
26999
29669
  else if (isCopiedRangeMarker(value)) value.id = freshId("bookmark", value.id);
27000
29670
  }
27001
29671
  });
29672
+ for (const marker of keptMarkers) {
29673
+ const cut = marker.keptCut;
29674
+ if (!isKeptCut(cut)) continue;
29675
+ marker.keptCut = remapKeptCutHolders(cut, (id) => remapped.get(slotKey({
29676
+ space: IDENTITY_SPACES.REVISION,
29677
+ id
29678
+ })));
29679
+ }
27002
29680
  if (leaseExhausted) return Result.err(new DocumentOpRefusal({
27003
29681
  reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
27004
29682
  message: "The pasted content needs more ids than the lease holds.",
@@ -27357,6 +30035,11 @@ const compileInStory = (document, { intent, mode, firstBlockId, typedFormatting
27357
30035
  ...firstBlockId === void 0 ? {} : { firstBlockId }
27358
30036
  })
27359
30037
  });
30038
+ case "pasteBlocks": return compileBlockPaste(document, {
30039
+ intent,
30040
+ mode,
30041
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
30042
+ });
27360
30043
  case "replaceFragment": {
27361
30044
  if (intent.paragraphs.length === 0) return compileEditorIntent(document, {
27362
30045
  intent: {
@@ -27401,8 +30084,13 @@ const compileInStory = (document, { intent, mode, firstBlockId, typedFormatting
27401
30084
  const endpoint = paragraphAt(document, intent.to);
27402
30085
  const destinationFormatting = splitParagraphFields$1(document, intent.from).formatting;
27403
30086
  const endpointFormatting = splitParagraphFields$1(document, intent.to).formatting;
27404
- const prefixBoundary = intent.openStart === 0 && intent.from.offset > 0;
27405
- const suffixBoundary = intent.openEnd === 0 && endpoint !== void 0 && intent.to.offset < paragraphLength(endpoint);
30087
+ const keeps = (paragraph, from, to) => paragraph !== void 0 && holdsContentWithin({
30088
+ paragraph,
30089
+ from,
30090
+ to
30091
+ });
30092
+ const prefixBoundary = intent.openStart === 0 && keeps(destination, 0, intent.from.offset);
30093
+ const suffixBoundary = intent.openEnd === 0 && endpoint !== void 0 && keeps(endpoint, intent.to.offset, paragraphLength(endpoint));
27406
30094
  const normalized = [
27407
30095
  ...prefixBoundary ? [{
27408
30096
  type: "paragraph",
@@ -29584,6 +32272,7 @@ const paragraphMarkChange = object({
29584
32272
  info: trackedChangeInfo,
29585
32273
  resolutionJoin: optional(natural),
29586
32274
  survivor: optional(literal("first")),
32275
+ takenOverMark: optional(natural),
29587
32276
  splitDate: optional(string),
29588
32277
  deletion: optional(object({ info: trackedChangeInfo }))
29589
32278
  });
@@ -30219,7 +32908,7 @@ const SEQUENCED_EFFECT_TYPES = Object.freeze({
30219
32908
  deleteRange: "deleteRange",
30220
32909
  setRunProps: "setRunProps",
30221
32910
  setParagraphProps: NO_SEQUENCED_EFFECT,
30222
- insertBlocks: NO_SEQUENCED_EFFECT,
32911
+ insertBlocks: "insertBlocks",
30223
32912
  splitBlock: "splitBlock",
30224
32913
  joinBlocks: "joinBlocks",
30225
32914
  resolveRevision: "touchedBlocks",
@@ -30267,7 +32956,7 @@ const SEQUENCED_EFFECT_TYPES = Object.freeze({
30267
32956
  const sequencedEffectType = (op) => {
30268
32957
  if (op.type === DOCUMENT_OP_TYPES.INSERT_BLOCKS) switch (op.at.type) {
30269
32958
  case "before":
30270
- case "after": return NO_SEQUENCED_EFFECT;
32959
+ case "after": return DOCUMENT_OP_TYPES.INSERT_BLOCKS;
30271
32960
  case "beforeTable":
30272
32961
  case "afterTable":
30273
32962
  case "containerStart": return "touchedBlocks";
@@ -30277,6 +32966,15 @@ const sequencedEffectType = (op) => {
30277
32966
  }
30278
32967
  return SEQUENCED_EFFECT_TYPES[op.type];
30279
32968
  };
32969
+ /**
32970
+ * Whether a sequenced effect of `type` is one `op` may carry: the effect it
32971
+ * records, or the one a journal sequenced before that effect existed
32972
+ * recorded for it.
32973
+ */
32974
+ const acceptsSequencedEffect = (op, type) => {
32975
+ const recorded = sequencedEffectType(op);
32976
+ return type === recorded || recorded === DOCUMENT_OP_TYPES.INSERT_BLOCKS && type === "none";
32977
+ };
30280
32978
  const commonOperationFields = { undefinedFields: optional(array(array(nonemptyString))) };
30281
32979
  const position = object({
30282
32980
  story: isOpStory,
@@ -30817,6 +33515,10 @@ const isDocumentBatch = (value) => object({
30817
33515
  type: literal("joinBlocks"),
30818
33516
  firstLength: natural
30819
33517
  })(effect);
33518
+ case "insertBlocks": return object({
33519
+ type: literal("insertBlocks"),
33520
+ borderingRevisionIds: array(natural)
33521
+ })(effect);
30820
33522
  case "insertContent": return object({
30821
33523
  type: literal("insertContent"),
30822
33524
  cutIdentified: boolean
@@ -30906,7 +33608,7 @@ const decodeDocumentBatch = (value) => {
30906
33608
  if (!natural(value.revision) || !Array.isArray(effects) || effects.length !== value.ops.length || !effects.every((effect, index) => {
30907
33609
  if (!isRecord(effect)) return false;
30908
33610
  const op = value.ops.at(index);
30909
- return op !== void 0 && effect["type"] === sequencedEffectType(op);
33611
+ return op !== void 0 && acceptsSequencedEffect(op, effect["type"]);
30910
33612
  })) return Result.err(new BatchRejection({
30911
33613
  reason: BATCH_REJECTION_REASONS.INVALID_BATCH,
30912
33614
  message: "Sequenced effects must match their operation indexes"
@@ -31338,6 +34040,11 @@ const transformCommentPair = ({ op, over, effect }) => {
31338
34040
  }
31339
34041
  return Result.ok([op]);
31340
34042
  };
34043
+ // src/ops/sequencing/heldRevisions.ts
34044
+ /** The tracked changes a piece of content holds, by revision id. */
34045
+ const REVISION_KEY_PREFIX$1 = `${IDENTITY_SPACES.REVISION}:`;
34046
+ /** The ids of the revisions held in `content`, as the revisions part keys them. */
34047
+ const heldRevisionIds = (content) => identityKeysIn(content).flatMap((key) => key.startsWith(REVISION_KEY_PREFIX$1) ? [key.slice(REVISION_KEY_PREFIX$1.length)] : []);
31341
34048
  // src/ops/sequencing/inlineTransform.ts
31342
34049
  /**
31343
34050
  * Sequencing of inline insertions and of inline record splits and joins.
@@ -31671,11 +34378,6 @@ const transformInlinePair = (pair) => {
31671
34378
  }
31672
34379
  }
31673
34380
  };
31674
- // src/ops/sequencing/heldRevisions.ts
31675
- /** The tracked changes a piece of content holds, by revision id. */
31676
- const REVISION_KEY_PREFIX$1 = `${IDENTITY_SPACES.REVISION}:`;
31677
- /** The ids of the revisions held in `content`, as the revisions part keys them. */
31678
- const heldRevisionIds = (content) => identityKeysIn(content).flatMap((key) => key.startsWith(REVISION_KEY_PREFIX$1) ? [key.slice(REVISION_KEY_PREFIX$1.length)] : []);
31679
34381
  // src/ops/sequencing/restoreTransform.ts
31680
34382
  /**
31681
34383
  * Paragraph restorations against concurrent edits of the same paragraph.
@@ -32317,6 +35019,32 @@ const fragmentedDeletionOverlap = (op, over) => {
32317
35019
  const direct = op.revision === void 0 ? op : over;
32318
35020
  return tracked.revision !== void 0 && direct.revision === void 0 && (tracked.newIds?.revision?.length ?? 0) > 0 && sameParagraph(tracked.from, tracked.to) && sameParagraph(tracked.from, direct.from) && sameParagraph(tracked.from, direct.to) && Math.max(tracked.from.offset, direct.from.offset) < Math.min(tracked.to.offset, direct.to.offset);
32319
35021
  };
35022
+ /**
35023
+ * The positions an operation is rebased by, where its transform maps them
35024
+ * by paragraph and offset.
35025
+ */
35026
+ const mappedPositions = (op) => {
35027
+ switch (op.type) {
35028
+ case DOCUMENT_OP_TYPES.INSERT_TEXT:
35029
+ case DOCUMENT_OP_TYPES.SPLIT_BLOCK: return [op.at];
35030
+ case DOCUMENT_OP_TYPES.DELETE_RANGE:
35031
+ case DOCUMENT_OP_TYPES.SET_RUN_PROPS: return [op.from, op.to];
35032
+ default: return [];
35033
+ }
35034
+ };
35035
+ /**
35036
+ * Whether `op` has a position at an offset `over`'s range spans, where
35037
+ * `over` is a deletion whose ends name zero-width leaves. Such a deletion
35038
+ * changes the zero-width gaps only at those offsets: a direct one removes
35039
+ * the leaves strictly inside it but keeps some range boundaries there, and
35040
+ * a tracked one wraps leaves a position among them would fall inside. A
35041
+ * position elsewhere moves by its offset alone. The transform refuses the
35042
+ * pair, so it is outside the tracked-order policy too.
35043
+ */
35044
+ const zeroWidthSpanOverlap = (op, over) => {
35045
+ if (over.type !== DOCUMENT_OP_TYPES.DELETE_RANGE || (over.from.zeroWidthBefore ?? 0) === 0 && (over.to.zeroWidthBefore ?? 0) === 0) return false;
35046
+ return mappedPositions(op).some((position) => sameParagraph(position, over.from) && over.from.offset <= position.offset && position.offset <= over.to.offset);
35047
+ };
32320
35048
  // src/ops/sequencing/transform.ts
32321
35049
  const operationStory = (op) => {
32322
35050
  switch (op.type) {
@@ -32449,10 +35177,12 @@ const rejoinedOverFormat = ({ op, over, effect }) => {
32449
35177
  * comment anchor: it decides the same revisions after the edit, unless the
32450
35178
  * edit cut a revision record in two and gave its second half a new id, or is
32451
35179
  * a tracked edit whose records may continue a decided revision: one order
32452
- * decides those and the other does not, so the decision is refused.
35180
+ * decides those and the other does not, so the decision is refused. Over a
35181
+ * direct paragraph insertion it passes unless it decides a revision the
35182
+ * insertion's sequenced effect names as bordering it.
32453
35183
  * Undefined for every other pair.
32454
35184
  */
32455
- const decisionOverEdit = (op, over) => {
35185
+ const decisionOverEdit = (op, over, effect) => {
32456
35186
  if (op.type !== DOCUMENT_OP_TYPES.RESOLVE_REVISION) return void 0;
32457
35187
  switch (over.type) {
32458
35188
  case DOCUMENT_OP_TYPES.INSERT_TEXT:
@@ -32471,6 +35201,13 @@ const decisionOverEdit = (op, over) => {
32471
35201
  case DOCUMENT_OP_TYPES.CREATE_COMMENT:
32472
35202
  if (!isAnchoredComment(over)) return void 0;
32473
35203
  break;
35204
+ case DOCUMENT_OP_TYPES.INSERT_BLOCKS:
35205
+ if (over.at.type !== "before" && over.at.type !== "after") return void 0;
35206
+ if (over.revision !== void 0) break;
35207
+ if (effect?.type !== DOCUMENT_OP_TYPES.INSERT_BLOCKS) return refusal(op, over, "A concurrent paragraph insertion records no revisions it borders.");
35208
+ if (op.revisionIds.some((id) => effect.borderingRevisionIds.includes(id))) return refusal(op, over, "A concurrent paragraph insertion borders a paragraph mark this decision resolves.");
35209
+ if (heldRevisionIds(over.blocks).some((id) => op.revisionIds.some((decided) => String(decided) === id))) return refusal(op, over, "A concurrent paragraph insertion holds a copy of a revision this decision resolves.");
35210
+ return Result.ok([op]);
32474
35211
  default: return;
32475
35212
  }
32476
35213
  if ("revision" in over && over.revision !== void 0) return refusal(op, over, "A concurrent tracked edit may continue a revision this decision resolves.");
@@ -32490,7 +35227,7 @@ const transformRestoredOp = ({ op, over, effect, order }) => {
32490
35227
  if (story === void 0 || overStory === void 0) return refusal(op, over, "Package resources, numbering and section metadata require an exclusive edit.");
32491
35228
  if (!sameStory$1(story, overStory)) return Result.ok([op]);
32492
35229
  if (independent(op, over)) return Result.ok([op]);
32493
- const decided = decisionOverEdit(op, over);
35230
+ const decided = decisionOverEdit(op, over, effect);
32494
35231
  if (decided !== void 0) return decided;
32495
35232
  if (isAnchoredComment(op)) return moveCommentAnchor({
32496
35233
  op,
@@ -32584,7 +35321,7 @@ const transformRestoredOp = ({ op, over, effect, order }) => {
32584
35321
  if (op.type === DOCUMENT_OP_TYPES.INSERT_TEXT && over.type === DOCUMENT_OP_TYPES.SET_RUN_PROPS && op.runProps !== "inherit" && op.at.offset >= over.from.offset && op.at.offset <= over.to.offset) return refusal(op, over, "Explicit inserted formatting needs a range partition.");
32585
35322
  if (over.type === DOCUMENT_OP_TYPES.DELETE_RANGE && over.revision && op.type === DOCUMENT_OP_TYPES.INSERT_TEXT && op.at.offset > over.from.offset && op.at.offset < over.to.offset) return refusal(op, over, "Insertion inside tracked-deleted content requires wrapper affinity.");
32586
35323
  if (op.type === DOCUMENT_OP_TYPES.DELETE_RANGE && op.revision && over.type === DOCUMENT_OP_TYPES.INSERT_TEXT && over.at.offset > op.from.offset && over.at.offset < op.to.offset) return refusal(op, over, "Tracking a concurrent insertion requires a revision partition.");
32587
- if (over.type === DOCUMENT_OP_TYPES.DELETE_RANGE && ((over.from.zeroWidthBefore ?? 0) !== 0 || (over.to.zeroWidthBefore ?? 0) !== 0)) return refusal(op, over, "Tracked deletion and zero-width boundaries require an unchanged range.");
35324
+ if (zeroWidthSpanOverlap(op, over)) return refusal(op, over, "Tracked deletion and zero-width boundaries require an unchanged range.");
32588
35325
  const mapping = {
32589
35326
  over,
32590
35327
  effect,
@@ -32999,6 +35736,56 @@ const inspectBatch = (document, ops) => batchWith(inspectDocumentOps, document,
32999
35736
  document: left,
33000
35737
  effects
33001
35738
  }));
35739
+ /** The revisions a paragraph's mark records: the mark, its deletion, the one it took over. */
35740
+ const markRevisionIds = (paragraph) => {
35741
+ const mark = paragraph?.pPrMark;
35742
+ if (mark === void 0) return [];
35743
+ return [
35744
+ mark.info.id,
35745
+ ...mark.deletion === void 0 ? [] : [mark.deletion.info.id],
35746
+ ...mark.takenOverMark === void 0 ? [] : [mark.takenOverMark]
35747
+ ];
35748
+ };
35749
+ /** The row and cell revisions of the tables on the way down to a paragraph. */
35750
+ const holdingTableRevisionIds = (blocks, location) => {
35751
+ const ids = [];
35752
+ const change = (info) => {
35753
+ if (info !== void 0) ids.push(info.info.id);
35754
+ };
35755
+ let list = blocks;
35756
+ for (const step of location.list) {
35757
+ const block = list.at(step.block);
35758
+ if (step.kind === "tableCell" && block?.type === "table") {
35759
+ const row = block.rows.at(step.row);
35760
+ const cell = row?.cells.at(step.cell);
35761
+ change(row?.structuralChange);
35762
+ change(cell?.structuralChange);
35763
+ list = cell?.content ?? [];
35764
+ } else if (step.kind === "blockSdt" && block?.type === "blockSdt" || step.kind === "blockCustomXml" && block?.type === "blockCustomXml") list = block.content;
35765
+ else return ids;
35766
+ }
35767
+ return ids;
35768
+ };
35769
+ /**
35770
+ * The revisions a direct insertion before or after a paragraph borders: see
35771
+ * the `insertBlocks` sequenced effect. A tracked insertion records them too;
35772
+ * its own revision refuses a concurrent decision first.
35773
+ */
35774
+ const borderingRevisionIds = (document, op) => {
35775
+ if (op.at.type !== "before" && op.at.type !== "after") return [];
35776
+ const anchorId = idKey(op.at.blockId);
35777
+ const body = storyBody$1(document, op.story);
35778
+ const paragraphs = storyParagraphs(body);
35779
+ const index = paragraphs.findIndex(({ paragraph }) => paragraph.paraId !== void 0 && idKey(paragraph.paraId) === anchorId);
35780
+ const anchor = paragraphs.at(index);
35781
+ if (index < 0 || anchor === void 0) return [];
35782
+ const before = itemBefore(paragraphs, index)?.paragraph;
35783
+ return [.../* @__PURE__ */ new Set([
35784
+ ...markRevisionIds(anchor.paragraph),
35785
+ ...markRevisionIds(before),
35786
+ ...holdingTableRevisionIds(body.content, anchor)
35787
+ ])].sort((left, right) => left - right);
35788
+ };
33002
35789
  const batchWith = (applyOps, document, ops) => {
33003
35790
  let current = document;
33004
35791
  const inverses = [];
@@ -33019,6 +35806,10 @@ const batchWith = (applyOps, document, ops) => {
33019
35806
  firstLength: paragraphLength(paragraph)
33020
35807
  };
33021
35808
  }
35809
+ if (op.type === DOCUMENT_OP_TYPES.INSERT_BLOCKS && sequencedEffectType(op) === DOCUMENT_OP_TYPES.INSERT_BLOCKS) effect = {
35810
+ type: DOCUMENT_OP_TYPES.INSERT_BLOCKS,
35811
+ borderingRevisionIds: borderingRevisionIds(current, op)
35812
+ };
33022
35813
  const applied = applyOps(current, [op]);
33023
35814
  if (applied.isErr()) return Result.err(applied.error);
33024
35815
  if (op.type === DOCUMENT_OP_TYPES.INSERT_CONTENT) effect = {
@@ -34249,4 +37040,4 @@ const resolvedDocumentView = (document, decision) => {
34249
37040
  const storyBody = storyBody$1;
34250
37041
  const findStoryBody = findStoryBody$1;
34251
37042
  const sameStory = sameStory$2;
34252
- export { BATCH_ANNOTATION_KINDS, BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DEFAULT_ID_BLOCK_SIZES, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, EXCLUSIVE_PARTS, ID_KIND_LIMITS, ID_LEASE_KINDS, ID_LEASE_REFUSAL_REASONS, INHERIT_RUN_PROPS, IdLeaseRefusal, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, TYPED_TEXT_FORMATTING, acceptCopyOriginAncestors, addCopyOriginAncestor, allocateCommentAnchorIds, applyBatch, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, beginTrackedInsertionCompilation, blockControlHolding, captureDocumentOp, captureStoryParts, combineEditEffects, combineEdits, combineRecordedRevisions, commentAnchorSequence, commentDocumentIssue, commentReferenceOffsets, compareBatchOrder, compareGaps, compileEditorIntent, contentRank, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, deletionRemovesBlock, documentStories, editorParagraphGroups, editorParagraphGroupsThroughTextBoxes, editorPositionAtPhysicalPosition, finalBreakCarrier, findStoryBody, formatParaId, formattingEquals, freshCommentId, freshLeasedIds, groupInsertionRuns, idKey, idLeaseHolds, idLeaseRemaining, inlineLeafSpans, introducedDocumentIds, introducedIds, inverseMeetingDocument, isBlockBoundary, isCommentAnchorCarrierType, isCommentExhausted, isCopyOriginAncestors, isKeptCut, isTextOnlyRun, joinPropertyChangeLink, leasedIdCensus, locateParagraphInBlockList, locateParagraphThroughTextBoxes, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteDeletionOps, noteUsesCustomMark, orderAddressingBeforeRemoval, orderBatchOperations, orphanRootCommentIds, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, paragraphIdsIn, paragraphKeptCutsFromChanges, paragraphLength, paragraphLogicalText, paragraphMarkOutcome, paragraphPropertySnapshotToken, paragraphStatesItsFormatting, paragraphVisibleText, paragraphsThroughTextBoxes, parseDocumentBatch, pendingSuggestionIdsIn, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, planWellFormedRanges, planWholeParagraphReplacement, preservedCommentRangeMarkersAt, reconcileDocumentPartRelationships, recordsCopyOrigin, registerParagraphPropertySnapshot, registerStatedParagraphFormatting, rejectCopyOriginAncestors, replaceStoryBody, resolveSectionChange, resolveSectionChanges, resolvedDocumentView, reviewFieldsOf, revisionIdDemand, revisionSpan, runsMergeable, sameStory, sectionPropertiesAt, sectionRejectProperties, sectionResolutionPatch, shiftCopyOriginAncestors, storyBody, storyLacksClosingParagraph, storyParagraphs, suggestedCommentIds, suggestionRevisionInfos, survivingComments, textBoxContentsIn, toOpEnvelope, transferParagraphPropertySnapshot, transformBatch, transformPosition, trimIdLease, tryTrackedInsertionGroup, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withParagraphCopies, withParagraphRenderings, withTextBoxesClosed, withoutCommentThreads, withoutPendingSuggestions, zeroWidthLeavesAt };
37043
+ export { BATCH_ANNOTATION_KINDS, BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DEFAULT_ID_BLOCK_SIZES, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, EXCLUSIVE_PARTS, ID_KIND_LIMITS, ID_LEASE_KINDS, ID_LEASE_REFUSAL_REASONS, INHERIT_RUN_PROPS, IdLeaseRefusal, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, TYPED_TEXT_FORMATTING, acceptCopyOriginAncestors, addCopyOriginAncestor, allocateCommentAnchorIds, applyBatch, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, beginTrackedInsertionCompilation, blockControlHolding, captureDocumentOp, captureStoryParts, combineEditEffects, combineEdits, combineRecordedRevisions, commentAnchorSequence, commentDocumentIssue, commentReferenceOffsets, compareBatchOrder, compareGaps, compileEditorIntent, contentRank, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, deletionRemovesBlock, documentStories, editorParagraphGroups, editorParagraphGroupsThroughTextBoxes, editorPositionAtPhysicalPosition, finalBreakCarrier, findStoryBody, formatParaId, formattingEquals, freshCommentId, freshLeasedIds, groupInsertionRuns, idKey, idLeaseHolds, idLeaseRemaining, inlineLeafSpans, introducedDocumentIds, introducedIds, inverseMeetingDocument, isBlockBoundary, isCommentAnchorCarrierType, isCommentExhausted, isCopyOriginAncestors, isKeptCut, isKeptCutPiece, isTextOnlyRun, joinPropertyChangeLink, leasedIdCensus, locateParagraphInBlockList, locateParagraphThroughTextBoxes, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteDeletionOps, noteUsesCustomMark, orderAddressingBeforeRemoval, orderBatchOperations, orphanRootCommentIds, packageParagraphIds, packageResourcesOpOf, paragraphContentVerdict, paragraphHoldsContent, paragraphHoldsContentOnceAccepted, paragraphIdsIn, paragraphKeptCutsFromChanges, paragraphLength, paragraphLogicalText, paragraphMarkOutcome, paragraphPropertySnapshotToken, paragraphStatesItsFormatting, paragraphVisibleText, paragraphsThroughTextBoxes, parseDocumentBatch, pendingSuggestionIdsIn, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, planWellFormedRanges, planWholeParagraphReplacement, preservedCommentRangeMarkersAt, reconcileDocumentPartRelationships, recordsCopyOrigin, registerParagraphPropertySnapshot, registerStatedParagraphFormatting, rejectCopyOriginAncestors, replaceStoryBody, resolveSectionChange, resolveSectionChanges, resolvedDocumentView, reviewFieldsOf, revisionIdDemand, revisionSpan, runsMergeable, sameStory, sectionPropertiesAt, sectionRejectProperties, sectionResolutionPatch, shiftCopyOriginAncestors, storyBody, storyLacksClosingParagraph, storyParagraphs, storyPartsOpOf, suggestedCommentIds, suggestionRevisionInfos, survivingComments, textBoxContentsIn, toOpEnvelope, transferParagraphPropertySnapshot, transformBatch, transformPosition, trimIdLease, tryTrackedInsertionGroup, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, withParagraphCopies, withParagraphRenderings, withTextBoxesClosed, withoutCommentThreads, withoutPendingSuggestions, zeroWidthLeavesAt };