@stll/docx-core 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { E as PARAGRAPH_ALIGNMENTS, J as isNumberingLevel, Z as isNumberingReference, a as INSERTION_SEAM_POLICIES, tt as paragraphNumberingReference } from "../document-3WKQA1r3.js";
2
- import { r as hasIllegalXmlCharacters } from "../xmlEscape-T-2DeGlS.js";
2
+ import { a as hasIllegalXmlCharacters, t as sanitizeExternalUrl } from "../href-2XSCK-T8.js";
3
3
  import { Result, TaggedError, panic } from "better-result";
4
4
  //#region src/ops/equality.ts
5
5
  const NOTHING = /* @__PURE__ */ new Set();
@@ -274,6 +274,7 @@ const restoreDocumentOp = (op) => {
274
274
  /**
275
275
  * The operation schema this module reads and writes.
276
276
  *
277
+ * Version 9 adds exact, JSON-safe package resource replacement for clipboard imports.
277
278
  * Version 8 adds semantic table edits and exact whole-table restoration.
278
279
  * Version 7 adds lossless own-undefined operation snapshot presence and
279
280
  * explicit revision-boundary provenance. An explicit undefined patch value now
@@ -295,7 +296,7 @@ const restoreDocumentOp = (op) => {
295
296
  * and paragraph operations, and the review operations `setParagraphReview`,
296
297
  * `replaceInline` and `resolveRevision`.
297
298
  */
298
- const DOCUMENT_OP_SCHEMA_VERSION = 8;
299
+ const DOCUMENT_OP_SCHEMA_VERSION = 9;
299
300
  /**
300
301
  * The main story has a fixed address; other editable parts use their stable
301
302
  * relationship id or note id. Comment bodies are not yet editable stories.
@@ -320,7 +321,7 @@ const SECTION_BOUNDARY_POLICIES = Object.freeze({
320
321
  REMOVE: "remove",
321
322
  REPLACE: "replace"
322
323
  });
323
- /** The operation kinds of schema version 8. */
324
+ /** The operation kinds of schema version 9. */
324
325
  const DOCUMENT_OP_TYPES = Object.freeze({
325
326
  CREATE_HEADER_FOOTER: "createHeaderFooter",
326
327
  REMOVE_HEADER_FOOTER: "removeHeaderFooter",
@@ -360,7 +361,8 @@ const DOCUMENT_OP_TYPES = Object.freeze({
360
361
  SET_TABLE: "setTable",
361
362
  CREATE_NUMBERING_INSTANCE: "createNumberingInstance",
362
363
  DELETE_NUMBERING_INSTANCE: "deleteNumberingInstance",
363
- SET_SECTION_ENDPOINT: "setSectionEndpoint"
364
+ SET_SECTION_ENDPOINT: "setSectionEndpoint",
365
+ SET_PACKAGE_RESOURCES: "setPackageResources"
364
366
  });
365
367
  /** Whether a tracked run patch appends an independently rejectable review. */
366
368
  const PROPERTY_REVIEW_POLICIES = Object.freeze({ APPEND: "append" });
@@ -382,7 +384,7 @@ const REVISION_DECISIONS = Object.freeze({
382
384
  });
383
385
  /** An operation in the envelope it is journaled and sent in. */
384
386
  const toOpEnvelope = (op) => ({
385
- schema: 8,
387
+ schema: 9,
386
388
  op: captureDocumentOp(op)
387
389
  });
388
390
  //#endregion
@@ -977,6 +979,8 @@ const INLINE_KINDS = {
977
979
  const isInlineContainer = (item) => INLINE_KINDS[item.type] === "container";
978
980
  /** A zero-width boundary that opens a range: it belongs with what follows it. */
979
981
  const isOpeningMarker = (item) => INLINE_KINDS[item.type] === "openingMarker";
982
+ /** A source range boundary is zero-width and remains outside replacement revisions. */
983
+ const isRangeBoundary = (item) => INLINE_KINDS[item.type] === "openingMarker" || INLINE_KINDS[item.type] === "closingMarker";
980
984
  /** Tracked content that direct text must not join: it is on its way out. */
981
985
  const isRemovedRevision = (item) => item.type === "deletion" || item.type === "moveFrom";
982
986
  const runContentWidth = (content) => {
@@ -1127,20 +1131,40 @@ const isPlainRecord = (value) => {
1127
1131
  const prototype = Object.getPrototypeOf(value);
1128
1132
  return prototype === Object.prototype || prototype === null;
1129
1133
  };
1130
- const walk = (value, visit, heldBy) => {
1134
+ const walk = ({ value, visit, context = {
1135
+ heldBy: void 0,
1136
+ ownerType: void 0
1137
+ } }) => {
1131
1138
  if (typeof value !== "object" || value === null) return;
1132
1139
  if (Array.isArray(value)) {
1133
- for (const item of value) walk(item, visit, heldBy);
1140
+ for (const item of value) walk({
1141
+ value: item,
1142
+ visit,
1143
+ context
1144
+ });
1134
1145
  return;
1135
1146
  }
1136
1147
  if (value instanceof Map) {
1137
- for (const item of value.values()) walk(item, visit, heldBy);
1148
+ for (const item of value.values()) walk({
1149
+ value: item,
1150
+ visit,
1151
+ context
1152
+ });
1138
1153
  return;
1139
1154
  }
1140
1155
  if (!isPlainRecord(value)) return;
1141
1156
  const entries = Object.entries(value);
1142
- visit(entries, heldBy);
1143
- for (const [key, field] of entries) walk(field, visit, key);
1157
+ visit(entries, context);
1158
+ const type = fieldOf(entries, "type");
1159
+ const ownerType = typeof type === "string" ? type : void 0;
1160
+ for (const [heldBy, field] of entries) walk({
1161
+ value: field,
1162
+ visit,
1163
+ context: {
1164
+ heldBy,
1165
+ ownerType
1166
+ }
1167
+ });
1144
1168
  };
1145
1169
  /** The package's stories, each once: the body without its derived section view. */
1146
1170
  const storiesOf = (pkg) => ({
@@ -1159,14 +1183,54 @@ const paragraphIdOf = (entries) => {
1159
1183
  /** Every `paraId` of every paragraph in a value, nested ones included, in document order. */
1160
1184
  const paragraphIdsIn = (value) => {
1161
1185
  const out = [];
1162
- walk(value, (entries) => {
1163
- const id = paragraphIdOf(entries);
1164
- if (id !== void 0) out.push(id);
1186
+ walk({
1187
+ value,
1188
+ visit: (entries) => {
1189
+ const id = paragraphIdOf(entries);
1190
+ if (id !== void 0) out.push(id);
1191
+ }
1165
1192
  });
1166
1193
  return out;
1167
1194
  };
1168
1195
  /** Every paragraph id of a package, each story walked once. */
1169
1196
  const packageParagraphIds = (pkg) => paragraphIdsIn(storiesOf(pkg));
1197
+ /** Bookmark ids, names and uniquely paired starts from every package story. */
1198
+ const packageBookmarkCensus = (pkg) => {
1199
+ const ids = /* @__PURE__ */ new Set();
1200
+ const names = /* @__PURE__ */ new Set();
1201
+ const starts = /* @__PURE__ */ new Map();
1202
+ const ends = /* @__PURE__ */ new Map();
1203
+ walk({
1204
+ value: storiesOf(pkg),
1205
+ visit: (entries) => {
1206
+ const type = fieldOf(entries, "type");
1207
+ const id = fieldOf(entries, "id");
1208
+ if (typeof id !== "number") return;
1209
+ if (type === "bookmarkStart") {
1210
+ ids.add(id);
1211
+ const name = fieldOf(entries, "name");
1212
+ if (typeof name !== "string") return;
1213
+ names.add(name);
1214
+ const prior = starts.get(id);
1215
+ starts.set(id, {
1216
+ name,
1217
+ count: (prior?.count ?? 0) + 1
1218
+ });
1219
+ } else if (type === "bookmarkEnd") {
1220
+ ids.add(id);
1221
+ ends.set(id, (ends.get(id) ?? 0) + 1);
1222
+ }
1223
+ }
1224
+ });
1225
+ return {
1226
+ ids,
1227
+ names,
1228
+ pairs: [...starts].flatMap(([id, start]) => start.count === 1 && ends.get(id) === 1 ? [{
1229
+ id,
1230
+ name: start.name
1231
+ }] : [])
1232
+ };
1233
+ };
1170
1234
  /**
1171
1235
  * The key two spellings of one id share. `ST_LongHexNumber` is hex, so
1172
1236
  * `0000abcd` and `0000ABCD` are the same id; every lookup and comparison of
@@ -1214,9 +1278,10 @@ const revisionIdOf = (entries, heldBy) => {
1214
1278
  const id = fieldOf(infoEntries, "id");
1215
1279
  return typeof id === "number" && typeof fieldOf(infoEntries, "author") === "string" ? id : void 0;
1216
1280
  };
1217
- const controlIdOf = (entries) => {
1281
+ const controlIdOf = (entries, { heldBy, ownerType }) => {
1218
1282
  const id = fieldOf(entries, "id");
1219
- return typeof fieldOf(entries, "sdtType") === "string" && typeof id === "number" ? id : void 0;
1283
+ if (typeof id !== "number") return void 0;
1284
+ return heldBy === "properties" && (ownerType === "inlineSdt" || ownerType === "blockSdt") || heldBy === CONTENT_CONTROL_STACK || typeof fieldOf(entries, "sdtType") === "string" ? id : void 0;
1220
1285
  };
1221
1286
  /**
1222
1287
  * Every revision and content-control id in a value, as slot keys: tracked
@@ -1226,25 +1291,31 @@ const controlIdOf = (entries) => {
1226
1291
  const identityKeysIn = (value) => {
1227
1292
  const out = [];
1228
1293
  const stacked = /* @__PURE__ */ new Map();
1229
- walk(value, (entries, heldBy) => {
1230
- const revision = revisionIdOf(entries, heldBy);
1231
- if (revision !== void 0) out.push(slotKey({
1232
- space: IDENTITY_SPACES.REVISION,
1233
- id: revision
1234
- }));
1235
- const control = controlIdOf(entries);
1236
- if (control === void 0) return;
1237
- if (heldBy === CONTENT_CONTROL_STACK) {
1238
- const record = Object.fromEntries(entries);
1239
- const seen = stacked.get(control) ?? [];
1240
- if (seen.some((other) => structurallyEqual(other, record))) return;
1241
- seen.push(record);
1242
- stacked.set(control, seen);
1243
- }
1244
- out.push(slotKey({
1245
- space: IDENTITY_SPACES.CONTROL,
1246
- id: control
1247
- }));
1294
+ walk({
1295
+ value,
1296
+ visit: (entries, { heldBy, ownerType }) => {
1297
+ const revision = revisionIdOf(entries, heldBy);
1298
+ if (revision !== void 0) out.push(slotKey({
1299
+ space: IDENTITY_SPACES.REVISION,
1300
+ id: revision
1301
+ }));
1302
+ const control = controlIdOf(entries, {
1303
+ heldBy,
1304
+ ownerType
1305
+ });
1306
+ if (control === void 0) return;
1307
+ if (heldBy === CONTENT_CONTROL_STACK) {
1308
+ const record = Object.fromEntries(entries);
1309
+ const seen = stacked.get(control) ?? [];
1310
+ if (seen.some((other) => structurallyEqual(other, record))) return;
1311
+ seen.push(record);
1312
+ stacked.set(control, seen);
1313
+ }
1314
+ out.push(slotKey({
1315
+ space: IDENTITY_SPACES.CONTROL,
1316
+ id: control
1317
+ }));
1318
+ }
1248
1319
  });
1249
1320
  return out;
1250
1321
  };
@@ -1253,27 +1324,30 @@ const CONTENT_CONTROL_STACK = "contentControls";
1253
1324
  /** Pending cut references reserve IDs without becoming physical model identities. */
1254
1325
  const reservedIdentityKeysIn = (value) => {
1255
1326
  const out = [];
1256
- walk(value, (entries, heldBy) => {
1257
- if (heldBy === "deferredRemove") {
1258
- const blockers = fieldOf(entries, "blockers");
1259
- if (Array.isArray(blockers)) {
1260
- for (const id of blockers) if (typeof id === "number") out.push(slotKey({
1261
- space: IDENTITY_SPACES.REVISION,
1262
- id
1263
- }));
1327
+ walk({
1328
+ value,
1329
+ visit: (entries, { heldBy }) => {
1330
+ if (heldBy === "deferredRemove") {
1331
+ const blockers = fieldOf(entries, "blockers");
1332
+ if (Array.isArray(blockers)) {
1333
+ for (const id of blockers) if (typeof id === "number") out.push(slotKey({
1334
+ space: IDENTITY_SPACES.REVISION,
1335
+ id
1336
+ }));
1337
+ }
1338
+ return;
1264
1339
  }
1265
- return;
1266
- }
1267
- if (heldBy !== "retainedAfter") return;
1268
- for (const field of ["source", "target"]) {
1269
- const slots = fieldOf(entries, field);
1270
- if (!Array.isArray(slots)) continue;
1271
- for (const slot of slots) {
1272
- if (typeof slot !== "object" || slot === null || !("space" in slot) || !("id" in slot)) continue;
1273
- if ((slot.space === IDENTITY_SPACES.REVISION || slot.space === IDENTITY_SPACES.CONTROL) && typeof slot.id === "number") out.push(slotKey({
1274
- space: slot.space,
1275
- id: slot.id
1276
- }));
1340
+ if (heldBy !== "retainedAfter") return;
1341
+ for (const field of ["source", "target"]) {
1342
+ const slots = fieldOf(entries, field);
1343
+ if (!Array.isArray(slots)) continue;
1344
+ for (const slot of slots) {
1345
+ if (typeof slot !== "object" || slot === null || !("space" in slot) || !("id" in slot)) continue;
1346
+ if ((slot.space === IDENTITY_SPACES.REVISION || slot.space === IDENTITY_SPACES.CONTROL) && typeof slot.id === "number") out.push(slotKey({
1347
+ space: slot.space,
1348
+ id: slot.id
1349
+ }));
1350
+ }
1277
1351
  }
1278
1352
  }
1279
1353
  });
@@ -1852,6 +1926,12 @@ const leafSpans = (items) => {
1852
1926
  walk(items, []);
1853
1927
  return out;
1854
1928
  };
1929
+ /** Source leaf coordinates without the ancestry needed by edit planning. */
1930
+ const inlineLeafSpans = (items) => leafSpans(items).map(({ node, before, after }) => ({
1931
+ node,
1932
+ before,
1933
+ after
1934
+ }));
1855
1935
  /** Gaps in document order: by offset, then by the zero-width leaves before them. */
1856
1936
  const compareGaps = (left, right) => left.offset === right.offset ? left.zeroWidthBefore - right.zeroWidthBefore : left.offset - right.offset;
1857
1937
  //#endregion
@@ -2097,7 +2177,7 @@ const priorValues = (base, patch) => {
2097
2177
  //#endregion
2098
2178
  //#region src/ops/storyLifecycle.ts
2099
2179
  /** Explicit story lifecycle and section property edits, with exact JSON-safe inverses. */
2100
- const refuse$3 = (op, message) => Result.err(new DocumentOpRefusal({
2180
+ const refuse$5 = (op, message) => Result.err(new DocumentOpRefusal({
2101
2181
  opType: op.type,
2102
2182
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
2103
2183
  message
@@ -2208,12 +2288,14 @@ const restoreParts = (document, parts) => {
2208
2288
  if (fields.headers !== void 0) if (fields.headers === null) delete section.headers;
2209
2289
  else section.headers = new Map(fields.headers.map(([variant, part]) => {
2210
2290
  const rId = section.properties.headerReferences?.find(({ type }) => type === variant)?.rId;
2211
- return [variant, (rId === void 0 ? void 0 : pkg.headers?.get(rId)) ?? part];
2291
+ const owned = rId === void 0 ? void 0 : pkg.headers?.get(rId);
2292
+ return [variant, owned && structurallyEqual(owned, part) ? owned : part];
2212
2293
  }));
2213
2294
  if (fields.footers !== void 0) if (fields.footers === null) delete section.footers;
2214
2295
  else section.footers = new Map(fields.footers.map(([variant, part]) => {
2215
2296
  const rId = section.properties.footerReferences?.find(({ type }) => type === variant)?.rId;
2216
- return [variant, (rId === void 0 ? void 0 : pkg.footers?.get(rId)) ?? part];
2297
+ const owned = rId === void 0 ? void 0 : pkg.footers?.get(rId);
2298
+ return [variant, owned && structurallyEqual(owned, part) ? owned : part];
2217
2299
  }));
2218
2300
  sections[fields.index] = section;
2219
2301
  }
@@ -2359,7 +2441,7 @@ const applyStoryLifecycle = (document, op) => {
2359
2441
  return storyLifecycleEdit(document, restoreParts(document, cloneModel(op.parts)), op);
2360
2442
  }
2361
2443
  const properties = sectionPropertiesAt(document, op.sectionIndex);
2362
- if (!properties) return refuse$3(op, "The section does not exist.");
2444
+ if (!properties) return refuse$5(op, "The section does not exist.");
2363
2445
  if (op.type === DOCUMENT_OP_TYPES.SET_SECTION_PROPS) {
2364
2446
  const nextProps = applyFormattingPatch(properties, op.patch) ?? {};
2365
2447
  let next = withSectionProperties(document, op.sectionIndex, nextProps);
@@ -2384,8 +2466,8 @@ const applyStoryLifecycle = (document, op) => {
2384
2466
  let nextRefs = [...refs ?? []];
2385
2467
  const nextProps = { ...properties };
2386
2468
  if (op.type === DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER) {
2387
- if (!op.story.rId || document.package.relationships?.has(op.story.rId) || document.package.headers?.has(op.story.rId) || document.package.footers?.has(op.story.rId) || refs?.some(({ type }) => type === op.referenceType)) return refuse$3(op, "The header/footer identity or section variant is already used.");
2388
- if (op.content.length === 0 || storyParagraphs({ content: op.content }).length === 0) return refuse$3(op, "A header/footer needs an addressable paragraph.");
2469
+ if (!op.story.rId || document.package.relationships?.has(op.story.rId) || document.package.headers?.has(op.story.rId) || document.package.footers?.has(op.story.rId) || refs?.some(({ type }) => type === op.referenceType)) return refuse$5(op, "The header/footer identity or section variant is already used.");
2470
+ if (op.content.length === 0 || storyParagraphs({ content: op.content }).length === 0) return refuse$5(op, "A header/footer needs an addressable paragraph.");
2389
2471
  const part = {
2390
2472
  type: kind,
2391
2473
  hdrFtrType: op.referenceType,
@@ -2399,7 +2481,7 @@ const applyStoryLifecycle = (document, op) => {
2399
2481
  if (op.referenceType === "first") nextProps.titlePg = true;
2400
2482
  if (op.referenceType === "even") nextProps.evenAndOddHeaders = true;
2401
2483
  } else {
2402
- if (!parts?.has(op.story.rId) || !refs?.some(({ type, rId }) => type === op.referenceType && rId === op.story.rId)) return refuse$3(op, "The section does not own this header/footer variant.");
2484
+ if (!parts?.has(op.story.rId) || !refs?.some(({ type, rId }) => type === op.referenceType && rId === op.story.rId)) return refuse$5(op, "The section does not own this header/footer variant.");
2403
2485
  nextRefs = nextRefs.filter(({ type }) => type !== op.referenceType);
2404
2486
  if (![...sectionEnds(document.package.document).map(({ properties: sectionProps }) => sectionProps), document.package.document.finalSectionProperties ?? {}].some((sectionProps, index) => index !== op.sectionIndex && (kind === "header" ? sectionProps.headerReferences : sectionProps.footerReferences)?.some(({ rId }) => rId === op.story.rId)) && !nextRefs.some(({ rId }) => rId === op.story.rId)) nextParts.delete(op.story.rId);
2405
2487
  }
@@ -2458,49 +2540,31 @@ const applyStoryLifecycle = (document, op) => {
2458
2540
  return storyLifecycleEdit(document, next, op);
2459
2541
  };
2460
2542
  //#endregion
2461
- //#region src/ops/edits.ts
2462
- const TOUCHED_STATES = [
2463
- "modified",
2464
- "inserted",
2465
- "removed"
2466
- ];
2467
- /** A block's net change after two changes in turn; `undefined` when it came and went. */
2468
- const TOUCH_TRANSITIONS = {
2469
- modified: {
2470
- modified: "modified",
2471
- inserted: "modified",
2472
- removed: "removed"
2473
- },
2474
- inserted: {
2475
- modified: "inserted",
2476
- inserted: "inserted",
2477
- removed: void 0
2478
- },
2479
- removed: {
2480
- modified: "modified",
2481
- inserted: "modified",
2482
- removed: "removed"
2483
- }
2484
- };
2485
- /** Edits made in turn, starting from `document`, as one edit. */
2486
- const combineEdits = (document, edits) => {
2487
- const touched = /* @__PURE__ */ new Map();
2488
- for (const edit of edits) for (const state of TOUCHED_STATES) for (const id of edit.touched[state]) {
2489
- const previous = touched.get(id);
2490
- const next = previous === void 0 ? state : TOUCH_TRANSITIONS[previous][state];
2491
- if (next === void 0) touched.delete(id);
2492
- else touched.set(id, next);
2543
+ //#region src/ops/gaps.ts
2544
+ const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
2545
+ const isLowSurrogate = (code) => code >= 56320 && code <= 57343;
2546
+ const resolveGap = ({ paragraph, position, fallback }) => {
2547
+ const text = paragraphLogicalText(paragraph);
2548
+ const { offset, zeroWidthBefore } = position;
2549
+ if (!Number.isInteger(offset) || offset < 0 || offset > text.length) return DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET;
2550
+ if (offset > 0 && offset < text.length && isHighSurrogate(text.charCodeAt(offset - 1)) && isLowSurrogate(text.charCodeAt(offset))) return DOCUMENT_OP_REFUSAL_REASONS.SPLITS_SURROGATE_PAIR;
2551
+ const available = zeroWidthLeavesAt(paragraph.content, offset).length;
2552
+ if (zeroWidthBefore !== void 0) return Number.isInteger(zeroWidthBefore) && zeroWidthBefore >= 0 && zeroWidthBefore <= available ? {
2553
+ offset,
2554
+ zeroWidthBefore
2555
+ } : DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET;
2556
+ switch (fallback) {
2557
+ case "afterAll": return {
2558
+ offset,
2559
+ zeroWidthBefore: available
2560
+ };
2561
+ case "beforeAll": return {
2562
+ offset,
2563
+ zeroWidthBefore: 0
2564
+ };
2565
+ case "insertion": return defaultInsertionGap(paragraph.content, offset);
2566
+ default: return fallback;
2493
2567
  }
2494
- const ids = (state) => [...touched].flatMap(([id, value]) => value === state ? [id] : []);
2495
- return {
2496
- document: edits.at(-1)?.document ?? document,
2497
- inverse: edits.toReversed().flatMap(({ inverse }) => inverse),
2498
- touched: {
2499
- modified: ids("modified"),
2500
- inserted: ids("inserted"),
2501
- removed: ids("removed")
2502
- }
2503
- };
2504
2568
  };
2505
2569
  //#endregion
2506
2570
  //#region src/ops/review.ts
@@ -2812,10 +2876,9 @@ const wrapList = (nodes, cursor, state) => {
2812
2876
  offset: gap.offset - start.position,
2813
2877
  zeroWidthBefore: gap.offset === start.position ? gap.zeroWidthBefore - start.zeroWidthSeen : gap.zeroWidthBefore
2814
2878
  });
2815
- const beforeChain = spanningRecords([node], [localGap(state.gaps[0])], 0, 1);
2816
2879
  const afterChain = spanningRecords([node], [localGap(state.gaps[1])], 0, 1);
2817
2880
  const retainedAfter = region === 1 && state.kind === WRAP_KINDS.DELETION ? afterChain.flatMap((record, depth) => {
2818
- const source = beforeChain.includes(record) ? [] : identitySlots(record);
2881
+ const source = identitySlots(record);
2819
2882
  return source.length === 0 ? [] : [{
2820
2883
  depth,
2821
2884
  source,
@@ -3536,6 +3599,51 @@ const insertBlocks = ({ document, op, applyOps }) => {
3536
3599
  }
3537
3600
  };
3538
3601
  //#endregion
3602
+ //#region src/ops/edits.ts
3603
+ const TOUCHED_STATES = [
3604
+ "modified",
3605
+ "inserted",
3606
+ "removed"
3607
+ ];
3608
+ /** A block's net change after two changes in turn; `undefined` when it came and went. */
3609
+ const TOUCH_TRANSITIONS = {
3610
+ modified: {
3611
+ modified: "modified",
3612
+ inserted: "modified",
3613
+ removed: "removed"
3614
+ },
3615
+ inserted: {
3616
+ modified: "inserted",
3617
+ inserted: "inserted",
3618
+ removed: void 0
3619
+ },
3620
+ removed: {
3621
+ modified: "modified",
3622
+ inserted: "modified",
3623
+ removed: "removed"
3624
+ }
3625
+ };
3626
+ /** Edits made in turn, starting from `document`, as one edit. */
3627
+ const combineEdits = (document, edits) => {
3628
+ const touched = /* @__PURE__ */ new Map();
3629
+ for (const edit of edits) for (const state of TOUCHED_STATES) for (const id of edit.touched[state]) {
3630
+ const previous = touched.get(id);
3631
+ const next = previous === void 0 ? state : TOUCH_TRANSITIONS[previous][state];
3632
+ if (next === void 0) touched.delete(id);
3633
+ else touched.set(id, next);
3634
+ }
3635
+ const ids = (state) => [...touched].flatMap(([id, value]) => value === state ? [id] : []);
3636
+ return {
3637
+ document: edits.at(-1)?.document ?? document,
3638
+ inverse: edits.toReversed().flatMap(({ inverse }) => inverse),
3639
+ touched: {
3640
+ modified: ids("modified"),
3641
+ inserted: ids("inserted"),
3642
+ removed: ids("removed")
3643
+ }
3644
+ };
3645
+ };
3646
+ //#endregion
3539
3647
  //#region src/ops/runMerge.ts
3540
3648
  /**
3541
3649
  * Check if two TextFormatting objects are equivalent
@@ -5614,6 +5722,7 @@ const resolveRevision = (document, op, applyOps) => {
5614
5722
  if (candidate?.type !== "paragraph") break;
5615
5723
  leadingCut = Math.max(leadingCut, resolvedCutEdges.get(idKey(candidate.paraId ?? ""))?.first ?? 0);
5616
5724
  if ((resolvedContents.get(idKey(candidate.paraId ?? ""))?.length ?? 0) !== 0 || candidate.pPrMark === void 0 || !markWasAdded(candidate.pPrMark.kind)) break;
5725
+ if (op.decision === REVISION_DECISIONS.REJECT && ids.has(candidate.pPrMark.info.id)) leadingCut = Math.max(leadingCut, candidate.pPrMark.resolutionJoin ?? 0);
5617
5726
  }
5618
5727
  let depth = Math.max(mark.resolutionJoin, resolvedCutEdges.get(idKey(paragraph.paraId ?? ""))?.last ?? 0, leadingCut);
5619
5728
  if (trailing !== void 0) depth = Math.min(depth, trailing);
@@ -5970,7 +6079,7 @@ const stampedTableRevisionIds = ({ blocks, stamp, known }) => {
5970
6079
  //#endregion
5971
6080
  //#region src/ops/tables.ts
5972
6081
  /** Whole-table edits and their exact structural inverse. */
5973
- const refuse$2 = ({ op, reason, message }) => Result.err(new DocumentOpRefusal({
6082
+ const refuse$4 = ({ op, reason, message }) => Result.err(new DocumentOpRefusal({
5974
6083
  opType: op.type,
5975
6084
  reason,
5976
6085
  message
@@ -6011,7 +6120,7 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
6011
6120
  removed: []
6012
6121
  }
6013
6122
  });
6014
- if (!blocks.some((block) => block.type === "paragraph" && idKey(block.paraId ?? "") === idKey(anchor.paragraph.paraId ?? ""))) return refuse$2({
6123
+ if (!blocks.some((block) => block.type === "paragraph" && idKey(block.paraId ?? "") === idKey(anchor.paragraph.paraId ?? ""))) return refuse$4({
6015
6124
  op,
6016
6125
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
6017
6126
  message: "The structural inverse requires a surviving paragraph in this block list."
@@ -6019,13 +6128,13 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
6019
6128
  if (blocks.length === 0 || !validStructure(before) || !validStructure(blocks) || endsItsContainer(body, {
6020
6129
  list: anchor.list,
6021
6130
  index: before.length - 1
6022
- }) && (!endsInParagraph(before) || !endsInParagraph(blocks))) return refuse$2({
6131
+ }) && (!endsInParagraph(before) || !endsInParagraph(blocks))) return refuse$4({
6023
6132
  op,
6024
6133
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
6025
6134
  message: "A table has rows and cells; each cell and the story retain a final paragraph."
6026
6135
  });
6027
6136
  const fixedBlocks = (items) => items.filter((block) => block.type !== "table" && block.type !== "paragraph");
6028
- if (!structurallyEqual(fixedBlocks(before), fixedBlocks(blocks))) return refuse$2({
6137
+ if (!structurallyEqual(fixedBlocks(before), fixedBlocks(blocks))) return refuse$4({
6029
6138
  op,
6030
6139
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
6031
6140
  message: "A table structural inverse preserves surrounding block wrappers and markers."
@@ -6037,17 +6146,17 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
6037
6146
  if ([...beforeParagraphs, ...afterParagraphs].some((paragraph) => {
6038
6147
  const id = idKey(paragraph.paraId ?? "");
6039
6148
  return !structurallyEqual(paragraph.sectionProperties, (beforeById.has(id) ? afterById : beforeById).get(id)?.sectionProperties);
6040
- })) return refuse$2({
6149
+ })) return refuse$4({
6041
6150
  op,
6042
6151
  reason: DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY,
6043
6152
  message: "Table edits preserve section boundaries."
6044
6153
  });
6045
- if ([...beforeParagraphs, ...afterParagraphs].some(({ paraId }) => paraId === void 0 || (!beforeById.has(idKey(paraId)) || !afterById.has(idKey(paraId))) && !isParaId(paraId))) return refuse$2({
6154
+ if ([...beforeParagraphs, ...afterParagraphs].some(({ paraId }) => paraId === void 0 || (!beforeById.has(idKey(paraId)) || !afterById.has(idKey(paraId))) && !isParaId(paraId))) return refuse$4({
6046
6155
  op,
6047
6156
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID,
6048
6157
  message: "An added or removed paragraph needs a usable id."
6049
6158
  });
6050
- if ([...beforeParagraphs, ...afterParagraphs].some(({ content }) => textsIn(content).some(hasIllegalXmlCharacters))) return refuse$2({
6159
+ if ([...beforeParagraphs, ...afterParagraphs].some(({ content }) => textsIn(content).some(hasIllegalXmlCharacters))) return refuse$4({
6051
6160
  op,
6052
6161
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT,
6053
6162
  message: "The table holds text that cannot be written to XML."
@@ -6058,7 +6167,7 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
6058
6167
  body,
6059
6168
  location,
6060
6169
  op
6061
- }) && !structurallyEqual(paragraph.pPrMark, afterById.get(idKey(paragraph.paraId ?? ""))?.pPrMark)) return refuse$2({
6170
+ }) && !structurallyEqual(paragraph.pPrMark, afterById.get(idKey(paragraph.paraId ?? ""))?.pPrMark)) return refuse$4({
6062
6171
  op,
6063
6172
  reason: DOCUMENT_OP_REFUSAL_REASONS.CONTAINER_FINAL_MARK,
6064
6173
  message: "Removing this final paragraph mark would make the structural inverse invalid."
@@ -6066,7 +6175,7 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
6066
6175
  }
6067
6176
  const remaining = countIds(packageParagraphIds(document.package));
6068
6177
  for (const id of paragraphIdsIn(before)) remaining.set(idKey(id), (remaining.get(idKey(id)) ?? 1) - 1);
6069
- if (collides(remaining, paragraphIdsIn(blocks))) return refuse$2({
6178
+ if (collides(remaining, paragraphIdsIn(blocks))) return refuse$4({
6070
6179
  op,
6071
6180
  reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
6072
6181
  message: "A paragraph id is already used in the package."
@@ -6074,7 +6183,7 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
6074
6183
  const records = countKeys(packageIdentityKeys(document.package));
6075
6184
  for (const key of identityKeysIn(before)) records.set(key, (records.get(key) ?? 1) - 1);
6076
6185
  const incoming = identityKeysIn(blocks);
6077
- if (incoming.some((key) => (records.get(key) ?? 0) > 0) || new Set(incoming).size !== incoming.length) return refuse$2({
6186
+ if (incoming.some((key) => (records.get(key) ?? 0) > 0) || new Set(incoming).size !== incoming.length) return refuse$4({
6078
6187
  op,
6079
6188
  reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
6080
6189
  message: "A revision or content-control id is already used in the package."
@@ -6132,14 +6241,14 @@ const commitBlocks = ({ document, op, anchor, blocks }) => {
6132
6241
  body: nextBody,
6133
6242
  location,
6134
6243
  op
6135
- }) && !structurallyEqual(paragraph.pPrMark, previousParagraphs.get(idKey(paragraph.paraId ?? ""))?.pPrMark)) return refuse$2({
6244
+ }) && !structurallyEqual(paragraph.pPrMark, previousParagraphs.get(idKey(paragraph.paraId ?? ""))?.pPrMark)) return refuse$4({
6136
6245
  op,
6137
6246
  reason: DOCUMENT_OP_REFUSAL_REASONS.CONTAINER_FINAL_MARK,
6138
6247
  message: "A table edit cannot add a final paragraph mark."
6139
6248
  });
6140
6249
  }
6141
6250
  const valid = validateOpsDocument(next);
6142
- if (valid.isErr()) return refuse$2({
6251
+ if (valid.isErr()) return refuse$4({
6143
6252
  op,
6144
6253
  reason: valid.error.reason,
6145
6254
  message: valid.error.message
@@ -6164,32 +6273,32 @@ const applyTableOp = (document, op) => {
6164
6273
  const body = storyBody(document, op.story);
6165
6274
  switch (op.type) {
6166
6275
  case DOCUMENT_OP_TYPES.INSERT_TABLE: {
6167
- if (op.at.type !== "before" && op.at.type !== "after") return refuse$2({
6276
+ if (op.at.type !== "before" && op.at.type !== "after") return refuse$4({
6168
6277
  op,
6169
6278
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
6170
6279
  message: "Insert before or after a paragraph."
6171
6280
  });
6172
6281
  const anchor = storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(op.at.blockId));
6173
- if (anchor === void 0) return refuse$2({
6282
+ if (anchor === void 0) return refuse$4({
6174
6283
  op,
6175
6284
  reason: DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND,
6176
6285
  message: "The table insertion anchor does not exist."
6177
6286
  });
6178
6287
  const blocks = [...blockListAt(body.content, anchor.list)];
6179
6288
  const terminal = op.at.type === "after" && endsItsContainer(body, anchor);
6180
- if (op.terminal !== void 0 && !terminal) return refuse$2({
6289
+ if (op.terminal !== void 0 && !terminal) return refuse$4({
6181
6290
  op,
6182
6291
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
6183
6292
  message: "A terminal insertion must follow its container's final paragraph."
6184
6293
  });
6185
- if (terminal && op.terminal === void 0) return refuse$2({
6294
+ if (terminal && op.terminal === void 0) return refuse$4({
6186
6295
  op,
6187
6296
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
6188
6297
  message: "A terminal table insertion supplies the preceding paragraph id."
6189
6298
  });
6190
6299
  let preceding;
6191
6300
  if (op.terminal !== void 0) {
6192
- if (op.revision !== void 0 && anchor.paragraph.pPrMark !== void 0) return refuse$2({
6301
+ if (op.revision !== void 0 && anchor.paragraph.pPrMark !== void 0) return refuse$4({
6193
6302
  op,
6194
6303
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
6195
6304
  message: "The final paragraph already carries a mark revision."
@@ -6211,7 +6320,7 @@ const applyTableOp = (document, op) => {
6211
6320
  anchor,
6212
6321
  blocks
6213
6322
  });
6214
- if (op.table.preserved !== void 0 || op.table.bookmarks !== void 0 || op.table.carrierStack !== void 0 || (op.table.propertyChanges?.length ?? 0) > 0) return refuse$2({
6323
+ if (op.table.preserved !== void 0 || op.table.bookmarks !== void 0 || op.table.carrierStack !== void 0 || (op.table.propertyChanges?.length ?? 0) > 0) return refuse$4({
6215
6324
  op,
6216
6325
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
6217
6326
  message: "Tracked table construction does not support captured markup or table property revisions."
@@ -6255,12 +6364,12 @@ const applyTableOp = (document, op) => {
6255
6364
  usedElsewhere: () => outside
6256
6365
  });
6257
6366
  switch (fresh.kind) {
6258
- case "needsIds": return refuse$2({
6367
+ case "needsIds": return refuse$4({
6259
6368
  op,
6260
6369
  reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
6261
6370
  message: "The preceding table break needs an additional revision id."
6262
6371
  });
6263
- case "invalidId": return refuse$2({
6372
+ case "invalidId": return refuse$4({
6264
6373
  op,
6265
6374
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
6266
6375
  message: "The preceding table break has an invalid revision id."
@@ -6285,13 +6394,13 @@ const applyTableOp = (document, op) => {
6285
6394
  const located = locateTableRow(document, op);
6286
6395
  if (located.isErr()) return Result.err(located.error);
6287
6396
  const location = located.value;
6288
- if (op.expected !== void 0 && !equalForStaleness(location.table, op.expected)) return refuse$2({
6397
+ if (op.expected !== void 0 && !equalForStaleness(location.table, op.expected)) return refuse$4({
6289
6398
  op,
6290
6399
  reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
6291
6400
  message: "The table to remove has changed."
6292
6401
  });
6293
6402
  const anchor = storyParagraphs(body).find((paragraph) => sameBlockList(paragraph.list, location.list));
6294
- if (anchor === void 0) return refuse$2({
6403
+ if (anchor === void 0) return refuse$4({
6295
6404
  op,
6296
6405
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
6297
6406
  message: "Removing a table requires a surviving paragraph in its block list."
@@ -6299,7 +6408,7 @@ const applyTableOp = (document, op) => {
6299
6408
  const blocks = [...blockListAt(body.content, location.list)];
6300
6409
  if (op.revision === void 0) blocks.splice(location.index, 1);
6301
6410
  else {
6302
- if (location.table.preserved !== void 0 || location.table.bookmarks !== void 0 || location.table.carrierStack !== void 0 || (location.table.propertyChanges?.length ?? 0) > 0) return refuse$2({
6411
+ if (location.table.preserved !== void 0 || location.table.bookmarks !== void 0 || location.table.carrierStack !== void 0 || (location.table.propertyChanges?.length ?? 0) > 0) return refuse$4({
6303
6412
  op,
6304
6413
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
6305
6414
  message: "Tracked table deletion does not support captured markup or table property revisions."
@@ -6327,12 +6436,12 @@ const applyTableOp = (document, op) => {
6327
6436
  }
6328
6437
  case DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS: {
6329
6438
  const anchor = storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(op.blockId));
6330
- if (anchor === void 0) return refuse$2({
6439
+ if (anchor === void 0) return refuse$4({
6331
6440
  op,
6332
6441
  reason: DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND,
6333
6442
  message: "The structural inverse anchor does not exist."
6334
6443
  });
6335
- if (!equalForStaleness(blockListAt(body.content, anchor.list), op.expected)) return refuse$2({
6444
+ if (!equalForStaleness(blockListAt(body.content, anchor.list), op.expected)) return refuse$4({
6336
6445
  op,
6337
6446
  reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
6338
6447
  message: "The container blocks have changed."
@@ -6584,6 +6693,297 @@ const applyRowOp = (document, op) => {
6584
6693
  }
6585
6694
  };
6586
6695
  //#endregion
6696
+ //#region src/ops/packageResources.ts
6697
+ const partOf = (present, value) => {
6698
+ if (!present) return { type: "omitted" };
6699
+ return value === void 0 ? { type: "undefined" } : {
6700
+ type: "present",
6701
+ value: cloneModel(value)
6702
+ };
6703
+ };
6704
+ /** Capture style and numbering definitions as ordinary JSON data, preserving field presence. */
6705
+ const packageResourcesOf = ({ package: pkg }) => ({
6706
+ styles: partOf(Object.hasOwn(pkg, "styles"), pkg.styles),
6707
+ numbering: partOf(Object.hasOwn(pkg, "numbering"), pkg.numbering)
6708
+ });
6709
+ const valueOf = (part) => {
6710
+ switch (part.type) {
6711
+ case "omitted":
6712
+ case "undefined": return;
6713
+ case "present": return part.value;
6714
+ default: return part;
6715
+ }
6716
+ };
6717
+ /** Binary media travels as a byte array, rather than an ArrayBuffer that JSON discards. */
6718
+ const mediaRecordOf = (media) => Object.assign({}, media, { data: [...new Uint8Array(media.data)] });
6719
+ const mediaFileOf = (record) => Object.assign({}, record, { data: new Uint8Array(record.data).buffer });
6720
+ const presenceOf = (present, map) => {
6721
+ if (!present) return "omitted";
6722
+ return map === void 0 ? "undefined" : "present";
6723
+ };
6724
+ const packageMapOf = (present, map) => ({
6725
+ presence: presenceOf(present, map),
6726
+ entries: map ?? /* @__PURE__ */ new Map()
6727
+ });
6728
+ const relationshipsOf = ({ package: pkg }) => packageMapOf(Object.hasOwn(pkg, "relationships"), pkg.relationships);
6729
+ const mediaOf = ({ package: pkg }) => packageMapOf(Object.hasOwn(pkg, "media"), pkg.media);
6730
+ const entryOf = (stored, record) => stored === void 0 ? { type: "absent" } : {
6731
+ type: "present",
6732
+ value: record(stored)
6733
+ };
6734
+ const mapChangeOf = ({ before, after, record }) => {
6735
+ const entries = [];
6736
+ for (const key of /* @__PURE__ */ new Set([...before.entries.keys(), ...after.entries.keys()])) {
6737
+ const previous = before.entries.get(key);
6738
+ const next = after.entries.get(key);
6739
+ if (previous === next) continue;
6740
+ const change = {
6741
+ key,
6742
+ expected: entryOf(previous, record),
6743
+ next: entryOf(next, record)
6744
+ };
6745
+ if (!structurallyEqual(change.expected, change.next)) entries.push(change);
6746
+ }
6747
+ return {
6748
+ expected: before.presence,
6749
+ next: after.presence,
6750
+ entries
6751
+ };
6752
+ };
6753
+ /** Describe the package resource difference as one operation carrying only changed entries. */
6754
+ const packageResourcesOpOf = ({ before, after }) => ({
6755
+ type: DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES,
6756
+ expected: packageResourcesOf(before),
6757
+ resources: packageResourcesOf(after),
6758
+ relationships: mapChangeOf({
6759
+ before: relationshipsOf(before),
6760
+ after: relationshipsOf(after),
6761
+ record: (relationship) => cloneModel(relationship)
6762
+ }),
6763
+ media: mapChangeOf({
6764
+ before: mediaOf(before),
6765
+ after: mediaOf(after),
6766
+ record: mediaRecordOf
6767
+ })
6768
+ });
6769
+ const applyMapChange = ({ current, change, record, stored }) => {
6770
+ if (current.presence !== change.expected) return {
6771
+ type: "refused",
6772
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
6773
+ message: "The package resources changed."
6774
+ };
6775
+ if (duplicates(change.entries.map(({ key }) => key))) return {
6776
+ type: "refused",
6777
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
6778
+ message: "Package resource changes repeat a key."
6779
+ };
6780
+ const entries = new Map(current.entries);
6781
+ for (const { key, expected, next } of change.entries) {
6782
+ if (!structurallyEqual(entryOf(current.entries.get(key), record), expected)) return {
6783
+ type: "refused",
6784
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
6785
+ message: "The package resources changed."
6786
+ };
6787
+ if (next.type === "present") entries.set(key, stored(next.value));
6788
+ else entries.delete(key);
6789
+ }
6790
+ if (change.next !== "present" && entries.size > 0) return {
6791
+ type: "refused",
6792
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
6793
+ message: "A removed package map still has entries."
6794
+ };
6795
+ return {
6796
+ type: "applied",
6797
+ map: {
6798
+ presence: change.next,
6799
+ entries
6800
+ }
6801
+ };
6802
+ };
6803
+ const inverseMapChange = (change) => ({
6804
+ expected: change.next,
6805
+ next: change.expected,
6806
+ entries: change.entries.map(({ key, expected, next }) => ({
6807
+ key,
6808
+ expected: next,
6809
+ next: expected
6810
+ }))
6811
+ });
6812
+ const presentEntries = (change) => change.entries.flatMap(({ key, next }) => next.type === "present" ? [[key, next.value]] : []);
6813
+ const duplicates = (ids) => new Set(ids).size !== ids.length;
6814
+ /** Validate the definitions and entries this operation adds or changes. */
6815
+ const resourceViolation = ({ op: { resources, relationships: relationshipChange, media: mediaChange }, expected, relationships, media }) => {
6816
+ const styles = valueOf(resources.styles);
6817
+ if (styles !== void 0 && duplicates(styles.styles.map(({ styleId }) => styleId))) return "Imported styles contain duplicate ids.";
6818
+ const numbering = valueOf(resources.numbering);
6819
+ if (numbering !== void 0) {
6820
+ const abstracts = numbering.abstractNums.map(({ abstractNumId }) => abstractNumId);
6821
+ const nums = numbering.nums.map(({ numId }) => numId);
6822
+ if (duplicates(abstracts) || duplicates(nums) || abstracts.some((id) => !Number.isSafeInteger(id) || id < 0 || id > 2147483647) || nums.some((id) => !Number.isSafeInteger(id) || id <= 0 || id > 2147483647)) return "Imported numbering contains invalid or duplicate ids.";
6823
+ if (numbering.nums.some(({ abstractNumId }) => !abstracts.includes(abstractNumId))) return "An imported numbering instance has no abstract definition.";
6824
+ }
6825
+ const changedRelationships = presentEntries(relationshipChange);
6826
+ if (changedRelationships.some(([key, relationship]) => key.length === 0 || key !== relationship.id)) return "Imported relationships contain invalid ids.";
6827
+ if (presentEntries(mediaChange).some(([key, file]) => key !== file.path || !key.startsWith("word/media/") || key.split("/").includes("..") || file.data.some((byte) => !Number.isInteger(byte) || byte < 0 || byte > 255))) return "Imported media contains invalid paths or bytes.";
6828
+ for (const [, relationship] of changedRelationships) {
6829
+ if (!relationship.type.endsWith("/image") || relationship.targetMode === "External") continue;
6830
+ const target = relationship.target.startsWith("/") ? relationship.target.slice(1) : `word/${relationship.target}`;
6831
+ if (!media.has(target)) return "An imported image relationship has no media part.";
6832
+ }
6833
+ const available = {
6834
+ style: new Set(styles?.styles.map(({ styleId }) => styleId) ?? []),
6835
+ numbering: new Set(numbering?.nums.map(({ numId }) => numId) ?? []),
6836
+ relationship: new Set(relationships.keys())
6837
+ };
6838
+ const unavailable = (kind, id) => !available[kind].has(id);
6839
+ const previousStyles = new Map(valueOf(expected.styles)?.styles.map((style) => [style.styleId, style]));
6840
+ for (const style of styles?.styles ?? []) {
6841
+ if (structurallyEqual(style, previousStyles.get(style.styleId))) continue;
6842
+ if (resourceReferencesMatch({
6843
+ value: style,
6844
+ matches: unavailable,
6845
+ relationshipScope: "main"
6846
+ })) return "An imported style references an unavailable package resource.";
6847
+ }
6848
+ const previousAbstracts = new Map(valueOf(expected.numbering)?.abstractNums.map((abstract) => [abstract.abstractNumId, abstract]));
6849
+ for (const abstract of numbering?.abstractNums ?? []) {
6850
+ if (structurallyEqual(abstract, previousAbstracts.get(abstract.abstractNumId))) continue;
6851
+ if (resourceReferencesMatch({
6852
+ value: abstract,
6853
+ matches: unavailable,
6854
+ relationshipScope: "main"
6855
+ })) return "An imported numbering definition references an unavailable style.";
6856
+ }
6857
+ const previousNums = new Map(valueOf(expected.numbering)?.nums.map((num) => [num.numId, num]));
6858
+ for (const num of numbering?.nums ?? []) {
6859
+ if (structurallyEqual(num, previousNums.get(num.numId))) continue;
6860
+ if (resourceReferencesMatch({
6861
+ value: num,
6862
+ matches: unavailable,
6863
+ relationshipScope: "main"
6864
+ })) return "An imported numbering instance references an unavailable style.";
6865
+ }
6866
+ };
6867
+ const referenceKinds = new Map(Object.entries({
6868
+ styleId: "style",
6869
+ basedOn: "style",
6870
+ next: "style",
6871
+ link: "style",
6872
+ pStyle: "style",
6873
+ numStyleLink: "style",
6874
+ styleLink: "style",
6875
+ numId: "numbering",
6876
+ rId: "relationship",
6877
+ hlinkRId: "relationship",
6878
+ imageRId: "relationship"
6879
+ }));
6880
+ const resourceReferencesMatch = ({ value, matches, relationshipScope }) => {
6881
+ if (typeof value !== "object" || value === null) return false;
6882
+ if (value instanceof Map) return [...value.values()].some((item) => resourceReferencesMatch({
6883
+ value: item,
6884
+ matches,
6885
+ relationshipScope
6886
+ }));
6887
+ if (Array.isArray(value)) return value.some((item) => resourceReferencesMatch({
6888
+ value: item,
6889
+ matches,
6890
+ relationshipScope
6891
+ }));
6892
+ return Object.entries(value).some(([key, item]) => {
6893
+ if (key === "listRendering") return false;
6894
+ const kind = referenceKinds.get(key);
6895
+ if (kind !== void 0 && (kind !== "relationship" || relationshipScope === "main") && (typeof item === "string" || typeof item === "number") && matches(kind, item)) return true;
6896
+ return resourceReferencesMatch({
6897
+ value: item,
6898
+ matches,
6899
+ relationshipScope: key === "headers" || key === "footers" ? "part" : relationshipScope
6900
+ });
6901
+ });
6902
+ };
6903
+ const missingIds = (before, after) => {
6904
+ const kept = new Set(after);
6905
+ return new Set(before.filter((id) => !kept.has(id)));
6906
+ };
6907
+ const applyPackageResourcesOp = (document, op) => {
6908
+ const expected = packageResourcesOf(document);
6909
+ const failed = (reason, message) => Result.err(new DocumentOpRefusal({
6910
+ reason,
6911
+ message,
6912
+ opType: op.type
6913
+ }));
6914
+ if (!structurallyEqual(expected, op.expected)) return failed(DOCUMENT_OP_REFUSAL_REASONS.STALE, "The package resources changed.");
6915
+ const owned = cloneModel(op);
6916
+ const relationships = applyMapChange({
6917
+ current: relationshipsOf(document),
6918
+ change: owned.relationships,
6919
+ record: (relationship) => cloneModel(relationship),
6920
+ stored: (relationship) => cloneModel(relationship)
6921
+ });
6922
+ if (relationships.type === "refused") return failed(relationships.reason, relationships.message);
6923
+ const media = applyMapChange({
6924
+ current: mediaOf(document),
6925
+ change: owned.media,
6926
+ record: mediaRecordOf,
6927
+ stored: mediaFileOf
6928
+ });
6929
+ if (media.type === "refused") return failed(media.reason, media.message);
6930
+ const violation = resourceViolation({
6931
+ op: owned,
6932
+ expected,
6933
+ relationships: relationships.map.entries,
6934
+ media: media.map.entries
6935
+ });
6936
+ if (violation !== void 0) return failed(DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, violation);
6937
+ const { resources } = owned;
6938
+ const pkg = { ...document.package };
6939
+ delete pkg.styles;
6940
+ delete pkg.numbering;
6941
+ delete pkg.relationships;
6942
+ delete pkg.media;
6943
+ if (resources.styles.type !== "omitted") pkg.styles = valueOf(resources.styles);
6944
+ if (resources.numbering.type !== "omitted") pkg.numbering = valueOf(resources.numbering);
6945
+ if (relationships.map.presence !== "omitted") pkg.relationships = relationships.map.presence === "present" ? new Map(relationships.map.entries) : void 0;
6946
+ if (media.map.presence !== "omitted") pkg.media = media.map.presence === "present" ? new Map(media.map.entries) : void 0;
6947
+ const removed = {
6948
+ style: missingIds(document.package.styles?.styles.map(({ styleId }) => styleId) ?? [], pkg.styles?.styles.map(({ styleId }) => styleId) ?? []),
6949
+ numbering: missingIds(document.package.numbering?.nums.map(({ numId }) => numId) ?? [], pkg.numbering?.nums.map(({ numId }) => numId) ?? []),
6950
+ relationship: missingIds([...document.package.relationships?.keys() ?? []], [...pkg.relationships?.keys() ?? []])
6951
+ };
6952
+ if (resourceReferencesMatch({
6953
+ value: pkg,
6954
+ matches: (kind, id) => removed[kind].has(id),
6955
+ relationshipScope: "main"
6956
+ })) return failed(DOCUMENT_OP_REFUSAL_REASONS.STALE, "A removed package resource is still referenced.");
6957
+ if (structurallyEqual(expected, resources) && owned.relationships.expected === owned.relationships.next && owned.relationships.entries.length === 0 && owned.media.expected === owned.media.next && owned.media.entries.length === 0) return Result.ok({
6958
+ document,
6959
+ inverse: [],
6960
+ touched: {
6961
+ modified: [],
6962
+ inserted: [],
6963
+ removed: []
6964
+ }
6965
+ });
6966
+ const updated = {
6967
+ ...document,
6968
+ package: pkg
6969
+ };
6970
+ return Result.ok({
6971
+ document: updated,
6972
+ inverse: [{
6973
+ type: DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES,
6974
+ expected: packageResourcesOf(updated),
6975
+ resources: expected,
6976
+ relationships: inverseMapChange(owned.relationships),
6977
+ media: inverseMapChange(owned.media)
6978
+ }],
6979
+ touched: {
6980
+ modified: [],
6981
+ inserted: [],
6982
+ removed: []
6983
+ }
6984
+ });
6985
+ };
6986
+ //#endregion
6587
6987
  //#region src/ops/numberingSections.ts
6588
6988
  const failed = (op, reason, message) => Result.err(new DocumentOpRefusal({
6589
6989
  message,
@@ -6880,12 +7280,12 @@ const CELL_VERTICAL_MERGES = {
6880
7280
  RESTART: "restart",
6881
7281
  CONTINUE: "continue"
6882
7282
  };
6883
- const refuse$1 = ({ op, reason, message }) => Result.err(new DocumentOpRefusal({
7283
+ const refuse$3 = ({ op, reason, message }) => Result.err(new DocumentOpRefusal({
6884
7284
  opType: op.type,
6885
7285
  reason,
6886
7286
  message
6887
7287
  }));
6888
- const mismatch = (op, message) => refuse$1({
7288
+ const mismatch = (op, message) => refuse$3({
6889
7289
  op,
6890
7290
  reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
6891
7291
  message
@@ -6903,19 +7303,19 @@ const authored = (formatting) => {
6903
7303
  return next;
6904
7304
  };
6905
7305
  const freshCells = ({ document, op, ids, count }) => {
6906
- if (ids.length !== count) return refuse$1({
7306
+ if (ids.length !== count) return refuse$3({
6907
7307
  op,
6908
7308
  reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
6909
7309
  message: `This edit requires ${count} fresh paragraph ids.`
6910
7310
  });
6911
- if (ids.some((id) => !isParaId(id))) return refuse$1({
7311
+ if (ids.some((id) => !isParaId(id))) return refuse$3({
6912
7312
  op,
6913
7313
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID,
6914
7314
  message: "New table paragraphs need usable paragraph ids."
6915
7315
  });
6916
7316
  const occupied = new Set(packageParagraphIds(document.package).map(idKey));
6917
7317
  for (const id of ids) {
6918
- if (occupied.has(idKey(id))) return refuse$1({
7318
+ if (occupied.has(idKey(id))) return refuse$3({
6919
7319
  op,
6920
7320
  reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
6921
7321
  message: "A new table paragraph id is already in use."
@@ -6942,7 +7342,7 @@ const commitTable = ({ document, op, location, table }) => {
6942
7342
  const afterIds = paragraphIdsIn(table);
6943
7343
  const old = new Set(beforeIds.map(idKey));
6944
7344
  const nextIds = new Set(afterIds.map(idKey));
6945
- if (afterIds.some((id) => !old.has(idKey(id)) && !isParaId(id))) return refuse$1({
7345
+ if (afterIds.some((id) => !old.has(idKey(id)) && !isParaId(id))) return refuse$3({
6946
7346
  op,
6947
7347
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID,
6948
7348
  message: "An added table paragraph has an invalid id."
@@ -6961,7 +7361,7 @@ const commitTable = ({ document, op, location, table }) => {
6961
7361
  }
6962
7362
  };
6963
7363
  const valid = validateOpsDocument(next);
6964
- if (valid.isErr()) return refuse$1({
7364
+ if (valid.isErr()) return refuse$3({
6965
7365
  op,
6966
7366
  reason: valid.error.reason,
6967
7367
  message: valid.error.message
@@ -7037,17 +7437,17 @@ const stampsFor = (op, count) => {
7037
7437
  const revision = op.revision;
7038
7438
  if (revision === void 0) return Result.ok([]);
7039
7439
  const ids = [revision.id, ...op.newIds?.revision ?? []];
7040
- if (new Set(ids).size !== ids.length) return refuse$1({
7440
+ if (new Set(ids).size !== ids.length) return refuse$3({
7041
7441
  op,
7042
7442
  reason: DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION,
7043
7443
  message: "Revision ids must be distinct within the operation."
7044
7444
  });
7045
- if (ids.slice(0, count).some((id) => !Number.isInteger(id) || id < 0 || id > 2147483647)) return refuse$1({
7445
+ if (ids.slice(0, count).some((id) => !Number.isInteger(id) || id < 0 || id > 2147483647)) return refuse$3({
7046
7446
  op,
7047
7447
  reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
7048
7448
  message: "Revision ids must be nonnegative 31-bit integers."
7049
7449
  });
7050
- if (ids.length < count) return refuse$1({
7450
+ if (ids.length < count) return refuse$3({
7051
7451
  op,
7052
7452
  reason: DOCUMENT_OP_REFUSAL_REASONS.NEEDS_NEW_IDS,
7053
7453
  message: `This table change needs ${count} distinct revision ids.`
@@ -7059,12 +7459,12 @@ const columnEdit = ({ document, op, table, grid }) => {
7059
7459
  if (!Number.isSafeInteger(op.column) || op.column < 0 || op.column >= grid.width + (insert ? 1 : 0)) return mismatch(op, "Column is outside the logical grid.");
7060
7460
  if (!insert && grid.width === 1) return mismatch(op, "Deleting the final column requires deleting the table.");
7061
7461
  if (insert && (!Number.isSafeInteger(op.width) || op.width <= 0)) return mismatch(op, "A column width must be a positive twip count.");
7062
- if (hasStructuralMarkup(table)) return refuse$1({
7462
+ if (hasStructuralMarkup(table)) return refuse$3({
7063
7463
  op,
7064
7464
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
7065
7465
  message: "Indexed table markup must be relocated before changing columns."
7066
7466
  });
7067
- if (hasReview(table)) return refuse$1({
7467
+ if (hasReview(table)) return refuse$3({
7068
7468
  op,
7069
7469
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
7070
7470
  message: "Resolve table reviews before changing its columns."
@@ -7081,7 +7481,7 @@ const columnEdit = ({ document, op, table, grid }) => {
7081
7481
  count: boundaryRows
7082
7482
  }) : Result.ok([]);
7083
7483
  if (fresh.isErr()) return Result.err(fresh.error);
7084
- if (op.revision !== void 0 && table.columnWidths === void 0) return refuse$1({
7484
+ if (op.revision !== void 0 && table.columnWidths === void 0) return refuse$3({
7085
7485
  op,
7086
7486
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
7087
7487
  message: "Tracked column edits require an explicit previous grid."
@@ -7147,7 +7547,7 @@ const columnEdit = ({ document, op, table, grid }) => {
7147
7547
  continue;
7148
7548
  }
7149
7549
  if (!insert && hit) {
7150
- if (entry.end - entry.start === 1 && hasTableCellDependencies(entry.cell)) return refuse$1({
7550
+ if (entry.end - entry.start === 1 && hasTableCellDependencies(entry.cell)) return refuse$3({
7151
7551
  op,
7152
7552
  reason: DOCUMENT_OP_REFUSAL_REASONS.DEPENDENT_RECORDS,
7153
7553
  message: "Resolve dependent anchors and review records before removing this cell."
@@ -7187,7 +7587,7 @@ const columnEdit = ({ document, op, table, grid }) => {
7187
7587
  }
7188
7588
  });
7189
7589
  }
7190
- if (!cells.some((cell) => cell.structuralChange?.type !== "tableCellDeletion")) return refuse$1({
7590
+ if (!cells.some((cell) => cell.structuralChange?.type !== "tableCellDeletion")) return refuse$3({
7191
7591
  op,
7192
7592
  reason: DOCUMENT_OP_REFUSAL_REASONS.TABLE_ROW_EMPTY,
7193
7593
  message: "Deleting this column would leave a row without an active cell."
@@ -7240,12 +7640,12 @@ const mergeSelection = ({ table, grid, op }) => {
7240
7640
  });
7241
7641
  };
7242
7642
  const merge = ({ document, op, table, grid }) => {
7243
- if (hasStructuralMarkup(table)) return refuse$1({
7643
+ if (hasStructuralMarkup(table)) return refuse$3({
7244
7644
  op,
7245
7645
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
7246
7646
  message: "Indexed table markup must be relocated before changing cells."
7247
7647
  });
7248
- if (hasReview(table)) return refuse$1({
7648
+ if (hasReview(table)) return refuse$3({
7249
7649
  op,
7250
7650
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
7251
7651
  message: "Resolve table reviews before changing cells."
@@ -7302,7 +7702,7 @@ const merge = ({ document, op, table, grid }) => {
7302
7702
  rows
7303
7703
  });
7304
7704
  }
7305
- if (op.revision !== void 0) return refuse$1({
7705
+ if (op.revision !== void 0) return refuse$3({
7306
7706
  op,
7307
7707
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
7308
7708
  message: "Cell merge markup cannot record horizontal content relocation; tracked moves are required."
@@ -7355,12 +7755,12 @@ const split = ({ document, op, table, grid, location }) => {
7355
7755
  const target = grid.rows[location.rowIndex]?.find((entry) => entry.index === location.cellIndex);
7356
7756
  if (!target) return mismatch(op, "The addressed cell is absent.");
7357
7757
  if (target.row !== target.ownerRow || target.index !== target.ownerIndex) return mismatch(op, "A vertical merge continuation must be addressed through its owner cell.");
7358
- if (hasStructuralMarkup(table)) return refuse$1({
7758
+ if (hasStructuralMarkup(table)) return refuse$3({
7359
7759
  op,
7360
7760
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
7361
7761
  message: "Indexed table markup must be relocated before changing cells."
7362
7762
  });
7363
- if (hasReview(table)) return refuse$1({
7763
+ if (hasReview(table)) return refuse$3({
7364
7764
  op,
7365
7765
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
7366
7766
  message: "Resolve table reviews before changing cells."
@@ -7368,7 +7768,7 @@ const split = ({ document, op, table, grid, location }) => {
7368
7768
  const group = grid.rows.flatMap((row) => row.filter((cell) => cell.ownerRow === target.ownerRow && cell.ownerIndex === target.ownerIndex));
7369
7769
  if (group.length > 1) return mismatch(op, "Splitting a cell inside a vertical merge is unsupported.");
7370
7770
  const span = target.end - target.start;
7371
- if (span === 1) return refuse$1({
7771
+ if (span === 1) return refuse$3({
7372
7772
  op,
7373
7773
  reason: DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE,
7374
7774
  message: "A one-cell, one-column split would not change the table."
@@ -7467,7 +7867,7 @@ const tableEditParagraphDemand = (location, op) => {
7467
7867
  const group = grid.value.rows.flatMap((row) => row.filter((cell) => cell.ownerRow === target.ownerRow && cell.ownerIndex === target.ownerIndex));
7468
7868
  if (group.length > 1) return mismatch(op, "Splitting a cell inside a vertical merge is unsupported.");
7469
7869
  const span = target.end - target.start;
7470
- if (span === 1) return refuse$1({
7870
+ if (span === 1) return refuse$3({
7471
7871
  op,
7472
7872
  reason: DOCUMENT_OP_REFUSAL_REASONS.NO_CHANGE,
7473
7873
  message: "A one-cell, one-column split would not change the table."
@@ -7485,7 +7885,7 @@ const applyTableEdit = (document, op) => {
7485
7885
  const location = located.value;
7486
7886
  const table = location.table;
7487
7887
  if (op.type === DOCUMENT_OP_TYPES.SET_TABLE) {
7488
- if (!equalForStaleness(table, op.expected)) return refuse$1({
7888
+ if (!equalForStaleness(table, op.expected)) return refuse$3({
7489
7889
  op,
7490
7890
  reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
7491
7891
  message: "The table changed since this inverse was recorded."
@@ -7503,7 +7903,7 @@ const applyTableEdit = (document, op) => {
7503
7903
  "propertyChanges",
7504
7904
  "structuralChange"
7505
7905
  ].some((key) => Object.hasOwn(record, key) && Reflect.get(record, key) === void 0);
7506
- if (ambiguous(table) || table.rows.some((row) => ambiguous(row) || row.cells.some(ambiguous))) return refuse$1({
7906
+ if (ambiguous(table) || table.rows.some((row) => ambiguous(row) || row.cells.some(ambiguous))) return refuse$3({
7507
7907
  op,
7508
7908
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
7509
7909
  message: "Explicit undefined review fields have no persisted OOXML property snapshot."
@@ -7512,7 +7912,7 @@ const applyTableEdit = (document, op) => {
7512
7912
  const grid = tableGrid(table, op.type);
7513
7913
  if (grid.isErr()) return Result.err(grid.error);
7514
7914
  if (op.type === DOCUMENT_OP_TYPES.DELETE_COLUMN && op.column === 0 && grid.value.width === 1) {
7515
- if (table.rows.some((row) => row.cells.some(hasTableCellDependencies))) return refuse$1({
7915
+ if (table.rows.some((row) => row.cells.some(hasTableCellDependencies))) return refuse$3({
7516
7916
  op,
7517
7917
  reason: DOCUMENT_OP_REFUSAL_REASONS.DEPENDENT_RECORDS,
7518
7918
  message: "Resolve dependent anchors and review records before removing the table."
@@ -7559,17 +7959,17 @@ const applyTableEdit = (document, op) => {
7559
7959
  break;
7560
7960
  case DOCUMENT_OP_TYPES.SET_TABLE_GRID: {
7561
7961
  if (op.columnWidths.length !== grid.value.width || op.columnWidths.some((width) => !Number.isSafeInteger(width) || width <= 0)) return mismatch(op, "Column widths must match the grid and be positive twip counts.");
7562
- if (table.formatting?.gridChange !== void 0) return refuse$1({
7962
+ if (table.formatting?.gridChange !== void 0) return refuse$3({
7563
7963
  op,
7564
7964
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
7565
7965
  message: "Resolve the existing grid revision before resizing."
7566
7966
  });
7567
- if (op.revision !== void 0 && table.columnWidths === void 0) return refuse$1({
7967
+ if (op.revision !== void 0 && table.columnWidths === void 0) return refuse$3({
7568
7968
  op,
7569
7969
  reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
7570
7970
  message: "A grid revision requires an explicit previous grid."
7571
7971
  });
7572
- if (table.propertyChanges !== void 0) return refuse$1({
7972
+ if (table.propertyChanges !== void 0) return refuse$3({
7573
7973
  op,
7574
7974
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
7575
7975
  message: "Resolve the table property history before resizing its grid."
@@ -7606,7 +8006,7 @@ const applyTableEdit = (document, op) => {
7606
8006
  "gridChange",
7607
8007
  "preserved"
7608
8008
  ].includes(key))) return mismatch(op, "Grid and source provenance require a grid operation.");
7609
- if (table.propertyChanges !== void 0) return refuse$1({
8009
+ if (table.propertyChanges !== void 0) return refuse$3({
7610
8010
  op,
7611
8011
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
7612
8012
  message: "Resolve the existing table property revision."
@@ -7641,7 +8041,7 @@ const applyTableEdit = (document, op) => {
7641
8041
  ].includes(key))) return mismatch(op, "Omitted grid slots require a topology operation.");
7642
8042
  const row = table.rows[location.rowIndex];
7643
8043
  if (!row) return mismatch(op, "The addressed row is absent.");
7644
- if (row.propertyChanges !== void 0) return refuse$1({
8044
+ if (row.propertyChanges !== void 0) return refuse$3({
7645
8045
  op,
7646
8046
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
7647
8047
  message: "Resolve the existing row property revision."
@@ -7682,7 +8082,7 @@ const applyTableEdit = (document, op) => {
7682
8082
  const row = table.rows[location.rowIndex];
7683
8083
  const cell = row?.cells[location.cellIndex];
7684
8084
  if (!row || !cell) return mismatch(op, "The addressed cell is absent.");
7685
- if (cell.propertyChanges !== void 0) return refuse$1({
8085
+ if (cell.propertyChanges !== void 0) return refuse$3({
7686
8086
  op,
7687
8087
  reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
7688
8088
  message: "Resolve the existing cell property revision."
@@ -7798,7 +8198,7 @@ const refusal$1 = (op, reason, message) => new DocumentOpRefusal({
7798
8198
  reason,
7799
8199
  opType: op?.type
7800
8200
  });
7801
- const refuse = (op, reason, message) => Result.err(refusal$1(op, reason, message));
8201
+ const refuse$2 = (op, reason, message) => Result.err(refusal$1(op, reason, message));
7802
8202
  /**
7803
8203
  * Whether a tracked operation's stamp can name the first record it creates:
7804
8204
  * a revision id in range that no record in the package carries.
@@ -7831,8 +8231,6 @@ const reviewRestoring = (story, result, original) => ({
7831
8231
  });
7832
8232
  /** Characters `insertText` does not carry: each is an inline atom of its own. */
7833
8233
  const NON_TEXT_CHARACTER_PATTERN = /[\t\n\r]/u;
7834
- const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
7835
- const isLowSurrogate = (code) => code >= 56320 && code <= 57343;
7836
8234
  /** The paragraph carrying an id, compared as hex; the contract makes it unique. */
7837
8235
  const findParagraph = (op, paragraphs, blockId) => {
7838
8236
  const key = idKey(blockId);
@@ -7840,30 +8238,6 @@ const findParagraph = (op, paragraphs, blockId) => {
7840
8238
  return match === void 0 ? Result.err(refusal$1(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, `No paragraph is ${blockId}.`)) : Result.ok(match);
7841
8239
  };
7842
8240
  const locate = (document, op, story, blockId) => findParagraph(op, storyParagraphs(storyBody(document, story)), blockId);
7843
- /** The gap a position names, or why it names none in this paragraph. */
7844
- const resolveGap = (paragraph, position, fallback) => {
7845
- const text = paragraphLogicalText(paragraph);
7846
- const { offset, zeroWidthBefore } = position;
7847
- if (!Number.isInteger(offset) || offset < 0 || offset > text.length) return DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET;
7848
- if (offset > 0 && offset < text.length && isHighSurrogate(text.charCodeAt(offset - 1)) && isLowSurrogate(text.charCodeAt(offset))) return DOCUMENT_OP_REFUSAL_REASONS.SPLITS_SURROGATE_PAIR;
7849
- const available = zeroWidthLeavesAt(paragraph.content, offset).length;
7850
- if (zeroWidthBefore !== void 0) return Number.isInteger(zeroWidthBefore) && zeroWidthBefore >= 0 && zeroWidthBefore <= available ? {
7851
- offset,
7852
- zeroWidthBefore
7853
- } : DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET;
7854
- switch (fallback) {
7855
- case "afterAll": return {
7856
- offset,
7857
- zeroWidthBefore: available
7858
- };
7859
- case "beforeAll": return {
7860
- offset,
7861
- zeroWidthBefore: 0
7862
- };
7863
- case "insertion": return defaultInsertionGap(paragraph.content, offset);
7864
- default: return fallback;
7865
- }
7866
- };
7867
8241
  const isGap = (value) => typeof value === "object";
7868
8242
  /**
7869
8243
  * A range of one paragraph. Absent `zeroWidthBefore` leaves the zero-width
@@ -7874,8 +8248,16 @@ const locateRange = (document, op, from, to) => {
7874
8248
  const located = locate(document, op, from.story, from.blockId);
7875
8249
  if (located.isErr()) return Result.err(located.error);
7876
8250
  const { paragraph } = located.value;
7877
- const start = resolveGap(paragraph, from, "afterAll");
7878
- const end = resolveGap(paragraph, to, "beforeAll");
8251
+ const start = resolveGap({
8252
+ paragraph,
8253
+ position: from,
8254
+ fallback: "afterAll"
8255
+ });
8256
+ const end = resolveGap({
8257
+ paragraph,
8258
+ position: to,
8259
+ fallback: "beforeAll"
8260
+ });
7879
8261
  const invalid = (reason) => Result.err(refusal$1(op, reason, `[${from.offset}, ${to.offset}) is not a range of ${from.blockId}.`));
7880
8262
  if (!isGap(start)) return invalid(start);
7881
8263
  if (!isGap(end)) return invalid(end);
@@ -7893,7 +8275,11 @@ const locateRange = (document, op, from, to) => {
7893
8275
  const locatePosition = (document, op, at, fallback) => {
7894
8276
  const located = locate(document, op, at.story, at.blockId);
7895
8277
  if (located.isErr()) return Result.err(located.error);
7896
- const gap = resolveGap(located.value.paragraph, at, fallback);
8278
+ const gap = resolveGap({
8279
+ paragraph: located.value.paragraph,
8280
+ position: at,
8281
+ fallback
8282
+ });
7897
8283
  if (!isGap(gap)) return Result.err(refusal$1(op, gap, `${at.offset} is not a position in ${at.blockId}.`));
7898
8284
  return Result.ok({
7899
8285
  location: located.value,
@@ -8011,7 +8397,7 @@ const inserted = (options) => {
8011
8397
  let { content } = options;
8012
8398
  if (revision !== void 0) {
8013
8399
  const inverse = insertionInverse(location.paragraph.content, content, start, end);
8014
- if (inverse === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The insertion would merge records that were separate.");
8400
+ if (inverse === void 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The insertion would merge records that were separate.");
8015
8401
  const wrapped = wrappedContent(op, {
8016
8402
  items: content,
8017
8403
  from: start,
@@ -8050,13 +8436,13 @@ const inserted = (options) => {
8050
8436
  });
8051
8437
  };
8052
8438
  const insertText = (document, op) => {
8053
- if (op.text === "" || NON_TEXT_CHARACTER_PATTERN.test(op.text) || hasIllegalXmlCharacters(op.text)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The text cannot be inserted.");
8439
+ if (op.text === "" || NON_TEXT_CHARACTER_PATTERN.test(op.text) || hasIllegalXmlCharacters(op.text)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The text cannot be inserted.");
8054
8440
  const located = locatePosition(document, op, op.at, "afterAll");
8055
8441
  if (located.isErr()) return Result.err(located.error);
8056
8442
  const { location } = located.value;
8057
8443
  const { offset } = op.at;
8058
8444
  const content = insertTextInContent(location.paragraph.content, offset, op.text, op.runProps);
8059
- if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INSIDE_TRACKED_DELETION, `${offset} in ${op.at.blockId} is inside tracked-removed content.`);
8445
+ if (content === void 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INSIDE_TRACKED_DELETION, `${offset} in ${op.at.blockId} is inside tracked-removed content.`);
8060
8446
  const start = {
8061
8447
  offset,
8062
8448
  zeroWidthBefore: zeroWidthLeavesAt(content, offset).length
@@ -8083,16 +8469,16 @@ const insertContent = (document, op) => {
8083
8469
  ...op.slice,
8084
8470
  content: cloneModel(op.slice.content)
8085
8471
  };
8086
- if (slice.content.length === 0 || holdsEmptyRecord(slice.content)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The slice holds nothing, or an empty run, text node, or revision wrapper.");
8087
- if (!Number.isInteger(slice.openStart) || !Number.isInteger(slice.openEnd) || slice.openStart < 0 || slice.openEnd < 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Open depths are counts.");
8088
- if (textsIn(slice.content).some(hasIllegalXmlCharacters)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The slice holds text that cannot be written.");
8472
+ if (slice.content.length === 0 || holdsEmptyRecord(slice.content)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The slice holds nothing, or an empty run, text node, or revision wrapper.");
8473
+ if (!Number.isInteger(slice.openStart) || !Number.isInteger(slice.openEnd) || slice.openStart < 0 || slice.openEnd < 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Open depths are counts.");
8474
+ if (textsIn(slice.content).some(hasIllegalXmlCharacters)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The slice holds text that cannot be written.");
8089
8475
  const incoming = paragraphIdsIn(slice.content);
8090
- if (incoming.length > 0 && collides(countIds(packageParagraphIds(document.package)), incoming)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The slice holds a paragraph id the package already uses.");
8476
+ if (incoming.length > 0 && collides(countIds(packageParagraphIds(document.package)), incoming)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The slice holds a paragraph id the package already uses.");
8091
8477
  const located = locatePosition(document, op, op.at, "insertion");
8092
8478
  if (located.isErr()) return Result.err(located.error);
8093
8479
  const { location, gap } = located.value;
8094
8480
  const content = insertSliceAt(location.paragraph.content, gap, slice);
8095
- if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `The slice's open ends do not fit ${op.at.offset} in ${op.at.blockId}.`);
8481
+ if (content === void 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `The slice's open ends do not fit ${op.at.offset} in ${op.at.blockId}.`);
8096
8482
  return inserted({
8097
8483
  document,
8098
8484
  op,
@@ -8120,16 +8506,16 @@ const joinedContent = (op, joined, where) => {
8120
8506
  const isCount = (value) => Number.isInteger(value) && value >= 0;
8121
8507
  const deleteRange = (document, op) => {
8122
8508
  const join = op.join ?? 0;
8123
- if (!isCount(join)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
8124
- if (op.revision !== void 0 && join !== 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A tracked deletion joins nothing.");
8509
+ if (!isCount(join)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
8510
+ if (op.revision !== void 0 && join !== 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A tracked deletion joins nothing.");
8125
8511
  const located = locateRange(document, op, op.from, op.to);
8126
8512
  if (located.isErr()) return Result.err(located.error);
8127
8513
  const { story, location, from, to, empty } = located.value;
8128
8514
  const { expected } = op;
8129
- if (empty) return expected === void 0 || expected.content.length === 0 ? unchanged(document) : refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The range to delete is empty.");
8515
+ if (empty) return expected === void 0 || expected.content.length === 0 ? unchanged(document) : refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The range to delete is empty.");
8130
8516
  const { paragraph } = location;
8131
8517
  const { content: remaining, removed } = deleteBetween(paragraph.content, from, to);
8132
- if (expected !== void 0 && !equalForStaleness(expected, removed)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The range of ${op.from.blockId} holds other content than expected.`);
8518
+ if (expected !== void 0 && !equalForStaleness(expected, removed)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The range of ${op.from.blockId} holds other content than expected.`);
8133
8519
  if (removed.content.length === 0) return unchanged(document);
8134
8520
  if (op.revision !== void 0) {
8135
8521
  const wrapped = wrappedContent(op, {
@@ -8180,12 +8566,12 @@ const deleteRange = (document, op) => {
8180
8566
  });
8181
8567
  };
8182
8568
  const splitInline = (document, op) => {
8183
- if (!isCount(op.depth) || op.depth === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A split cuts one level or more.");
8569
+ if (!isCount(op.depth) || op.depth === 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A split cuts one level or more.");
8184
8570
  const located = locatePosition(document, op, op.at, "beforeAll");
8185
8571
  if (located.isErr()) return Result.err(located.error);
8186
8572
  const { location, gap } = located.value;
8187
8573
  const content = splitAt(location.paragraph.content, gap, op.depth);
8188
- if (content === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `Fewer than ${op.depth} records run across ${op.at.offset} in ${op.at.blockId}.`);
8574
+ if (content === void 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, `Fewer than ${op.depth} records run across ${op.at.offset} in ${op.at.blockId}.`);
8189
8575
  return editOne({
8190
8576
  document,
8191
8577
  op,
@@ -8206,7 +8592,7 @@ const splitInline = (document, op) => {
8206
8592
  });
8207
8593
  };
8208
8594
  const joinInline = (document, op) => {
8209
- if (!isCount(op.depth) || op.depth === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join merges one level or more.");
8595
+ if (!isCount(op.depth) || op.depth === 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join merges one level or more.");
8210
8596
  const located = locatePosition(document, op, op.at, "beforeAll");
8211
8597
  if (located.isErr()) return Result.err(located.error);
8212
8598
  const { location, gap } = located.value;
@@ -8246,16 +8632,16 @@ const statesValues = (formatting, expected) => {
8246
8632
  const setRunProps = (document, op) => {
8247
8633
  const joinStart = op.joinStart ?? 0;
8248
8634
  const joinEnd = op.joinEnd ?? 0;
8249
- if (!isCount(joinStart) || !isCount(joinEnd)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
8635
+ if (!isCount(joinStart) || !isCount(joinEnd)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
8250
8636
  const { revision } = op;
8251
- if (revision !== void 0 && (joinStart !== 0 || joinEnd !== 0)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A tracked patch joins nothing.");
8637
+ if (revision !== void 0 && (joinStart !== 0 || joinEnd !== 0)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A tracked patch joins nothing.");
8252
8638
  const located = locateRange(document, op, op.from, op.to);
8253
8639
  if (located.isErr()) return Result.err(located.error);
8254
8640
  const { story, location, from, to, empty } = located.value;
8255
8641
  if (empty) return unchanged(document);
8256
8642
  const { paragraph } = location;
8257
8643
  const { expected } = op;
8258
- if (expected !== void 0 && !runsBetween(paragraph.content, from, to).every((run) => statesValues(run.formatting, expected))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The runs of ${op.from.blockId} state other values than expected.`);
8644
+ if (expected !== void 0 && !runsBetween(paragraph.content, from, to).every((run) => statesValues(run.formatting, expected))) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `The runs of ${op.from.blockId} state other values than expected.`);
8259
8645
  if (revision !== void 0) {
8260
8646
  const changes = /* @__PURE__ */ new Map();
8261
8647
  const recordChange = (options) => {
@@ -8390,9 +8776,9 @@ const setParagraphProps = (document, op) => {
8390
8776
  const located = locate(document, op, op.story, op.blockId);
8391
8777
  if (located.isErr()) return Result.err(located.error);
8392
8778
  const { paragraph } = located.value;
8393
- if (op.expected !== void 0 && !statesValues(paragraph.formatting, op.expected)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} states other paragraph properties than expected.`);
8779
+ if (op.expected !== void 0 && !statesValues(paragraph.formatting, op.expected)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} states other paragraph properties than expected.`);
8394
8780
  const { revision } = op;
8395
- if (revision !== void 0 && namesMarkFormatting(op.patch)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "A paragraph property change does not record the paragraph mark's run properties.");
8781
+ if (revision !== void 0 && namesMarkFormatting(op.patch)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "A paragraph property change does not record the paragraph mark's run properties.");
8396
8782
  const formatting = patchedSet(paragraph.formatting, op.patch, op.whenEmpty);
8397
8783
  if (structurallyEqual(formatting, paragraph.formatting)) return unchanged(document);
8398
8784
  if (revision !== void 0) {
@@ -8484,15 +8870,15 @@ const trackSplit = ({ op, stamp, paragraph, first, made, madeSecond, resolutionJ
8484
8870
  }) : paragraphPropertyChange(stampInfo(stamp), paragraph.formatting)];
8485
8871
  };
8486
8872
  const splitBlock = (document, op) => {
8487
- if (!isParaId(op.newBlockId)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${op.newBlockId} is not a paragraph id.`);
8488
- if (collides(countIds(packageParagraphIds(document.package)), [op.newBlockId])) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, `${op.newBlockId} is already used in the package.`);
8489
- if (op.newHalf !== void 0 && !isSplitHalf(op.newHalf)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A half is first or second.");
8873
+ if (!isParaId(op.newBlockId)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${op.newBlockId} is not a paragraph id.`);
8874
+ if (collides(countIds(packageParagraphIds(document.package)), [op.newBlockId])) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, `${op.newBlockId} is already used in the package.`);
8875
+ if (op.newHalf !== void 0 && !isSplitHalf(op.newHalf)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A half is first or second.");
8490
8876
  const located = locatePosition(document, op, op.at, "insertion");
8491
8877
  if (located.isErr()) return Result.err(located.error);
8492
8878
  const { location, gap } = located.value;
8493
8879
  const { paragraph } = location;
8494
8880
  const newHalf = op.newHalf ?? (gap.offset === paragraphLength(paragraph) ? SPLIT_HALVES.SECOND : SPLIT_HALVES.FIRST);
8495
- if (newHalf === SPLIT_HALVES.SECOND && (op.newParagraph?.propertyChanges?.length ?? 0) > 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The second half takes the paragraph's property changes with its mark.");
8881
+ if (newHalf === SPLIT_HALVES.SECOND && (op.newParagraph?.propertyChanges?.length ?? 0) > 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The second half takes the paragraph's property changes with its mark.");
8496
8882
  const cut = cutAt(paragraph.content, gap);
8497
8883
  const made = {
8498
8884
  ...op.newParagraph ?? (paragraph.formatting === void 0 ? {} : { formatting: paragraph.formatting }),
@@ -8594,10 +8980,10 @@ const splitBlock = (document, op) => {
8594
8980
  */
8595
8981
  const trackJoin = ({ document, op, stamp, at, leading, trailing }) => {
8596
8982
  const depth = op.depth ?? 0;
8597
- if (!isCount(depth)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
8598
- if (depth !== 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "A tracked paragraph mark cannot record an inline merge depth.");
8599
- if ((op.survivor ?? SPLIT_HALVES.SECOND) !== SPLIT_HALVES.SECOND) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Resolving a tracked join leaves the second paragraph.");
8600
- if (leading.pPrMark !== void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT, `The mark of ${op.blockId} already carries a tracked change.`);
8983
+ if (!isCount(depth)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
8984
+ if (depth !== 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE, "A tracked paragraph mark cannot record an inline merge depth.");
8985
+ if ((op.survivor ?? SPLIT_HALVES.SECOND) !== SPLIT_HALVES.SECOND) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Resolving a tracked join leaves the second paragraph.");
8986
+ if (leading.pPrMark !== void 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT, `The mark of ${op.blockId} already carries a tracked change.`);
8601
8987
  const first = {
8602
8988
  ...leading,
8603
8989
  pPrMark: {
@@ -8640,12 +9026,12 @@ const joinBlocks = (document, op) => {
8640
9026
  if (first.isErr()) return Result.err(first.error);
8641
9027
  const next = findParagraph(op, paragraphs, op.nextBlockId);
8642
9028
  if (next.isErr()) return Result.err(next.error);
8643
- if (!sameBlockList(first.value.list, next.value.list) || next.value.index !== first.value.index + 1) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, `${op.nextBlockId} does not directly follow ${op.blockId}.`);
9029
+ if (!sameBlockList(first.value.list, next.value.list) || next.value.index !== first.value.index + 1) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, `${op.nextBlockId} does not directly follow ${op.blockId}.`);
8644
9030
  const leading = first.value.paragraph;
8645
9031
  const trailing = next.value.paragraph;
8646
- if (leading.sectionProperties !== void 0 && op.sectionBoundary !== SECTION_BOUNDARY_POLICIES.REMOVE) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, `${op.blockId} ends a section.`);
9032
+ if (leading.sectionProperties !== void 0 && op.sectionBoundary !== SECTION_BOUNDARY_POLICIES.REMOVE) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, `${op.blockId} ends a section.`);
8647
9033
  const survivorSide = op.survivor ?? SPLIT_HALVES.SECOND;
8648
- if (!isSplitHalf(survivorSide)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A half is first or second.");
9034
+ if (!isSplitHalf(survivorSide)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A half is first or second.");
8649
9035
  const survivor = survivorSide === SPLIT_HALVES.SECOND ? trailing : leading;
8650
9036
  const retired = survivorSide === SPLIT_HALVES.SECOND ? leading : trailing;
8651
9037
  if (op.expectedRetired !== void 0 && !equalForStaleness({
@@ -8654,8 +9040,8 @@ const joinBlocks = (document, op) => {
8654
9040
  }, {
8655
9041
  type: "paragraph",
8656
9042
  ...op.expectedRetired
8657
- })) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${retired.paraId ?? ""} states other fields than expected.`);
8658
- if (op.expectedSurvivor !== void 0 && !equalForStaleness(reviewFieldsOf(survivor), op.expectedSurvivor)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${survivor.paraId ?? ""} states other review fields than expected.`);
9043
+ })) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${retired.paraId ?? ""} states other fields than expected.`);
9044
+ if (op.expectedSurvivor !== void 0 && !equalForStaleness(reviewFieldsOf(survivor), op.expectedSurvivor)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${survivor.paraId ?? ""} states other review fields than expected.`);
8659
9045
  if (op.revision !== void 0) return trackJoin({
8660
9046
  document,
8661
9047
  op,
@@ -8665,9 +9051,9 @@ const joinBlocks = (document, op) => {
8665
9051
  trailing
8666
9052
  });
8667
9053
  const retiredId = retired.paraId ?? "";
8668
- if (!isParaId(retiredId)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${retiredId} could not name the paragraph again.`);
9054
+ if (!isParaId(retiredId)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, `${retiredId} could not name the paragraph again.`);
8669
9055
  const depth = op.depth ?? 0;
8670
- if (!isCount(depth)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
9056
+ if (!isCount(depth)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A join depth is a count.");
8671
9057
  const merged = joinedContent(op, joinContent(leading.content, trailing.content, depth), `between ${op.blockId} and ${op.nextBlockId}`);
8672
9058
  if (merged.isErr()) return Result.err(merged.error);
8673
9059
  const joined = withReviewFields({
@@ -8766,32 +9152,32 @@ const sameSectionBreaks = (before, after) => {
8766
9152
  };
8767
9153
  const replaceBlocks = (document, op) => {
8768
9154
  const [firstExpected] = op.expected;
8769
- if (firstExpected === void 0 || op.blocks.length === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "A replacement names the paragraphs it replaces and the ones it puts in their place.");
9155
+ if (firstExpected === void 0 || op.blocks.length === 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "A replacement names the paragraphs it replaces and the ones it puts in their place.");
8770
9156
  const paragraphs = storyParagraphs(storyBody(document, op.story));
8771
9157
  const found = [];
8772
9158
  for (const expected of op.expected) {
8773
- if (expected.paraId === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, "A replaced paragraph has no id.");
9159
+ if (expected.paraId === void 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, "A replaced paragraph has no id.");
8774
9160
  const located = findParagraph(op, paragraphs, expected.paraId);
8775
9161
  if (located.isErr()) return Result.err(located.error);
8776
9162
  found.push(located.value);
8777
9163
  }
8778
9164
  const [start] = found;
8779
- if (start === void 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "Nothing to replace.");
8780
- if (!found.every((location, offset) => sameBlockList(location.list, start.list) && location.index === start.index + offset)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, "The replaced paragraphs are not adjacent.");
8781
- if (found.some((location, offset) => !equalForStaleness(location.paragraph, op.expected[offset]))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The paragraphs to replace have changed.");
8782
- if (op.blocks.some(({ paraId }) => paraId === void 0)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A replacement paragraph has no id.");
8783
- if (op.blocks.some(({ content }) => holdsEmptyRecord(content))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "A replacement paragraph holds an empty run, text node, or revision wrapper.");
9165
+ if (start === void 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_BLOCK_LIST, "Nothing to replace.");
9166
+ if (!found.every((location, offset) => sameBlockList(location.list, start.list) && location.index === start.index + offset)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.NOT_ADJACENT, "The replaced paragraphs are not adjacent.");
9167
+ if (found.some((location, offset) => !equalForStaleness(location.paragraph, op.expected[offset]))) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, "The paragraphs to replace have changed.");
9168
+ if (op.blocks.some(({ paraId }) => paraId === void 0)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A replacement paragraph has no id.");
9169
+ if (op.blocks.some(({ content }) => holdsEmptyRecord(content))) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "A replacement paragraph holds an empty run, text node, or revision wrapper.");
8784
9170
  const before = found.map(({ paragraph }) => paragraph);
8785
9171
  const kept = new Set(before.map(({ paraId }) => idKey(paraId ?? "")));
8786
9172
  const placed = new Set(op.blocks.map(({ paraId }) => idKey(paraId ?? "")));
8787
- if ([...op.blocks.filter(({ paraId }) => !kept.has(idKey(paraId ?? ""))), ...before.filter(({ paraId }) => !placed.has(idKey(paraId ?? "")))].some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A paragraph the replacement adds or removes has no usable id.");
8788
- if (op.sectionBoundaries !== SECTION_BOUNDARY_POLICIES.REPLACE && !sameSectionBreaks(before, op.blocks)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, "A replacement keeps every section break where it is.");
9173
+ if ([...op.blocks.filter(({ paraId }) => !kept.has(idKey(paraId ?? ""))), ...before.filter(({ paraId }) => !placed.has(idKey(paraId ?? "")))].some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID, "A paragraph the replacement adds or removes has no usable id.");
9174
+ if (op.sectionBoundaries !== SECTION_BOUNDARY_POLICIES.REPLACE && !sameSectionBreaks(before, op.blocks)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY, "A replacement keeps every section break where it is.");
8789
9175
  const remaining = countIds(packageParagraphIds(document.package));
8790
9176
  for (const id of paragraphIdsIn(before)) remaining.set(idKey(id), (remaining.get(idKey(id)) ?? 1) - 1);
8791
- if (collides(remaining, paragraphIdsIn(op.blocks))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "A replacement paragraph id is already used in the package.");
9177
+ if (collides(remaining, paragraphIdsIn(op.blocks))) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "A replacement paragraph id is already used in the package.");
8792
9178
  const outside = identitiesOutside(document, before);
8793
9179
  const incomingRecords = identityKeysIn(op.blocks);
8794
- if (incomingRecords.some((key) => outside.has(key)) || new Set(incomingRecords).size !== incomingRecords.length) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "A replacement carries a revision or content-control id already used in the package.");
9180
+ if (incomingRecords.some((key) => outside.has(key)) || new Set(incomingRecords).size !== incomingRecords.length) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "A replacement carries a revision or content-control id already used in the package.");
8795
9181
  const replaced = replaceParagraphs({
8796
9182
  document,
8797
9183
  story: op.story,
@@ -8822,15 +9208,15 @@ const setParagraphReview = (document, op) => {
8822
9208
  const located = locate(document, op, op.story, op.blockId);
8823
9209
  if (located.isErr()) return Result.err(located.error);
8824
9210
  const { paragraph } = located.value;
8825
- if (!equalForStaleness(reviewFieldsOf(paragraph), op.expected)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} states other review fields than expected.`);
9211
+ if (!equalForStaleness(reviewFieldsOf(paragraph), op.expected)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} states other review fields than expected.`);
8826
9212
  const review = cloneModel(op.review);
8827
9213
  const next = withReviewFields(paragraph, review);
8828
9214
  if (structurallyEqual(next, paragraph)) return unchanged(document);
8829
- if (review.pPrMark !== void 0 && !structurallyEqual(review.pPrMark, paragraph.pPrMark) && endsItsContainer(storyBody(document, op.story), located.value) && !(located.value.list.some((step) => step.kind === "tableCell") && (review.pPrMark.kind === "ins" || review.pPrMark.kind === "del"))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.CONTAINER_FINAL_MARK, `${op.blockId} ends its container: there is no next paragraph its mark could join.`);
9215
+ if (review.pPrMark !== void 0 && !structurallyEqual(review.pPrMark, paragraph.pPrMark) && endsItsContainer(storyBody(document, op.story), located.value) && !(located.value.list.some((step) => step.kind === "tableCell") && (review.pPrMark.kind === "ins" || review.pPrMark.kind === "del"))) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.CONTAINER_FINAL_MARK, `${op.blockId} ends its container: there is no next paragraph its mark could join.`);
8830
9216
  const taken = identitiesOutside(document, [paragraph]);
8831
9217
  for (const key of identityKeysIn(paragraph.content)) taken.add(key);
8832
9218
  const incoming = reviewKeysOf(review);
8833
- if (incoming.some((key) => taken.has(key)) || new Set(incoming).size !== incoming.length) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The review fields carry a revision id already used in the package.");
9219
+ if (incoming.some((key) => taken.has(key)) || new Set(incoming).size !== incoming.length) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The review fields carry a revision id already used in the package.");
8834
9220
  const replaced = replaceParagraphs({
8835
9221
  document,
8836
9222
  story: op.story,
@@ -8849,18 +9235,18 @@ const replaceInline = (document, op) => {
8849
9235
  const located = locate(document, op, op.story, op.blockId);
8850
9236
  if (located.isErr()) return Result.err(located.error);
8851
9237
  const { paragraph } = located.value;
8852
- if (!equalForStaleness(paragraph.content, op.expected)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} holds other content than expected.`);
9238
+ if (!equalForStaleness(paragraph.content, op.expected)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STALE, `${op.blockId} holds other content than expected.`);
8853
9239
  const content = cloneModel(op.content);
8854
- if (holdsEmptyRecord(content)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The content holds an empty run, text node, or revision wrapper.");
8855
- if (textsIn(content).some(hasIllegalXmlCharacters)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The content holds text that cannot be written.");
9240
+ if (holdsEmptyRecord(content)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "The content holds an empty run, text node, or revision wrapper.");
9241
+ if (textsIn(content).some(hasIllegalXmlCharacters)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT, "The content holds text that cannot be written.");
8856
9242
  if (structurallyEqual(content, paragraph.content)) return unchanged(document);
8857
9243
  const remaining = countIds(packageParagraphIds(document.package));
8858
9244
  for (const id of paragraphIdsIn(paragraph.content)) remaining.set(idKey(id), (remaining.get(idKey(id)) ?? 1) - 1);
8859
- if (collides(remaining, paragraphIdsIn(content))) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The content holds a paragraph id the package already uses.");
9245
+ if (collides(remaining, paragraphIdsIn(content))) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The content holds a paragraph id the package already uses.");
8860
9246
  const taken = identitiesOutside(document, [paragraph]);
8861
9247
  for (const key of reviewKeysOf(reviewFieldsOf(paragraph))) taken.add(key);
8862
9248
  const incoming = identityKeysIn(content);
8863
- if (incoming.some((key) => taken.has(key)) || new Set(incoming).size !== incoming.length) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The content carries a revision or content-control id already used in the package.");
9249
+ if (incoming.some((key) => taken.has(key)) || new Set(incoming).size !== incoming.length) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The content carries a revision or content-control id already used in the package.");
8864
9250
  const next = withContent(paragraph, content);
8865
9251
  const replaced = replaceParagraphs({
8866
9252
  document,
@@ -8879,15 +9265,15 @@ const replaceInline = (document, op) => {
8879
9265
  const editNote = (document, op) => {
8880
9266
  const kind = op.type === DOCUMENT_OP_TYPES.ADD_NOTE ? op.note.type : op.story.kind;
8881
9267
  const id = op.type === DOCUMENT_OP_TYPES.ADD_NOTE ? op.note.id : op.story.id;
8882
- if (!Number.isInteger(id) || id <= 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, "A normal note needs a positive integer id.");
9268
+ if (!Number.isInteger(id) || id <= 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID, "A normal note needs a positive integer id.");
8883
9269
  const collection = kind === "footnote" ? document.package.footnotes : document.package.endnotes;
8884
9270
  if (op.type === DOCUMENT_OP_TYPES.ADD_NOTE) {
8885
- if (collection?.some((note) => note.id === id)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The note id is already used.");
8886
- if (op.note.noteType !== void 0 && op.note.noteType !== "normal") return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A reference can only create a normal note.");
8887
- if (op.note.content.length === 0) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "A note needs an addressable paragraph.");
9271
+ if (collection?.some((note) => note.id === id)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION, "The note id is already used.");
9272
+ if (op.note.noteType !== void 0 && op.note.noteType !== "normal") return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A reference can only create a normal note.");
9273
+ if (op.note.content.length === 0) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT, "A note needs an addressable paragraph.");
8888
9274
  const note = cloneModel(op.note);
8889
9275
  const markers = storyParagraphs({ content: note.content }).flatMap(({ paragraph }) => leafSpans(paragraph.content)).filter(({ node }) => node.type === "noteMarker");
8890
- if (markers.length > 1 || markers.some(({ node }) => node.type === "noteMarker" && node.kind !== kind)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A note needs one matching automatic reference mark.");
9276
+ if (markers.length > 1 || markers.some(({ node }) => node.type === "noteMarker" && node.kind !== kind)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "A note needs one matching automatic reference mark.");
8891
9277
  note.content = noteContentWithAutomaticMark({
8892
9278
  note,
8893
9279
  customMark: false
@@ -8906,7 +9292,7 @@ const editNote = (document, op) => {
8906
9292
  }
8907
9293
  };
8908
9294
  const valid = validateOpsDocument(withNote);
8909
- if (valid.isErr()) return refuse(op, valid.error.reason, valid.error.message);
9295
+ if (valid.isErr()) return refuse$2(op, valid.error.reason, valid.error.message);
8910
9296
  const reference = insertContent(withNote, {
8911
9297
  type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
8912
9298
  at: op.at,
@@ -8925,13 +9311,13 @@ const editNote = (document, op) => {
8925
9311
  if (reference.isErr()) return reference;
8926
9312
  return storyLifecycleEdit(document, reference.value.document, op);
8927
9313
  }
8928
- if (!collection?.find((candidate) => candidate.id === id)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, "The note does not exist.");
9314
+ if (!collection?.find((candidate) => candidate.id === id)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND, "The note does not exist.");
8929
9315
  const located = locateRange(document, op, op.at, {
8930
9316
  ...op.at,
8931
9317
  offset: op.at.offset + 1
8932
9318
  });
8933
9319
  if (located.isErr()) return Result.err(located.error);
8934
- if (!leafSpans(located.value.location.paragraph.content).some(({ node, before, after }) => before.offset === op.at.offset && after.offset === op.at.offset + 1 && (kind === "footnote" && node.type === "footnoteRef" || kind === "endnote" && node.type === "endnoteRef") && node.id === id)) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The position does not name the note reference.");
9320
+ if (!leafSpans(located.value.location.paragraph.content).some(({ node, before, after }) => before.offset === op.at.offset && after.offset === op.at.offset + 1 && (kind === "footnote" && node.type === "footnoteRef" || kind === "endnote" && node.type === "endnoteRef") && node.id === id)) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "The position does not name the note reference.");
8935
9321
  const removed = deleteRange(document, {
8936
9322
  type: DOCUMENT_OP_TYPES.DELETE_RANGE,
8937
9323
  from: op.at,
@@ -8944,7 +9330,7 @@ const editNote = (document, op) => {
8944
9330
  if (documentStories(removed.value.document).some((story) => {
8945
9331
  if (typeof story !== "string" && story.kind === kind && "id" in story && story.id === id) return false;
8946
9332
  return storyParagraphs(storyBody(removed.value.document, story)).some(({ paragraph }) => leafSpans(paragraph.content).some(({ node }) => (kind === "footnote" && node.type === "footnoteRef" || kind === "endnote" && node.type === "endnoteRef") && node.id === id));
8947
- })) return refuse(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Another reference still owns this note.");
9333
+ })) return refuse$2(op, DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH, "Another reference still owns this note.");
8948
9334
  return storyLifecycleEdit(document, kind === "footnote" ? {
8949
9335
  ...removed.value.document,
8950
9336
  package: {
@@ -8996,6 +9382,7 @@ const dispatch = (document, op) => {
8996
9382
  case DOCUMENT_OP_TYPES.INSERT_ROW:
8997
9383
  case DOCUMENT_OP_TYPES.DELETE_ROW:
8998
9384
  case DOCUMENT_OP_TYPES.SET_TABLE_ROWS: return applyRowOp(document, op);
9385
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES: return applyPackageResourcesOp(document, op);
8999
9386
  case DOCUMENT_OP_TYPES.INSERT_COLUMN:
9000
9387
  case DOCUMENT_OP_TYPES.DELETE_COLUMN:
9001
9388
  case DOCUMENT_OP_TYPES.MERGE_CELLS:
@@ -9052,7 +9439,8 @@ const stampOf = (op) => {
9052
9439
  case DOCUMENT_OP_TYPES.SET_CONTAINER_BLOCKS:
9053
9440
  case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
9054
9441
  case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
9055
- case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT: return;
9442
+ case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT:
9443
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES: return;
9056
9444
  default: return op;
9057
9445
  }
9058
9446
  };
@@ -9133,7 +9521,7 @@ const applyDocumentOp = (document, input) => {
9133
9521
  };
9134
9522
  /** Apply a journal envelope only when its schema matches this reader. */
9135
9523
  const applyDocumentOpEnvelope = (document, envelope) => {
9136
- if (envelope.schema !== 8) return Result.err(refusal$1(envelope.op, DOCUMENT_OP_REFUSAL_REASONS.UNSUPPORTED_SCHEMA, `Document operation schema ${envelope.schema} is unsupported; this reader accepts 8.`));
9524
+ if (envelope.schema !== 9) return Result.err(refusal$1(envelope.op, DOCUMENT_OP_REFUSAL_REASONS.UNSUPPORTED_SCHEMA, `Document operation schema ${envelope.schema} is unsupported; this reader accepts 9.`));
9137
9525
  return applyDocumentOp(document, envelope.op);
9138
9526
  };
9139
9527
  /**
@@ -9158,92 +9546,316 @@ const applyDocumentOps = (document, ops) => {
9158
9546
  });
9159
9547
  };
9160
9548
  //#endregion
9161
- //#region src/ops/editorIntentCensus.ts
9162
- const sameFieldsExcept = (before, after, excluded) => {
9163
- const beforeFields = Object.entries(before).filter(([key]) => !excluded.has(key));
9164
- const afterFields = new Map(Object.entries(after).filter(([key]) => !excluded.has(key)));
9165
- return beforeFields.length === afterFields.size && beforeFields.every(([key, value]) => afterFields.has(key) && afterFields.get(key) === value);
9549
+ //#region src/ops/tocIntent.ts
9550
+ const refuse$1 = (message, reason = DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE) => Result.err(new DocumentOpRefusal({
9551
+ message,
9552
+ reason,
9553
+ opType: DOCUMENT_OP_TYPES.REPLACE_INLINE
9554
+ }));
9555
+ const isPendingOrUnsupported = (content) => content.some((item) => {
9556
+ if (item.type === "bookmarkStart" || item.type === "bookmarkEnd") return false;
9557
+ if (item.type === "run") return (item.propertyChanges?.length ?? 0) > 0;
9558
+ if (item.type === "hyperlink") return isPendingOrUnsupported(item.children);
9559
+ return true;
9560
+ });
9561
+ const takeBookmarkId = (census, reserved) => {
9562
+ for (let id = 1; Number.isSafeInteger(id); id += 1) {
9563
+ if (census.ids.has(id) || reserved.has(id)) continue;
9564
+ reserved.add(id);
9565
+ return id;
9566
+ }
9166
9567
  };
9167
- const PACKAGE_CONTENT_FIELDS = /* @__PURE__ */ new Set(["document"]);
9168
- const DOCUMENT_CONTENT_FIELDS = /* @__PURE__ */ new Set(["content", "sections"]);
9169
- const adjustCounts = ({ counts, keys, delta }) => {
9170
- for (const key of keys) {
9171
- const count = (counts.get(key) ?? 0) + delta;
9172
- if (count < 0) panic("An incremental identity census cannot have a negative count.");
9173
- if (count === 0) counts.delete(key);
9174
- else counts.set(key, count);
9568
+ const takeParagraphIds = ({ document, count, reserved }) => {
9569
+ const occupied = new Set([...packageParagraphIds(document.package), ...reserved ?? []].map(idKey));
9570
+ const ids = [];
9571
+ for (let id = 1; id < 2147483648 && ids.length < count; id += 1) {
9572
+ const candidate = id.toString(16).padStart(8, "0").toUpperCase();
9573
+ if (occupied.has(candidate)) continue;
9574
+ occupied.add(candidate);
9575
+ ids.push(candidate);
9576
+ }
9577
+ return ids.length === count ? ids : void 0;
9578
+ };
9579
+ const takeBookmarkName = (census, reserved) => {
9580
+ for (let suffix = 1;; suffix += 1) {
9581
+ const name = `_Toc${suffix}`;
9582
+ if (census.names.has(name) || reserved.has(name)) continue;
9583
+ reserved.add(name);
9584
+ return name;
9585
+ }
9586
+ };
9587
+ const paragraphFor = (document, position) => storyParagraphs(storyBody(document, position.story)).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(position.blockId))?.paragraph;
9588
+ const bookmarkAtStart = (paragraph, id, name) => [
9589
+ {
9590
+ type: "bookmarkStart",
9591
+ id,
9592
+ name
9593
+ },
9594
+ ...paragraph.content,
9595
+ {
9596
+ type: "bookmarkEnd",
9597
+ id
9598
+ }
9599
+ ];
9600
+ /** Map original endpoints through the bookmark wrappers emitted by TOC compilation. */
9601
+ const mapTocBookmarkPosition = (position, ops) => {
9602
+ if (position.offset !== 0) return position;
9603
+ let prepended = 0;
9604
+ for (const op of ops) {
9605
+ if (op.type !== DOCUMENT_OP_TYPES.REPLACE_INLINE || !sameStory(op.story, position.story) || idKey(op.blockId) !== idKey(position.blockId)) continue;
9606
+ prepended += 1;
9175
9607
  }
9608
+ return prepended === 0 ? position : {
9609
+ ...position,
9610
+ zeroWidthBefore: (position.zeroWidthBefore ?? 0) + prepended
9611
+ };
9176
9612
  };
9177
- const censusOf = (identities, paragraphs) => {
9178
- const idsIn = (space) => new Set([...identities.keys()].filter((key) => key.startsWith(`${space}:`)).map((key) => Number(key.slice(space.length + 1))));
9613
+ const paragraphBookmarks = (content) => {
9614
+ const starts = /* @__PURE__ */ new Map();
9615
+ const ends = /* @__PURE__ */ new Set();
9616
+ for (const item of content) if (item.type === "bookmarkStart") starts.set(item.id, item.name);
9617
+ else if (item.type === "bookmarkEnd") ends.add(item.id);
9618
+ else if (item.type === "hyperlink") {
9619
+ const nested = paragraphBookmarks(item.children);
9620
+ for (const [id, name] of nested.starts) starts.set(id, name);
9621
+ for (const id of nested.ends) ends.add(id);
9622
+ }
9179
9623
  return {
9180
- revisions: idsIn(IDENTITY_SPACES.REVISION),
9181
- controls: idsIn(IDENTITY_SPACES.CONTROL),
9182
- paragraphs: new Set(paragraphs.keys()),
9183
- stories: /* @__PURE__ */ new Map()
9624
+ starts,
9625
+ ends
9184
9626
  };
9185
9627
  };
9186
- /** Cache immutable versions and update plain main stories without walking unchanged leaves. */
9187
- const createCensusReader = () => {
9188
- const versions = /* @__PURE__ */ new WeakMap();
9189
- const paragraphKeys = /* @__PURE__ */ new WeakMap();
9190
- let latest;
9191
- const keysOf = (paragraph) => {
9192
- let keys = paragraphKeys.get(paragraph);
9193
- if (keys === void 0) {
9194
- keys = {
9195
- identities: identityKeysIn(paragraph).concat(reservedIdentityKeysIn(paragraph)),
9196
- paragraphs: paragraphIdsIn(paragraph).map(idKey)
9197
- };
9198
- paragraphKeys.set(paragraph, keys);
9199
- }
9200
- return keys;
9201
- };
9202
- return (document) => {
9203
- const cached = versions.get(document);
9204
- if (cached !== void 0) {
9205
- latest = cached;
9206
- return cached.census;
9207
- }
9208
- const before = latest;
9209
- const oldContent = before?.document.package.document.content;
9210
- const content = document.package.document.content;
9211
- let identities;
9212
- let paragraphs;
9213
- if (before !== void 0 && oldContent !== void 0 && oldContent.every((block) => block.type === "paragraph") && content.every((block) => block.type === "paragraph") && sameFieldsExcept(before.document.package, document.package, PACKAGE_CONTENT_FIELDS) && sameFieldsExcept(before.document.package.document, document.package.document, DOCUMENT_CONTENT_FIELDS)) {
9214
- identities = new Map(before.identities);
9215
- paragraphs = new Map(before.paragraphs);
9216
- const changed = /* @__PURE__ */ new Map();
9217
- for (const paragraph of oldContent) changed.set(paragraph, (changed.get(paragraph) ?? 0) - 1);
9218
- for (const paragraph of content) changed.set(paragraph, (changed.get(paragraph) ?? 0) + 1);
9219
- for (const [paragraph, delta] of changed) {
9220
- if (delta === 0) continue;
9221
- const keys = keysOf(paragraph);
9222
- adjustCounts({
9223
- counts: identities,
9224
- keys: keys.identities,
9225
- delta
9226
- });
9227
- adjustCounts({
9228
- counts: paragraphs,
9229
- keys: keys.paragraphs,
9230
- delta
9231
- });
9628
+ const tocParagraphs = (intent, links) => {
9629
+ const paragraphs = [{
9630
+ type: "paragraph",
9631
+ formatting: {
9632
+ ...intent.titleStyleId === void 0 ? {} : { styleId: intent.titleStyleId },
9633
+ alignment: "center"
9634
+ },
9635
+ content: [{
9636
+ type: "run",
9637
+ formatting: { bold: true },
9638
+ content: [{
9639
+ type: "text",
9640
+ text: intent.title
9641
+ }]
9642
+ }]
9643
+ }];
9644
+ for (const { heading, name } of links) paragraphs.push({
9645
+ type: "paragraph",
9646
+ formatting: {
9647
+ ...heading.styleId === void 0 ? {} : { styleId: heading.styleId },
9648
+ ...heading.level === 0 ? {} : { indentLeft: heading.level * 720 },
9649
+ tabs: [{
9650
+ position: intent.tabPosition,
9651
+ alignment: "right",
9652
+ leader: "dot"
9653
+ }]
9654
+ },
9655
+ content: [
9656
+ {
9657
+ type: "hyperlink",
9658
+ anchor: name,
9659
+ children: [{
9660
+ type: "run",
9661
+ content: [{
9662
+ type: "text",
9663
+ text: heading.text
9664
+ }]
9665
+ }]
9666
+ },
9667
+ {
9668
+ type: "run",
9669
+ content: [{ type: "tab" }]
9670
+ },
9671
+ {
9672
+ type: "complexField",
9673
+ instruction: `PAGEREF ${name} \\h`,
9674
+ fieldType: "PAGEREF",
9675
+ fieldCode: [{
9676
+ type: "run",
9677
+ content: [{
9678
+ type: "instrText",
9679
+ text: `PAGEREF ${name} \\h`
9680
+ }]
9681
+ }],
9682
+ fieldResult: [{
9683
+ type: "run",
9684
+ content: [{
9685
+ type: "text",
9686
+ text: "1"
9687
+ }]
9688
+ }],
9689
+ dirty: true
9232
9690
  }
9233
- } else {
9234
- identities = countKeys(packageIdentityKeys(document.package).concat(reservedIdentityKeysIn(document.package)));
9235
- paragraphs = countKeys(packageParagraphIds(document.package).map(idKey));
9691
+ ]
9692
+ });
9693
+ return paragraphs;
9694
+ };
9695
+ /** These paragraphs are newly constructed for this compile, so assigning their ids is local. */
9696
+ const identifyTocParagraphs = (paragraphs, ids) => {
9697
+ for (const [index, paragraph] of paragraphs.entries()) paragraph.paraId = ids.at(index) ?? panic("TOC allocation must cover every generated paragraph.");
9698
+ return paragraphs;
9699
+ };
9700
+ const compileGenerateTOCIntent = (document, intent, mode) => {
9701
+ if (intent.headings.length === 0) return Result.ok({
9702
+ ops: [],
9703
+ selection: intent.at
9704
+ });
9705
+ if (mode.type === "suggesting") return refuse$1("TOC suggestions require serializable wrapper review provenance.");
9706
+ if (intent.at.story !== OP_STORIES.MAIN) return refuse$1("TOC generation is supported in the main document story only.");
9707
+ if (intent.title === "" || hasIllegalXmlCharacters(intent.title) || intent.headings.some(({ text }) => hasIllegalXmlCharacters(text))) return refuse$1("TOC text is empty or contains characters that XML cannot represent.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_TEXT);
9708
+ if (!Number.isSafeInteger(intent.tabPosition) || intent.tabPosition < 0) return refuse$1("The TOC tab position must be a nonnegative integer.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET);
9709
+ const target = paragraphFor(document, intent.at);
9710
+ if (target === void 0) return refuse$1("The TOC insertion paragraph does not exist.", DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND);
9711
+ if (target.paraId === void 0) return refuse$1("The TOC insertion paragraph has no stable identity.", DOCUMENT_OP_REFUSAL_REASONS.MISSING_BLOCK_ID);
9712
+ const initialGap = resolveGap({
9713
+ paragraph: target,
9714
+ position: intent.at,
9715
+ fallback: "insertion"
9716
+ });
9717
+ if (typeof initialGap !== "object") return refuse$1("The TOC insertion position is invalid.", initialGap);
9718
+ const targetLength = paragraphLength(target);
9719
+ const locations = storyParagraphs(storyBody(document, intent.at.story));
9720
+ const links = [];
9721
+ const bookmarkIds = [];
9722
+ const seenHeadings = /* @__PURE__ */ new Set();
9723
+ const census = packageBookmarkCensus(document.package);
9724
+ const reservedBookmarkIds = /* @__PURE__ */ new Set();
9725
+ const reservedBookmarkNames = /* @__PURE__ */ new Set();
9726
+ for (const heading of intent.headings) {
9727
+ if (!Number.isInteger(heading.level) || heading.level < 0 || heading.level > 8) return refuse$1("TOC heading levels must be between zero and eight.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET);
9728
+ const location = locations.find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(heading.blockId));
9729
+ if (location === void 0) return refuse$1("A TOC heading paragraph does not exist.", DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND);
9730
+ if (paragraphLogicalText(location.paragraph).trim() !== heading.text.trim() || location.paragraph.paraId === void 0 || isPendingOrUnsupported(location.paragraph.content) || (location.paragraph.propertyChanges?.length ?? 0) > 0 || location.paragraph.pPrMark !== void 0 || location.paragraph.reviewCarrier !== void 0) return refuse$1("A TOC heading is stale or contains pending review wrappers.");
9731
+ const headingKey = idKey(heading.blockId);
9732
+ if (seenHeadings.has(headingKey)) return refuse$1("A TOC heading is listed more than once.");
9733
+ seenHeadings.add(headingKey);
9734
+ const local = paragraphBookmarks(location.paragraph.content);
9735
+ const existing = [...local.starts].find(([id, name]) => name.startsWith("_Toc") && local.ends.has(id) && census.pairs.some((pair) => pair.id === id && pair.name === name));
9736
+ if (existing !== void 0) {
9737
+ bookmarkIds.push(existing[0]);
9738
+ links.push({
9739
+ heading,
9740
+ name: existing[1]
9741
+ });
9742
+ continue;
9236
9743
  }
9237
- const version = {
9238
- document,
9239
- identities,
9240
- paragraphs,
9241
- census: censusOf(identities, paragraphs)
9744
+ const id = takeBookmarkId(census, reservedBookmarkIds);
9745
+ if (id === void 0) return refuse$1("The bookmark identity space is exhausted.");
9746
+ bookmarkIds.push(id);
9747
+ links.push({
9748
+ heading,
9749
+ name: takeBookmarkName(census, reservedBookmarkNames)
9750
+ });
9751
+ }
9752
+ const ops = [];
9753
+ let insertionAt = {
9754
+ ...intent.at,
9755
+ ...initialGap
9756
+ };
9757
+ for (const [index, { heading, name }] of links.entries()) {
9758
+ const paragraph = locations.find(({ paragraph: candidate }) => idKey(candidate.paraId ?? "") === idKey(heading.blockId))?.paragraph;
9759
+ if (paragraph === void 0) return refuse$1("A TOC heading paragraph disappeared.");
9760
+ const id = bookmarkIds[index];
9761
+ if (id === void 0) return refuse$1("A TOC bookmark id was not allocated.");
9762
+ if (census.pairs.some((pair) => pair.id === id && pair.name === name)) continue;
9763
+ const op = {
9764
+ type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
9765
+ story: intent.at.story,
9766
+ blockId: paragraph.paraId ?? "",
9767
+ expected: paragraph.content,
9768
+ content: bookmarkAtStart(paragraph, id, name)
9242
9769
  };
9243
- versions.set(document, version);
9244
- latest = version;
9245
- return version.census;
9246
- };
9770
+ ops.push(op);
9771
+ const applied = applyDocumentOp(document, op);
9772
+ if (applied.isErr()) return Result.err(applied.error);
9773
+ document = applied.value.document;
9774
+ insertionAt = mapTocBookmarkPosition(insertionAt, [op]);
9775
+ }
9776
+ const currentTarget = paragraphFor(document, intent.at);
9777
+ if (currentTarget === void 0) return refuse$1("The TOC insertion paragraph disappeared.");
9778
+ const gap = resolveGap({
9779
+ paragraph: currentTarget,
9780
+ position: insertionAt,
9781
+ fallback: "insertion"
9782
+ });
9783
+ if (typeof gap !== "object") return refuse$1("The TOC insertion position is invalid after bookmark updates.", gap);
9784
+ if (gap.offset !== 0 && gap.offset !== paragraphLength(currentTarget) && (isPendingOrUnsupported(currentTarget.content) || (currentTarget.propertyChanges?.length ?? 0) > 0 || currentTarget.pPrMark !== void 0 || currentTarget.reviewCarrier !== void 0)) return refuse$1("TOC insertion cannot split pending review wrappers.");
9785
+ const toc = tocParagraphs(intent, links);
9786
+ const story = intent.at.story;
9787
+ if (gap.offset === 0 || gap.offset === targetLength) {
9788
+ const ids = takeParagraphIds({
9789
+ document,
9790
+ count: toc.length,
9791
+ reserved: mode.reservedBlockIds
9792
+ });
9793
+ if (ids === void 0) return refuse$1("The paragraph identity space is exhausted.");
9794
+ ops.push({
9795
+ type: DOCUMENT_OP_TYPES.INSERT_BLOCKS,
9796
+ story,
9797
+ at: gap.offset === 0 ? {
9798
+ type: "before",
9799
+ blockId: intent.at.blockId
9800
+ } : {
9801
+ type: "after",
9802
+ blockId: intent.at.blockId
9803
+ },
9804
+ blocks: identifyTocParagraphs(toc, ids)
9805
+ });
9806
+ return Result.ok({
9807
+ ops,
9808
+ selection: {
9809
+ ...insertionAt,
9810
+ ...gap
9811
+ }
9812
+ });
9813
+ }
9814
+ const newBlockId = takeParagraphIds({
9815
+ document,
9816
+ count: 1,
9817
+ reserved: mode.reservedBlockIds
9818
+ })?.at(0);
9819
+ if (newBlockId === void 0) return refuse$1("The paragraph identity space is exhausted.");
9820
+ const split = {
9821
+ type: DOCUMENT_OP_TYPES.SPLIT_BLOCK,
9822
+ at: {
9823
+ ...insertionAt,
9824
+ ...gap
9825
+ },
9826
+ newBlockId,
9827
+ newHalf: SPLIT_HALVES.FIRST,
9828
+ newParagraph: target.formatting === void 0 ? {} : { formatting: target.formatting }
9829
+ };
9830
+ ops.push(split);
9831
+ const afterSplit = applyDocumentOp(document, split);
9832
+ if (afterSplit.isErr()) return Result.err(afterSplit.error);
9833
+ document = afterSplit.value.document;
9834
+ const tocIds = takeParagraphIds({
9835
+ document,
9836
+ count: toc.length,
9837
+ reserved: mode.reservedBlockIds
9838
+ });
9839
+ if (tocIds === void 0) return refuse$1("The paragraph identity space is exhausted.");
9840
+ const blocks = identifyTocParagraphs(toc, tocIds);
9841
+ ops.push({
9842
+ type: DOCUMENT_OP_TYPES.INSERT_BLOCKS,
9843
+ story,
9844
+ at: {
9845
+ type: "before",
9846
+ blockId: intent.at.blockId
9847
+ },
9848
+ blocks
9849
+ });
9850
+ return Result.ok({
9851
+ ops,
9852
+ selection: {
9853
+ story,
9854
+ blockId: intent.at.blockId,
9855
+ offset: 0,
9856
+ zeroWidthBefore: 0
9857
+ }
9858
+ });
9247
9859
  };
9248
9860
  //#endregion
9249
9861
  //#region src/ops/plan.ts
@@ -9303,7 +9915,8 @@ const withNewIds = (op, newIds) => {
9303
9915
  case DOCUMENT_OP_TYPES.SET_TABLE:
9304
9916
  case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
9305
9917
  case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
9306
- case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT: return op;
9918
+ case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT:
9919
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES: return op;
9307
9920
  default: return op;
9308
9921
  }
9309
9922
  };
@@ -9394,6 +10007,10 @@ const replacementDeletionSegments = ({ spans, from, to, mode }) => {
9394
10007
  const start = laterGap(span.before, from);
9395
10008
  const end = earlierGap(span.after, to);
9396
10009
  if (compareGaps(start, end) >= 0) continue;
10010
+ if (isParagraphContent(span.node) && isRangeBoundary(span.node)) {
10011
+ open = void 0;
10012
+ continue;
10013
+ }
9397
10014
  let plan = isCommentAnchor(span.node) ? "anchor" : "direct";
9398
10015
  if (mode.type === "suggesting") plan = leafPlan(span, mode.author);
9399
10016
  else if (span.ancestors.some(isRemovedRevisionNode)) plan = "untouched";
@@ -9446,7 +10063,7 @@ const createTrackedPlan = ({ document, revision, newIds }) => {
9446
10063
  };
9447
10064
  const append = (input) => {
9448
10065
  let op = input;
9449
- if (input.revision !== void 0) {
10066
+ if (input.type !== DOCUMENT_OP_TYPES.REPLACE_INLINE && input.revision !== void 0) {
9450
10067
  let stampId = revision.id;
9451
10068
  if (stampUsed) {
9452
10069
  if (remaining <= taken) return outOfIds();
@@ -9472,7 +10089,7 @@ const createTrackedPlan = ({ document, revision, newIds }) => {
9472
10089
  });
9473
10090
  const applied = applyDocumentOp(current, op);
9474
10091
  if (applied.isErr()) return Result.err(applied.error);
9475
- stampUsed ||= input.revision !== void 0 && applied.value.revisions.length > 0;
10092
+ stampUsed ||= stampOf(input) !== void 0 && applied.value.revisions.length > 0;
9476
10093
  const before = current;
9477
10094
  current = applied.value.document;
9478
10095
  const story = (() => {
@@ -9482,7 +10099,8 @@ const createTrackedPlan = ({ document, revision, newIds }) => {
9482
10099
  case DOCUMENT_OP_TYPES.INSERT_CONTENT:
9483
10100
  case DOCUMENT_OP_TYPES.SPLIT_BLOCK: return input.at.story;
9484
10101
  case DOCUMENT_OP_TYPES.JOIN_BLOCKS:
9485
- case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS: return input.story;
10102
+ case DOCUMENT_OP_TYPES.SET_PARAGRAPH_PROPS:
10103
+ case DOCUMENT_OP_TYPES.REPLACE_INLINE: return input.story;
9486
10104
  default: return input;
9487
10105
  }
9488
10106
  })();
@@ -9709,6 +10327,289 @@ const planTrackedDeletion = (document, options) => {
9709
10327
  return appended.isErr() ? Result.err(appended.error) : Result.ok(plan.ops);
9710
10328
  };
9711
10329
  //#endregion
10330
+ //#region src/ops/hyperlinkIntent.ts
10331
+ const refuse = (message, reason = DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE) => Result.err(new DocumentOpRefusal({
10332
+ message,
10333
+ reason,
10334
+ opType: DOCUMENT_OP_TYPES.REPLACE_INLINE
10335
+ }));
10336
+ /** Cutting these records cannot duplicate review identities or unmodeled wrappers. */
10337
+ const editable = (items) => items.every((item) => {
10338
+ switch (item.type) {
10339
+ case "run": return (item.propertyChanges?.length ?? 0) === 0;
10340
+ case "bookmarkStart":
10341
+ case "bookmarkEnd": return true;
10342
+ case "hyperlink": return editable(item.children);
10343
+ default: return false;
10344
+ }
10345
+ });
10346
+ const HYPERLINK_STYLE_ID = "Hyperlink";
10347
+ const styledRun = (run, intent) => {
10348
+ if (run.formatting === void 0) return run;
10349
+ const formatting = { ...run.formatting };
10350
+ if (intent.type === "setHyperlink") delete formatting.color;
10351
+ else if (formatting.styleId === HYPERLINK_STYLE_ID || intent.hyperlinkStyleId !== void 0 && formatting.styleId === intent.hyperlinkStyleId) delete formatting.styleId;
10352
+ if (structurallyEqual(formatting, run.formatting)) return run;
10353
+ const next = { ...run };
10354
+ if (Object.keys(formatting).length === 0) delete next.formatting;
10355
+ else next.formatting = formatting;
10356
+ return next;
10357
+ };
10358
+ /** Flatten only the edited hyperlinks; unrelated run formatting and zero-width markers stay. */
10359
+ const linkedChildren = (items, intent) => {
10360
+ const children = [];
10361
+ for (const item of items) switch (item.type) {
10362
+ case "run":
10363
+ children.push(intent.type === "setHyperlink" ? styledRun(item, intent) : item);
10364
+ break;
10365
+ case "bookmarkStart":
10366
+ case "bookmarkEnd":
10367
+ children.push(item);
10368
+ break;
10369
+ case "hyperlink":
10370
+ if (item.children.length === 0) {
10371
+ children.push(item);
10372
+ break;
10373
+ }
10374
+ for (const child of item.children) if (child.type === "run") children.push(styledRun(child, intent));
10375
+ else children.push(child);
10376
+ break;
10377
+ default: return panic("Validated hyperlink edit contains an unsupported inline node.");
10378
+ }
10379
+ return children;
10380
+ };
10381
+ const hyperlink = (intent, children) => {
10382
+ const result = {
10383
+ type: "hyperlink",
10384
+ children
10385
+ };
10386
+ if (intent.href.startsWith("#")) result.anchor = intent.href.slice(1);
10387
+ else if (intent.href !== "") result.href = intent.href;
10388
+ if (intent.tooltip !== void 0) result.tooltip = intent.tooltip;
10389
+ return result;
10390
+ };
10391
+ /** Link text segments while structural markers and empty links retain their authored positions. */
10392
+ const wrapLinkedChildren = (intent, children) => {
10393
+ const result = [];
10394
+ let link;
10395
+ for (const child of children) {
10396
+ if (child.type === "run") {
10397
+ if (link === void 0) {
10398
+ link = hyperlink(intent, []);
10399
+ result.push(link);
10400
+ }
10401
+ link.children.push(child);
10402
+ continue;
10403
+ }
10404
+ link = void 0;
10405
+ result.push(child);
10406
+ }
10407
+ return result;
10408
+ };
10409
+ /** Wrapper edits compile to exact-inverse content ops, never to a projection snapshot. */
10410
+ const compileHyperlinkIntent = (document, { intent: sourceIntent, mode, compileEmptyReplacement }) => {
10411
+ let intent = sourceIntent;
10412
+ if (intent.type !== "removeHyperlink" && intent.href !== "" && !intent.href.startsWith("#")) {
10413
+ const href = sanitizeExternalUrl(intent.href);
10414
+ if (href === void 0) return refuse("Hyperlink targets must use a supported URL scheme.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_OPERATION);
10415
+ intent = {
10416
+ ...intent,
10417
+ href
10418
+ };
10419
+ }
10420
+ const selected = selectedParagraphRuns(document, intent.from, intent.to);
10421
+ if (selected.isErr()) return Result.err(selected.error);
10422
+ const locations = selected.value.flat();
10423
+ const pieces = [];
10424
+ for (const { paragraph } of locations) {
10425
+ if (!editable(paragraph.content)) return refuse("Hyperlink edits cannot cut pending review identities or unsupported inline wrappers.");
10426
+ const blockId = paragraph.paraId ?? "";
10427
+ const from = idKey(blockId) === idKey(intent.from.blockId) ? intent.from : {
10428
+ story: intent.from.story,
10429
+ blockId,
10430
+ offset: 0
10431
+ };
10432
+ const to = idKey(blockId) === idKey(intent.to.blockId) ? intent.to : {
10433
+ story: intent.to.story,
10434
+ blockId,
10435
+ offset: paragraphLength(paragraph)
10436
+ };
10437
+ const start = resolveGap({
10438
+ paragraph,
10439
+ position: from,
10440
+ fallback: "insertion"
10441
+ });
10442
+ if (typeof start !== "object") return refuse("Invalid hyperlink range start.", start);
10443
+ const end = resolveGap({
10444
+ paragraph,
10445
+ position: to,
10446
+ fallback: "insertion"
10447
+ });
10448
+ if (typeof end !== "object") return refuse("Invalid hyperlink range end.", end);
10449
+ if (start.offset > end.offset || start.offset === end.offset && start.zeroWidthBefore > end.zeroWidthBefore) return refuse("Hyperlink range endpoints are reversed.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET);
10450
+ const [before = [], middle = [], after = []] = partitionContent(paragraph.content, [start, end]);
10451
+ pieces.push({
10452
+ paragraph,
10453
+ from,
10454
+ to,
10455
+ before: asParagraphContent(before),
10456
+ middle: asParagraphContent(middle),
10457
+ after: asParagraphContent(after)
10458
+ });
10459
+ }
10460
+ if (mode.type === "suggesting") return refuse("Hyperlink suggestions require serializable wrapper review provenance.");
10461
+ if (intent.type === "insertHyperlink") {
10462
+ if (intent.text === "") return refuse("A hyperlink insertion needs text.", DOCUMENT_OP_REFUSAL_REASONS.EMPTY_CONTENT);
10463
+ const content = [hyperlink(intent, [{
10464
+ type: "run",
10465
+ content: [{
10466
+ type: "text",
10467
+ text: intent.text
10468
+ }]
10469
+ }])];
10470
+ const deletion = compileEmptyReplacement(document, {
10471
+ from: intent.from,
10472
+ to: intent.to
10473
+ });
10474
+ if (deletion.isErr()) return deletion;
10475
+ const applied = applyDocumentOps(document, deletion.value.ops);
10476
+ if (applied.isErr()) return Result.err(applied.error);
10477
+ const at = deletion.value.selection;
10478
+ const target = selectedParagraphRuns(applied.value.document, at, at);
10479
+ if (target.isErr()) return Result.err(target.error);
10480
+ const paragraph = target.value.at(0)?.at(0)?.paragraph;
10481
+ if (!paragraph) return refuse("Hyperlink insertion lost its paragraph.");
10482
+ const gap = resolveGap({
10483
+ paragraph,
10484
+ position: at,
10485
+ fallback: "insertion"
10486
+ });
10487
+ if (typeof gap !== "object") return refuse("Invalid hyperlink insertion gap.", gap);
10488
+ const [before = [], after = []] = partitionContent(paragraph.content, [gap]);
10489
+ const replacement = asParagraphContent(before).concat(content, asParagraphContent(after));
10490
+ return Result.ok({
10491
+ ops: deletion.value.ops.concat([{
10492
+ type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
10493
+ story: at.story,
10494
+ blockId: at.blockId,
10495
+ expected: paragraph.content,
10496
+ content: replacement
10497
+ }]),
10498
+ selection: {
10499
+ ...at,
10500
+ offset: at.offset + intent.text.length,
10501
+ zeroWidthBefore: 0
10502
+ }
10503
+ });
10504
+ }
10505
+ const ops = [];
10506
+ for (const piece of pieces) {
10507
+ if (piece.from.offset === piece.to.offset) continue;
10508
+ const children = linkedChildren(piece.middle, intent);
10509
+ const replacement = intent.type === "setHyperlink" ? wrapLinkedChildren(intent, children) : children;
10510
+ if (structurallyEqual(piece.middle, replacement)) continue;
10511
+ ops.push({
10512
+ type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
10513
+ story: intent.from.story,
10514
+ blockId: piece.from.blockId,
10515
+ expected: piece.paragraph.content,
10516
+ content: piece.before.concat(replacement, piece.after)
10517
+ });
10518
+ }
10519
+ return Result.ok({
10520
+ ops,
10521
+ selection: intent.to
10522
+ });
10523
+ };
10524
+ //#endregion
10525
+ //#region src/ops/editorIntentCensus.ts
10526
+ const sameFieldsExcept = (before, after, excluded) => {
10527
+ const beforeFields = Object.entries(before).filter(([key]) => !excluded.has(key));
10528
+ const afterFields = new Map(Object.entries(after).filter(([key]) => !excluded.has(key)));
10529
+ return beforeFields.length === afterFields.size && beforeFields.every(([key, value]) => afterFields.has(key) && afterFields.get(key) === value);
10530
+ };
10531
+ const PACKAGE_CONTENT_FIELDS = /* @__PURE__ */ new Set(["document"]);
10532
+ const DOCUMENT_CONTENT_FIELDS = /* @__PURE__ */ new Set(["content", "sections"]);
10533
+ const adjustCounts = ({ counts, keys, delta }) => {
10534
+ for (const key of keys) {
10535
+ const count = (counts.get(key) ?? 0) + delta;
10536
+ if (count < 0) panic("An incremental identity census cannot have a negative count.");
10537
+ if (count === 0) counts.delete(key);
10538
+ else counts.set(key, count);
10539
+ }
10540
+ };
10541
+ const censusOf = (identities, paragraphs) => {
10542
+ const idsIn = (space) => new Set([...identities.keys()].filter((key) => key.startsWith(`${space}:`)).map((key) => Number(key.slice(space.length + 1))));
10543
+ return {
10544
+ revisions: idsIn(IDENTITY_SPACES.REVISION),
10545
+ controls: idsIn(IDENTITY_SPACES.CONTROL),
10546
+ paragraphs: new Set(paragraphs.keys()),
10547
+ stories: /* @__PURE__ */ new Map()
10548
+ };
10549
+ };
10550
+ /** Cache immutable versions and update plain main stories without walking unchanged leaves. */
10551
+ const createCensusReader = () => {
10552
+ const versions = /* @__PURE__ */ new WeakMap();
10553
+ const paragraphKeys = /* @__PURE__ */ new WeakMap();
10554
+ let latest;
10555
+ const keysOf = (paragraph) => {
10556
+ let keys = paragraphKeys.get(paragraph);
10557
+ if (keys === void 0) {
10558
+ keys = {
10559
+ identities: identityKeysIn(paragraph).concat(reservedIdentityKeysIn(paragraph)),
10560
+ paragraphs: paragraphIdsIn(paragraph).map(idKey)
10561
+ };
10562
+ paragraphKeys.set(paragraph, keys);
10563
+ }
10564
+ return keys;
10565
+ };
10566
+ return (document) => {
10567
+ const cached = versions.get(document);
10568
+ if (cached !== void 0) {
10569
+ latest = cached;
10570
+ return cached.census;
10571
+ }
10572
+ const before = latest;
10573
+ const oldContent = before?.document.package.document.content;
10574
+ const content = document.package.document.content;
10575
+ let identities;
10576
+ let paragraphs;
10577
+ if (before !== void 0 && oldContent !== void 0 && oldContent.every((block) => block.type === "paragraph") && content.every((block) => block.type === "paragraph") && sameFieldsExcept(before.document.package, document.package, PACKAGE_CONTENT_FIELDS) && sameFieldsExcept(before.document.package.document, document.package.document, DOCUMENT_CONTENT_FIELDS)) {
10578
+ identities = new Map(before.identities);
10579
+ paragraphs = new Map(before.paragraphs);
10580
+ const changed = /* @__PURE__ */ new Map();
10581
+ for (const paragraph of oldContent) changed.set(paragraph, (changed.get(paragraph) ?? 0) - 1);
10582
+ for (const paragraph of content) changed.set(paragraph, (changed.get(paragraph) ?? 0) + 1);
10583
+ for (const [paragraph, delta] of changed) {
10584
+ if (delta === 0) continue;
10585
+ const keys = keysOf(paragraph);
10586
+ adjustCounts({
10587
+ counts: identities,
10588
+ keys: keys.identities,
10589
+ delta
10590
+ });
10591
+ adjustCounts({
10592
+ counts: paragraphs,
10593
+ keys: keys.paragraphs,
10594
+ delta
10595
+ });
10596
+ }
10597
+ } else {
10598
+ identities = countKeys(packageIdentityKeys(document.package).concat(reservedIdentityKeysIn(document.package)));
10599
+ paragraphs = countKeys(packageParagraphIds(document.package).map(idKey));
10600
+ }
10601
+ const version = {
10602
+ document,
10603
+ identities,
10604
+ paragraphs,
10605
+ census: censusOf(identities, paragraphs)
10606
+ };
10607
+ versions.set(document, version);
10608
+ latest = version;
10609
+ return version.census;
10610
+ };
10611
+ };
10612
+ //#endregion
9712
10613
  //#region src/ops/rangeReplacement.ts
9713
10614
  /** Tracked replacement fragments share deletion's validation and physical-id pool. */
9714
10615
  /** Own inserted marks can be cancelled, moving the prefix to its next live paragraph. */
@@ -9740,7 +10641,7 @@ const planTrackedReplace = (document, options) => {
9740
10641
  opType: DOCUMENT_OP_TYPES.INSERT_CONTENT
9741
10642
  }));
9742
10643
  if (replacement.tail.openStart !== 0 || replacement.tail.openEnd !== 0) return refuse("Tracked replacement requires a closed tail slice.");
9743
- if (identityKeysIn(replacement).length > 0 || replacement.paragraphs.some(({ sectionProperties }) => sectionProperties !== void 0)) return refuse("Tracked replacement cannot insert identified review, content-control or section records.");
10644
+ if (replacement.paragraphs.some(({ sectionProperties }) => sectionProperties !== void 0)) return refuse("Tracked replacement cannot import section-bearing paragraphs.");
9744
10645
  const plan = createTrackedPlan({
9745
10646
  document,
9746
10647
  revision,
@@ -9752,6 +10653,35 @@ const planTrackedReplace = (document, options) => {
9752
10653
  plan
9753
10654
  });
9754
10655
  if (deleted.isErr()) return Result.err(deleted.error);
10656
+ if (options.sourceContainerPolicy === "separate" && (replacement.tail.content.length > 0 || replacement.paragraphs.some((paragraph) => paragraph.content.length > 0))) {
10657
+ const deletionIds = new Set(plan.ops.flatMap((op) => op.type === DOCUMENT_OP_TYPES.DELETE_RANGE && op.revision !== void 0 ? [op.revision.id] : []));
10658
+ const deletionBlocks = new Set(plan.ops.flatMap((op) => {
10659
+ if (op.type === DOCUMENT_OP_TYPES.DELETE_RANGE) return [idKey(op.from.blockId)];
10660
+ if (op.type === DOCUMENT_OP_TYPES.JOIN_BLOCKS) return [idKey(op.nextBlockId)];
10661
+ return [];
10662
+ }));
10663
+ const breakRemovedSeam = (node) => {
10664
+ let next = node;
10665
+ if (node.type === "deletion" && deletionIds.has(node.info.id) && node.resolutionJoins !== void 0 && node.resolutionJoins.remove > 0) next = Object.assign({}, node, { resolutionJoins: Object.assign({}, node.resolutionJoins, { remove: 0 }) });
10666
+ const children = childNodes(next);
10667
+ if (children === void 0) return next;
10668
+ const changed = children.map(breakRemovedSeam);
10669
+ return changed.every((child, index) => child === children[index]) ? next : rebuildNode(next, changed);
10670
+ };
10671
+ for (const { paragraph } of storyParagraphs(storyBody(plan.document(), from.story))) {
10672
+ if (!deletionBlocks.has(idKey(paragraph.paraId ?? ""))) continue;
10673
+ const content = paragraph.content.map(breakRemovedSeam);
10674
+ if (content.every((node, index) => node === paragraph.content[index])) continue;
10675
+ const patched = plan.append({
10676
+ type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
10677
+ story: from.story,
10678
+ blockId: paragraph.paraId ?? "",
10679
+ expected: paragraph.content,
10680
+ content: asParagraphContent(content)
10681
+ });
10682
+ if (patched.isErr()) return Result.err(patched.error);
10683
+ }
10684
+ }
9755
10685
  let at = rangeStartAfterDeletion({
9756
10686
  before: document,
9757
10687
  after: plan.document(),
@@ -9775,11 +10705,12 @@ const planTrackedReplace = (document, options) => {
9775
10705
  openStart: 0,
9776
10706
  openEnd: 0
9777
10707
  },
10708
+ ...options.seamPolicy === void 0 ? {} : { seamPolicy: options.seamPolicy },
9778
10709
  revision
9779
10710
  });
9780
10711
  if (inserted.isErr()) return Result.err(inserted.error);
9781
10712
  }
9782
- const { type: _type, paraId, content: _content, sectionProperties: _section, pPrMark: _mark, ...newParagraph } = paragraph;
10713
+ const { type: _type, paraId, content: _content, sectionProperties: _section, pPrMark: _mark, propertyChanges: _changes, ...newParagraph } = paragraph;
9783
10714
  const split = plan.append({
9784
10715
  type: DOCUMENT_OP_TYPES.SPLIT_BLOCK,
9785
10716
  at: {
@@ -9823,6 +10754,11 @@ const intentEndpoints = (intent) => {
9823
10754
  fromOffset: 0,
9824
10755
  toOffset: 0
9825
10756
  };
10757
+ case "setHyperlink":
10758
+ case "removeHyperlink":
10759
+ case "insertHyperlink":
10760
+ case "replaceFragment":
10761
+ case "moveFragment":
9826
10762
  case "replaceText":
9827
10763
  case "insertAtom":
9828
10764
  case "formatRun": return {
@@ -9839,6 +10775,13 @@ const intentEndpoints = (intent) => {
9839
10775
  fromOffset: void 0,
9840
10776
  toOffset: void 0
9841
10777
  };
10778
+ case "generateTOC": return {
10779
+ story: intent.at.story,
10780
+ fromId: intent.at.blockId,
10781
+ toId: intent.at.blockId,
10782
+ fromOffset: intent.at.offset,
10783
+ toOffset: intent.at.offset
10784
+ };
9842
10785
  case "setList": {
9843
10786
  const first = intent.items.at(0);
9844
10787
  const last = intent.items.at(-1);
@@ -9894,6 +10837,19 @@ const createEditorIntentIdAllocator = () => {
9894
10837
  demand += leafRevisionDemand(span.ancestors.length);
9895
10838
  }
9896
10839
  }
10840
+ const incoming = intent.type === "replaceFragment" || intent.type === "moveFragment" ? intent.paragraphs : [];
10841
+ for (const paragraph of incoming) {
10842
+ demand += 4;
10843
+ for (const span of leafSpans(paragraph.content)) demand += 4 * (1 + span.ancestors.length);
10844
+ }
10845
+ if (incoming.length > 0) demand += 8;
10846
+ if (intent.type === "moveFragment") {
10847
+ const target = storyParagraphs(storyBody(document, intent.target.story)).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(intent.target.blockId));
10848
+ if (target !== void 0) {
10849
+ demand += 3;
10850
+ for (const span of leafSpans(target.paragraph.content)) demand += 4 * (1 + span.ancestors.length);
10851
+ }
10852
+ }
9897
10853
  const fresh = (occupied, count) => {
9898
10854
  const ids = [];
9899
10855
  for (let id = 1; id <= 2147483647 && ids.length < count; id += 1) if (!occupied.has(id)) ids.push(id);
@@ -10025,6 +10981,144 @@ const splitParagraphFields = (document, at) => {
10025
10981
  const survivor = editorParagraphGroups(document, at.story).find(({ paragraphs }) => paragraphs.some(({ paraId }) => idKey(paraId ?? "") === idKey(at.blockId)))?.paragraphs.at(-1);
10026
10982
  return survivor?.formatting === void 0 ? {} : { formatting: survivor.formatting };
10027
10983
  };
10984
+ /** A compound intent consumes one identity pool across its sequential plans. */
10985
+ const modeAfterOps = (document, mode) => {
10986
+ if (mode.newIds === void 0) return mode;
10987
+ const occupied = new Set(packageIdentityKeys(document.package).concat(reservedIdentityKeysIn(document.package)));
10988
+ const revisionIds = mode.newIds.revision?.filter((id) => !occupied.has(`${IDENTITY_SPACES.REVISION}:${id}`));
10989
+ const controlIds = mode.newIds.control?.filter((id) => !occupied.has(`${IDENTITY_SPACES.CONTROL}:${id}`));
10990
+ const newIds = {
10991
+ ...revisionIds === void 0 ? {} : { revision: revisionIds },
10992
+ ...controlIds === void 0 ? {} : { control: controlIds }
10993
+ };
10994
+ if (mode.type === "editing") return {
10995
+ type: "editing",
10996
+ newIds
10997
+ };
10998
+ if (!occupied.has(`${IDENTITY_SPACES.REVISION}:${mode.revision.id}`)) return {
10999
+ type: "suggesting",
11000
+ revision: mode.revision,
11001
+ newIds
11002
+ };
11003
+ const id = newIds.revision?.at(0) ?? 2147483648;
11004
+ return {
11005
+ type: "suggesting",
11006
+ revision: {
11007
+ ...mode.revision,
11008
+ id
11009
+ },
11010
+ newIds: {
11011
+ ...newIds,
11012
+ ...revisionIds === void 0 ? {} : { revision: revisionIds.slice(1) }
11013
+ }
11014
+ };
11015
+ };
11016
+ /** Imported identities are package-local facts, never destination identities. */
11017
+ const isCopiedRangeStart = (value) => "type" in value && (value.type === "bookmarkStart" || value.type === "moveFromRangeStart" || value.type === "moveToRangeStart");
11018
+ const isCopiedRangeMarker = (value) => isCopiedRangeStart(value) || "type" in value && (value.type === "bookmarkEnd" || value.type === "moveFromRangeEnd" || value.type === "moveToRangeEnd");
11019
+ const isMoveAnchor = (node) => isCommentAnchor(node) || isParagraphContent(node) && isRangeBoundary(node);
11020
+ /** Suggested moves retain source anchors; their inserted copy carries only tracked content. */
11021
+ const withoutMoveAnchors = (nodes) => {
11022
+ const out = [];
11023
+ for (const node of nodes) {
11024
+ if (isMoveAnchor(node)) continue;
11025
+ const children = childNodes(node);
11026
+ const retained = children === void 0 ? node : rebuildNode(node, withoutMoveAnchors(children));
11027
+ if (!isEmptyRecord(retained)) out.push(retained);
11028
+ }
11029
+ return out;
11030
+ };
11031
+ const identifyClipboardParagraphs = ({ document, paragraphs, mode, firstBlockId }) => {
11032
+ const copy = cloneModel([...paragraphs]);
11033
+ const occupied = new Set(packageIdentityKeys(document.package).concat(reservedIdentityKeysIn(document.package)));
11034
+ for (const id of mode.newIds?.revision ?? []) occupied.add(`${IDENTITY_SPACES.REVISION}:${id}`);
11035
+ for (const id of mode.newIds?.control ?? []) occupied.add(`${IDENTITY_SPACES.CONTROL}:${id}`);
11036
+ if (mode.type === "suggesting") occupied.add(`${IDENTITY_SPACES.REVISION}:${mode.revision.id}`);
11037
+ const blockIds = new Set(packageParagraphIds(document.package).map(idKey));
11038
+ const markers = /* @__PURE__ */ new Set();
11039
+ const names = /* @__PURE__ */ new Set();
11040
+ const renamedBookmarks = /* @__PURE__ */ new Map();
11041
+ const visit = (value, callback) => {
11042
+ if (typeof value !== "object" || value === null) return;
11043
+ if (Array.isArray(value)) {
11044
+ for (const item of value) visit(item, callback);
11045
+ return;
11046
+ }
11047
+ callback(value);
11048
+ for (const field of Object.values(value)) visit(field, callback);
11049
+ };
11050
+ visit(document.package, (value) => {
11051
+ if ("type" in value && "id" in value && typeof value.id === "number" && isCopiedRangeMarker(value)) markers.add(value.id);
11052
+ if (isCopiedRangeStart(value) && "name" in value && typeof value.name === "string") names.add(value.name);
11053
+ });
11054
+ visit(copy, (value) => {
11055
+ if (!isCopiedRangeStart(value) || !("name" in value) || typeof value.name !== "string") return;
11056
+ const original = value.name;
11057
+ const renamed = renamedBookmarks.get(original);
11058
+ if (renamed !== void 0) {
11059
+ value.name = renamed;
11060
+ return;
11061
+ }
11062
+ let name = original;
11063
+ let suffix = 1;
11064
+ while (names.has(name)) {
11065
+ name = `${original}_paste${suffix}`;
11066
+ suffix += 1;
11067
+ }
11068
+ names.add(name);
11069
+ renamedBookmarks.set(original, name);
11070
+ value.name = name;
11071
+ });
11072
+ const remapped = /* @__PURE__ */ new Map();
11073
+ const nextInSpace = /* @__PURE__ */ new Map();
11074
+ let nextBlock = firstBlockId ?? 1;
11075
+ const freshBlock = () => {
11076
+ while (nextBlock <= 2147483647 && blockIds.has(nextBlock.toString(16).padStart(8, "0").toUpperCase())) nextBlock += 1;
11077
+ if (nextBlock > 2147483647) return void 0;
11078
+ const id = nextBlock.toString(16).padStart(8, "0").toUpperCase();
11079
+ blockIds.add(id);
11080
+ nextBlock += 1;
11081
+ return id;
11082
+ };
11083
+ const freshId = (space, oldId) => {
11084
+ const key = `${space}:${oldId}`;
11085
+ const existing = remapped.get(key);
11086
+ if (existing !== void 0) return existing;
11087
+ let id = nextInSpace.get(space) ?? 1;
11088
+ while (space === "bookmark" ? markers.has(id) : occupied.has(`${space}:${id}`)) id += 1;
11089
+ if (space === "bookmark") markers.add(id);
11090
+ else occupied.add(`${space}:${id}`);
11091
+ remapped.set(key, id);
11092
+ nextInSpace.set(space, id + 1);
11093
+ return id;
11094
+ };
11095
+ const remintedControls = /* @__PURE__ */ new WeakSet();
11096
+ visit(copy, (value) => {
11097
+ if ("type" in value && value.type === "inlineSdt" && "properties" in value && typeof value.properties === "object" && value.properties !== null && "id" in value.properties && typeof value.properties.id === "number") {
11098
+ value.properties.id = freshId(IDENTITY_SPACES.CONTROL, value.properties.id);
11099
+ remintedControls.add(value.properties);
11100
+ }
11101
+ if ("type" in value && value.type === "hyperlink" && "anchor" in value && typeof value.anchor === "string") value.anchor = renamedBookmarks.get(value.anchor) ?? value.anchor;
11102
+ if ("id" in value && typeof value.id === "number" && !remintedControls.has(value)) {
11103
+ if ("space" in value && (value.space === IDENTITY_SPACES.REVISION || value.space === IDENTITY_SPACES.CONTROL)) value.id = freshId(value.space, value.id);
11104
+ else if ("sdtType" in value) value.id = freshId(IDENTITY_SPACES.CONTROL, value.id);
11105
+ else if ("author" in value && !("type" in value)) value.id = freshId(IDENTITY_SPACES.REVISION, value.id);
11106
+ else if (isCopiedRangeMarker(value)) value.id = freshId("bookmark", value.id);
11107
+ }
11108
+ });
11109
+ for (const [index, paragraph] of copy.entries()) {
11110
+ delete paragraph.paraId;
11111
+ if (index === copy.length - 1) continue;
11112
+ const id = freshBlock();
11113
+ if (id === void 0) return Result.err(new DocumentOpRefusal({
11114
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID,
11115
+ message: "The pasted block identity allocator is exhausted.",
11116
+ opType: DOCUMENT_OP_TYPES.SPLIT_BLOCK
11117
+ }));
11118
+ paragraph.paraId = id;
11119
+ }
11120
+ return Result.ok(copy);
11121
+ };
10028
11122
  /** Direct and tracked joins choose paragraph properties from the same editing-view group. */
10029
11123
  const joinParagraphPropertyAlignment = ({ document, current, intent, revision }) => {
10030
11124
  const groups = editorParagraphGroups(document, intent.story);
@@ -10064,7 +11158,12 @@ const textSeamDepth = (paragraph, offset) => {
10064
11158
  return 0;
10065
11159
  };
10066
11160
  /** Compile one batch; the caller applies it atomically and journals its exact inverse. */
10067
- const compileEditorIntent = (document, { intent, mode }) => {
11161
+ const compileEditorIntent = (document, { intent, mode, firstBlockId }) => {
11162
+ if (firstBlockId !== void 0 && (!Number.isInteger(firstBlockId) || firstBlockId < 1 || firstBlockId > 2147483648)) return Result.err(new DocumentOpRefusal({
11163
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID,
11164
+ message: "The pasted block identity allocator is exhausted or invalid.",
11165
+ opType: DOCUMENT_OP_TYPES.SPLIT_BLOCK
11166
+ }));
10068
11167
  const allocationFields = mode.newIds === void 0 ? {} : { newIds: mode.newIds };
10069
11168
  const tracked = mode.type === "suggesting" ? {
10070
11169
  revision: mode.revision,
@@ -10072,14 +11171,486 @@ const compileEditorIntent = (document, { intent, mode }) => {
10072
11171
  } : allocationFields;
10073
11172
  let ops;
10074
11173
  let selection;
11174
+ const editedSeams = [];
10075
11175
  switch (intent.type) {
11176
+ case "generateTOC": {
11177
+ const compiled = compileGenerateTOCIntent(document, intent, mode);
11178
+ if (compiled.isErr()) return compiled;
11179
+ ops = compiled.value.ops;
11180
+ selection = compiled.value.selection;
11181
+ break;
11182
+ }
11183
+ case "setHyperlink":
11184
+ case "removeHyperlink":
11185
+ case "insertHyperlink": return compileHyperlinkIntent(document, {
11186
+ intent,
11187
+ mode,
11188
+ compileEmptyReplacement: (source, { from, to }) => compileEditorIntent(source, {
11189
+ intent: {
11190
+ type: "replaceText",
11191
+ from,
11192
+ to,
11193
+ text: ""
11194
+ },
11195
+ mode
11196
+ })
11197
+ });
11198
+ case "replaceFragment": {
11199
+ if (intent.paragraphs.length === 0) return compileEditorIntent(document, {
11200
+ intent: {
11201
+ type: "replaceText",
11202
+ from: intent.from,
11203
+ to: intent.to,
11204
+ text: ""
11205
+ },
11206
+ mode
11207
+ });
11208
+ const destination = paragraphAt(document, intent.from);
11209
+ if (destination === void 0) return Result.err(new DocumentOpRefusal({
11210
+ reason: DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND,
11211
+ message: "The clipboard destination paragraph does not exist.",
11212
+ opType: DOCUMENT_OP_TYPES.INSERT_CONTENT
11213
+ }));
11214
+ const endpoint = paragraphAt(document, intent.to);
11215
+ const destinationFormatting = splitParagraphFields(document, intent.from).formatting;
11216
+ const endpointFormatting = splitParagraphFields(document, intent.to).formatting;
11217
+ const prefixBoundary = intent.openStart === 0 && intent.from.offset > 0;
11218
+ const suffixBoundary = intent.openEnd === 0 && endpoint !== void 0 && intent.to.offset < paragraphLength(endpoint);
11219
+ const normalized = [
11220
+ ...prefixBoundary ? [{
11221
+ type: "paragraph",
11222
+ content: [],
11223
+ ...destinationFormatting === void 0 ? {} : { formatting: destinationFormatting }
11224
+ }] : [],
11225
+ ...intent.paragraphs,
11226
+ ...suffixBoundary ? [{
11227
+ type: "paragraph",
11228
+ content: [],
11229
+ ...endpointFormatting === void 0 ? {} : { formatting: endpointFormatting }
11230
+ }] : []
11231
+ ];
11232
+ const identified = identifyClipboardParagraphs({
11233
+ document,
11234
+ paragraphs: normalized,
11235
+ mode,
11236
+ firstBlockId
11237
+ });
11238
+ if (identified.isErr()) return identified;
11239
+ const paragraphs = identified.value;
11240
+ for (const [index, paragraph] of paragraphs.entries()) {
11241
+ const openStart = index === 0 && intent.openStart === 1;
11242
+ const openEnd = index === normalized.length - 1 && intent.openEnd === 1;
11243
+ if (!openStart && !openEnd) continue;
11244
+ delete paragraph.propertyChanges;
11245
+ delete paragraph.pPrMark;
11246
+ delete paragraph.reviewCarrier;
11247
+ delete paragraph.sectionProperties;
11248
+ delete paragraph.formatting;
11249
+ const inherited = openStart ? destinationFormatting : endpointFormatting;
11250
+ if (inherited !== void 0) paragraph.formatting = inherited;
11251
+ }
11252
+ if (paragraphs.some((paragraph) => paragraph.reviewCarrier !== void 0)) return Result.err(new DocumentOpRefusal({
11253
+ reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
11254
+ message: "A clipboard paragraph cannot import a private review-resolution carrier.",
11255
+ opType: DOCUMENT_OP_TYPES.INSERT_CONTENT
11256
+ }));
11257
+ if (paragraphs.some((paragraph) => (paragraph.sectionProperties?.headerReferences?.length ?? 0) > 0 || (paragraph.sectionProperties?.footerReferences?.length ?? 0) > 0)) return Result.err(new DocumentOpRefusal({
11258
+ reason: DOCUMENT_OP_REFUSAL_REASONS.SECTION_BOUNDARY,
11259
+ message: "Clipboard section headers and footers require importing their source package parts.",
11260
+ opType: DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT
11261
+ }));
11262
+ if (mode.type === "suggesting" && paragraphs.some((paragraph) => paragraph.pPrMark !== void 0)) return Result.err(new DocumentOpRefusal({
11263
+ reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
11264
+ message: "A copied paragraph mark cannot coexist with the tracked paste mark in the paragraph's single mark slot.",
11265
+ opType: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW
11266
+ }));
11267
+ const tail = paragraphs.at(-1);
11268
+ if (mode.type === "suggesting" && tail !== void 0 && (tail.sectionProperties !== void 0 || tail.pPrMark !== void 0 || (tail.propertyChanges?.length ?? 0) > 0)) return Result.err(new DocumentOpRefusal({
11269
+ reason: DOCUMENT_OP_REFUSAL_REASONS.UNTRACKABLE,
11270
+ message: "A tracked paste cannot attach copied paragraph review or section metadata to a retained destination mark without a separately rejectable mark change.",
11271
+ opType: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW
11272
+ }));
11273
+ const leading = paragraphs.slice(0, -1);
11274
+ if (mode.type === "suggesting") {
11275
+ const planned = planTrackedReplace(document, {
11276
+ sourceContainerPolicy: "separate",
11277
+ from: intent.from,
11278
+ to: intent.to,
11279
+ revision: mode.revision,
11280
+ newIds: mode.newIds,
11281
+ seamPolicy: INSERTION_SEAM_POLICIES.MERGE_PLAIN_RUNS,
11282
+ replacement: {
11283
+ paragraphs: leading.map(({ sectionProperties: _section, ...paragraph }) => paragraph),
11284
+ tail: {
11285
+ openStart: 0,
11286
+ openEnd: 0,
11287
+ content: tail?.content ?? []
11288
+ }
11289
+ }
11290
+ });
11291
+ if (planned.isErr()) return Result.err(planned.error);
11292
+ ops = planned.value;
11293
+ const applied = applyDocumentOps(document, ops);
11294
+ if (applied.isErr()) return Result.err(applied.error);
11295
+ const at = rangeStartAfterDeletion({
11296
+ before: document,
11297
+ after: applied.value.document,
11298
+ from: intent.from,
11299
+ to: intent.to
11300
+ });
11301
+ const insertionAt = leading.length > 0 ? {
11302
+ ...at,
11303
+ offset: 0,
11304
+ zeroWidthBefore: 0
11305
+ } : at;
11306
+ const insertionParagraph = paragraphAt(document, insertionAt);
11307
+ selection = {
11308
+ ...insertionAt,
11309
+ ...gapAfterInserted({
11310
+ offset: insertionAt.offset,
11311
+ zeroWidthBefore: insertionAt.zeroWidthBefore ?? (insertionParagraph === void 0 ? 0 : defaultInsertionGap(insertionParagraph.content, insertionAt.offset).zeroWidthBefore)
11312
+ }, tail?.content ?? [])
11313
+ };
11314
+ } else {
11315
+ const deleted = compileEditorIntent(document, {
11316
+ intent: {
11317
+ type: "replaceText",
11318
+ from: intent.from,
11319
+ to: intent.to,
11320
+ text: ""
11321
+ },
11322
+ mode
11323
+ });
11324
+ if (deleted.isErr()) return deleted;
11325
+ ops = [...deleted.value.ops];
11326
+ let at = {
11327
+ ...deleted.value.selection,
11328
+ zeroWidthBefore: deleted.value.selection.zeroWidthBefore ?? defaultInsertionGap(destination.content, intent.from.offset).zeroWidthBefore
11329
+ };
11330
+ for (const paragraph of leading) {
11331
+ if (paragraph.content.length > 0) ops.push({
11332
+ type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
11333
+ at,
11334
+ slice: {
11335
+ openStart: 0,
11336
+ openEnd: 0,
11337
+ content: paragraph.content
11338
+ },
11339
+ seamPolicy: INSERTION_SEAM_POLICIES.MERGE_PLAIN_RUNS,
11340
+ ...allocationFields
11341
+ });
11342
+ const { type: _type, paraId, content: _content, sectionProperties: _section, pPrMark: _mark, ...newParagraph } = paragraph;
11343
+ ops.push({
11344
+ type: DOCUMENT_OP_TYPES.SPLIT_BLOCK,
11345
+ at: {
11346
+ ...at,
11347
+ ...gapAfterInserted({
11348
+ offset: at.offset,
11349
+ zeroWidthBefore: at.zeroWidthBefore ?? 0
11350
+ }, paragraph.content)
11351
+ },
11352
+ newBlockId: paraId ?? "",
11353
+ newHalf: SPLIT_HALVES.FIRST,
11354
+ newParagraph,
11355
+ ...allocationFields
11356
+ });
11357
+ at = {
11358
+ story: at.story,
11359
+ blockId: at.blockId,
11360
+ offset: 0,
11361
+ zeroWidthBefore: 0
11362
+ };
11363
+ }
11364
+ if (tail !== void 0 && tail.content.length > 0) ops.push({
11365
+ type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
11366
+ at,
11367
+ slice: {
11368
+ openStart: 0,
11369
+ openEnd: 0,
11370
+ content: tail.content
11371
+ },
11372
+ ...allocationFields
11373
+ });
11374
+ selection = {
11375
+ ...at,
11376
+ ...gapAfterInserted({
11377
+ offset: at.offset,
11378
+ zeroWidthBefore: at.zeroWidthBefore ?? 0
11379
+ }, tail?.content ?? [])
11380
+ };
11381
+ }
11382
+ if (mode.type === "editing" && intent.openStart === 1 && leading.length > 0) {
11383
+ const first = leading.at(0);
11384
+ if (first?.paraId === void 0) panic("An identified leading clipboard paragraph must have an id.");
11385
+ editedSeams.push({
11386
+ story: intent.from.story,
11387
+ blockId: first.paraId,
11388
+ offset: intent.from.offset
11389
+ });
11390
+ }
11391
+ if (tail !== void 0) {
11392
+ const applied = applyDocumentOps(document, ops);
11393
+ if (applied.isErr()) return Result.err(applied.error);
11394
+ const trailing = editorParagraphGroups(applied.value.document, selection.story).find(({ paragraphs: group }) => group.some(({ paraId }) => idKey(paraId ?? "") === idKey(selection.blockId)))?.paragraphs.at(-1);
11395
+ const trailingMarkAt = trailing?.paraId === void 0 ? selection : {
11396
+ ...selection,
11397
+ blockId: trailing.paraId,
11398
+ offset: 0
11399
+ };
11400
+ const current = paragraphAt(applied.value.document, trailingMarkAt);
11401
+ const patch = Object.fromEntries([...Object.keys(current?.formatting ?? {}).map((key) => [key, null]), ...Object.entries(tail.formatting ?? {})]);
11402
+ const formatting = compileEditorIntent(applied.value.document, {
11403
+ intent: {
11404
+ type: "formatParagraph",
11405
+ at: trailingMarkAt,
11406
+ patch
11407
+ },
11408
+ mode: modeAfterOps(applied.value.document, mode)
11409
+ });
11410
+ if (formatting.isErr()) return formatting;
11411
+ ops.push(...formatting.value.ops);
11412
+ }
11413
+ for (const [index, paragraph] of paragraphs.entries()) {
11414
+ if (paragraph.pPrMark === void 0 && (paragraph.propertyChanges?.length ?? 0) === 0 && paragraph.sectionProperties === void 0) continue;
11415
+ const blockId = index === paragraphs.length - 1 ? selection.blockId : paragraph.paraId ?? "";
11416
+ const applied = applyDocumentOps(document, ops);
11417
+ if (applied.isErr()) return Result.err(applied.error);
11418
+ const current = paragraphAt(applied.value.document, {
11419
+ story: selection.story,
11420
+ blockId,
11421
+ offset: 0
11422
+ });
11423
+ if (current === void 0) panic("An allocated clipboard paragraph must remain present.");
11424
+ if (paragraph.pPrMark !== void 0 && current.pPrMark !== void 0) return Result.err(new DocumentOpRefusal({
11425
+ reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
11426
+ message: "A copied paragraph mark cannot replace the destination's pending paragraph mark.",
11427
+ opType: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW
11428
+ }));
11429
+ const expected = reviewFieldsOf(current);
11430
+ const copiedChange = paragraph.propertyChanges?.at(0);
11431
+ const currentChange = current.propertyChanges?.at(0);
11432
+ if (copiedChange !== void 0 && currentChange !== void 0 && packageIdentityKeys(document.package).includes(`${IDENTITY_SPACES.REVISION}:${currentChange.info.id}`)) return Result.err(new DocumentOpRefusal({
11433
+ reason: DOCUMENT_OP_REFUSAL_REASONS.REVISION_CONFLICT,
11434
+ message: "Copied paragraph review cannot replace a pre-existing destination review.",
11435
+ opType: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW
11436
+ }));
11437
+ const changes = [...paragraph.propertyChanges ?? current.propertyChanges ?? []];
11438
+ if (paragraph.pPrMark !== void 0 || copiedChange !== void 0) {
11439
+ const review = reviewFieldsOf(current);
11440
+ if (changes.length > 0) review.propertyChanges = changes;
11441
+ if (paragraph.pPrMark !== void 0) review.pPrMark = paragraph.pPrMark;
11442
+ ops.push({
11443
+ type: DOCUMENT_OP_TYPES.SET_PARAGRAPH_REVIEW,
11444
+ story: selection.story,
11445
+ blockId,
11446
+ expected,
11447
+ review
11448
+ });
11449
+ }
11450
+ if (paragraph.sectionProperties !== void 0) ops.push({
11451
+ type: DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT,
11452
+ endpoint: {
11453
+ type: "paragraph",
11454
+ blockId
11455
+ },
11456
+ expected: current.sectionProperties === void 0 ? { type: Object.hasOwn(current, "sectionProperties") ? "undefined" : "omitted" } : {
11457
+ type: "present",
11458
+ value: current.sectionProperties
11459
+ },
11460
+ properties: {
11461
+ type: "present",
11462
+ value: paragraph.sectionProperties
11463
+ }
11464
+ });
11465
+ }
11466
+ if (mode.type === "editing" && tail !== void 0) {
11467
+ const width = paragraphLength(tail);
11468
+ if (width > 0) {
11469
+ for (const offset of /* @__PURE__ */ new Set([selection.offset, selection.offset - width])) if (offset >= 0) editedSeams.push({
11470
+ ...selection,
11471
+ offset
11472
+ });
11473
+ }
11474
+ }
11475
+ if (intent.openEnd === 0 && endpoint !== void 0 && intent.to.offset === paragraphLength(endpoint)) {
11476
+ const bodyParagraphs = storyParagraphs(storyBody(document, intent.to.story));
11477
+ const endLocation = bodyParagraphs.find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(intent.to.blockId));
11478
+ const following = bodyParagraphs.find((location) => endLocation !== void 0 && sameBlockList(location.list, endLocation.list) && location.index === endLocation.index + 1);
11479
+ if (following?.paragraph.paraId !== void 0) selection = {
11480
+ story: intent.to.story,
11481
+ blockId: following.paragraph.paraId,
11482
+ ...defaultInsertionGap(following.paragraph.content, 0)
11483
+ };
11484
+ }
11485
+ break;
11486
+ }
11487
+ case "moveFragment": {
11488
+ const range = selectedParagraphRuns(document, intent.from, intent.to);
11489
+ if (range.isErr()) return Result.err(range.error);
11490
+ const sourceParagraph = paragraphAt(document, intent.from);
11491
+ const fromGap = intent.from.zeroWidthBefore ?? (sourceParagraph === void 0 ? 0 : zeroWidthLeavesAt(sourceParagraph.content, intent.from.offset).length);
11492
+ const toGap = intent.to.zeroWidthBefore ?? 0;
11493
+ if (idKey(intent.from.blockId) === idKey(intent.to.blockId) && intent.from.offset === intent.to.offset && fromGap >= toGap) {
11494
+ if (fromGap > toGap && (intent.from.zeroWidthBefore !== void 0 || intent.to.zeroWidthBefore !== void 0)) return Result.err(new DocumentOpRefusal({
11495
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET,
11496
+ message: "The move source marker gaps are reversed.",
11497
+ opType: DOCUMENT_OP_TYPES.DELETE_RANGE
11498
+ }));
11499
+ return Result.ok({
11500
+ ops: [],
11501
+ selection: intent.target
11502
+ });
11503
+ }
11504
+ const locations = storyParagraphs(storyBody(document, intent.from.story));
11505
+ const indexOf = (at) => locations.findIndex(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(at.blockId));
11506
+ const first = indexOf(intent.from);
11507
+ const last = indexOf(intent.to);
11508
+ const targetIndex = indexOf(intent.target);
11509
+ const targetGap = intent.target.zeroWidthBefore ?? defaultInsertionGap(paragraphAt(document, intent.target)?.content ?? [], intent.target.offset).zeroWidthBefore;
11510
+ const targetPosition = {
11511
+ offset: intent.target.offset,
11512
+ zeroWidthBefore: targetGap
11513
+ };
11514
+ if (intent.target.story === intent.from.story && targetIndex >= first && targetIndex <= last && (targetIndex !== first || compareGaps(targetPosition, {
11515
+ offset: intent.from.offset,
11516
+ zeroWidthBefore: fromGap
11517
+ }) >= 0) && (targetIndex !== last || compareGaps(targetPosition, {
11518
+ offset: intent.to.offset,
11519
+ zeroWidthBefore: toGap
11520
+ }) <= 0)) return Result.ok({
11521
+ ops: [],
11522
+ selection: intent.target
11523
+ });
11524
+ const anchorDeletions = [];
11525
+ const sourceAnchors = mode.type === "editing" ? range.value.flat() : [];
11526
+ for (const { paragraph } of sourceAnchors) {
11527
+ const blockId = paragraph.paraId ?? "";
11528
+ const from = idKey(blockId) === idKey(intent.from.blockId) ? {
11529
+ offset: intent.from.offset,
11530
+ zeroWidthBefore: fromGap
11531
+ } : {
11532
+ offset: 0,
11533
+ zeroWidthBefore: 0
11534
+ };
11535
+ const to = idKey(blockId) === idKey(intent.to.blockId) ? {
11536
+ offset: intent.to.offset,
11537
+ zeroWidthBefore: toGap
11538
+ } : {
11539
+ offset: paragraphLength(paragraph),
11540
+ zeroWidthBefore: zeroWidthLeavesAt(paragraph.content, paragraphLength(paragraph)).length
11541
+ };
11542
+ for (const span of leafSpans(paragraph.content)) {
11543
+ if (!isMoveAnchor(span.node) || span.ancestors.some(isRemovedRevisionNode) || compareGaps(span.before, from) < 0 || compareGaps(span.after, to) > 0) continue;
11544
+ anchorDeletions.push({
11545
+ type: DOCUMENT_OP_TYPES.DELETE_RANGE,
11546
+ from: {
11547
+ story: intent.from.story,
11548
+ blockId,
11549
+ ...span.before
11550
+ },
11551
+ to: {
11552
+ story: intent.from.story,
11553
+ blockId,
11554
+ ...span.after
11555
+ }
11556
+ });
11557
+ }
11558
+ }
11559
+ const deleted = compileEditorIntent(document, {
11560
+ intent: {
11561
+ type: "replaceText",
11562
+ from: intent.from,
11563
+ to: intent.to,
11564
+ text: ""
11565
+ },
11566
+ mode
11567
+ });
11568
+ if (deleted.isErr()) return deleted;
11569
+ const logicalDeletions = anchorDeletions.length === 0 ? deleted.value.ops : [...deleted.value.ops.filter((op) => op.type === DOCUMENT_OP_TYPES.DELETE_RANGE).concat(anchorDeletions).sort((left, right) => indexOf(right.from) - indexOf(left.from) || compareGaps({
11570
+ offset: right.from.offset,
11571
+ zeroWidthBefore: right.from.zeroWidthBefore ?? 0
11572
+ }, {
11573
+ offset: left.from.offset,
11574
+ zeroWidthBefore: left.from.zeroWidthBefore ?? 0
11575
+ })), ...deleted.value.ops.filter((op) => op.type !== DOCUMENT_OP_TYPES.DELETE_RANGE)];
11576
+ const anchors = new Set(anchorDeletions);
11577
+ const deletionOps = [];
11578
+ let afterDeletion = document;
11579
+ for (const planned of logicalDeletions) {
11580
+ let op = planned;
11581
+ if (planned.type === DOCUMENT_OP_TYPES.DELETE_RANGE && anchors.has(planned)) {
11582
+ const paragraph = paragraphAt(afterDeletion, planned.from);
11583
+ if (paragraph === void 0) panic("A move anchor lost its selected paragraph.");
11584
+ op = {
11585
+ type: DOCUMENT_OP_TYPES.REPLACE_INLINE,
11586
+ story: planned.from.story,
11587
+ blockId: planned.from.blockId,
11588
+ expected: paragraph.content,
11589
+ content: deleteBetween(paragraph.content, {
11590
+ offset: planned.from.offset,
11591
+ zeroWidthBefore: planned.from.zeroWidthBefore ?? 0
11592
+ }, {
11593
+ offset: planned.to.offset,
11594
+ zeroWidthBefore: planned.to.zeroWidthBefore ?? 0
11595
+ }).content
11596
+ };
11597
+ }
11598
+ const applied = applyDocumentOps(afterDeletion, [op]);
11599
+ if (applied.isErr()) return Result.err(applied.error);
11600
+ afterDeletion = applied.value.document;
11601
+ deletionOps.push(op);
11602
+ }
11603
+ let target = intent.target;
11604
+ for (const op of logicalDeletions) {
11605
+ if (op.type === DOCUMENT_OP_TYPES.DELETE_RANGE && op.revision === void 0 && idKey(target.blockId) === idKey(op.from.blockId) && target.story === op.from.story && target.offset >= op.to.offset) {
11606
+ const source = paragraphAt(document, op.from);
11607
+ const deletionFromGap = op.from.zeroWidthBefore ?? zeroWidthLeavesAt(source?.content ?? [], op.from.offset).length;
11608
+ const deletionToGap = op.to.zeroWidthBefore ?? 0;
11609
+ const deletionTargetGap = target.zeroWidthBefore ?? defaultInsertionGap(source?.content ?? [], target.offset).zeroWidthBefore;
11610
+ const rebased = Object.assign({}, target, { offset: target.offset - (op.to.offset - op.from.offset) });
11611
+ if (target.offset === op.to.offset) rebased.zeroWidthBefore = deletionFromGap + deletionTargetGap - deletionToGap;
11612
+ target = rebased;
11613
+ }
11614
+ if (op.type === DOCUMENT_OP_TYPES.JOIN_BLOCKS && op.revision === void 0 && idKey(target.blockId) === idKey(op.blockId) && target.story === op.story) target = Object.assign({}, target, { blockId: op.nextBlockId });
11615
+ else if (op.type === DOCUMENT_OP_TYPES.JOIN_BLOCKS && op.revision === void 0 && idKey(target.blockId) === idKey(op.nextBlockId) && target.story === op.story) {
11616
+ const prefix = paragraphAt(document, {
11617
+ story: op.story,
11618
+ blockId: op.blockId,
11619
+ offset: 0
11620
+ });
11621
+ const remaining = idKey(op.blockId) === idKey(intent.from.blockId) ? intent.from.offset : 0;
11622
+ if (prefix !== void 0) {
11623
+ const rebased = Object.assign({}, target, { offset: target.offset + remaining });
11624
+ if (target.offset === 0 && idKey(op.blockId) === idKey(intent.from.blockId)) rebased.zeroWidthBefore = fromGap + (target.zeroWidthBefore ?? 0);
11625
+ target = rebased;
11626
+ }
11627
+ }
11628
+ }
11629
+ const paragraphs = mode.type === "suggesting" ? intent.paragraphs.map((paragraph) => Object.assign({}, paragraph, { content: asParagraphContent(withoutMoveAnchors(paragraph.content)) })) : intent.paragraphs;
11630
+ const inserted = compileEditorIntent(afterDeletion, {
11631
+ intent: {
11632
+ type: "replaceFragment",
11633
+ from: target,
11634
+ to: target,
11635
+ paragraphs,
11636
+ openStart: intent.openStart,
11637
+ openEnd: intent.openEnd
11638
+ },
11639
+ mode: modeAfterOps(afterDeletion, mode),
11640
+ ...firstBlockId === void 0 ? {} : { firstBlockId }
11641
+ });
11642
+ if (inserted.isErr()) return inserted;
11643
+ ops = [...deletionOps, ...inserted.value.ops];
11644
+ selection = inserted.value.selection;
11645
+ break;
11646
+ }
10076
11647
  case "table": {
10077
11648
  const operation = intent.operation;
10078
11649
  const located = locateTableRow(document, operation);
10079
11650
  if (located.isErr()) return Result.err(located.error);
10080
11651
  const demand = tableEditParagraphDemand(located.value, operation);
10081
11652
  if (demand.isErr()) return Result.err(demand.error);
10082
- const occupied = new Set(packageParagraphIds(document.package).map(idKey));
11653
+ const occupied = new Set([...packageParagraphIds(document.package), ...mode.reservedBlockIds ?? []].map(idKey));
10083
11654
  const newBlockIds = [];
10084
11655
  for (let nextId = 1; newBlockIds.length < demand.value; nextId += 1) {
10085
11656
  if (nextId >= 2147483648) return Result.err(new DocumentOpRefusal({
@@ -10252,6 +11823,7 @@ const compileEditorIntent = (document, { intent, mode }) => {
10252
11823
  const formatting = intentRunFormatting(document, intent);
10253
11824
  if (mode.type === "suggesting") {
10254
11825
  const planned = planTrackedReplace(document, {
11826
+ sourceContainerPolicy: "join",
10255
11827
  from: intent.from,
10256
11828
  to: intent.to,
10257
11829
  revision: mode.revision,
@@ -10330,6 +11902,7 @@ const compileEditorIntent = (document, { intent, mode }) => {
10330
11902
  }];
10331
11903
  if (mode.type === "suggesting") {
10332
11904
  const planned = planTrackedReplace(document, {
11905
+ sourceContainerPolicy: "join",
10333
11906
  from,
10334
11907
  to,
10335
11908
  revision: mode.revision,
@@ -10365,7 +11938,7 @@ const compileEditorIntent = (document, { intent, mode }) => {
10365
11938
  }
10366
11939
  ops = [];
10367
11940
  let survivorId = from.blockId;
10368
- if (from.blockId !== to.blockId || from.offset !== to.offset) {
11941
+ if (from.blockId !== to.blockId || from.offset !== to.offset || (from.zeroWidthBefore ?? 0) !== (to.zeroWidthBefore ?? 0)) {
10369
11942
  const partitioned = selectedParagraphRuns(document, from, to);
10370
11943
  if (partitioned.isErr()) return Result.err(partitioned.error);
10371
11944
  survivorId = partitioned.value.at(0)?.at(-1)?.paragraph.paraId ?? from.blockId;
@@ -10643,14 +12216,17 @@ const compileEditorIntent = (document, { intent, mode }) => {
10643
12216
  current = aligned.value.document;
10644
12217
  }
10645
12218
  }
10646
- if (intent.type === "replaceText" && intent.text.length > 0) for (const offset of /* @__PURE__ */ new Set([selection.offset, selection.offset - intent.text.length])) {
10647
- const at = {
12219
+ const insertedWidth = intent.type === "replaceText" ? intent.text.length : 0;
12220
+ if (insertedWidth > 0) {
12221
+ for (const offset of /* @__PURE__ */ new Set([selection.offset, selection.offset - insertedWidth])) if (offset >= 0) editedSeams.push({
10648
12222
  ...selection,
10649
12223
  offset
10650
- };
12224
+ });
12225
+ }
12226
+ for (const at of editedSeams) {
10651
12227
  const paragraph = paragraphAt(current, at);
10652
12228
  if (paragraph === void 0) panic("An edited paragraph must exist at its seam.");
10653
- const depth = textSeamDepth(paragraph, offset);
12229
+ const depth = textSeamDepth(paragraph, at.offset);
10654
12230
  if (depth === 0) continue;
10655
12231
  const join = {
10656
12232
  type: DOCUMENT_OP_TYPES.JOIN_INLINE,
@@ -10955,6 +12531,7 @@ const operationFields = {
10955
12531
  createNumberingInstance: void 0,
10956
12532
  deleteNumberingInstance: void 0,
10957
12533
  setSectionEndpoint: void 0,
12534
+ setPackageResources: void 0,
10958
12535
  addNote: void 0,
10959
12536
  createHeaderFooter: void 0,
10960
12537
  removeHeaderFooter: void 0,
@@ -11011,7 +12588,7 @@ const isJsonData = ({ value, ancestors, depth, budget }) => {
11011
12588
  return valid;
11012
12589
  };
11013
12590
  const isDocumentBatch = (value) => object({
11014
- schema: literal(8),
12591
+ schema: literal(9),
11015
12592
  opId: nonemptyString,
11016
12593
  actor: nonemptyString,
11017
12594
  baseRev: natural,
@@ -11068,7 +12645,7 @@ const validateDocumentBatch = (value) => {
11068
12645
  return decoded;
11069
12646
  };
11070
12647
  const decodeDocumentBatch = (value) => {
11071
- if (value["schema"] !== 8) return Result.err(new BatchRejection({
12648
+ if (value["schema"] !== 9) return Result.err(new BatchRejection({
11072
12649
  reason: BATCH_REJECTION_REASONS.UNSUPPORTED_SCHEMA,
11073
12650
  message: "Unsupported document operation schema"
11074
12651
  }));
@@ -11173,6 +12750,7 @@ const operationStory = (op) => {
11173
12750
  case DOCUMENT_OP_TYPES.CREATE_NUMBERING_INSTANCE:
11174
12751
  case DOCUMENT_OP_TYPES.DELETE_NUMBERING_INSTANCE:
11175
12752
  case DOCUMENT_OP_TYPES.SET_SECTION_ENDPOINT:
12753
+ case DOCUMENT_OP_TYPES.SET_PACKAGE_RESOURCES:
11176
12754
  case DOCUMENT_OP_TYPES.ADD_NOTE:
11177
12755
  case DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER:
11178
12756
  case DOCUMENT_OP_TYPES.REMOVE_HEADER_FOOTER:
@@ -11209,7 +12787,7 @@ const refusal = (op, over, message) => Result.err(new BatchRejection({
11209
12787
  const transformRestoredOp = ({ op, over, effect, order }) => {
11210
12788
  const story = operationStory(op);
11211
12789
  const overStory = operationStory(over);
11212
- if (story === void 0 || overStory === void 0) return refusal(op, over, "Numbering and section metadata require an exclusive edit.");
12790
+ if (story === void 0 || overStory === void 0) return refusal(op, over, "Package resources, numbering and section metadata require an exclusive edit.");
11213
12791
  if (!sameStory$1(story, overStory)) return Result.ok([op]);
11214
12792
  if (independent(op, over)) return Result.ok([op]);
11215
12793
  if (effect?.type === "touchedBlocks" && op.type !== DOCUMENT_OP_TYPES.RESOLVE_REVISION) {
@@ -11906,4 +13484,4 @@ const createClient = (document) => {
11906
13484
  };
11907
13485
  };
11908
13486
  //#endregion
11909
- export { BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, compileEditorIntent, createClient, createEditorIntentIdAllocator, createSequencer, documentStories, editorParagraphGroups, findStoryBody, formattingEquals, isTextOnlyRun, mergeRunContent, normalizeForOps, noteUsesCustomMark, packageParagraphIds, paragraphLength, paragraphLogicalText, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, planTrackedDeletion, planTrackedReplace, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, storyBody, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch };
13487
+ export { BATCH_REJECTION_REASONS, BATCH_WIRE_OP_TYPES, BatchRejection, DOCUMENT_OP_REFUSAL_REASONS, DOCUMENT_OP_SCHEMA_VERSION, DOCUMENT_OP_TYPES, DocumentOpRefusal, DocumentOpsContractError, EMPTY_PROPERTY_SETS, INHERIT_RUN_PROPS, MAX_BATCH_WIRE_BYTES, OBJECT_REPLACEMENT_CHARACTER, OP_STORIES, PARAGRAPH_MARK_FORMATTING_KEYS, PROPERTY_REVIEW_POLICIES, REVISION_DECISIONS, SPLIT_HALVES, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, compareGaps, compileEditorIntent, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, documentStories, editorParagraphGroups, findStoryBody, formattingEquals, idKey, inlineLeafSpans, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, packageParagraphIds, packageResourcesOpOf, paragraphLength, paragraphLogicalText, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, planTrackedDeletion, planTrackedReplace, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, storyBody, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, zeroWidthLeavesAt };