@beyondwork/docx-react-component 1.0.135 → 1.0.136

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/api/public-types.d.cts +2 -2
  2. package/dist/api/public-types.d.ts +2 -2
  3. package/dist/api/v3.cjs +183 -39
  4. package/dist/api/v3.d.cts +3 -3
  5. package/dist/api/v3.d.ts +3 -3
  6. package/dist/api/v3.js +2 -2
  7. package/dist/{canonical-document-CfZIc-fC.d.cts → canonical-document-COmM7v11.d.cts} +1 -1
  8. package/dist/{canonical-document-CfZIc-fC.d.ts → canonical-document-COmM7v11.d.ts} +1 -1
  9. package/dist/{chunk-5CCYF333.js → chunk-HUWZ7AHE.js} +123 -0
  10. package/dist/{chunk-GIFXKIM5.js → chunk-JZZKTL7K.js} +620 -50
  11. package/dist/{chunk-EPFVMUKF.js → chunk-NX7W6T7L.js} +169 -37
  12. package/dist/compare.d.cts +1 -1
  13. package/dist/compare.d.ts +1 -1
  14. package/dist/core/commands/formatting-commands.d.cts +2 -2
  15. package/dist/core/commands/formatting-commands.d.ts +2 -2
  16. package/dist/core/commands/image-commands.d.cts +2 -2
  17. package/dist/core/commands/image-commands.d.ts +2 -2
  18. package/dist/core/commands/section-layout-commands.d.cts +2 -2
  19. package/dist/core/commands/section-layout-commands.d.ts +2 -2
  20. package/dist/core/commands/style-commands.d.cts +2 -2
  21. package/dist/core/commands/style-commands.d.ts +2 -2
  22. package/dist/core/commands/table-structure-commands.d.cts +2 -2
  23. package/dist/core/commands/table-structure-commands.d.ts +2 -2
  24. package/dist/core/commands/text-commands.d.cts +2 -2
  25. package/dist/core/commands/text-commands.d.ts +2 -2
  26. package/dist/core/selection/mapping.d.cts +2 -2
  27. package/dist/core/selection/mapping.d.ts +2 -2
  28. package/dist/core/state/editor-state.d.cts +2 -2
  29. package/dist/core/state/editor-state.d.ts +2 -2
  30. package/dist/index.cjs +1075 -154
  31. package/dist/index.d.cts +5 -5
  32. package/dist/index.d.ts +5 -5
  33. package/dist/index.js +123 -23
  34. package/dist/io/docx-session.d.cts +4 -4
  35. package/dist/io/docx-session.d.ts +4 -4
  36. package/dist/legal.d.cts +1 -1
  37. package/dist/legal.d.ts +1 -1
  38. package/dist/{loader-BQ7AB-0v.d.cts → loader-Cr35kVUi.d.cts} +3 -3
  39. package/dist/{loader-Cy6OYBfn.d.ts → loader-uGY6nDZP.d.ts} +3 -3
  40. package/dist/{public-types-D31xKNGc.d.cts → public-types-8kVIB5HW.d.ts} +16 -8
  41. package/dist/{public-types-DqYt8GdP.d.ts → public-types-CSSH2Whc.d.cts} +16 -8
  42. package/dist/public-types.d.cts +2 -2
  43. package/dist/public-types.d.ts +2 -2
  44. package/dist/runtime/collab.d.cts +3 -3
  45. package/dist/runtime/collab.d.ts +3 -3
  46. package/dist/runtime/document-runtime.cjs +737 -46
  47. package/dist/runtime/document-runtime.d.cts +2 -2
  48. package/dist/runtime/document-runtime.d.ts +2 -2
  49. package/dist/runtime/document-runtime.js +2 -2
  50. package/dist/{session-DA-F2fCw.d.cts → session-Beg8ihOi.d.cts} +3 -3
  51. package/dist/{session-DqL8H0oZ.d.ts → session-Dgp-2uYw.d.ts} +3 -3
  52. package/dist/session.d.cts +5 -5
  53. package/dist/session.d.ts +5 -5
  54. package/dist/tailwind.d.cts +2 -2
  55. package/dist/tailwind.d.ts +2 -2
  56. package/dist/{types-SllbCtGs.d.ts → types-Cin_abw3.d.ts} +2 -2
  57. package/dist/{types-B2y94n5t.d.cts → types-qsS39ZkQ.d.cts} +2 -2
  58. package/dist/ui-tailwind/editor-surface/search-plugin.d.cts +3 -3
  59. package/dist/ui-tailwind/editor-surface/search-plugin.d.ts +3 -3
  60. package/dist/ui-tailwind.d.cts +3 -3
  61. package/dist/ui-tailwind.d.ts +3 -3
  62. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -24380,6 +24380,106 @@ function setStartOverride(catalog, numberingInstanceId, level, startAt) {
24380
24380
  overrides: mergeOverride(instance.overrides, { level, startAt })
24381
24381
  };
24382
24382
  }
24383
+ function mergeFragmentNumberingCatalog(target, fragment) {
24384
+ const catalog = cloneNumberingCatalog(target);
24385
+ const abstractIdMap = /* @__PURE__ */ new Map();
24386
+ const instanceIdMap = /* @__PURE__ */ new Map();
24387
+ const picBulletIdMap = /* @__PURE__ */ new Map();
24388
+ if (!fragment) {
24389
+ return { catalog, abstractIdMap, instanceIdMap, picBulletIdMap };
24390
+ }
24391
+ for (const [picBulletId, entry] of Object.entries(fragment.numPicBullets ?? {})) {
24392
+ const mappedId = mapPicBulletId(catalog, picBulletId, entry);
24393
+ picBulletIdMap.set(picBulletId, mappedId);
24394
+ }
24395
+ for (const [abstractId, definition] of Object.entries(fragment.abstractDefinitions)) {
24396
+ const mappedId = mapAbstractDefinition(catalog, definition, picBulletIdMap);
24397
+ abstractIdMap.set(abstractId, mappedId);
24398
+ }
24399
+ for (const [instanceId, instance] of Object.entries(fragment.instances)) {
24400
+ const mappedAbstractId = abstractIdMap.get(instance.abstractNumberingId) ?? instance.abstractNumberingId;
24401
+ const mappedId = mapNumberingInstance(
24402
+ catalog,
24403
+ instance,
24404
+ mappedAbstractId,
24405
+ picBulletIdMap
24406
+ );
24407
+ instanceIdMap.set(instanceId, mappedId);
24408
+ }
24409
+ return { catalog, abstractIdMap, instanceIdMap, picBulletIdMap };
24410
+ }
24411
+ function mapPicBulletId(catalog, picBulletId, entry) {
24412
+ const existing = catalog.numPicBullets?.[picBulletId];
24413
+ if (existing && existing.rawXml === entry.rawXml) return picBulletId;
24414
+ const mappedId = existing ? nextNumericString(Object.keys(catalog.numPicBullets ?? {})) : picBulletId;
24415
+ const numPicBullets = { ...catalog.numPicBullets ?? {} };
24416
+ numPicBullets[mappedId] = {
24417
+ ...stripSourceRef(structuredClone(entry)),
24418
+ numPicBulletId: mappedId
24419
+ };
24420
+ catalog.numPicBullets = numPicBullets;
24421
+ return mappedId;
24422
+ }
24423
+ function mapAbstractDefinition(catalog, definition, picBulletIdMap) {
24424
+ const existing = catalog.abstractDefinitions[definition.abstractNumberingId];
24425
+ if (existing && sameJson(comparableAbstract(existing), comparableAbstract(definition))) {
24426
+ return definition.abstractNumberingId;
24427
+ }
24428
+ const mappedId = existing ? nextCanonicalNumericId("abstract-num:", Object.keys(catalog.abstractDefinitions)) : definition.abstractNumberingId;
24429
+ catalog.abstractDefinitions[mappedId] = {
24430
+ ...stripSourceRef(structuredClone(definition)),
24431
+ abstractNumberingId: mappedId,
24432
+ nsid: freshLongHex(catalog, mappedId, "nsid"),
24433
+ tplc: freshLongHex(catalog, mappedId, "tmpl"),
24434
+ levels: definition.levels.map((level) => remapLevelPicBullet(level, picBulletIdMap))
24435
+ };
24436
+ return mappedId;
24437
+ }
24438
+ function mapNumberingInstance(catalog, instance, abstractNumberingId, picBulletIdMap) {
24439
+ const existing = catalog.instances[instance.numberingInstanceId];
24440
+ const candidate = {
24441
+ ...instance,
24442
+ abstractNumberingId,
24443
+ overrides: instance.overrides.map(
24444
+ (override) => remapOverridePicBullet(override, picBulletIdMap)
24445
+ )
24446
+ };
24447
+ if (existing && sameJson(comparableInstance(existing), comparableInstance(candidate))) {
24448
+ return instance.numberingInstanceId;
24449
+ }
24450
+ const mappedId = existing ? nextCanonicalNumericId("num:", Object.keys(catalog.instances)) : instance.numberingInstanceId;
24451
+ catalog.instances[mappedId] = {
24452
+ ...stripSourceRef(structuredClone(instance)),
24453
+ overrides: candidate.overrides.map((override) => stripOverrideSourceRefs(override)),
24454
+ numberingInstanceId: mappedId,
24455
+ abstractNumberingId
24456
+ };
24457
+ return mappedId;
24458
+ }
24459
+ function remapLevelPicBullet(level, picBulletIdMap) {
24460
+ const cloned = stripSourceRef(structuredClone(level));
24461
+ if (!level.picBulletId) return cloned;
24462
+ return {
24463
+ ...cloned,
24464
+ picBulletId: picBulletIdMap.get(level.picBulletId) ?? level.picBulletId
24465
+ };
24466
+ }
24467
+ function remapOverridePicBullet(override, picBulletIdMap) {
24468
+ const cloned = stripOverrideSourceRefs(structuredClone(override));
24469
+ if (!override.levelDefinition) return cloned;
24470
+ return {
24471
+ ...cloned,
24472
+ levelDefinition: remapLevelPicBullet(override.levelDefinition, picBulletIdMap)
24473
+ };
24474
+ }
24475
+ function stripOverrideSourceRefs(override) {
24476
+ const cloned = stripSourceRef(override);
24477
+ if (!override.levelDefinition) return cloned;
24478
+ return {
24479
+ ...cloned,
24480
+ levelDefinition: stripSourceRef(override.levelDefinition)
24481
+ };
24482
+ }
24383
24483
  function mergeOverride(overrides, nextOverride) {
24384
24484
  return [
24385
24485
  ...overrides.filter((override) => override.level !== nextOverride.level),
@@ -24451,6 +24551,28 @@ function hashLongHex(input) {
24451
24551
  }
24452
24552
  return hash.toString(16).toUpperCase().padStart(8, "0").slice(-8);
24453
24553
  }
24554
+ function stripSourceRef(value) {
24555
+ const { sourceRef: _sourceRef, ...rest } = value;
24556
+ return rest;
24557
+ }
24558
+ function comparableAbstract(definition) {
24559
+ return {
24560
+ ...stripSourceRef(definition),
24561
+ levels: definition.levels.map((level) => stripSourceRef(level))
24562
+ };
24563
+ }
24564
+ function comparableInstance(instance) {
24565
+ return {
24566
+ ...stripSourceRef(instance),
24567
+ overrides: instance.overrides.map((override) => ({
24568
+ ...stripSourceRef(override),
24569
+ ...override.levelDefinition ? { levelDefinition: stripSourceRef(override.levelDefinition) } : {}
24570
+ }))
24571
+ };
24572
+ }
24573
+ function sameJson(left, right) {
24574
+ return JSON.stringify(left) === JSON.stringify(right);
24575
+ }
24454
24576
 
24455
24577
  // src/core/commands/list-commands.ts
24456
24578
  function toggleNumberedList(document2, paragraphIndexes, context, options = {}) {
@@ -24498,7 +24620,7 @@ function splitListParagraph(document2, paragraphIndex, paragraphIsEmpty, context
24498
24620
  action: "split"
24499
24621
  };
24500
24622
  }
24501
- const target = paragraphs[resolvedParagraphIndex];
24623
+ const target = paragraphs[resolvedParagraphIndex]?.paragraph;
24502
24624
  if (!target?.numbering) {
24503
24625
  return {
24504
24626
  document: working,
@@ -24550,7 +24672,7 @@ function backspaceAtListStart(document2, paragraphIndex, context, options = {})
24550
24672
  handled: false
24551
24673
  };
24552
24674
  }
24553
- const target = paragraphs[resolvedParagraphIndex];
24675
+ const target = paragraphs[resolvedParagraphIndex]?.paragraph;
24554
24676
  if (!target?.numbering) {
24555
24677
  return {
24556
24678
  document: working,
@@ -24596,7 +24718,7 @@ function restartNumbering(document2, paragraphIndex, context, startAt = 1, optio
24596
24718
  affectedParagraphIndexes: []
24597
24719
  };
24598
24720
  }
24599
- const target = paragraphs[resolvedParagraphIndex];
24721
+ const target = paragraphs[resolvedParagraphIndex]?.paragraph;
24600
24722
  if (!target?.numbering) {
24601
24723
  return {
24602
24724
  document: working,
@@ -24618,8 +24740,13 @@ function restartNumbering(document2, paragraphIndex, context, startAt = 1, optio
24618
24740
  );
24619
24741
  setStartOverride(catalog, numberingInstanceId, target.numbering.level, startAt);
24620
24742
  const affectedParagraphIndexes = [];
24743
+ const targetStoryKey = paragraphs[resolvedParagraphIndex]?.storyKey;
24621
24744
  for (let index = resolvedParagraphIndex; index < paragraphs.length; index += 1) {
24622
- const paragraph = paragraphs[index];
24745
+ const entry = paragraphs[index];
24746
+ if (entry?.storyKey !== targetStoryKey) {
24747
+ break;
24748
+ }
24749
+ const paragraph = entry.paragraph;
24623
24750
  if (!paragraph?.numbering) {
24624
24751
  break;
24625
24752
  }
@@ -24663,7 +24790,7 @@ function continueNumbering(document2, paragraphIndex, context, options = {}) {
24663
24790
  affectedParagraphIndexes: []
24664
24791
  };
24665
24792
  }
24666
- const target = paragraphs[resolvedParagraphIndex];
24793
+ const target = paragraphs[resolvedParagraphIndex]?.paragraph;
24667
24794
  if (!target?.numbering) {
24668
24795
  return {
24669
24796
  document: working,
@@ -24692,8 +24819,13 @@ function continueNumbering(document2, paragraphIndex, context, options = {}) {
24692
24819
  };
24693
24820
  }
24694
24821
  const affectedParagraphIndexes = [];
24822
+ const targetStoryKey = paragraphs[resolvedParagraphIndex]?.storyKey;
24695
24823
  for (let index = resolvedParagraphIndex; index < paragraphs.length; index += 1) {
24696
- const paragraph = paragraphs[index];
24824
+ const entry = paragraphs[index];
24825
+ if (entry?.storyKey !== targetStoryKey) {
24826
+ break;
24827
+ }
24828
+ const paragraph = entry.paragraph;
24697
24829
  if (!paragraph?.numbering) {
24698
24830
  break;
24699
24831
  }
@@ -24739,12 +24871,13 @@ function toggleListKind(document2, paragraphIndexes, kind, context, options) {
24739
24871
  }
24740
24872
  const catalog = cloneNumberingCatalog(working.numbering);
24741
24873
  const allAlreadyKind = normalizedIndexes.every((index) => {
24742
- const paragraph = paragraphs[index];
24743
- return paragraph.numbering ? getListKind(catalog, paragraph.numbering.numberingInstanceId) === kind : false;
24874
+ const paragraph = paragraphs[index]?.paragraph;
24875
+ return paragraph?.numbering ? getListKind(catalog, paragraph.numbering.numberingInstanceId) === kind : false;
24744
24876
  });
24745
24877
  if (allAlreadyKind) {
24746
24878
  for (const index of normalizedIndexes) {
24747
- delete paragraphs[index].numbering;
24879
+ const paragraph = paragraphs[index]?.paragraph;
24880
+ if (paragraph) delete paragraph.numbering;
24748
24881
  }
24749
24882
  working.numbering = catalog;
24750
24883
  return {
@@ -24754,7 +24887,8 @@ function toggleListKind(document2, paragraphIndexes, kind, context, options) {
24754
24887
  }
24755
24888
  const numberingInstanceId = findAdjacentCompatibleInstance(paragraphs, catalog, normalizedIndexes[0], kind) ?? ensureDefaultListInstance(catalog, kind);
24756
24889
  for (const index of normalizedIndexes) {
24757
- const paragraph = paragraphs[index];
24890
+ const paragraph = paragraphs[index]?.paragraph;
24891
+ if (!paragraph) continue;
24758
24892
  paragraph.numbering = {
24759
24893
  numberingInstanceId,
24760
24894
  level: clampLevel(paragraph.numbering?.level ?? 0)
@@ -24785,10 +24919,11 @@ function adjustListLevels(document2, paragraphIndexes, delta, context, options)
24785
24919
  };
24786
24920
  }
24787
24921
  const affectedParagraphIndexes = resolved.paragraphIndexes.filter(
24788
- (index) => Boolean(paragraphs[index]?.numbering)
24922
+ (index) => Boolean(paragraphs[index]?.paragraph.numbering)
24789
24923
  );
24790
24924
  for (const index of affectedParagraphIndexes) {
24791
- const paragraph = paragraphs[index];
24925
+ const paragraph = paragraphs[index]?.paragraph;
24926
+ if (!paragraph) continue;
24792
24927
  if (!paragraph.numbering) {
24793
24928
  continue;
24794
24929
  }
@@ -24808,17 +24943,21 @@ function normalizeListCommandTargets(options) {
24808
24943
  }
24809
24944
  function resolveListCommandParagraphIndexes(document2, paragraphs, paragraphIndexes, context, editableTargets) {
24810
24945
  if (editableTargets.length === 0) {
24811
- return { paragraphIndexes: normalizeParagraphIndexes(paragraphs, paragraphIndexes) };
24946
+ return {
24947
+ paragraphIndexes: normalizeParagraphIndexesForStory(
24948
+ paragraphs,
24949
+ paragraphIndexes,
24950
+ context.activeStoryKey
24951
+ )
24952
+ };
24812
24953
  }
24813
24954
  const currentTargets = collectEditableTargetRefs(document2, context.editableTargetCache);
24814
- const paragraphIndexByTargetKey = /* @__PURE__ */ new Map();
24815
- let paragraphIndex = 0;
24816
- for (const target of currentTargets) {
24817
- if (!isParagraphTextTarget(target)) continue;
24818
- if (!paragraphIndexByTargetKey.has(target.targetKey)) {
24819
- paragraphIndexByTargetKey.set(target.targetKey, paragraphIndex);
24820
- paragraphIndex += 1;
24821
- }
24955
+ const paragraphIndexByAddress = /* @__PURE__ */ new Map();
24956
+ for (let index = 0; index < paragraphs.length; index += 1) {
24957
+ const entry = paragraphs[index];
24958
+ if (!entry) continue;
24959
+ paragraphIndexByAddress.set(`${entry.storyKey}
24960
+ ${entry.blockPath}`, index);
24822
24961
  }
24823
24962
  const resolvedIndexes = [];
24824
24963
  for (const target of editableTargets) {
@@ -24843,7 +24982,8 @@ function resolveListCommandParagraphIndexes(document2, paragraphs, paragraphInde
24843
24982
  }
24844
24983
  };
24845
24984
  }
24846
- const currentIndex = paragraphIndexByTargetKey.get(current.targetKey);
24985
+ const currentIndex = paragraphIndexByAddress.get(`${current.storyKey}
24986
+ ${current.blockPath}`);
24847
24987
  if (currentIndex === void 0) {
24848
24988
  return {
24849
24989
  paragraphIndexes: [],
@@ -24918,18 +25058,28 @@ function sortJson(value) {
24918
25058
  return value;
24919
25059
  }
24920
25060
  function findAdjacentCompatibleInstance(paragraphs, catalog, fromIndex, kind) {
25061
+ const current = paragraphs[fromIndex];
24921
25062
  const previous = paragraphs[fromIndex - 1];
24922
- if (previous?.numbering) {
24923
- const previousKind = getListKind(catalog, previous.numbering.numberingInstanceId);
25063
+ if (previous?.storyKey !== current?.storyKey) {
25064
+ return void 0;
25065
+ }
25066
+ const previousParagraph = previous?.paragraph;
25067
+ if (previousParagraph?.numbering) {
25068
+ const previousKind = getListKind(catalog, previousParagraph.numbering.numberingInstanceId);
24924
25069
  if (previousKind === kind) {
24925
- return previous.numbering.numberingInstanceId;
25070
+ return previousParagraph.numbering.numberingInstanceId;
24926
25071
  }
24927
25072
  }
24928
25073
  return void 0;
24929
25074
  }
24930
25075
  function findPreviousCompatibleInstance(paragraphs, catalog, fromIndex, kind) {
25076
+ const storyKey2 = paragraphs[fromIndex]?.storyKey;
24931
25077
  for (let index = fromIndex - 1; index >= 0; index -= 1) {
24932
- const paragraph = paragraphs[index];
25078
+ const entry = paragraphs[index];
25079
+ if (entry?.storyKey !== storyKey2) {
25080
+ break;
25081
+ }
25082
+ const paragraph = entry.paragraph;
24933
25083
  if (!paragraph?.numbering) {
24934
25084
  continue;
24935
25085
  }
@@ -24948,7 +25098,14 @@ function cloneEnvelope(document2, timestamp) {
24948
25098
  function captureEditableParagraphs(document2) {
24949
25099
  if (isDocumentRoot(document2.content)) {
24950
25100
  const paragraphs = [];
24951
- collectEditableParagraphs(document2.content.children, paragraphs);
25101
+ for (const context of collectStoryBlockContexts(document2)) {
25102
+ collectEditableParagraphs(
25103
+ context.blocks,
25104
+ paragraphs,
25105
+ context.storyKey,
25106
+ context.basePath
25107
+ );
25108
+ }
24952
25109
  return paragraphs;
24953
25110
  }
24954
25111
  const fallback = {
@@ -24956,23 +25113,39 @@ function captureEditableParagraphs(document2) {
24956
25113
  children: [{ type: "paragraph", children: [] }]
24957
25114
  };
24958
25115
  document2.content = fallback;
24959
- return fallback.children;
25116
+ return [{
25117
+ paragraph: fallback.children[0],
25118
+ storyKey: "main",
25119
+ blockPath: "main/block[0]"
25120
+ }];
24960
25121
  }
24961
- function collectEditableParagraphs(blocks, output) {
24962
- for (const block of blocks) {
25122
+ function collectEditableParagraphs(blocks, output, storyKey2, basePath) {
25123
+ for (let blockIndex = 0; blockIndex < blocks.length; blockIndex += 1) {
25124
+ const block = blocks[blockIndex];
25125
+ if (!block) continue;
25126
+ const blockPath = `${basePath}/block[${blockIndex}]`;
24963
25127
  switch (block.type) {
24964
25128
  case "paragraph":
24965
- output.push(block);
25129
+ output.push({ paragraph: block, storyKey: storyKey2, blockPath });
24966
25130
  break;
24967
25131
  case "table":
24968
- for (const row2 of block.rows) {
24969
- for (const cell of row2.cells) {
24970
- collectEditableParagraphs(cell.children, output);
25132
+ for (let rowIndex = 0; rowIndex < block.rows.length; rowIndex += 1) {
25133
+ const row2 = block.rows[rowIndex];
25134
+ if (!row2) continue;
25135
+ for (let cellIndex = 0; cellIndex < row2.cells.length; cellIndex += 1) {
25136
+ const cell = row2.cells[cellIndex];
25137
+ if (!cell) continue;
25138
+ collectEditableParagraphs(
25139
+ cell.children,
25140
+ output,
25141
+ storyKey2,
25142
+ `${blockPath}/row[${rowIndex}]/cell[${cellIndex}]`
25143
+ );
24971
25144
  }
24972
25145
  }
24973
25146
  break;
24974
25147
  case "sdt":
24975
- collectEditableParagraphs(block.children, output);
25148
+ collectEditableParagraphs(block.children, output, storyKey2, blockPath);
24976
25149
  break;
24977
25150
  case "custom_xml":
24978
25151
  break;
@@ -24984,6 +25157,18 @@ function collectEditableParagraphs(blocks, output) {
24984
25157
  function normalizeParagraphIndexes(paragraphs, paragraphIndexes) {
24985
25158
  return [...new Set(paragraphIndexes)].filter((index) => Number.isInteger(index) && index >= 0 && index < paragraphs.length).sort((left, right) => left - right);
24986
25159
  }
25160
+ function normalizeParagraphIndexesForStory(paragraphs, paragraphIndexes, storyKey2) {
25161
+ if (storyKey2 === void 0) {
25162
+ return normalizeParagraphIndexes(paragraphs, paragraphIndexes);
25163
+ }
25164
+ const storyParagraphIndexes = [];
25165
+ for (let index = 0; index < paragraphs.length; index += 1) {
25166
+ if (paragraphs[index]?.storyKey === storyKey2) {
25167
+ storyParagraphIndexes.push(index);
25168
+ }
25169
+ }
25170
+ return [...new Set(paragraphIndexes)].filter((index) => Number.isInteger(index) && index >= 0 && index < storyParagraphIndexes.length).map((index) => storyParagraphIndexes[index]).sort((left, right) => left - right);
25171
+ }
24987
25172
  function clampLevel(level) {
24988
25173
  return Math.max(0, Math.min(8, level));
24989
25174
  }
@@ -31279,9 +31464,9 @@ function findTableStructureTargetForSelection(document2, descriptor, operation2,
31279
31464
  if (descriptor.editability === "non-editable" && descriptor.nonEditableReason !== "nested-table-not-editable") {
31280
31465
  return null;
31281
31466
  }
31282
- const activeStoryKey = editableTargetStoryKey(activeStory);
31467
+ const activeStoryKey2 = editableTargetStoryKey(activeStory);
31283
31468
  const targets = collectEditableTargetRefs(document2).filter(
31284
- (target) => target.commandFamily === "table-structure" && target.table !== void 0 && target.storyKey === activeStoryKey && tableStructureTargetMatchesDescriptor2(target, descriptor)
31469
+ (target) => target.commandFamily === "table-structure" && target.table !== void 0 && target.storyKey === activeStoryKey2 && tableStructureTargetMatchesDescriptor2(target, descriptor)
31285
31470
  );
31286
31471
  const scope = preferredTableStructureScope(operation2);
31287
31472
  return targets.find((target) => {
@@ -36544,8 +36729,9 @@ function applyFragmentInsert(document2, selection, fragment, context) {
36544
36729
  workingDocument = collapseResult.document;
36545
36730
  workingSelection = collapseResult.selection;
36546
36731
  if (context.textTarget?.kind === "table-paragraph" || context.textTarget?.kind === "text-leaf") {
36732
+ const { precomputedSurface: _precomputedSurface, ...contextWithoutPrecomputedSurface } = context;
36547
36733
  workingContext = {
36548
- ...context,
36734
+ ...contextWithoutPrecomputedSurface,
36549
36735
  textTarget: {
36550
36736
  ...context.textTarget,
36551
36737
  paragraphEnd: Math.max(
@@ -36557,7 +36743,11 @@ function applyFragmentInsert(document2, selection, fragment, context) {
36557
36743
  }
36558
36744
  }
36559
36745
  const splitResult = splitParagraph(workingDocument, workingSelection, workingContext);
36560
- const splitRoot = splitResult.document.content;
36746
+ const preparedFragment = prepareFragmentNumberingForInsertion(
36747
+ splitResult.document,
36748
+ fragment
36749
+ );
36750
+ const splitRoot = preparedFragment.document.content;
36561
36751
  if (!splitRoot || splitRoot.type !== "doc") {
36562
36752
  return {
36563
36753
  changed: false,
@@ -36568,9 +36758,9 @@ function applyFragmentInsert(document2, selection, fragment, context) {
36568
36758
  const targetedBlockPath = workingContext.textTarget?.kind === "table-paragraph" || workingContext.textTarget?.kind === "text-leaf" ? workingContext.textTarget.blockPath : void 0;
36569
36759
  if (targetedBlockPath) {
36570
36760
  const targeted = insertFragmentBlocksAfterPath(
36571
- splitResult.document,
36761
+ preparedFragment.document,
36572
36762
  targetedBlockPath,
36573
- fragment.blocks
36763
+ preparedFragment.blocks
36574
36764
  );
36575
36765
  if (targeted) {
36576
36766
  return {
@@ -36602,7 +36792,7 @@ function applyFragmentInsert(document2, selection, fragment, context) {
36602
36792
  const rightHalfIndex = scope.blockIndex + 1;
36603
36793
  const splicedChildren = [
36604
36794
  ...splitRoot.children.slice(0, rightHalfIndex),
36605
- ...fragment.blocks.map((block) => cloneBlock(block)),
36795
+ ...preparedFragment.blocks.map((block) => cloneBlock(block)),
36606
36796
  ...splitRoot.children.slice(rightHalfIndex)
36607
36797
  ];
36608
36798
  const nextRoot = {
@@ -36610,7 +36800,7 @@ function applyFragmentInsert(document2, selection, fragment, context) {
36610
36800
  children: splicedChildren
36611
36801
  };
36612
36802
  const nextDocument = {
36613
- ...splitResult.document,
36803
+ ...preparedFragment.document,
36614
36804
  updatedAt: context.timestamp,
36615
36805
  content: nextRoot
36616
36806
  };
@@ -36622,14 +36812,47 @@ function applyFragmentInsert(document2, selection, fragment, context) {
36622
36812
  mapping: createEmptyMapping()
36623
36813
  };
36624
36814
  }
36625
- function cloneBlock(block) {
36626
- if (block.type === "paragraph") {
36627
- return {
36628
- ...block,
36629
- children: block.children.map((child) => ({ ...child }))
36815
+ function prepareFragmentNumberingForInsertion(document2, fragment) {
36816
+ if (!fragment.numbering) {
36817
+ return { document: document2, blocks: fragment.blocks };
36818
+ }
36819
+ const merged = mergeFragmentNumberingCatalog(document2.numbering, fragment.numbering);
36820
+ return {
36821
+ document: {
36822
+ ...document2,
36823
+ numbering: merged.catalog
36824
+ },
36825
+ blocks: fragment.blocks.map((block) => cloneBlock(block, merged.instanceIdMap))
36826
+ };
36827
+ }
36828
+ function cloneBlock(block, numberingInstanceIdMap) {
36829
+ const cloned = structuredClone(block);
36830
+ remapNumberingReferences(cloned, numberingInstanceIdMap);
36831
+ return cloned;
36832
+ }
36833
+ function remapNumberingReferences(value, numberingInstanceIdMap) {
36834
+ if (!numberingInstanceIdMap?.size || !value || typeof value !== "object") {
36835
+ return;
36836
+ }
36837
+ if (Array.isArray(value)) {
36838
+ for (const entry of value) {
36839
+ remapNumberingReferences(entry, numberingInstanceIdMap);
36840
+ }
36841
+ return;
36842
+ }
36843
+ const record = value;
36844
+ if (record.numbering?.numberingInstanceId) {
36845
+ const mappedId = numberingInstanceIdMap.get(record.numbering.numberingInstanceId) ?? record.numbering.numberingInstanceId;
36846
+ record.numbering = {
36847
+ ...record.numbering,
36848
+ numberingInstanceId: mappedId
36630
36849
  };
36631
36850
  }
36632
- return JSON.parse(JSON.stringify(block));
36851
+ remapNumberingReferences(record.children, numberingInstanceIdMap);
36852
+ remapNumberingReferences(record.rows, numberingInstanceIdMap);
36853
+ remapNumberingReferences(record.cells, numberingInstanceIdMap);
36854
+ remapNumberingReferences(record.txbxBlocks, numberingInstanceIdMap);
36855
+ remapNumberingReferences(record.content, numberingInstanceIdMap);
36633
36856
  }
36634
36857
  function insertFragmentBlocksAfterPath(document2, blockPath, fragmentBlocks) {
36635
36858
  const tokens = parseCanonicalBlockPath2(blockPath);
@@ -56476,6 +56699,16 @@ function coerceIssueValue2(value) {
56476
56699
  function insertScopeMarkers(document2, params) {
56477
56700
  const { scopeId } = params;
56478
56701
  const root = document2.content;
56702
+ if (!Number.isFinite(params.from) || !Number.isFinite(params.to)) {
56703
+ const from = Number.isFinite(params.from) ? params.from : 0;
56704
+ const to = Number.isFinite(params.to) ? params.to : from;
56705
+ return {
56706
+ status: "non-finite-range",
56707
+ scopeId,
56708
+ from,
56709
+ to
56710
+ };
56711
+ }
56479
56712
  const normalizedFrom = Math.min(params.from, params.to);
56480
56713
  const normalizedTo = Math.max(params.from, params.to);
56481
56714
  if (!root || root.type !== "doc" || root.children.length === 0) {
@@ -56928,6 +57161,14 @@ function isRecord3(value) {
56928
57161
  }
56929
57162
 
56930
57163
  // src/runtime/workflow/coordinator.ts
57164
+ function createScopeMarkerMutationMapping() {
57165
+ return {
57166
+ steps: [],
57167
+ metadata: {
57168
+ layoutNeutralScopeMarkers: true
57169
+ }
57170
+ };
57171
+ }
56931
57172
  var MODE_RESTRICTIVENESS = {
56932
57173
  edit: 0,
56933
57174
  suggest: 1,
@@ -57119,12 +57360,12 @@ function createWorkflowCoordinator(deps) {
57119
57360
  function getCachedInteractionGuardSnapshot() {
57120
57361
  const state = deps.getState();
57121
57362
  const activeStory = deps.getActiveStory();
57122
- const activeStoryKey = storyTargetKey(activeStory);
57363
+ const activeStoryKey2 = storyTargetKey(activeStory);
57123
57364
  const protectionSnapshot = deps.getProtectionSnapshot();
57124
57365
  const documentMode = deps.getDocumentMode();
57125
57366
  const overlay = overlayStore.getOverlay();
57126
57367
  const sharedWorkflowState = overlayStore.getSharedWorkflowState();
57127
- if (cachedInteractionGuardSnapshot && cachedInteractionGuardSnapshot.activeStoryKey === activeStoryKey && cachedInteractionGuardSnapshot.selection === state.selection && cachedInteractionGuardSnapshot.readOnly === state.readOnly && cachedInteractionGuardSnapshot.documentMode === documentMode && cachedInteractionGuardSnapshot.protectionSnapshot === protectionSnapshot && cachedInteractionGuardSnapshot.overlay === overlay && cachedInteractionGuardSnapshot.sharedWorkflowState === sharedWorkflowState) {
57368
+ if (cachedInteractionGuardSnapshot && cachedInteractionGuardSnapshot.activeStoryKey === activeStoryKey2 && cachedInteractionGuardSnapshot.selection === state.selection && cachedInteractionGuardSnapshot.readOnly === state.readOnly && cachedInteractionGuardSnapshot.documentMode === documentMode && cachedInteractionGuardSnapshot.protectionSnapshot === protectionSnapshot && cachedInteractionGuardSnapshot.overlay === overlay && cachedInteractionGuardSnapshot.sharedWorkflowState === sharedWorkflowState) {
57128
57369
  return cachedInteractionGuardSnapshot.snapshot;
57129
57370
  }
57130
57371
  const blockedReasons = evaluateBlockedReasons(state.selection);
@@ -57165,7 +57406,7 @@ function createWorkflowCoordinator(deps) {
57165
57406
  blockedReasons
57166
57407
  };
57167
57408
  cachedInteractionGuardSnapshot = {
57168
- activeStoryKey,
57409
+ activeStoryKey: activeStoryKey2,
57169
57410
  selection: state.selection,
57170
57411
  readOnly: state.readOnly,
57171
57412
  documentMode,
@@ -57194,13 +57435,13 @@ function createWorkflowCoordinator(deps) {
57194
57435
  function getCachedWorkflowMarkupSnapshot() {
57195
57436
  const state = deps.getState();
57196
57437
  const activeStory = deps.getActiveStory();
57197
- const activeStoryKey = storyTargetKey(activeStory);
57438
+ const activeStoryKey2 = storyTargetKey(activeStory);
57198
57439
  const protectionSnapshot = deps.getProtectionSnapshot();
57199
57440
  const preservation = deps.getDocument().preservation;
57200
57441
  const overlay = overlayStore.getOverlay();
57201
57442
  const metadataDefinitions = overlayStore.getMetadataDefinitions();
57202
57443
  const metadataEntries = overlayStore.getMetadataEntries();
57203
- if (cachedWorkflowMarkupSnapshot && cachedWorkflowMarkupSnapshot.activeStoryKey === activeStoryKey && cachedWorkflowMarkupSnapshot.protectionSnapshot === protectionSnapshot && cachedWorkflowMarkupSnapshot.preservation === preservation && cachedWorkflowMarkupSnapshot.overlay === overlay && cachedWorkflowMarkupSnapshot.metadataDefinitions === metadataDefinitions && cachedWorkflowMarkupSnapshot.metadataEntries === metadataEntries) {
57444
+ if (cachedWorkflowMarkupSnapshot && cachedWorkflowMarkupSnapshot.activeStoryKey === activeStoryKey2 && cachedWorkflowMarkupSnapshot.protectionSnapshot === protectionSnapshot && cachedWorkflowMarkupSnapshot.preservation === preservation && cachedWorkflowMarkupSnapshot.overlay === overlay && cachedWorkflowMarkupSnapshot.metadataDefinitions === metadataDefinitions && cachedWorkflowMarkupSnapshot.metadataEntries === metadataEntries) {
57204
57445
  return cachedWorkflowMarkupSnapshot.snapshot;
57205
57446
  }
57206
57447
  const snapshot = collectWorkflowMarkupSnapshot({
@@ -57211,7 +57452,7 @@ function createWorkflowCoordinator(deps) {
57211
57452
  workflowMetadataSnapshot: overlayStore.getMetadataSnapshot()
57212
57453
  });
57213
57454
  cachedWorkflowMarkupSnapshot = {
57214
- activeStoryKey,
57455
+ activeStoryKey: activeStoryKey2,
57215
57456
  protectionSnapshot,
57216
57457
  preservation,
57217
57458
  overlay,
@@ -57235,6 +57476,60 @@ function createWorkflowCoordinator(deps) {
57235
57476
  activeStory: deps.getActiveStory()
57236
57477
  };
57237
57478
  }
57479
+ function createPlantFailureResult(input) {
57480
+ const { scopeId, anchor, assoc, plantResult } = input;
57481
+ return {
57482
+ scopeId: "",
57483
+ anchor: {
57484
+ kind: "range",
57485
+ from: anchor.from,
57486
+ to: anchor.to,
57487
+ assoc
57488
+ },
57489
+ plantStatus: {
57490
+ planted: false,
57491
+ reason: plantResult.status,
57492
+ ...plantResult.status === "non-paragraph-target" ? {
57493
+ blockIndex: plantResult.blockIndex,
57494
+ blockKind: plantResult.blockKind
57495
+ } : {},
57496
+ ...plantResult.status === "range-out-of-bounds" ? { storyLength: plantResult.storyLength } : {},
57497
+ requestedFrom: plantResult.from,
57498
+ requestedTo: plantResult.to
57499
+ }
57500
+ };
57501
+ }
57502
+ function buildWorkflowScope(input) {
57503
+ const { params, scopeId, publicAnchor } = input;
57504
+ return {
57505
+ scopeId,
57506
+ mode: params.mode ?? "comment",
57507
+ anchor: publicAnchor,
57508
+ ...params.storyTarget ? { storyTarget: params.storyTarget } : {},
57509
+ ...params.label ? { label: params.label } : {},
57510
+ ...params.visibility ? { visibility: params.visibility } : {},
57511
+ ...params.guardPolicy ? { guardPolicy: params.guardPolicy } : {},
57512
+ ...params.scopeMetadataFields && params.scopeMetadataFields.length > 0 ? { metadata: [...params.scopeMetadataFields] } : {}
57513
+ };
57514
+ }
57515
+ function buildWorkflowMetadataEntry(input) {
57516
+ const { params, scopeId, publicAnchor } = input;
57517
+ if (!params.persistence || params.persistence === "runtime-only") return null;
57518
+ const requestedMetadata = params.metadata ?? {};
57519
+ const entryPersistence = requestedMetadata.metadataPersistence ?? (params.persistence === "session" ? "external" : "internal");
57520
+ return {
57521
+ entryId: requestedMetadata.entryId ?? `scope-metadata-${scopeId}`,
57522
+ metadataId: requestedMetadata.metadataId ?? "workflow.scope",
57523
+ anchor: publicAnchor,
57524
+ ...params.storyTarget ? { storyTarget: params.storyTarget } : {},
57525
+ scopeId,
57526
+ ...requestedMetadata.workItemId ? { workItemId: requestedMetadata.workItemId } : {},
57527
+ ...requestedMetadata.value !== void 0 ? { value: requestedMetadata.value } : params.persistence === "document-metadata" && params.label ? { value: { label: params.label } } : {},
57528
+ metadataPersistence: entryPersistence,
57529
+ ...requestedMetadata.storageRef !== void 0 ? { storageRef: requestedMetadata.storageRef } : {},
57530
+ ...requestedMetadata.metadataVersion !== void 0 ? { metadataVersion: requestedMetadata.metadataVersion } : {}
57531
+ };
57532
+ }
57238
57533
  function addScope(params) {
57239
57534
  const state = deps.getState();
57240
57535
  const scopeId = params.scopeId ?? `scope-${clock().replace(/[^0-9]/gu, "")}-${Math.floor(Math.random() * 1e6)}`;
@@ -57277,6 +57572,7 @@ function createWorkflowCoordinator(deps) {
57277
57572
  deps.dispatch({
57278
57573
  type: "document.replace",
57279
57574
  document: nextDocument,
57575
+ mapping: createScopeMarkerMutationMapping(),
57280
57576
  origin: { source: "api", at: clock() }
57281
57577
  });
57282
57578
  const callerAssoc = params.anchor.kind === "range" ? params.anchor.assoc : { start: -1, end: 1 };
@@ -57333,6 +57629,84 @@ function createWorkflowCoordinator(deps) {
57333
57629
  }
57334
57630
  return { scopeId, anchor: publicAnchor };
57335
57631
  }
57632
+ function addScopes(paramsList) {
57633
+ if (paramsList.length === 0) return [];
57634
+ let nextDocument = deps.getDocument();
57635
+ let documentChanged = false;
57636
+ const results = [];
57637
+ const scopesToAdd = [];
57638
+ const metadataEntriesToAdd = [];
57639
+ const newScopeIds = /* @__PURE__ */ new Set();
57640
+ for (const params of paramsList) {
57641
+ const scopeId = params.scopeId ?? `scope-${clock().replace(/[^0-9]/gu, "")}-${Math.floor(Math.random() * 1e6)}`;
57642
+ const anchor = params.anchor.kind === "range" ? { from: params.anchor.from, to: params.anchor.to } : null;
57643
+ if (!anchor) {
57644
+ results.push({ scopeId, anchor: params.anchor });
57645
+ continue;
57646
+ }
57647
+ const callerAssoc = params.anchor.kind === "range" ? params.anchor.assoc : { start: -1, end: 1 };
57648
+ const plantResult = insertScopeMarkers(nextDocument, {
57649
+ scopeId,
57650
+ from: anchor.from,
57651
+ to: anchor.to
57652
+ });
57653
+ if (plantResult.status !== "planted") {
57654
+ results.push(
57655
+ createPlantFailureResult({
57656
+ scopeId,
57657
+ anchor,
57658
+ assoc: callerAssoc,
57659
+ plantResult
57660
+ })
57661
+ );
57662
+ continue;
57663
+ }
57664
+ nextDocument = plantResult.document;
57665
+ documentChanged = true;
57666
+ const publicAnchor = {
57667
+ kind: "range",
57668
+ from: plantResult.plantedRange.from,
57669
+ to: plantResult.plantedRange.to,
57670
+ assoc: callerAssoc
57671
+ };
57672
+ newScopeIds.add(scopeId);
57673
+ scopesToAdd.push(buildWorkflowScope({ params, scopeId, publicAnchor }));
57674
+ const entry = buildWorkflowMetadataEntry({ params, scopeId, publicAnchor });
57675
+ if (entry) metadataEntriesToAdd.push(entry);
57676
+ results.push({ scopeId, anchor: publicAnchor });
57677
+ }
57678
+ if (documentChanged) {
57679
+ deps.dispatch({
57680
+ type: "document.replace",
57681
+ document: nextDocument,
57682
+ mapping: createScopeMarkerMutationMapping(),
57683
+ origin: { source: "api", at: clock() }
57684
+ });
57685
+ }
57686
+ if (scopesToAdd.length > 0) {
57687
+ const currentOverlay = overlayStore.getOverlay() ?? {
57688
+ overlayVersion: "workflow-overlay/1",
57689
+ scopes: []
57690
+ };
57691
+ const existingScopes = currentOverlay.scopes.filter(
57692
+ (existing) => !newScopeIds.has(existing.scopeId)
57693
+ );
57694
+ deps.dispatch({
57695
+ type: "workflow.set-overlay",
57696
+ overlay: { ...currentOverlay, scopes: [...existingScopes, ...scopesToAdd] },
57697
+ origin: { source: "api", at: clock() }
57698
+ });
57699
+ }
57700
+ if (metadataEntriesToAdd.length > 0) {
57701
+ const priorEntries = overlayStore.getMetadataEntries();
57702
+ deps.dispatch({
57703
+ type: "workflow.set-metadata-entries",
57704
+ entries: [...priorEntries, ...metadataEntriesToAdd],
57705
+ origin: { source: "api", at: clock() }
57706
+ });
57707
+ }
57708
+ return results;
57709
+ }
57336
57710
  function removeScope(scopeId) {
57337
57711
  const overlay = overlayStore.getOverlay();
57338
57712
  if (overlay) {
@@ -57350,6 +57724,7 @@ function createWorkflowCoordinator(deps) {
57350
57724
  deps.dispatch({
57351
57725
  type: "document.replace",
57352
57726
  document: nextDocument,
57727
+ mapping: createScopeMarkerMutationMapping(),
57353
57728
  origin: { source: "api", at: clock() }
57354
57729
  });
57355
57730
  }
@@ -57743,6 +58118,7 @@ function createWorkflowCoordinator(deps) {
57743
58118
  }
57744
58119
  return {
57745
58120
  addScope,
58121
+ addScopes,
57746
58122
  removeScope,
57747
58123
  addInvisibleScope,
57748
58124
  setScopeVisibility,
@@ -69724,8 +70100,8 @@ function resolveEditableTextTarget(input) {
69724
70100
  `Editable target ref is malformed: ${shapeIssues[0]?.path ?? "$"}.`
69725
70101
  );
69726
70102
  }
69727
- const activeStoryKey = input.activeStoryKey ?? "main";
69728
- if (input.target.storyKey !== activeStoryKey) {
70103
+ const activeStoryKey2 = input.activeStoryKey ?? "main";
70104
+ if (input.target.storyKey !== activeStoryKey2) {
69729
70105
  return reject(
69730
70106
  "editable_target_wrong_story",
69731
70107
  "Editable target ref does not belong to the active story."
@@ -69821,8 +70197,8 @@ function resolveEditableCommandTarget(input) {
69821
70197
  `Editable target ref is malformed: ${shapeIssues[0]?.path ?? "$"}.`
69822
70198
  );
69823
70199
  }
69824
- const activeStoryKey = input.activeStoryKey ?? input.target.storyKey;
69825
- if (input.target.storyKey !== activeStoryKey) {
70200
+ const activeStoryKey2 = input.activeStoryKey ?? input.target.storyKey;
70201
+ if (input.target.storyKey !== activeStoryKey2) {
69826
70202
  return rejectCommand(
69827
70203
  "editable_target_wrong_story",
69828
70204
  "Editable target ref does not belong to the active story."
@@ -70237,8 +70613,8 @@ function resolveEditableTableStructureTarget(input) {
70237
70613
  `Editable target ref is malformed: ${shapeIssues[0]?.path ?? "$"}.`
70238
70614
  );
70239
70615
  }
70240
- const activeStoryKey = input.activeStoryKey ?? input.target.storyKey;
70241
- if (input.target.storyKey !== activeStoryKey) {
70616
+ const activeStoryKey2 = input.activeStoryKey ?? input.target.storyKey;
70617
+ if (input.target.storyKey !== activeStoryKey2) {
70242
70618
  return reject2(
70243
70619
  "editable_target_wrong_story",
70244
70620
  "Editable target ref does not belong to the active story."
@@ -70853,7 +71229,7 @@ function createDocumentRuntime(options) {
70853
71229
  if (cached) {
70854
71230
  return cached;
70855
71231
  }
70856
- const activeStoryKey = storyTargetKey(nextActiveStory);
71232
+ const activeStoryKey2 = storyTargetKey(nextActiveStory);
70857
71233
  const snapshot = createEditorSurfaceSnapshot(document2, state.selection, nextActiveStory, {
70858
71234
  viewportBlockRanges: null,
70859
71235
  editableTargetsByBlockPath: getEditableTargetsByBlockPath(document2),
@@ -70871,31 +71247,31 @@ function createDocumentRuntime(options) {
70871
71247
  preservation: document2.preservation,
70872
71248
  review: document2.review,
70873
71249
  effectiveMarkupModeProvider,
70874
- activeStoryKey,
71250
+ activeStoryKey: activeStoryKey2,
70875
71251
  snapshot
70876
71252
  };
70877
71253
  return snapshot;
70878
71254
  }
70879
71255
  function getReusableCachedFullSurface(document2, nextActiveStory) {
70880
- const activeStoryKey = storyTargetKey(nextActiveStory);
70881
- if (cachedFullSurface && cachedFullSurface.content === document2.content && cachedFullSurface.subParts === document2.subParts && cachedFullSurface.styles === document2.styles && cachedFullSurface.numbering === document2.numbering && cachedFullSurface.media === document2.media && cachedFullSurface.preservation === document2.preservation && cachedFullSurface.review === document2.review && cachedFullSurface.effectiveMarkupModeProvider === effectiveMarkupModeProvider && cachedFullSurface.activeStoryKey === activeStoryKey) {
71256
+ const activeStoryKey2 = storyTargetKey(nextActiveStory);
71257
+ if (cachedFullSurface && cachedFullSurface.content === document2.content && cachedFullSurface.subParts === document2.subParts && cachedFullSurface.styles === document2.styles && cachedFullSurface.numbering === document2.numbering && cachedFullSurface.media === document2.media && cachedFullSurface.preservation === document2.preservation && cachedFullSurface.review === document2.review && cachedFullSurface.effectiveMarkupModeProvider === effectiveMarkupModeProvider && cachedFullSurface.activeStoryKey === activeStoryKey2) {
70882
71258
  return cachedFullSurface.snapshot;
70883
71259
  }
70884
71260
  return void 0;
70885
71261
  }
70886
71262
  function getCachedSurface(document2, nextActiveStory, options2 = {}) {
70887
- const activeStoryKey = storyTargetKey(nextActiveStory);
71263
+ const activeStoryKey2 = storyTargetKey(nextActiveStory);
70888
71264
  const surfaceViewportRanges = "viewportBlockRangesOverride" in options2 ? options2.viewportBlockRangesOverride ?? null : viewportBlockRanges;
70889
71265
  const surfaceViewportRangesKey = "viewportBlockRangesOverride" in options2 ? serializeViewportRanges(surfaceViewportRanges) : viewportRangesKey;
70890
71266
  const surfaceCacheKey = options2.enrichCulledPlaceholders === false ? `${surfaceViewportRangesKey}|raw-placeholders` : surfaceViewportRangesKey;
70891
- if (cachedSurface && cachedSurface.content === document2.content && cachedSurface.subParts === document2.subParts && cachedSurface.styles === document2.styles && cachedSurface.numbering === document2.numbering && cachedSurface.media === document2.media && cachedSurface.preservation === document2.preservation && cachedSurface.review === document2.review && cachedSurface.effectiveMarkupModeProvider === effectiveMarkupModeProvider && cachedSurface.activeStoryKey === activeStoryKey && cachedSurface.viewportRangesKey === surfaceCacheKey) {
71267
+ if (cachedSurface && cachedSurface.content === document2.content && cachedSurface.subParts === document2.subParts && cachedSurface.styles === document2.styles && cachedSurface.numbering === document2.numbering && cachedSurface.media === document2.media && cachedSurface.preservation === document2.preservation && cachedSurface.review === document2.review && cachedSurface.effectiveMarkupModeProvider === effectiveMarkupModeProvider && cachedSurface.activeStoryKey === activeStoryKey2 && cachedSurface.viewportRangesKey === surfaceCacheKey) {
70892
71268
  return cachedSurface.snapshot;
70893
71269
  }
70894
71270
  const snapshot = createEditorSurfaceSnapshot(document2, state.selection, nextActiveStory, {
70895
71271
  viewportBlockRanges: surfaceViewportRanges,
70896
71272
  editableTargetsByBlockPath: options2.editableTargetsByBlockPathOverride ?? getEditableTargetsByBlockPathForRanges(
70897
71273
  document2,
70898
- activeStoryKey,
71274
+ activeStoryKey2,
70899
71275
  surfaceViewportRanges
70900
71276
  ),
70901
71277
  paragraphCascadeCache: ensureParagraphCascadeCacheForStyles(document2.styles),
@@ -70918,7 +71294,7 @@ function createDocumentRuntime(options) {
70918
71294
  preservation: document2.preservation,
70919
71295
  review: document2.review,
70920
71296
  effectiveMarkupModeProvider,
70921
- activeStoryKey,
71297
+ activeStoryKey: activeStoryKey2,
70922
71298
  snapshot: enrichedSnapshot
70923
71299
  };
70924
71300
  }
@@ -70931,11 +71307,11 @@ function createDocumentRuntime(options) {
70931
71307
  preservation: document2.preservation,
70932
71308
  review: document2.review,
70933
71309
  effectiveMarkupModeProvider,
70934
- activeStoryKey,
71310
+ activeStoryKey: activeStoryKey2,
70935
71311
  viewportRangesKey: surfaceCacheKey,
70936
71312
  snapshot: enrichedSnapshot
70937
71313
  };
70938
- cachedSurfaceFingerprint = `${activeStoryKey}|${surfaceCacheKey}|${String(state.selection.anchor)}:${String(state.selection.head)}`;
71314
+ cachedSurfaceFingerprint = `${activeStoryKey2}|${surfaceCacheKey}|${String(state.selection.anchor)}:${String(state.selection.head)}`;
70939
71315
  return enrichedSnapshot;
70940
71316
  }
70941
71317
  function getSelectionCorridorViewportRanges(previousSurface) {
@@ -70966,7 +71342,7 @@ function createDocumentRuntime(options) {
70966
71342
  return -1;
70967
71343
  }
70968
71344
  function cachePatchedLocalTextSurface(surface, fullSurfaceForCache) {
70969
- const activeStoryKey = storyTargetKey(activeStory);
71345
+ const activeStoryKey2 = storyTargetKey(activeStory);
70970
71346
  const rangesKey = serializeViewportRanges(surface.viewportBlockRanges);
70971
71347
  cachedSurface = {
70972
71348
  content: state.document.content,
@@ -70977,7 +71353,7 @@ function createDocumentRuntime(options) {
70977
71353
  preservation: state.document.preservation,
70978
71354
  review: state.document.review,
70979
71355
  effectiveMarkupModeProvider,
70980
- activeStoryKey,
71356
+ activeStoryKey: activeStoryKey2,
70981
71357
  viewportRangesKey: rangesKey,
70982
71358
  snapshot: surface
70983
71359
  };
@@ -70992,11 +71368,11 @@ function createDocumentRuntime(options) {
70992
71368
  preservation: state.document.preservation,
70993
71369
  review: state.document.review,
70994
71370
  effectiveMarkupModeProvider,
70995
- activeStoryKey,
71371
+ activeStoryKey: activeStoryKey2,
70996
71372
  snapshot: fullSurface
70997
71373
  };
70998
71374
  }
70999
- cachedSurfaceFingerprint = `${activeStoryKey}|${rangesKey}|${String(state.selection.anchor)}:${String(state.selection.head)}`;
71375
+ cachedSurfaceFingerprint = `${activeStoryKey2}|${rangesKey}|${String(state.selection.anchor)}:${String(state.selection.head)}`;
71000
71376
  }
71001
71377
  function createLocalTextCorridorSurfaceFromFullSurface(fullSurface) {
71002
71378
  const ranges = getSelectionCorridorViewportRanges(fullSurface);
@@ -71391,7 +71767,7 @@ function createDocumentRuntime(options) {
71391
71767
  return snapshot.suggestions.find((suggestion) => suggestion.changeIds.includes(changeId));
71392
71768
  }
71393
71769
  function getCachedDocumentNavigationSnapshot(nextState, nextActiveStory) {
71394
- const activeStoryKey = storyTargetKey(nextActiveStory);
71770
+ const activeStoryKey2 = storyTargetKey(nextActiveStory);
71395
71771
  const buildSnapshot = () => layoutEngine.getNavigationSnapshot(
71396
71772
  {
71397
71773
  document: nextState.document,
@@ -71404,7 +71780,7 @@ function createDocumentRuntime(options) {
71404
71780
  nextState.selection,
71405
71781
  nextActiveStory
71406
71782
  );
71407
- if (cachedNavigation && cachedNavigation.document === nextState.document && cachedNavigation.activeStoryKey === activeStoryKey && cachedNavigation.workspaceMode === viewState.workspaceMode && cachedNavigation.zoomLevel === viewState.zoomLevel) {
71783
+ if (cachedNavigation && cachedNavigation.document === nextState.document && cachedNavigation.activeStoryKey === activeStoryKey2 && cachedNavigation.workspaceMode === viewState.workspaceMode && cachedNavigation.zoomLevel === viewState.zoomLevel) {
71408
71784
  if (cachedNavigation.selectionHead === nextState.selection.head) {
71409
71785
  return cachedNavigation.snapshot;
71410
71786
  }
@@ -71412,7 +71788,7 @@ function createDocumentRuntime(options) {
71412
71788
  if (snapshot2.activePageIndex === cachedNavigation.snapshot.activePageIndex && snapshot2.activeSectionIndex === cachedNavigation.snapshot.activeSectionIndex) {
71413
71789
  cachedNavigation = {
71414
71790
  document: nextState.document,
71415
- activeStoryKey,
71791
+ activeStoryKey: activeStoryKey2,
71416
71792
  workspaceMode: viewState.workspaceMode,
71417
71793
  zoomLevel: viewState.zoomLevel,
71418
71794
  selectionHead: nextState.selection.head,
@@ -71422,7 +71798,7 @@ function createDocumentRuntime(options) {
71422
71798
  }
71423
71799
  cachedNavigation = {
71424
71800
  document: nextState.document,
71425
- activeStoryKey,
71801
+ activeStoryKey: activeStoryKey2,
71426
71802
  workspaceMode: viewState.workspaceMode,
71427
71803
  zoomLevel: viewState.zoomLevel,
71428
71804
  selectionHead: nextState.selection.head,
@@ -71435,7 +71811,7 @@ function createDocumentRuntime(options) {
71435
71811
  incrementInvalidationCounter("runtime.snapshot.navigationMisses");
71436
71812
  cachedNavigation = {
71437
71813
  document: nextState.document,
71438
- activeStoryKey,
71814
+ activeStoryKey: activeStoryKey2,
71439
71815
  workspaceMode: viewState.workspaceMode,
71440
71816
  zoomLevel: viewState.zoomLevel,
71441
71817
  selectionHead: nextState.selection.head,
@@ -71453,18 +71829,18 @@ function createDocumentRuntime(options) {
71453
71829
  return storyTargetKey(nextActiveStory);
71454
71830
  }
71455
71831
  function getCachedPageLayoutSnapshot(nextState, nextActiveStory) {
71456
- const activeStoryKey = storyTargetKey(nextActiveStory);
71832
+ const activeStoryKey2 = storyTargetKey(nextActiveStory);
71457
71833
  const activeSectionIndex = resolvePageLayoutActiveSectionIndex(
71458
71834
  nextState,
71459
71835
  nextActiveStory
71460
71836
  );
71461
- if (cachedPageLayout && cachedPageLayout.revisionToken === nextState.revisionToken && cachedPageLayout.activeStoryKey === activeStoryKey && cachedPageLayout.activeSectionIndex === activeSectionIndex) {
71837
+ if (cachedPageLayout && cachedPageLayout.revisionToken === nextState.revisionToken && cachedPageLayout.activeStoryKey === activeStoryKey2 && cachedPageLayout.activeSectionIndex === activeSectionIndex) {
71462
71838
  return cachedPageLayout.snapshot;
71463
71839
  }
71464
71840
  const snapshot = derivePageLayoutSnapshot(nextState, nextActiveStory, storySelections);
71465
71841
  cachedPageLayout = {
71466
71842
  revisionToken: nextState.revisionToken,
71467
- activeStoryKey,
71843
+ activeStoryKey: activeStoryKey2,
71468
71844
  activeSectionIndex,
71469
71845
  snapshot
71470
71846
  };
@@ -71534,8 +71910,8 @@ function createDocumentRuntime(options) {
71534
71910
  if (activeStory.kind === "main") {
71535
71911
  return surface.blocks;
71536
71912
  }
71537
- const activeStoryKey = storyTargetKey(activeStory);
71538
- return surface.secondaryStories.find((story) => storyTargetKey(story.target) === activeStoryKey)?.blocks ?? null;
71913
+ const activeStoryKey2 = storyTargetKey(activeStory);
71914
+ return surface.secondaryStories.find((story) => storyTargetKey(story.target) === activeStoryKey2)?.blocks ?? null;
71539
71915
  }
71540
71916
  function findSurfaceOpaqueTargetIntersectingRange(blocks, range) {
71541
71917
  for (const block of blocks) {
@@ -71710,12 +72086,12 @@ function createDocumentRuntime(options) {
71710
72086
  };
71711
72087
  }
71712
72088
  function getCachedRuntimeContextAnalytics(query) {
71713
- const activeStoryKey = storyTargetKey(activeStory);
72089
+ const activeStoryKey2 = storyTargetKey(activeStory);
71714
72090
  const queryKey = getRuntimeContextAnalyticsQueryKey(query);
71715
72091
  const cachedEntry = cachedContextAnalyticsSnapshots.get(queryKey);
71716
72092
  const effectiveScopeKind = query?.scopeKind ?? "selection";
71717
72093
  const selectionCacheKey = effectiveScopeKind === "selection" ? state.selection : null;
71718
- if (cachedEntry && cachedEntry.revisionToken === state.revisionToken && cachedEntry.activeStoryKey === activeStoryKey && cachedEntry.selection === selectionCacheKey && cachedEntry.readOnly === state.readOnly && cachedEntry.documentMode === viewState.documentMode && cachedEntry.workflowOverlay === overlayStore.getOverlay() && cachedEntry.protectionSnapshot === protectionSnapshot && cachedEntry.warnings === state.warnings && cachedEntry.fatalError === state.fatalError) {
72094
+ if (cachedEntry && cachedEntry.revisionToken === state.revisionToken && cachedEntry.activeStoryKey === activeStoryKey2 && cachedEntry.selection === selectionCacheKey && cachedEntry.readOnly === state.readOnly && cachedEntry.documentMode === viewState.documentMode && cachedEntry.workflowOverlay === overlayStore.getOverlay() && cachedEntry.protectionSnapshot === protectionSnapshot && cachedEntry.warnings === state.warnings && cachedEntry.fatalError === state.fatalError) {
71719
72095
  return cachedEntry.snapshot;
71720
72096
  }
71721
72097
  const tWf = performance.now();
@@ -71772,7 +72148,7 @@ function createDocumentRuntime(options) {
71772
72148
  perfCounters.increment("ctxa.build.us", Math.round((performance.now() - tBuild) * 1e3));
71773
72149
  cachedContextAnalyticsSnapshots.set(queryKey, {
71774
72150
  revisionToken: state.revisionToken,
71775
- activeStoryKey,
72151
+ activeStoryKey: activeStoryKey2,
71776
72152
  // L7 Phase 1.6: store the selectionCacheKey we tested against, so the
71777
72153
  // same scopeKind invariant applies to future reads.
71778
72154
  selection: selectionCacheKey,
@@ -71970,7 +72346,7 @@ function createDocumentRuntime(options) {
71970
72346
  }
71971
72347
  let cachedSurfaceFingerprint = null;
71972
72348
  function refreshSurfaceOnly(options2 = {}) {
71973
- const activeStoryKey = storyTargetKey(activeStory);
72349
+ const activeStoryKey2 = storyTargetKey(activeStory);
71974
72350
  if (options2.forceProjection) {
71975
72351
  cachedFullSurface = void 0;
71976
72352
  }
@@ -71987,7 +72363,7 @@ function createDocumentRuntime(options) {
71987
72363
  viewportBlockRanges,
71988
72364
  editableTargetsByBlockPath: getEditableTargetsByBlockPathForRanges(
71989
72365
  state.document,
71990
- activeStoryKey,
72366
+ activeStoryKey2,
71991
72367
  viewportBlockRanges
71992
72368
  ),
71993
72369
  paragraphCascadeCache: ensureParagraphCascadeCacheForStyles(
@@ -72017,7 +72393,7 @@ function createDocumentRuntime(options) {
72017
72393
  preservation: state.document.preservation,
72018
72394
  review: state.document.review,
72019
72395
  effectiveMarkupModeProvider,
72020
- activeStoryKey,
72396
+ activeStoryKey: activeStoryKey2,
72021
72397
  snapshot: newSurface
72022
72398
  };
72023
72399
  }
@@ -72032,7 +72408,7 @@ function createDocumentRuntime(options) {
72032
72408
  preservation: state.document.preservation,
72033
72409
  review: state.document.review,
72034
72410
  effectiveMarkupModeProvider,
72035
- activeStoryKey,
72411
+ activeStoryKey: activeStoryKey2,
72036
72412
  viewportRangesKey,
72037
72413
  snapshot: newSurface
72038
72414
  };
@@ -72093,10 +72469,10 @@ function createDocumentRuntime(options) {
72093
72469
  return true;
72094
72470
  }
72095
72471
  function getCachedViewStateSnapshot() {
72096
- const activeStoryKey = storyTargetKey(activeStory);
72472
+ const activeStoryKey2 = storyTargetKey(activeStory);
72097
72473
  const surface = cachedRenderSnapshot.surface;
72098
72474
  const pageLayout = cachedRenderSnapshot.pageLayout;
72099
- if (cachedViewStateSnapshot && cachedViewStateSnapshot.activeStoryKey === activeStoryKey && cachedViewStateSnapshot.selection === state.selection && cachedViewStateSnapshot.viewStateRef === viewState && cachedViewStateSnapshot.surface === surface && cachedViewStateSnapshot.pageLayout === pageLayout && cachedViewStateSnapshot.numbering === state.document.numbering) {
72475
+ if (cachedViewStateSnapshot && cachedViewStateSnapshot.activeStoryKey === activeStoryKey2 && cachedViewStateSnapshot.selection === state.selection && cachedViewStateSnapshot.viewStateRef === viewState && cachedViewStateSnapshot.surface === surface && cachedViewStateSnapshot.pageLayout === pageLayout && cachedViewStateSnapshot.numbering === state.document.numbering) {
72100
72476
  return cachedViewStateSnapshot.snapshot;
72101
72477
  }
72102
72478
  const mainSurface = activeStory.kind === "main" ? surface : getCachedSurface(state.document, MAIN_STORY_TARGET);
@@ -72110,7 +72486,7 @@ function createDocumentRuntime(options) {
72110
72486
  state.document.numbering
72111
72487
  );
72112
72488
  cachedViewStateSnapshot = {
72113
- activeStoryKey,
72489
+ activeStoryKey: activeStoryKey2,
72114
72490
  selection: state.selection,
72115
72491
  viewStateRef: viewState,
72116
72492
  surface,
@@ -72644,6 +73020,17 @@ function createDocumentRuntime(options) {
72644
73020
  };
72645
73021
  resolvedReplayTextTarget = prepared.textTarget;
72646
73022
  } else {
73023
+ const listBoundaryJoinCommand = createListItemBoundaryJoinReplayCommand({
73024
+ command,
73025
+ document: replayState.document,
73026
+ selection: replayState.selection,
73027
+ surface: replaySnapshot.surface?.blocks ?? [],
73028
+ storyTarget: replayStory,
73029
+ timestamp: context.timestamp
73030
+ });
73031
+ if (listBoundaryJoinCommand) {
73032
+ executableCommand = listBoundaryJoinCommand;
73033
+ }
72647
73034
  const selectedListItemDeleteCommand = createSelectedListItemDeleteReplayCommand({
72648
73035
  command,
72649
73036
  document: replayState.document,
@@ -72801,6 +73188,17 @@ function createDocumentRuntime(options) {
72801
73188
  };
72802
73189
  resolvedReplayTextTarget = prepared.textTarget;
72803
73190
  } else {
73191
+ const listBoundaryJoinCommand = createListItemBoundaryJoinReplayCommand({
73192
+ command,
73193
+ document: stateForCommand.document,
73194
+ selection: stateForCommand.selection,
73195
+ surface: snapshotForCommand.surface?.blocks ?? [],
73196
+ storyTarget: replayStory,
73197
+ timestamp: context.timestamp
73198
+ });
73199
+ if (listBoundaryJoinCommand) {
73200
+ executableCommand = listBoundaryJoinCommand;
73201
+ }
72804
73202
  const selectedListItemDeleteCommand = createSelectedListItemDeleteReplayCommand({
72805
73203
  command,
72806
73204
  document: stateForCommand.document,
@@ -73110,8 +73508,8 @@ function createDocumentRuntime(options) {
73110
73508
  applyScopeReplacement(plan) {
73111
73509
  const resolveEditableTargetHint = (hint) => {
73112
73510
  if (!hint) return void 0;
73113
- const activeStoryKey = storyTargetKey(activeStory);
73114
- if (hint.storyKey !== activeStoryKey) return null;
73511
+ const activeStoryKey2 = storyTargetKey(activeStory);
73512
+ if (hint.storyKey !== activeStoryKey2) return null;
73115
73513
  const currentTargets = collectEditableTargetRefs(
73116
73514
  state.document,
73117
73515
  editableTargetBlockCache
@@ -73130,7 +73528,7 @@ function createDocumentRuntime(options) {
73130
73528
  document: state.document,
73131
73529
  surface: cachedRenderSnapshot.surface?.blocks ?? [],
73132
73530
  target,
73133
- activeStoryKey,
73531
+ activeStoryKey: activeStoryKey2,
73134
73532
  editableTargetCache: editableTargetBlockCache
73135
73533
  });
73136
73534
  if (resolved.kind === "rejected") {
@@ -73830,6 +74228,9 @@ function createDocumentRuntime(options) {
73830
74228
  addScope(params) {
73831
74229
  return workflowCoordinator.addScope(params);
73832
74230
  },
74231
+ addScopes(params) {
74232
+ return workflowCoordinator.addScopes(params);
74233
+ },
73833
74234
  getScope(scopeId) {
73834
74235
  return workflowCoordinator.getScope(scopeId);
73835
74236
  },
@@ -74813,6 +75214,9 @@ function createDocumentRuntime(options) {
74813
75214
  if (transaction.mapping.metadata?.scopeTagTouches) return false;
74814
75215
  return getLocalTextPatchMetadata(transaction.mapping) !== null;
74815
75216
  }
75217
+ function isLayoutNeutralScopeMarkerCommit(previous, next, transaction) {
75218
+ return transaction.markDirty && previous.document !== next.document && transaction.mapping.steps.length === 0 && transaction.mapping.metadata?.layoutNeutralScopeMarkers === true;
75219
+ }
74816
75220
  function applyTransactionToState(transaction, options2 = {}) {
74817
75221
  const effects = transaction.effects;
74818
75222
  const selectionUnchanged = transaction.nextState.selection === state.selection;
@@ -74841,6 +75245,11 @@ function createDocumentRuntime(options) {
74841
75245
  transaction,
74842
75246
  transaction.effects
74843
75247
  );
75248
+ const layoutNeutralScopeMarkerCommit = isLayoutNeutralScopeMarkerCommit(
75249
+ previous,
75250
+ state,
75251
+ transaction
75252
+ );
74844
75253
  perfCounters.increment("commit.refreshClassify.us", Math.round((performance.now() - tClassify0) * 1e3));
74845
75254
  const tOverlay0 = performance.now();
74846
75255
  const skipOverlaySync = useLocalTextCommitSnapshot && canSkipOverlaySyncForLocalText(transaction);
@@ -74889,9 +75298,12 @@ function createDocumentRuntime(options) {
74889
75298
  ...detachedWorkflowScopeWarnings.cleared
74890
75299
  ]
74891
75300
  };
74892
- if (!useLocalTextCommitSnapshot && transaction.markDirty && previous.document !== state.document) {
75301
+ if (!useLocalTextCommitSnapshot && !layoutNeutralScopeMarkerCommit && transaction.markDirty && previous.document !== state.document) {
74893
75302
  applyViewportRanges(getSelectionCorridorViewportRanges(cachedRenderSnapshot.surface));
74894
75303
  }
75304
+ if (layoutNeutralScopeMarkerCommit && viewportBlockRanges !== null) {
75305
+ getCachedFullSurface(state.document, activeStory);
75306
+ }
74895
75307
  const tValidation0 = performance.now();
74896
75308
  const patchSourceSurface = getReusableCachedFullSurface(previous.document, activeStory) ?? cachedRenderSnapshot.surface;
74897
75309
  const patchedFullLocalTextSurface = useLocalTextCommitSnapshot ? tryPatchLocalTextSurface(patchSourceSurface, transaction.mapping) : null;
@@ -75260,6 +75672,39 @@ function createDocumentRuntime(options) {
75260
75672
  const preSelection = selection;
75261
75673
  const preActiveStory = activeStory;
75262
75674
  const priorDocument = state.document;
75675
+ const listBoundaryJoin = createListItemBoundaryJoinReplacement({
75676
+ command: commandForDispatch,
75677
+ document: state.document,
75678
+ editableTarget,
75679
+ selection,
75680
+ storyTarget: activeStory,
75681
+ targetResolution,
75682
+ timestamp
75683
+ });
75684
+ if (listBoundaryJoin && context.documentMode !== "suggesting") {
75685
+ const replacementCommand = {
75686
+ type: "document.replace",
75687
+ document: listBoundaryJoin.document,
75688
+ selection: listBoundaryJoin.selection,
75689
+ mapping: listBoundaryJoin.mapping,
75690
+ protectionSelection: selection,
75691
+ origin: commandForDispatch.origin
75692
+ };
75693
+ const transaction = executeEditorCommand(baseState, replacementCommand, context);
75694
+ commit(transaction);
75695
+ options.onCommandApplied?.(commandForDispatch, transaction, context, {
75696
+ preSelection,
75697
+ activeStory: preActiveStory,
75698
+ priorDocument
75699
+ });
75700
+ return completeDispatch(classifyAck({
75701
+ command: commandForDispatch,
75702
+ opId,
75703
+ priorState: baseState,
75704
+ transaction,
75705
+ newRevisionToken: state.revisionToken
75706
+ }));
75707
+ }
75263
75708
  const selectedListItemDelete = createSelectedListItemDeleteReplacement({
75264
75709
  command: commandForDispatch,
75265
75710
  document: state.document,
@@ -78167,6 +78612,56 @@ function stripStoryTarget2(selection) {
78167
78612
  function isTopLevelMainStoryBlockPath(blockPath) {
78168
78613
  return typeof blockPath === "string" && /^main\/block\[\d+\]$/u.test(blockPath);
78169
78614
  }
78615
+ function createListItemBoundaryJoinReplacement(input) {
78616
+ const { command, document: document2, editableTarget, selection, storyTarget, targetResolution, timestamp } = input;
78617
+ const direction = listItemBoundaryJoinDirection(command, selection, targetResolution);
78618
+ if (!direction || editableTarget?.listAddress?.operationScope !== "list-text" || targetResolution?.kind !== "accepted") {
78619
+ return null;
78620
+ }
78621
+ const storyBlocks = getStoryBlocks(document2, storyTarget);
78622
+ const replacement = joinNumberedParagraphAtStoryPath(
78623
+ storyBlocks,
78624
+ editableTarget.blockPath,
78625
+ storyTarget,
78626
+ direction
78627
+ );
78628
+ if (!replacement) {
78629
+ return null;
78630
+ }
78631
+ const nextDocument = replaceStoryBlocks({
78632
+ ...document2,
78633
+ updatedAt: timestamp
78634
+ }, storyTarget, replacement.blocks);
78635
+ const deletedFrom = direction === "backward" ? Math.max(0, selection.anchor - 1) : selection.anchor;
78636
+ const deletedTo = direction === "backward" ? selection.anchor : selection.anchor + 1;
78637
+ const nextAnchor = direction === "backward" ? deletedFrom : selection.anchor;
78638
+ return {
78639
+ document: nextDocument,
78640
+ selection: createSelectionSnapshot(nextAnchor, nextAnchor),
78641
+ mapping: {
78642
+ steps: [{
78643
+ from: deletedFrom,
78644
+ to: deletedTo,
78645
+ insertSize: 0
78646
+ }],
78647
+ metadata: {
78648
+ invalidatesStructures: true
78649
+ }
78650
+ }
78651
+ };
78652
+ }
78653
+ function listItemBoundaryJoinDirection(command, selection, targetResolution) {
78654
+ if (selection.isCollapsed !== true || targetResolution?.kind !== "accepted") {
78655
+ return null;
78656
+ }
78657
+ if (command.type === "text.delete-backward" && selection.anchor === targetResolution.range.from) {
78658
+ return "backward";
78659
+ }
78660
+ if (command.type === "text.delete-forward" && selection.anchor === targetResolution.range.to) {
78661
+ return "forward";
78662
+ }
78663
+ return null;
78664
+ }
78170
78665
  function createSelectedListItemDeleteReplacement(input) {
78171
78666
  const { command, document: document2, editableTarget, selection, storyTarget, targetResolution, timestamp } = input;
78172
78667
  if (command.type !== "text.delete-backward" && command.type !== "text.delete-forward") {
@@ -78214,6 +78709,152 @@ function removeNumberedParagraphAtStoryPath(blocks, blockPath, storyTarget) {
78214
78709
  if (!tokens) return null;
78215
78710
  return removeNumberedParagraphFromBlocks(blocks, tokens);
78216
78711
  }
78712
+ function joinNumberedParagraphAtStoryPath(blocks, blockPath, storyTarget, direction) {
78713
+ const tokens = parseStoryBlockPathTokens(blockPath, storyTarget);
78714
+ if (!tokens) return null;
78715
+ return joinNumberedParagraphFromBlocks(blocks, tokens, direction);
78716
+ }
78717
+ function joinNumberedParagraphFromBlocks(blocks, tokens, direction) {
78718
+ const [token, ...rest] = tokens;
78719
+ if (!token || token.kind !== "block") return null;
78720
+ const block = blocks[token.index];
78721
+ if (!block) return null;
78722
+ if (rest.length === 0) {
78723
+ return joinAdjacentNumberedParagraphs(blocks, token.index, direction);
78724
+ }
78725
+ const next = rest[0];
78726
+ if (block.type === "table" && next?.kind === "row") {
78727
+ const updatedTable = joinNumberedParagraphInTable(block, rest, direction);
78728
+ if (!updatedTable) return null;
78729
+ return {
78730
+ blocks: [
78731
+ ...blocks.slice(0, token.index),
78732
+ updatedTable,
78733
+ ...blocks.slice(token.index + 1)
78734
+ ]
78735
+ };
78736
+ }
78737
+ if ((block.type === "sdt" || block.type === "custom_xml") && next?.kind === "block") {
78738
+ const updatedChildren = joinNumberedParagraphFromBlocks(block.children, rest, direction);
78739
+ if (!updatedChildren) return null;
78740
+ return {
78741
+ blocks: [
78742
+ ...blocks.slice(0, token.index),
78743
+ { ...block, children: updatedChildren.blocks },
78744
+ ...blocks.slice(token.index + 1)
78745
+ ]
78746
+ };
78747
+ }
78748
+ if (block.type === "paragraph" && next?.kind === "inline") {
78749
+ const updatedParagraph = joinNumberedParagraphInTextBoxInline(block, rest, direction);
78750
+ if (!updatedParagraph) return null;
78751
+ return {
78752
+ blocks: [
78753
+ ...blocks.slice(0, token.index),
78754
+ updatedParagraph,
78755
+ ...blocks.slice(token.index + 1)
78756
+ ]
78757
+ };
78758
+ }
78759
+ return null;
78760
+ }
78761
+ function joinAdjacentNumberedParagraphs(blocks, targetIndex, direction) {
78762
+ const target = blocks[targetIndex];
78763
+ if (target?.type !== "paragraph" || !target.numbering) {
78764
+ return null;
78765
+ }
78766
+ if (direction === "backward") {
78767
+ const previousIndex = targetIndex - 1;
78768
+ const previous = blocks[previousIndex];
78769
+ if (previous?.type !== "paragraph" || !previous.numbering) {
78770
+ return null;
78771
+ }
78772
+ const merged2 = {
78773
+ ...previous,
78774
+ children: [...previous.children, ...target.children]
78775
+ };
78776
+ return {
78777
+ blocks: [
78778
+ ...blocks.slice(0, previousIndex),
78779
+ merged2,
78780
+ ...blocks.slice(targetIndex + 1)
78781
+ ]
78782
+ };
78783
+ }
78784
+ const nextIndex = targetIndex + 1;
78785
+ const next = blocks[nextIndex];
78786
+ if (next?.type !== "paragraph" || !next.numbering) {
78787
+ return null;
78788
+ }
78789
+ const merged = {
78790
+ ...target,
78791
+ children: [...target.children, ...next.children]
78792
+ };
78793
+ return {
78794
+ blocks: [
78795
+ ...blocks.slice(0, targetIndex),
78796
+ merged,
78797
+ ...blocks.slice(nextIndex + 1)
78798
+ ]
78799
+ };
78800
+ }
78801
+ function joinNumberedParagraphInTable(table, tokens, direction) {
78802
+ const [rowToken, cellToken, ...childTokens] = tokens;
78803
+ if (rowToken?.kind !== "row" || cellToken?.kind !== "cell" || childTokens[0]?.kind !== "block") {
78804
+ return null;
78805
+ }
78806
+ const row2 = table.rows[rowToken.index];
78807
+ const cell = row2?.cells[cellToken.index];
78808
+ if (!row2 || !cell) return null;
78809
+ const updatedChildren = joinNumberedParagraphFromBlocks(cell.children, childTokens, direction);
78810
+ if (!updatedChildren) return null;
78811
+ const nextCells = [
78812
+ ...row2.cells.slice(0, cellToken.index),
78813
+ { ...cell, children: updatedChildren.blocks },
78814
+ ...row2.cells.slice(cellToken.index + 1)
78815
+ ];
78816
+ const nextRows = [
78817
+ ...table.rows.slice(0, rowToken.index),
78818
+ { ...row2, cells: nextCells },
78819
+ ...table.rows.slice(rowToken.index + 1)
78820
+ ];
78821
+ return { ...table, rows: nextRows };
78822
+ }
78823
+ function joinNumberedParagraphInTextBoxInline(paragraph, tokens, direction) {
78824
+ const [inlineToken, textBoxToken, ...childTokens] = tokens;
78825
+ if (inlineToken?.kind !== "inline" || textBoxToken?.kind !== "txbx" || childTokens[0]?.kind !== "block") {
78826
+ return null;
78827
+ }
78828
+ const inline = paragraph.children[inlineToken.index];
78829
+ if (!inline) return null;
78830
+ const updatedInline = joinNumberedParagraphInInlineTextBox(inline, childTokens, direction);
78831
+ if (!updatedInline) return null;
78832
+ return {
78833
+ ...paragraph,
78834
+ children: [
78835
+ ...paragraph.children.slice(0, inlineToken.index),
78836
+ updatedInline,
78837
+ ...paragraph.children.slice(inlineToken.index + 1)
78838
+ ]
78839
+ };
78840
+ }
78841
+ function joinNumberedParagraphInInlineTextBox(inline, tokens, direction) {
78842
+ if (inline.type === "shape" && inline.txbxBlocks) {
78843
+ const updatedBlocks = joinNumberedParagraphFromBlocks(inline.txbxBlocks, tokens, direction);
78844
+ return updatedBlocks ? { ...inline, txbxBlocks: updatedBlocks.blocks } : null;
78845
+ }
78846
+ if (inline.type === "drawing_frame" && inline.content.type === "shape" && inline.content.txbxBlocks) {
78847
+ const updatedBlocks = joinNumberedParagraphFromBlocks(inline.content.txbxBlocks, tokens, direction);
78848
+ return updatedBlocks ? {
78849
+ ...inline,
78850
+ content: {
78851
+ ...inline.content,
78852
+ txbxBlocks: updatedBlocks.blocks
78853
+ }
78854
+ } : null;
78855
+ }
78856
+ return null;
78857
+ }
78217
78858
  function removeNumberedParagraphFromBlocks(blocks, tokens) {
78218
78859
  const [token, ...rest] = tokens;
78219
78860
  if (!token || token.kind !== "block") return null;
@@ -78376,6 +79017,56 @@ function createSelectedListItemDeleteReplayCommand(input) {
78376
79017
  origin: command.origin
78377
79018
  };
78378
79019
  }
79020
+ function createListItemBoundaryJoinReplayCommand(input) {
79021
+ const { command, document: document2, selection, surface, storyTarget, timestamp } = input;
79022
+ if (command.type !== "text.delete-backward" && command.type !== "text.delete-forward") {
79023
+ return null;
79024
+ }
79025
+ const editableTarget = command.editableTarget;
79026
+ if (!editableTarget) {
79027
+ return null;
79028
+ }
79029
+ const targetResolution = resolveEditableTextTarget({
79030
+ document: document2,
79031
+ selection,
79032
+ surface,
79033
+ target: editableTarget,
79034
+ activeStoryKey: canonicalEditableTargetStoryKey(storyTarget)
79035
+ });
79036
+ const resolvedEditableTarget = targetResolution.kind === "accepted" ? editableTarget : storyTarget.kind !== "main" && blockPathBelongsToStoryTarget(editableTarget.blockPath, storyTarget) ? resolveEditableCommandTarget({
79037
+ document: document2,
79038
+ target: editableTarget,
79039
+ activeStoryKey: canonicalEditableTargetStoryKey(storyTarget),
79040
+ commandFamilies: ["text-leaf"]
79041
+ }) : null;
79042
+ const selectedRange = {
79043
+ from: Math.min(selection.anchor, selection.head),
79044
+ to: Math.max(selection.anchor, selection.head)
79045
+ };
79046
+ const replacement = createListItemBoundaryJoinReplacement({
79047
+ command,
79048
+ document: document2,
79049
+ editableTarget: resolvedEditableTarget && resolvedEditableTarget.kind === "accepted" ? resolvedEditableTarget.target : editableTarget,
79050
+ selection,
79051
+ storyTarget,
79052
+ targetResolution: resolvedEditableTarget && resolvedEditableTarget.kind === "accepted" ? {
79053
+ kind: "accepted",
79054
+ range: selectedRange
79055
+ } : targetResolution,
79056
+ timestamp
79057
+ });
79058
+ if (!replacement) {
79059
+ return null;
79060
+ }
79061
+ return {
79062
+ type: "document.replace",
79063
+ document: replacement.document,
79064
+ selection: replacement.selection,
79065
+ mapping: replacement.mapping,
79066
+ protectionSelection: selection,
79067
+ origin: command.origin
79068
+ };
79069
+ }
78379
79070
  function parseStoryBlockPathTokens(blockPath, storyTarget) {
78380
79071
  if (!blockPath) {
78381
79072
  return null;
@@ -94542,6 +95233,9 @@ function createLoadingRuntimeBridge(input) {
94542
95233
  addScope: () => {
94543
95234
  throw createLoadingBoundaryError(input.snapshot.documentId, "scope");
94544
95235
  },
95236
+ addScopes: () => {
95237
+ throw createLoadingBoundaryError(input.snapshot.documentId, "scope");
95238
+ },
94545
95239
  getScope: () => null,
94546
95240
  compileScopeBundleById: () => null,
94547
95241
  compileScopeList: () => [],
@@ -126809,7 +127503,7 @@ var LAYER_DEBUG_PANES = [
126809
127503
  snippets: [
126810
127504
  { label: "Selection context", expression: "ref?.getRuntimeContextAnalytics?.()" },
126811
127505
  { label: "Document context", expression: "ref?.getRuntimeContextAnalytics?.({ scopeKind: 'document' })" },
126812
- { label: "Hot edit trace", expression: "runtime?.debug?.getHotEditTraces?.().at(-1)" },
127506
+ { label: "Hot edit trace", expression: "runtime?.debug?.getHotEditTraces?.()?.at(-1)" },
126813
127507
  { label: "View state", expression: "ref?.getViewState?.()" }
126814
127508
  ],
126815
127509
  routed: [
@@ -126823,8 +127517,8 @@ var LAYER_DEBUG_PANES = [
126823
127517
  focus: "Workflow scopes, markup, metadata, candidates, and scope-derived context.",
126824
127518
  snippets: [
126825
127519
  { label: "Scope snapshot", expression: "ref?.getWorkflowScopeSnapshot?.()" },
126826
- { label: "Query scopes", expression: "ref?.queryScopes?.({ includeHidden: true, includeInvisible: true })" },
126827
- { label: "Workflow markup", expression: "ref?.getWorkflowMarkupSnapshot?.()" }
127520
+ { label: "Query scopes", expression: "ref?.queryScopes?.({ includeHidden: true, includeInvisible: true, limit: 50 })" },
127521
+ { label: "Workflow markup", expression: "(() => { const m = ref?.getWorkflowMarkupSnapshot?.(); return m ? { itemCount: m.items?.length ?? 0, items: m.items?.slice(0, 50) ?? [] } : m; })()" }
126828
127522
  ],
126829
127523
  routed: [
126830
127524
  "Compiler replacement planning and semantic scope normalization remain Layer 08-owned."
@@ -126838,7 +127532,7 @@ var LAYER_DEBUG_PANES = [
126838
127532
  snippets: [
126839
127533
  { label: "Document analytics", expression: "ref?.getRuntimeContextAnalytics?.({ scopeKind: 'document' })" },
126840
127534
  { label: "Workflow analytics", expression: "ref?.getRuntimeContextAnalytics?.({ scopeKind: 'workflow_scope', scopeId: ref?.getInteractionGuardSnapshot?.()?.matchedScopeId })" },
126841
- { label: "Available scopes", expression: "ref?.queryScopes?.({ includeHidden: true, includeInvisible: true })" }
127535
+ { label: "Available scopes", expression: "ref?.queryScopes?.({ includeHidden: true, includeInvisible: true, limit: 50 })" }
126842
127536
  ],
126843
127537
  routed: [
126844
127538
  "AI audit references and action policy payloads are Layer 09-owned."
@@ -126866,7 +127560,7 @@ var LAYER_DEBUG_PANES = [
126866
127560
  snippets: [
126867
127561
  { label: "Navigation", expression: "ref?.getDocumentNavigationSnapshot?.()" },
126868
127562
  { label: "Review surface", expression: "({ comments: ref?.getCommentSidebarSnapshot?.(), changes: ref?.getTrackedChangesSnapshot?.() })" },
126869
- { label: "Hot edit traces", expression: "runtime?.debug?.getHotEditTraces?.()" },
127563
+ { label: "Hot edit traces", expression: "runtime?.debug?.getHotEditTraces?.()?.slice?.(-10)" },
126870
127564
  { label: "Compatibility", expression: "ref?.getCompatibilityReport?.()" }
126871
127565
  ],
126872
127566
  routed: [
@@ -126899,6 +127593,11 @@ var import_jsx_runtime83 = require("react/jsx-runtime");
126899
127593
  var MAX_HISTORY = 30;
126900
127594
  var MAX_ENTRIES = 50;
126901
127595
  var MAX_OUTPUT_CHARS = 8e3;
127596
+ var MAX_SERIALIZE_DEPTH = 6;
127597
+ var MAX_SERIALIZE_STRING_CHARS = 1e3;
127598
+ var MAX_SERIALIZE_ARRAY_ITEMS = 40;
127599
+ var MAX_SERIALIZE_OBJECT_KEYS = 80;
127600
+ var MAX_SERIALIZE_NODES = 2500;
126902
127601
  var HISTORY_STORAGE_KEY = "wre-runtime-repl-history";
126903
127602
  var HISTORY_STORAGE_VERSION = 1;
126904
127603
  function TwRuntimeReplDialog(props) {
@@ -127364,7 +128063,7 @@ function formatReplValue(value) {
127364
128063
  if (value === void 0) return "undefined";
127365
128064
  if (value === null) return "null";
127366
128065
  const type = typeof value;
127367
- if (type === "string") return JSON.stringify(value);
128066
+ if (type === "string") return truncate2(JSON.stringify(value), MAX_OUTPUT_CHARS);
127368
128067
  if (type === "number" || type === "boolean" || type === "bigint") {
127369
128068
  return String(value);
127370
128069
  }
@@ -127374,7 +128073,7 @@ function formatReplValue(value) {
127374
128073
  return `[Function${fn.name ? `: ${fn.name}` : ""}]`;
127375
128074
  }
127376
128075
  try {
127377
- const serialized = JSON.stringify(value, createCircularReplacer(), 2);
128076
+ const serialized = JSON.stringify(createReplPreview(value), null, 2);
127378
128077
  if (serialized === void 0) {
127379
128078
  return String(value);
127380
128079
  }
@@ -127390,21 +128089,113 @@ function formatReplError(error) {
127390
128089
  }
127391
128090
  return truncate2(String(error), MAX_OUTPUT_CHARS);
127392
128091
  }
127393
- function createCircularReplacer() {
127394
- const seen = /* @__PURE__ */ new WeakSet();
127395
- return function replacer(_key, value) {
127396
- if (typeof value === "bigint") return `${value.toString()}n`;
127397
- if (typeof value === "function") {
127398
- const fn = value;
127399
- return `[Function${fn.name ? `: ${fn.name}` : ""}]`;
128092
+ function createReplPreview(value) {
128093
+ return createReplPreviewValue(value, 0, {
128094
+ seen: /* @__PURE__ */ new WeakSet(),
128095
+ nodes: 0
128096
+ });
128097
+ }
128098
+ function createReplPreviewValue(value, depth, state) {
128099
+ if (value === null || typeof value === "number" || typeof value === "boolean") {
128100
+ return value;
128101
+ }
128102
+ if (typeof value === "string") {
128103
+ return value.length > MAX_SERIALIZE_STRING_CHARS ? `${value.slice(0, MAX_SERIALIZE_STRING_CHARS)}... [truncated ${value.length - MAX_SERIALIZE_STRING_CHARS} chars]` : value;
128104
+ }
128105
+ if (typeof value === "bigint") return `${value.toString()}n`;
128106
+ if (typeof value === "symbol") return value.toString();
128107
+ if (typeof value === "function") {
128108
+ const fn = value;
128109
+ return `[Function${fn.name ? `: ${fn.name}` : ""}]`;
128110
+ }
128111
+ if (typeof value !== "object") return String(value);
128112
+ state.nodes += 1;
128113
+ if (state.nodes > MAX_SERIALIZE_NODES) {
128114
+ return "[Max REPL preview nodes reached]";
128115
+ }
128116
+ const objectValue = value;
128117
+ if (state.seen.has(objectValue)) return "[Circular]";
128118
+ state.seen.add(objectValue);
128119
+ if (depth >= MAX_SERIALIZE_DEPTH) {
128120
+ return summarizePreviewBoundary(objectValue);
128121
+ }
128122
+ const domPreview = summarizeDomNode(objectValue);
128123
+ if (domPreview) return domPreview;
128124
+ if (Array.isArray(value)) {
128125
+ const preview = value.slice(0, MAX_SERIALIZE_ARRAY_ITEMS).map((item) => createReplPreviewValue(item, depth + 1, state));
128126
+ if (value.length > MAX_SERIALIZE_ARRAY_ITEMS) {
128127
+ preview.push(`[... ${value.length - MAX_SERIALIZE_ARRAY_ITEMS} more items]`);
127400
128128
  }
127401
- if (typeof value === "symbol") return value.toString();
127402
- if (value !== null && typeof value === "object") {
127403
- if (seen.has(value)) return "[Circular]";
127404
- seen.add(value);
128129
+ return preview;
128130
+ }
128131
+ if (value instanceof Date) {
128132
+ return Number.isNaN(value.getTime()) ? "[Invalid Date]" : value.toISOString();
128133
+ }
128134
+ if (value instanceof Map) {
128135
+ const entries = [];
128136
+ let index = 0;
128137
+ for (const [key, entryValue] of value.entries()) {
128138
+ if (index >= MAX_SERIALIZE_OBJECT_KEYS) {
128139
+ entries.push("[additional map entries omitted]");
128140
+ break;
128141
+ }
128142
+ entries.push([
128143
+ createReplPreviewValue(key, depth + 1, state),
128144
+ createReplPreviewValue(entryValue, depth + 1, state)
128145
+ ]);
128146
+ index += 1;
127405
128147
  }
127406
- return value;
127407
- };
128148
+ return { "[Map]": entries };
128149
+ }
128150
+ if (value instanceof Set) {
128151
+ const entries = [];
128152
+ let index = 0;
128153
+ for (const entryValue of value.values()) {
128154
+ if (index >= MAX_SERIALIZE_OBJECT_KEYS) {
128155
+ entries.push("[additional set entries omitted]");
128156
+ break;
128157
+ }
128158
+ entries.push(createReplPreviewValue(entryValue, depth + 1, state));
128159
+ index += 1;
128160
+ }
128161
+ return { "[Set]": entries };
128162
+ }
128163
+ const output = {};
128164
+ let count = 0;
128165
+ for (const key in value) {
128166
+ if (!Object.prototype.propertyIsEnumerable.call(value, key)) continue;
128167
+ if (count >= MAX_SERIALIZE_OBJECT_KEYS) {
128168
+ output["..."] = "[additional properties omitted]";
128169
+ break;
128170
+ }
128171
+ try {
128172
+ output[key] = createReplPreviewValue(
128173
+ value[key],
128174
+ depth + 1,
128175
+ state
128176
+ );
128177
+ } catch (error) {
128178
+ output[key] = `[unreadable property: ${formatReplError(error)}]`;
128179
+ }
128180
+ count += 1;
128181
+ }
128182
+ return output;
128183
+ }
128184
+ function summarizePreviewBoundary(value) {
128185
+ if (Array.isArray(value)) return `[Array(${value.length}) depth limit]`;
128186
+ const domPreview = summarizeDomNode(value);
128187
+ if (domPreview) return domPreview;
128188
+ const constructorName = value.constructor?.name;
128189
+ return constructorName && constructorName !== "Object" ? `[${constructorName} depth limit]` : "[Object depth limit]";
128190
+ }
128191
+ function summarizeDomNode(value) {
128192
+ const maybeNode = value;
128193
+ if (typeof maybeNode.nodeType !== "number" || typeof maybeNode.nodeName !== "string") {
128194
+ return null;
128195
+ }
128196
+ const id = typeof maybeNode.id === "string" && maybeNode.id.length > 0 ? `#${maybeNode.id}` : "";
128197
+ const className = typeof maybeNode.className === "string" && maybeNode.className.length > 0 ? `.${maybeNode.className.trim().replace(/\s+/g, ".")}` : "";
128198
+ return `[DOM ${maybeNode.nodeName.toLowerCase()}${id}${className}]`;
127408
128199
  }
127409
128200
  function truncate2(text, max) {
127410
128201
  if (text.length <= max) return text;
@@ -128754,9 +129545,23 @@ function findSurfaceBlockById(blocks, blockId) {
128754
129545
  }
128755
129546
  function createScopeFromAnchor(runtime, input) {
128756
129547
  const doc = runtime.getCanonicalDocument();
128757
- const storyTarget = input.anchor.storyTarget ?? { kind: "main" };
129548
+ const normalizedInputAnchor = normalizeCreateScopeAnchor(input.anchor);
129549
+ const storyTarget = normalizedInputAnchor.storyTarget ?? { kind: "main" };
128758
129550
  const storyLength = storyTarget.kind === "main" ? computeMainStoryLength(doc) : Number.MAX_SAFE_INTEGER;
128759
- const { from, to } = input.anchor;
129551
+ const { from, to } = normalizedInputAnchor;
129552
+ if (!Number.isFinite(from) || !Number.isFinite(to)) {
129553
+ const diagnosticFrom = Number.isFinite(from) ? from : 0;
129554
+ const diagnosticTo = Number.isFinite(to) ? to : diagnosticFrom;
129555
+ return {
129556
+ status: "range-invalid",
129557
+ reason: "non-finite-range",
129558
+ from: diagnosticFrom,
129559
+ to: diagnosticTo,
129560
+ storyLength,
129561
+ message: `createScopeFromAnchor requires finite numeric from/to offsets. Pass selection.activeRange or an object shaped as {from, to}; do not pass a malformed range.`,
129562
+ nextStep: "pass-selection-activeRange-or-finite-from-to"
129563
+ };
129564
+ }
128760
129565
  if (from < 0) {
128761
129566
  return {
128762
129567
  status: "range-invalid",
@@ -128854,6 +129659,29 @@ function createScopeFromAnchor(runtime, input) {
128854
129659
  }
128855
129660
  return { status: "created", scopeId: result.scopeId, anchor: result.anchor };
128856
129661
  }
129662
+ function normalizeCreateScopeAnchor(anchor) {
129663
+ const candidate = anchor;
129664
+ const activeRange = candidate.activeRange;
129665
+ if (activeRange?.kind === "range") {
129666
+ return {
129667
+ from: activeRange.from,
129668
+ to: activeRange.to,
129669
+ storyTarget: candidate.storyTarget
129670
+ };
129671
+ }
129672
+ if (candidate.kind === "range") {
129673
+ return {
129674
+ from: candidate.from ?? Number.NaN,
129675
+ to: candidate.to ?? Number.NaN,
129676
+ storyTarget: candidate.storyTarget
129677
+ };
129678
+ }
129679
+ return {
129680
+ from: candidate.from ?? Number.NaN,
129681
+ to: candidate.to ?? Number.NaN,
129682
+ storyTarget: candidate.storyTarget
129683
+ };
129684
+ }
128857
129685
 
128858
129686
  // src/api/v3/runtime/workflow.ts
128859
129687
  var createScopeMetadata = {
@@ -130100,7 +130928,8 @@ var SUPPORTED_COMMANDS2 = [
130100
130928
  "indent",
130101
130929
  "outdent",
130102
130930
  "restart-numbering",
130103
- "continue-numbering"
130931
+ "continue-numbering",
130932
+ "set-value"
130104
130933
  ];
130105
130934
  var UNSUPPORTED_COMMANDS2 = [
130106
130935
  "create",
@@ -130109,7 +130938,6 @@ var UNSUPPORTED_COMMANDS2 = [
130109
130938
  "join",
130110
130939
  "separate",
130111
130940
  "split",
130112
- "set-value",
130113
130941
  "apply-template",
130114
130942
  "capture-template",
130115
130943
  "apply-preset",
@@ -130158,10 +130986,10 @@ function createListsFamily2(runtime) {
130158
130986
  return resolved.kind === "resolved" ? toReadback(runtime.getCanonicalDocument(), resolved.target, resolved.paragraph) : null;
130159
130987
  },
130160
130988
  previewCommand(input) {
130161
- return previewListCommand(runtime.getCanonicalDocument(), input);
130989
+ return previewListCommand(runtime.getCanonicalDocument(), input, activeStoryKey(runtime));
130162
130990
  },
130163
130991
  applyCommand(input) {
130164
- const preview = previewListCommand(runtime.getCanonicalDocument(), input);
130992
+ const preview = previewListCommand(runtime.getCanonicalDocument(), input, activeStoryKey(runtime));
130165
130993
  if (!preview.supported || !preview.target) {
130166
130994
  return {
130167
130995
  applied: false,
@@ -130221,7 +131049,7 @@ function createListsFamily2(runtime) {
130221
131049
  }
130222
131050
  };
130223
131051
  }
130224
- function previewListCommand(document2, input) {
131052
+ function previewListCommand(document2, input, activeStoryKey2) {
130225
131053
  const resolved = resolveCurrentListTarget(document2, input);
130226
131054
  if (resolved.kind !== "resolved") {
130227
131055
  return {
@@ -130233,6 +131061,20 @@ function previewListCommand(document2, input) {
130233
131061
  }
130234
131062
  const target = toReadback(document2, resolved.target, resolved.paragraph);
130235
131063
  const targetRef = { targetKey: target.targetKey, addressKey: target.addressKey };
131064
+ if (activeStoryKey2 !== void 0 && target.storyKey !== activeStoryKey2) {
131065
+ return {
131066
+ command: input.command,
131067
+ supported: false,
131068
+ target,
131069
+ affectedTargets: [target],
131070
+ blockers: [{
131071
+ code: "list-target-wrong-story",
131072
+ ownerLayer: "L07",
131073
+ message: "List target does not belong to the runtime active story.",
131074
+ ...targetRef
131075
+ }]
131076
+ };
131077
+ }
130236
131078
  if (!SUPPORTED_COMMANDS2.includes(input.command)) {
130237
131079
  return {
130238
131080
  command: input.command,
@@ -130245,6 +131087,17 @@ function previewListCommand(document2, input) {
130245
131087
  const canContinuePrevious = canContinuePreviousSequence(document2, resolved.paragraphIndex);
130246
131088
  const canJoin = canJoinPreviousSequence(document2, resolved.paragraphIndex);
130247
131089
  const blockers = [];
131090
+ if (input.command === "set-value") {
131091
+ const value = input.startAt;
131092
+ if (!Number.isInteger(value) || value === void 0 || value < 1) {
131093
+ blockers.push({
131094
+ code: "list-command-preflight-blocked",
131095
+ ownerLayer: "L07",
131096
+ message: "runtime.lists.set-value requires a positive integer startAt value.",
131097
+ ...targetRef
131098
+ });
131099
+ }
131100
+ }
130248
131101
  if (input.command === "continue-numbering" && !canContinuePrevious) {
130249
131102
  blockers.push({
130250
131103
  code: "list-continue-target-missing",
@@ -130275,6 +131128,7 @@ function editorCommandForListCommand(command, editableTarget, timestamp, startAt
130275
131128
  case "outdent":
130276
131129
  return { type: "list.outdent", editableTargets: [editableTarget], origin };
130277
131130
  case "restart-numbering":
131131
+ case "set-value":
130278
131132
  return {
130279
131133
  type: "list.restart-numbering",
130280
131134
  editableTarget,
@@ -130358,33 +131212,35 @@ function resolveCurrentListTarget(document2, input) {
130358
131212
  return { kind: "resolved", ...resolved };
130359
131213
  }
130360
131214
  function currentListTargets(document2) {
130361
- const paragraphs = collectParagraphEntries(document2.content.children, "main");
131215
+ const paragraphs = collectParagraphEntries(document2);
130362
131216
  const targets = collectEditableTargetRefs(document2).filter(isListTextTarget);
130363
- const byBlockPath = /* @__PURE__ */ new Map();
130364
- for (const target of targets) byBlockPath.set(target.blockPath, target);
131217
+ const byStoryBlockPath = /* @__PURE__ */ new Map();
131218
+ for (const target of targets) byStoryBlockPath.set(storyBlockPathKey(target.storyKey, target.blockPath), target);
130365
131219
  const out = [];
130366
131220
  for (let paragraphIndex = 0; paragraphIndex < paragraphs.length; paragraphIndex += 1) {
130367
131221
  const entry = paragraphs[paragraphIndex];
130368
131222
  if (!entry?.paragraph.numbering) continue;
130369
- const target = byBlockPath.get(entry.blockPath);
131223
+ const target = byStoryBlockPath.get(storyBlockPathKey(entry.storyKey, entry.blockPath));
130370
131224
  if (!target) continue;
130371
- out.push({ target, paragraph: entry.paragraph, paragraphIndex });
131225
+ out.push({ target, paragraph: entry.paragraph, paragraphIndex, storyKey: entry.storyKey });
130372
131226
  }
130373
131227
  return out;
130374
131228
  }
130375
- function collectParagraphEntries(blocks, basePath) {
131229
+ function collectParagraphEntries(document2) {
130376
131230
  const out = [];
130377
- collectParagraphEntriesInto(blocks, basePath, out);
131231
+ for (const context of collectStoryBlockContexts(document2)) {
131232
+ collectParagraphEntriesInto(context.blocks, context.storyKey, context.basePath, out);
131233
+ }
130378
131234
  return out;
130379
131235
  }
130380
- function collectParagraphEntriesInto(blocks, basePath, out) {
131236
+ function collectParagraphEntriesInto(blocks, storyKey2, basePath, out) {
130381
131237
  for (let blockIndex = 0; blockIndex < blocks.length; blockIndex += 1) {
130382
131238
  const block = blocks[blockIndex];
130383
131239
  if (!block) continue;
130384
131240
  const blockPath = `${basePath}/block[${blockIndex}]`;
130385
131241
  switch (block.type) {
130386
131242
  case "paragraph":
130387
- out.push({ paragraph: block, blockPath });
131243
+ out.push({ paragraph: block, storyKey: storyKey2, blockPath });
130388
131244
  break;
130389
131245
  case "table":
130390
131246
  for (let rowIndex = 0; rowIndex < block.rows.length; rowIndex += 1) {
@@ -130395,6 +131251,7 @@ function collectParagraphEntriesInto(blocks, basePath, out) {
130395
131251
  if (!cell) continue;
130396
131252
  collectParagraphEntriesInto(
130397
131253
  cell.children,
131254
+ storyKey2,
130398
131255
  `${blockPath}/row[${rowIndex}]/cell[${cellIndex}]`,
130399
131256
  out
130400
131257
  );
@@ -130402,7 +131259,7 @@ function collectParagraphEntriesInto(blocks, basePath, out) {
130402
131259
  }
130403
131260
  break;
130404
131261
  case "sdt":
130405
- collectParagraphEntriesInto(block.children, blockPath, out);
131262
+ collectParagraphEntriesInto(block.children, storyKey2, blockPath, out);
130406
131263
  break;
130407
131264
  case "custom_xml":
130408
131265
  break;
@@ -130446,13 +131303,16 @@ function toReadback(document2, target, paragraph) {
130446
131303
  };
130447
131304
  }
130448
131305
  function canContinuePreviousSequence(document2, paragraphIndex) {
130449
- const paragraphs = collectParagraphEntries(document2.content.children, "main");
130450
- const current = paragraphs[paragraphIndex]?.paragraph;
131306
+ const paragraphs = collectParagraphEntries(document2);
131307
+ const currentEntry = paragraphs[paragraphIndex];
131308
+ const current = currentEntry?.paragraph;
130451
131309
  if (!current?.numbering) return false;
130452
131310
  const currentKind = getListKind(document2.numbering, current.numbering.numberingInstanceId);
130453
131311
  if (!currentKind) return false;
130454
131312
  for (let index = paragraphIndex - 1; index >= 0; index -= 1) {
130455
- const previous = paragraphs[index]?.paragraph;
131313
+ const previousEntry = paragraphs[index];
131314
+ if (previousEntry?.storyKey !== currentEntry.storyKey) break;
131315
+ const previous = previousEntry.paragraph;
130456
131316
  if (!previous?.numbering) continue;
130457
131317
  const previousKind = getListKind(document2.numbering, previous.numbering.numberingInstanceId);
130458
131318
  return previousKind === currentKind && previous.numbering.numberingInstanceId !== current.numbering.numberingInstanceId;
@@ -130460,14 +131320,25 @@ function canContinuePreviousSequence(document2, paragraphIndex) {
130460
131320
  return false;
130461
131321
  }
130462
131322
  function canJoinPreviousSequence(document2, paragraphIndex) {
130463
- const paragraphs = collectParagraphEntries(document2.content.children, "main");
130464
- const current = paragraphs[paragraphIndex]?.paragraph;
130465
- const previous = paragraphs[paragraphIndex - 1]?.paragraph;
131323
+ const paragraphs = collectParagraphEntries(document2);
131324
+ const currentEntry = paragraphs[paragraphIndex];
131325
+ const previousEntry = paragraphs[paragraphIndex - 1];
131326
+ if (previousEntry?.storyKey !== currentEntry?.storyKey) return false;
131327
+ const current = currentEntry?.paragraph;
131328
+ const previous = previousEntry?.paragraph;
130466
131329
  if (!current?.numbering || !previous?.numbering) return false;
130467
131330
  const currentKind = getListKind(document2.numbering, current.numbering.numberingInstanceId);
130468
131331
  const previousKind = getListKind(document2.numbering, previous.numbering.numberingInstanceId);
130469
131332
  return Boolean(currentKind) && currentKind === previousKind && current.numbering.numberingInstanceId !== previous.numbering.numberingInstanceId;
130470
131333
  }
131334
+ function storyBlockPathKey(storyKey2, blockPath) {
131335
+ return `${storyKey2}
131336
+ ${blockPath}`;
131337
+ }
131338
+ function activeStoryKey(runtime) {
131339
+ const activeStory = runtime.getRenderSnapshot()?.activeStory;
131340
+ return activeStory ? storyTargetKey(activeStory) : void 0;
131341
+ }
130471
131342
  function unsupportedCommandBlocker(command, target) {
130472
131343
  return {
130473
131344
  code: "list-command-unsupported",
@@ -134762,33 +135633,51 @@ function createPlaceholderScopes(runtime, input) {
134762
135633
  blockerDetails: Object.freeze([detail])
134763
135634
  };
134764
135635
  }
134765
- const compiler = createScopeCompilerService(runtime);
134766
135636
  const byOriginalIndex = /* @__PURE__ */ new Map();
134767
- for (const item of orderedHits) {
135637
+ const createdScopeIds = [];
135638
+ const scopeRequests = orderedHits.map((item) => {
134768
135639
  const text = item.text || query;
134769
135640
  const label = input.labelPrefix === void 0 ? text : `${input.labelPrefix} ${item.originalIndex + 1}`;
134770
- const result = createScopeFromAnchor(runtime, {
134771
- anchor: { from: item.hit.from, to: item.hit.to },
135641
+ return {
135642
+ anchor: {
135643
+ kind: "range",
135644
+ from: item.hit.from,
135645
+ to: item.hit.to,
135646
+ assoc: input.assoc ?? { start: 1, end: -1 }
135647
+ },
134772
135648
  mode: input.mode ?? "edit",
134773
135649
  label,
134774
135650
  ...input.visibility ? { visibility: input.visibility } : {},
134775
135651
  ...input.guardPolicy ? { guardPolicy: input.guardPolicy } : {},
134776
135652
  ...input.assoc ? { assoc: input.assoc } : {},
134777
- ...input.stableRefHint ? { stableRefHint: input.stableRefHint } : {}
134778
- });
134779
- if (result.status === "created") {
134780
- const compiled = compiler.compileScopeById(result.scopeId)?.scope;
135653
+ ...input.stableRefHint ? {
135654
+ scopeMetadataFields: [
135655
+ {
135656
+ key: "stableRefHint",
135657
+ valueType: "string",
135658
+ value: input.stableRefHint
135659
+ }
135660
+ ]
135661
+ } : {}
135662
+ };
135663
+ });
135664
+ const scopeResults = runtime.addScopes(scopeRequests);
135665
+ orderedHits.forEach((item, requestIndex) => {
135666
+ const text = item.text || query;
135667
+ const result = scopeResults[requestIndex];
135668
+ if (result && result.scopeId && result.plantStatus?.planted !== false) {
135669
+ createdScopeIds.push(result.scopeId);
134781
135670
  byOriginalIndex.set(item.originalIndex, {
134782
135671
  status: "created",
134783
135672
  text,
134784
135673
  excerpt: excerpt(text),
134785
- scopeId: result.scopeId,
134786
- ...compiled?.handle ? { handle: compiled.handle } : {}
135674
+ scopeId: result.scopeId
134787
135675
  });
134788
- continue;
135676
+ return;
134789
135677
  }
135678
+ const reason = result?.plantStatus?.reason ?? "unknown";
134790
135679
  const detail = blockerWithOwner(
134791
- `actions:placeholder-scopes:create-refused:${result.reason}`,
135680
+ `actions:placeholder-scopes:create-refused:${reason}`,
134792
135681
  "blocked",
134793
135682
  "The placeholder match could not be converted into a workflow scope.",
134794
135683
  "Refresh the document and retry; if it still refuses, route the target to the workflow/scope writer owner.",
@@ -134801,6 +135690,38 @@ function createPlaceholderScopes(runtime, input) {
134801
135690
  blockers: Object.freeze([detail.code]),
134802
135691
  blockerDetails: Object.freeze([detail])
134803
135692
  });
135693
+ });
135694
+ if (createdScopeIds.length > 0) {
135695
+ const createdScopeIdSet = new Set(createdScopeIds);
135696
+ const handlesByScopeId = new Map(
135697
+ createScopeCompilerService(runtime).compileAllScopes().filter((scope) => createdScopeIdSet.has(scope.handle.scopeId)).map((scope) => [scope.handle.scopeId, scope.handle])
135698
+ );
135699
+ for (const [originalIndex, item] of byOriginalIndex) {
135700
+ if (item.status !== "created" || !item.scopeId) continue;
135701
+ const handle = handlesByScopeId.get(item.scopeId);
135702
+ if (!handle) {
135703
+ const detail = blockerWithOwner(
135704
+ `actions:placeholder-scopes:create-unresolved:${item.scopeId}`,
135705
+ "blocked",
135706
+ "The placeholder scope marker was planted but did not enumerate as a current semantic scope handle.",
135707
+ "Treat this target as unresolved, refresh scope enumeration, and route persistent misses to the semantic-scope compiler owner.",
135708
+ "L08"
135709
+ );
135710
+ byOriginalIndex.set(originalIndex, {
135711
+ status: "blocked",
135712
+ text: item.text,
135713
+ excerpt: item.excerpt,
135714
+ scopeId: item.scopeId,
135715
+ blockers: Object.freeze([detail.code]),
135716
+ blockerDetails: Object.freeze([detail])
135717
+ });
135718
+ continue;
135719
+ }
135720
+ byOriginalIndex.set(originalIndex, {
135721
+ ...item,
135722
+ handle
135723
+ });
135724
+ }
134804
135725
  }
134805
135726
  const scopes = orderedHits.map((item) => byOriginalIndex.get(item.originalIndex)).filter((value) => value !== void 0);
134806
135727
  const created = scopes.filter((scope) => scope.status === "created").length;