@stll/docx-core 0.37.0 → 0.38.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,6 +1,7 @@
1
1
  import { D as PARAGRAPH_ALIGNMENTS, Q as isNumberingReference, Y as isNumberingLevel, dt as getSingularRunPropertyChange, nt as paragraphNumberingReference, o as INSERTION_SEAM_POLICIES, s as MAX_REVISION_ID, t as COMMENT_PART_RELATIONSHIPS } from "../document-C02Ulybe.js";
2
2
  import { a as hasIllegalXmlCharacters, t as sanitizeExternalUrl } from "../href-2XSCK-T8.js";
3
3
  import { Result, TaggedError, panic } from "better-result";
4
+ import { encodeUtf8 } from "@stll/utf8-boundaries";
4
5
  //#region src/ops/equality.ts
5
6
  const NOTHING = /* @__PURE__ */ new Set();
6
7
  const equal = (left, right, skipped) => {
@@ -2206,1066 +2207,1084 @@ const priorValues = (base, patch) => {
2206
2207
  return restore;
2207
2208
  };
2208
2209
  //#endregion
2209
- //#region src/ops/storyLifecycle.ts
2210
- /** Explicit story lifecycle and section property edits, with exact JSON-safe inverses. */
2211
- const refuse$5 = (op, message) => Result.err(new DocumentOpRefusal({
2210
+ //#region src/ops/comments.ts
2211
+ /** Semantic comment definitions and anchors, with narrow exact-state inverses. */
2212
+ const fail = (op, message, reason = DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH) => Result.err(new DocumentOpRefusal({
2212
2213
  opType: op.type,
2213
- reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
2214
+ reason,
2214
2215
  message
2215
2216
  }));
2216
- /** This total projection forces an ownership decision when the body model gains a field. */
2217
- const bodyValues = (body) => ({
2218
- content: body.content,
2219
- background: body.background ?? null,
2220
- finalSectionProperties: body.finalSectionProperties ?? null,
2221
- comments: body.comments ?? null
2222
- });
2223
- /** Capture only fields owned by the lifecycle delta; absent values survive JSON as null. */
2224
- const captureStoryParts = (document, owned) => {
2225
- const body = document.package.document;
2226
- const values = bodyValues(body);
2227
- const pkg = document.package;
2228
- const parts = {};
2229
- if (owned.body !== void 0) {
2230
- const fields = {};
2231
- if (owned.body.content !== void 0) fields.content = values.content;
2232
- if (owned.body.background !== void 0) fields.background = values.background;
2233
- if (owned.body.finalSectionProperties !== void 0) fields.finalSectionProperties = values.finalSectionProperties;
2234
- if (owned.body.comments !== void 0) fields.comments = values.comments;
2235
- parts.body = fields;
2217
+ const validId = (id) => Number.isInteger(id) && id >= 0 && id <= 2147483647;
2218
+ const anchorId = (node) => {
2219
+ switch (node.type) {
2220
+ case "commentRangeStart":
2221
+ case "commentRangeEnd":
2222
+ case "commentReference": return node.id;
2223
+ default: return;
2236
2224
  }
2237
- if (owned.sections !== void 0) parts.sections = owned.sections.map(({ index, properties, headers, footers }) => {
2238
- const fields = { index };
2239
- const section = body.sections?.at(index);
2240
- if (!section) return fields;
2241
- if (properties !== void 0) fields.properties = section.properties;
2242
- if (headers !== void 0) fields.headers = section.headers ? [...section.headers] : null;
2243
- if (footers !== void 0) fields.footers = section.footers ? [...section.footers] : null;
2244
- return fields;
2245
- });
2246
- if (owned.headers !== void 0) parts.headers = pkg.headers ? [...pkg.headers] : null;
2247
- if (owned.footers !== void 0) parts.footers = pkg.footers ? [...pkg.footers] : null;
2248
- if (owned.footnotes !== void 0) parts.footnotes = pkg.footnotes ?? null;
2249
- if (owned.endnotes !== void 0) parts.endnotes = pkg.endnotes ?? null;
2250
- if (owned.settings !== void 0) parts.settings = pkg.settings ?? null;
2251
- const undefinedFields = [];
2252
- const bodyKeys = Object.keys(owned.body ?? {}).filter((key) => key in values).filter((key) => Object.hasOwn(body, key) && Reflect.get(body, key) === void 0);
2253
- if (bodyKeys.length > 0) undefinedFields.push({
2254
- target: "body",
2255
- keys: bodyKeys
2256
- });
2257
- const packageKeys = Object.keys(owned).filter((key) => key !== "body" && key !== "sections" && key !== "undefinedFields").filter((key) => Object.hasOwn(pkg, key) && Reflect.get(pkg, key) === void 0);
2258
- if (packageKeys.length > 0) undefinedFields.push({
2259
- target: "package",
2260
- keys: packageKeys
2225
+ };
2226
+ const anchorsIn = (document) => {
2227
+ const anchors = [];
2228
+ for (const story of documentStories(document)) for (const { paragraph } of storyParagraphs(storyBody(document, story))) for (const span of leafSpans(paragraph.content)) if (isCommentAnchor(span.node)) anchors.push({
2229
+ story,
2230
+ blockId: paragraph.paraId ?? "",
2231
+ ...span
2261
2232
  });
2262
- for (const fields of owned.sections ?? []) {
2263
- const section = body.sections?.at(fields.index);
2264
- if (!section) continue;
2265
- const keys = Object.keys(fields).filter((key) => key !== "index").filter((key) => Object.hasOwn(section, key) && Reflect.get(section, key) === void 0);
2266
- if (keys.length > 0) undefinedFields.push({
2267
- target: "section",
2268
- index: fields.index,
2269
- keys
2270
- });
2271
- }
2272
- if (undefinedFields.length > 0) parts.undefinedFields = undefinedFields;
2273
- return parts;
2233
+ return anchors;
2274
2234
  };
2275
- /** Immutable operations share unowned fields; section content is a derived mirror. */
2276
- const changedParts = (before, after) => {
2277
- const oldBody = before.package.document;
2278
- const newBody = after.package.document;
2279
- const body = {};
2280
- if (oldBody.content !== newBody.content) body.content = oldBody.content;
2281
- if (oldBody.background !== newBody.background) body.background = oldBody.background ?? null;
2282
- if (oldBody.finalSectionProperties !== newBody.finalSectionProperties) body.finalSectionProperties = oldBody.finalSectionProperties ?? null;
2283
- if (oldBody.comments !== newBody.comments) body.comments = oldBody.comments ?? null;
2284
- const sections = [];
2285
- if (oldBody.sections !== newBody.sections) for (const [index, section] of (oldBody.sections ?? []).entries()) {
2286
- const next = newBody.sections?.at(index);
2287
- if (section === next) continue;
2288
- const changes = { index };
2289
- if (section.properties !== next?.properties) changes.properties = section.properties;
2290
- if (section.headers !== next?.headers) changes.headers = section.headers ? [...section.headers] : null;
2291
- if (section.footers !== next?.footers) changes.footers = section.footers ? [...section.footers] : null;
2292
- if (Object.keys(changes).length > 1) sections.push(changes);
2293
- }
2294
- const parts = {};
2295
- if (Object.keys(body).length > 0) parts.body = body;
2296
- if (sections.length > 0) parts.sections = sections;
2297
- if (before.package.headers !== after.package.headers) parts.headers = before.package.headers ? [...before.package.headers] : null;
2298
- if (before.package.footers !== after.package.footers) parts.footers = before.package.footers ? [...before.package.footers] : null;
2299
- if (before.package.footnotes !== after.package.footnotes) parts.footnotes = before.package.footnotes ?? null;
2300
- if (before.package.endnotes !== after.package.endnotes) parts.endnotes = before.package.endnotes ?? null;
2301
- if (before.package.settings !== after.package.settings) parts.settings = before.package.settings ?? null;
2302
- return captureStoryParts(before, parts);
2235
+ /**
2236
+ * Root comments without any owned source anchor. Loaded packages may carry
2237
+ * them; they stay preserved as read-only entries rather than refusing the
2238
+ * document, and no comment operation may create or target one.
2239
+ */
2240
+ const orphanRootCommentIds = (document) => {
2241
+ const comments = document.package.document.comments ?? [];
2242
+ const ids = new Set(comments.map(({ id }) => id));
2243
+ const anchored = new Set(anchorsIn(document).map(({ node }) => anchorId(node)));
2244
+ return new Set(comments.filter(({ id, parentId }) => (parentId === void 0 || !ids.has(parentId)) && !anchored.has(id)).map(({ id }) => id));
2303
2245
  };
2304
- const restoreParts = (document, parts) => {
2305
- const pkg = { ...document.package };
2306
- let body = document.package.document;
2307
- if (parts.body !== void 0) {
2308
- body = { ...body };
2309
- const fields = parts.body;
2310
- if (fields.content !== void 0) {
2311
- const existingBlocks = body.content;
2312
- body = withBodyContent(body, fields.content.map((block, index) => {
2313
- const previous = existingBlocks.at(index);
2314
- return previous && structurallyEqual(block, previous) ? previous : block;
2315
- }));
2246
+ /**
2247
+ * Shared loaded-comment activation contract; legacy parentId revision associations stay explicit.
2248
+ * `allowedOrphans` names unanchored root comments the caller accepts ("all" for a loaded package).
2249
+ */
2250
+ const commentDocumentIssue = (document, allowedOrphans = /* @__PURE__ */ new Set()) => {
2251
+ const comments = document.package.document.comments ?? [];
2252
+ const byId = new Map(comments.map((comment) => [comment.id, comment]));
2253
+ if (comments.some(({ id }) => !validId(id)) || byId.size !== comments.length) return "Comment identities must be unique bounded integers.";
2254
+ const anchors = anchorsIn(document);
2255
+ if (anchors.some(({ node }) => !byId.has(anchorId(node) ?? -1))) return "A comment anchor has no definition.";
2256
+ for (const comment of comments) {
2257
+ const own = anchors.filter(({ node }) => anchorId(node) === comment.id);
2258
+ const starts = own.filter(({ node }) => node.type === "commentRangeStart");
2259
+ const ends = own.filter(({ node }) => node.type === "commentRangeEnd");
2260
+ const references = own.filter(({ node }) => node.type === "commentReference");
2261
+ const start = starts.at(0);
2262
+ const end = ends.at(0);
2263
+ if (starts.length !== ends.length || starts.length > 1 || references.length > 1) return "Comment anchors are unbalanced or duplicated.";
2264
+ if (start && end && (!sameStory(start.story, end.story) || anchors.indexOf(start) > anchors.indexOf(end))) return "Comment range boundaries must be ordered in one story.";
2265
+ const parent = comment.parentId === void 0 ? void 0 : byId.get(comment.parentId);
2266
+ if (!parent && own.length === 0 && allowedOrphans !== "all" && !allowedOrphans.has(comment.id)) return "A root or revision-associated comment needs an owned source anchor.";
2267
+ if (comment.parentId !== void 0 && !validId(comment.parentId)) return "A comment parent identity is invalid.";
2268
+ const visited = /* @__PURE__ */ new Set([comment.id]);
2269
+ let current = parent;
2270
+ while (current) {
2271
+ if (visited.has(current.id)) return "Comment parent relations cannot cycle.";
2272
+ visited.add(current.id);
2273
+ current = current.parentId === void 0 ? void 0 : byId.get(current.parentId);
2316
2274
  }
2317
- if (fields.background !== void 0) if (fields.background === null) delete body.background;
2318
- else body.background = fields.background;
2319
- if (fields.finalSectionProperties !== void 0) if (fields.finalSectionProperties === null) delete body.finalSectionProperties;
2320
- else body.finalSectionProperties = fields.finalSectionProperties;
2321
- if (fields.comments !== void 0) if (fields.comments === null) delete body.comments;
2322
- else body.comments = fields.comments;
2323
2275
  }
2324
- if (parts.headers !== void 0) if (parts.headers === null) delete pkg.headers;
2325
- else pkg.headers = new Map(parts.headers.map(([rId, part]) => {
2326
- const previous = pkg.headers?.get(rId);
2327
- return [rId, previous && structurallyEqual(previous, part) ? previous : part];
2328
- }));
2329
- if (parts.footers !== void 0) if (parts.footers === null) delete pkg.footers;
2330
- else pkg.footers = new Map(parts.footers.map(([rId, part]) => {
2331
- const previous = pkg.footers?.get(rId);
2332
- return [rId, previous && structurallyEqual(previous, part) ? previous : part];
2333
- }));
2334
- if (parts.sections !== void 0 && body.sections !== void 0) {
2335
- const sections = [...body.sections];
2336
- for (const fields of parts.sections) {
2337
- const previous = sections.at(fields.index);
2338
- if (!previous) return panic("Owned lifecycle section is missing after staleness validation.");
2339
- const section = { ...previous };
2340
- if (fields.properties !== void 0) section.properties = fields.properties;
2341
- if (fields.headers !== void 0) if (fields.headers === null) delete section.headers;
2342
- else section.headers = new Map(fields.headers.map(([variant, part]) => {
2343
- const rId = section.properties.headerReferences?.find(({ type }) => type === variant)?.rId;
2344
- const owned = rId === void 0 ? void 0 : pkg.headers?.get(rId);
2345
- return [variant, owned && structurallyEqual(owned, part) ? owned : part];
2346
- }));
2347
- if (fields.footers !== void 0) if (fields.footers === null) delete section.footers;
2348
- else section.footers = new Map(fields.footers.map(([variant, part]) => {
2349
- const rId = section.properties.footerReferences?.find(({ type }) => type === variant)?.rId;
2350
- const owned = rId === void 0 ? void 0 : pkg.footers?.get(rId);
2351
- return [variant, owned && structurallyEqual(owned, part) ? owned : part];
2352
- }));
2353
- sections[fields.index] = section;
2354
- }
2355
- body = {
2356
- ...body,
2357
- sections
2358
- };
2276
+ };
2277
+ /** Allocate from the package's annotation domains without a hidden mutable counter. */
2278
+ const freshCommentId = (document) => {
2279
+ let maximum = -1;
2280
+ for (const comment of document.package.document.comments ?? []) maximum = Math.max(maximum, comment.id, comment.parentId ?? -1);
2281
+ for (const { node } of anchorsIn(document)) maximum = Math.max(maximum, anchorId(node) ?? -1);
2282
+ for (const key of packageIdentityKeys(document.package)) {
2283
+ if (!Object.values(IDENTITY_SPACES).some((space) => key.startsWith(`${space}:`))) continue;
2284
+ maximum = Math.max(maximum, Number(key.slice(key.lastIndexOf(":") + 1)));
2359
2285
  }
2360
- pkg.document = body;
2361
- if (parts.footnotes !== void 0) if (parts.footnotes === null) delete pkg.footnotes;
2362
- else {
2363
- const current = new Map(pkg.footnotes?.map((note) => [note.id, note]));
2364
- pkg.footnotes = parts.footnotes.map((note) => {
2365
- const previous = current.get(note.id);
2366
- return previous && structurallyEqual(previous, note) ? previous : note;
2286
+ if (!Number.isInteger(maximum) || maximum >= 2147483647) return Result.err(new DocumentOpRefusal({
2287
+ opType: DOCUMENT_OP_TYPES.CREATE_COMMENT,
2288
+ reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
2289
+ message: "The package annotation id space is exhausted."
2290
+ }));
2291
+ return Result.ok(maximum + 1);
2292
+ };
2293
+ const propertyPresence = (record, key) => {
2294
+ if (!Object.hasOwn(record, key)) return "absent";
2295
+ return Reflect.get(record, key) === void 0 ? "undefined" : "present";
2296
+ };
2297
+ const capture = (document, ids, addressed) => {
2298
+ const body = document.package.document;
2299
+ const relationships = [];
2300
+ let relationshipIndex = 0;
2301
+ for (const [key, relationship] of document.package.relationships ?? []) {
2302
+ if (isCommentRelationship(relationship.type)) relationships.push({
2303
+ index: relationshipIndex,
2304
+ key,
2305
+ relationship
2367
2306
  });
2307
+ relationshipIndex += 1;
2368
2308
  }
2369
- if (parts.endnotes !== void 0) if (parts.endnotes === null) delete pkg.endnotes;
2370
- else {
2371
- const current = new Map(pkg.endnotes?.map((note) => [note.id, note]));
2372
- pkg.endnotes = parts.endnotes.map((note) => {
2373
- const previous = current.get(note.id);
2374
- return previous && structurallyEqual(previous, note) ? previous : note;
2309
+ const records = [];
2310
+ for (const [index, comment] of (body.comments ?? []).entries()) if (ids.has(comment.id)) records.push({
2311
+ index,
2312
+ comment
2313
+ });
2314
+ const anchors = [];
2315
+ for (const { story, blockId } of addressed) {
2316
+ const found = findStoryBody(document, story);
2317
+ const paragraph = found && storyParagraphs(found).find(({ paragraph: value }) => idKey(value.paraId ?? "") === idKey(blockId))?.paragraph;
2318
+ if (paragraph) anchors.push({
2319
+ story,
2320
+ blockId,
2321
+ content: paragraph.content
2375
2322
  });
2376
2323
  }
2377
- if (parts.settings !== void 0) if (parts.settings === null) delete pkg.settings;
2378
- else pkg.settings = parts.settings;
2379
- for (const fields of parts.undefinedFields ?? []) switch (fields.target) {
2380
- case "body":
2381
- for (const key of fields.keys) {
2382
- if (!parts.body || !Object.hasOwn(parts.body, key) || Reflect.get(parts.body, key) !== null) return panic("Undefined body metadata names an unowned field.");
2383
- Reflect.set(pkg.document, key, void 0);
2384
- }
2385
- break;
2386
- case "package":
2387
- for (const key of fields.keys) {
2388
- if (!Object.hasOwn(parts, key) || Reflect.get(parts, key) !== null) return panic("Undefined package metadata names an unowned field.");
2389
- Reflect.set(pkg, key, void 0);
2390
- }
2391
- break;
2392
- case "section": {
2393
- const owned = parts.sections?.find(({ index }) => index === fields.index);
2394
- const section = pkg.document.sections?.at(fields.index);
2395
- if (!owned || !section) return panic("Undefined section metadata names an unowned section.");
2396
- for (const key of fields.keys) {
2397
- if (!Object.hasOwn(owned, key) || Reflect.get(owned, key) !== null) return panic("Undefined section metadata names an unowned field.");
2398
- Reflect.set(section, key, void 0);
2399
- }
2400
- break;
2401
- }
2324
+ return {
2325
+ relationshipPresence: propertyPresence(document.package, "relationships"),
2326
+ relationships,
2327
+ listPresence: propertyPresence(body, "comments"),
2328
+ records,
2329
+ anchors
2330
+ };
2331
+ };
2332
+ const changedAnchors = (before, after) => {
2333
+ const anchors = [];
2334
+ for (const story of documentStories(before)) {
2335
+ const next = new Map(storyParagraphs(storyBody(after, story)).map(({ paragraph }) => [idKey(paragraph.paraId ?? ""), paragraph]));
2336
+ for (const { paragraph } of storyParagraphs(storyBody(before, story))) if (paragraph.content !== next.get(idKey(paragraph.paraId ?? ""))?.content) anchors.push({
2337
+ story,
2338
+ blockId: paragraph.paraId ?? "",
2339
+ content: paragraph.content
2340
+ });
2402
2341
  }
2342
+ return anchors;
2343
+ };
2344
+ const scaffoldDelta = (before, after) => {
2345
+ const old = new Set(identityKeysIn(before.anchors));
2346
+ const next = new Set(identityKeysIn(after.anchors));
2347
+ const changed = [...old].filter((id) => !next.has(id)).concat([...next].filter((id) => !old.has(id)));
2348
+ const values = (space) => changed.filter((key) => key.startsWith(`${space}:`)).map((key) => Number(key.slice(key.indexOf(":") + 1)));
2403
2349
  return {
2404
- ...document,
2405
- package: pkg
2350
+ revision: values(IDENTITY_SPACES.REVISION),
2351
+ control: values(IDENTITY_SPACES.CONTROL)
2406
2352
  };
2407
2353
  };
2408
- /** Traverse changed blocks only; shared records cannot add, remove or modify an ID. */
2409
- const changedParagraphs = (before, after) => {
2410
- const oldParagraphs = /* @__PURE__ */ new Map();
2411
- const newParagraphs = /* @__PURE__ */ new Map();
2412
- const collect = (oldContent = [], newContent = []) => {
2413
- if (oldContent === newContent) return;
2414
- const oldBlocks = new Set(oldContent);
2415
- const newBlocks = new Set(newContent);
2416
- for (const [blocks, shared, output] of [[
2417
- oldContent,
2418
- newBlocks,
2419
- oldParagraphs
2420
- ], [
2421
- newContent,
2422
- oldBlocks,
2423
- newParagraphs
2424
- ]]) for (const block of blocks) {
2425
- if (shared.has(block)) continue;
2426
- for (const { paragraph } of storyParagraphs({ content: [block] })) output.set(paragraph.paraId ?? "", paragraph);
2354
+ /** Remove only owned anchors, then merge scaffolding with the shared exact field predicate. */
2355
+ const ownedSeams = (content, ids) => {
2356
+ let references = 0;
2357
+ return leafSpans(content).flatMap(({ node, before }) => {
2358
+ const id = anchorId(node);
2359
+ if (id === void 0 || !ids.has(id)) return [];
2360
+ const position = before.offset - references;
2361
+ if (node.type === "commentReference") references++;
2362
+ return [position];
2363
+ });
2364
+ };
2365
+ const normalizedWithoutAnchors = ({ content, ids, seams, start = 0 }) => {
2366
+ let normalized = [];
2367
+ let position = start;
2368
+ for (const node of withoutAnchors(content, ids)) {
2369
+ const children = childNodes(node);
2370
+ const normalizedNode = children === void 0 ? node : rebuildNode(node, normalizedWithoutAnchors({
2371
+ content: children,
2372
+ ids,
2373
+ seams,
2374
+ start: position
2375
+ }));
2376
+ if (seams.has(position)) normalized = mergeAlike(normalized, [normalizedNode]);
2377
+ else normalized.push(normalizedNode);
2378
+ position += leafSpans([normalizedNode]).at(-1)?.after.offset ?? 0;
2379
+ }
2380
+ return normalized;
2381
+ };
2382
+ const isCommentRelationship = (type) => Object.values(COMMENT_PART_RELATIONSHIPS).some((part) => part.type === type);
2383
+ /** Keep the same part ids as the packager: numeric rId maximum plus one. */
2384
+ const reconcilePartRelationships = (document, scope) => {
2385
+ const comments = document.package.document.comments ?? [];
2386
+ const relationships = new Map(document.package.relationships ?? []);
2387
+ let next = Math.max(0, ...[...relationships.keys()].map((id) => Number(/^rId(\d+)$/u.exec(id)?.at(1) ?? 0))) + 1;
2388
+ const extended = comments.some((comment) => comment.parentId !== void 0 || comment.done !== void 0);
2389
+ const numbering = document.package.numbering;
2390
+ const parts = {
2391
+ numbering: {
2392
+ type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
2393
+ target: "numbering.xml",
2394
+ needed: scope === "document" && ((numbering?.abstractNums.length ?? 0) > 0 || (numbering?.nums.length ?? 0) > 0)
2395
+ },
2396
+ comments: {
2397
+ ...COMMENT_PART_RELATIONSHIPS.comments,
2398
+ needed: comments.length > 0
2399
+ },
2400
+ commentsExtended: {
2401
+ ...COMMENT_PART_RELATIONSHIPS.commentsExtended,
2402
+ needed: extended
2427
2403
  }
2428
2404
  };
2429
- collect(before.package.document.content, after.package.document.content);
2430
- for (const key of ["headers", "footers"]) {
2431
- const oldParts = before.package[key];
2432
- const newParts = after.package[key];
2433
- if (oldParts === newParts) continue;
2434
- for (const rId of /* @__PURE__ */ new Set([...oldParts?.keys() ?? [], ...newParts?.keys() ?? []])) collect(oldParts?.get(rId)?.content, newParts?.get(rId)?.content);
2435
- }
2436
- for (const key of ["footnotes", "endnotes"]) {
2437
- const oldNotes = before.package[key];
2438
- const newNotes = after.package[key];
2439
- if (oldNotes === newNotes) continue;
2440
- const oldParts = new Map(oldNotes?.map((note) => [note.id, note]));
2441
- const newParts = new Map(newNotes?.map((note) => [note.id, note]));
2442
- for (const id of /* @__PURE__ */ new Set([...oldParts.keys(), ...newParts.keys()])) collect(oldParts.get(id)?.content, newParts.get(id)?.content);
2405
+ for (const [kind, part] of Object.entries(parts)) {
2406
+ const { needed } = part;
2407
+ const matching = [...relationships].filter(([, relationship]) => relationship.type === part.type);
2408
+ if (needed && matching.length === 0) {
2409
+ const id = `rId${next++}`;
2410
+ relationships.set(id, {
2411
+ id,
2412
+ type: part.type,
2413
+ target: part.target
2414
+ });
2415
+ }
2416
+ if (kind === "commentsExtended" && !needed) for (const [id] of matching) relationships.delete(id);
2443
2417
  }
2418
+ if (structurallyEqual([...relationships], [...document.package.relationships ?? []])) return document;
2444
2419
  return {
2445
- oldParagraphs,
2446
- newParagraphs
2420
+ ...document,
2421
+ package: {
2422
+ ...document.package,
2423
+ relationships
2424
+ }
2447
2425
  };
2448
2426
  };
2449
- const storyLifecycleEdit = (before, after, op) => {
2427
+ /** Reconcile modeled comment and numbering parts with their document relationships. */
2428
+ const reconcileDocumentPartRelationships = (document) => reconcilePartRelationships(document, "document");
2429
+ const edited = (before, after, op, ids) => {
2430
+ if (op.type !== DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE) after = reconcilePartRelationships(after, "comments");
2450
2431
  const invalid = contractViolation(after);
2451
- if (invalid) return Result.err(new DocumentOpRefusal({
2452
- opType: op.type,
2453
- reason: invalid.reason,
2454
- message: invalid.message
2455
- }));
2456
- const prior = changedParts(before, after);
2457
- const next = captureStoryParts(after, prior);
2458
- const { oldParagraphs, newParagraphs } = changedParagraphs(before, after);
2459
- const oldIds = new Set(oldParagraphs.keys());
2460
- const newIds = new Set(newParagraphs.keys());
2432
+ if (invalid) return fail(op, invalid.message, invalid.reason);
2433
+ const issue = commentDocumentIssue(after, orphanRootCommentIds(before));
2434
+ if (issue) return fail(op, issue);
2435
+ const anchors = changedAnchors(before, after);
2436
+ const prior = capture(before, ids, anchors);
2437
+ const next = capture(after, ids, anchors);
2438
+ if (structurallyEqual(prior, next)) return Result.ok({
2439
+ document: before,
2440
+ inverse: [],
2441
+ touched: {
2442
+ modified: [],
2443
+ inserted: [],
2444
+ removed: []
2445
+ }
2446
+ });
2461
2447
  return Result.ok({
2462
2448
  document: after,
2463
2449
  inverse: [{
2464
- type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
2450
+ type: DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE,
2451
+ ids: [...ids],
2452
+ scaffoldIds: scaffoldDelta(prior, next),
2465
2453
  expected: cloneModel(next),
2466
- parts: cloneModel(prior)
2454
+ state: cloneModel(prior)
2467
2455
  }],
2468
2456
  touched: {
2469
- modified: [...newIds].filter((id) => oldIds.has(id) && !structurallyEqual(oldParagraphs.get(id), newParagraphs.get(id))),
2470
- inserted: [...newIds].filter((id) => !oldIds.has(id)),
2471
- removed: [...oldIds].filter((id) => !newIds.has(id))
2457
+ modified: anchors.map(({ blockId }) => blockId),
2458
+ inserted: [],
2459
+ removed: []
2472
2460
  }
2473
2461
  });
2474
2462
  };
2475
- /** Ordered section breaks; the final section follows every paragraph sectPr. */
2476
- const sectionEnds = (body) => body.content.flatMap((block, index) => block.type === "paragraph" && block.sectionProperties !== void 0 ? [{
2477
- index,
2478
- properties: block.sectionProperties
2479
- }] : []);
2480
- const sectionPropertiesAt = (document, sectionIndex) => {
2481
- if (!Number.isInteger(sectionIndex) || sectionIndex < 0) return void 0;
2482
- const ends = sectionEnds(document.package.document);
2483
- if (sectionIndex > ends.length) return void 0;
2484
- return ends.at(sectionIndex)?.properties ?? document.package.document.finalSectionProperties ?? document.package.document.sections?.at(sectionIndex)?.properties ?? {};
2485
- };
2486
- const withSectionProperties = (document, sectionIndex, properties) => {
2487
- const body = document.package.document;
2488
- const end = sectionEnds(body).at(sectionIndex);
2489
- let next = { ...body };
2490
- if (end) {
2491
- const content = [...body.content];
2492
- const paragraph = content.at(end.index);
2493
- if (paragraph?.type === "paragraph") content[end.index] = {
2494
- ...paragraph,
2495
- sectionProperties: properties
2496
- };
2497
- next = withBodyContent(body, content);
2498
- } else next.finalSectionProperties = properties;
2499
- if (next.sections) next.sections = next.sections.map((section, index) => index === sectionIndex ? {
2500
- ...section,
2501
- properties
2502
- } : section);
2463
+ const withComments = (document, comments, presence = "present") => {
2464
+ const body = { ...document.package.document };
2465
+ switch (presence) {
2466
+ case "present":
2467
+ body.comments = comments;
2468
+ break;
2469
+ case "undefined":
2470
+ Reflect.set(body, "comments", void 0);
2471
+ break;
2472
+ case "absent":
2473
+ delete body.comments;
2474
+ break;
2475
+ default: return presence;
2476
+ }
2503
2477
  return {
2504
2478
  ...document,
2505
2479
  package: {
2506
2480
  ...document.package,
2507
- document: next
2481
+ document: body
2508
2482
  }
2509
2483
  };
2510
2484
  };
2511
- const undefinedFieldsIssue = (parts) => {
2512
- for (const fields of parts.undefinedFields ?? []) switch (fields.target) {
2513
- case "body":
2514
- if (fields.keys.some((key) => !parts.body || !Object.hasOwn(parts.body, key) || Reflect.get(parts.body, key) !== null)) return "Undefined body metadata must name owned null fields.";
2515
- break;
2516
- case "package":
2517
- if (fields.keys.some((key) => !Object.hasOwn(parts, key) || Reflect.get(parts, key) !== null)) return "Undefined package metadata must name owned null fields.";
2518
- break;
2519
- case "section": {
2520
- const owned = parts.sections?.find(({ index }) => index === fields.index);
2521
- if (!owned || fields.keys.some((key) => !Object.hasOwn(owned, key) || Reflect.get(owned, key) !== null)) return "Undefined section metadata must name owned null fields.";
2522
- break;
2485
+ const withoutAnchors = (nodes, ids) => {
2486
+ let changed = false;
2487
+ const kept = [];
2488
+ for (const node of nodes) {
2489
+ const id = anchorId(node);
2490
+ if (id !== void 0 && ids.has(id)) {
2491
+ changed = true;
2492
+ continue;
2493
+ }
2494
+ const children = childNodes(node);
2495
+ const filtered = children === void 0 ? void 0 : withoutAnchors(children, ids);
2496
+ if (filtered === children || filtered === void 0) {
2497
+ kept.push(node);
2498
+ continue;
2523
2499
  }
2500
+ changed = true;
2501
+ const next = rebuildNode(node, filtered);
2502
+ if (!isEmptyRecord(next)) kept.push(next);
2524
2503
  }
2504
+ return changed ? kept : nodes;
2525
2505
  };
2526
- const applyStoryLifecycle = (document, op) => {
2527
- if (op.type === DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS) {
2528
- const metadataIssue = undefinedFieldsIssue(op.parts);
2529
- if (metadataIssue) return refuse$5(op, metadataIssue);
2530
- if (!structurallyEqual(captureStoryParts(document, op.expected), op.expected)) return Result.err(new DocumentOpRefusal({
2531
- opType: op.type,
2532
- reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
2533
- message: "Story lifecycle inverse is stale."
2534
- }));
2535
- return storyLifecycleEdit(document, restoreParts(document, cloneModel(op.parts)), op);
2536
- }
2537
- const properties = sectionPropertiesAt(document, op.sectionIndex);
2538
- if (!properties) return refuse$5(op, "The section does not exist.");
2539
- if (op.type === DOCUMENT_OP_TYPES.SET_SECTION_PROPS) {
2540
- const nextProps = applyFormattingPatch(properties, op.patch) ?? {};
2541
- let next = withSectionProperties(document, op.sectionIndex, nextProps);
2542
- if (op.patch.evenAndOddHeaders !== void 0 && (op.patch.evenAndOddHeaders !== null || next.package.settings !== void 0)) {
2543
- const settings = { ...next.package.settings ?? { defaultTabStop: 720 } };
2544
- if (op.patch.evenAndOddHeaders === null) delete settings.evenAndOddHeaders;
2545
- else settings.evenAndOddHeaders = op.patch.evenAndOddHeaders;
2546
- next = {
2547
- ...next,
2548
- package: {
2549
- ...next.package,
2550
- settings
2551
- }
2552
- };
2553
- }
2554
- return storyLifecycleEdit(document, next, op);
2555
- }
2556
- const kind = op.story.kind;
2557
- const refs = kind === "header" ? properties.headerReferences : properties.footerReferences;
2558
- const parts = kind === "header" ? document.package.headers : document.package.footers;
2559
- const nextParts = new Map(parts);
2560
- let nextRefs = [...refs ?? []];
2561
- const nextProps = { ...properties };
2562
- if (op.type === DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER) {
2563
- 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.");
2564
- if (op.content.length === 0 || storyParagraphs({ content: op.content }).length === 0) return refuse$5(op, "A header/footer needs an addressable paragraph.");
2565
- const part = {
2566
- type: kind,
2567
- hdrFtrType: op.referenceType,
2568
- content: cloneModel(op.content)
2569
- };
2570
- nextParts.set(op.story.rId, part);
2571
- nextRefs.push({
2572
- type: op.referenceType,
2573
- rId: op.story.rId
2574
- });
2575
- if (op.referenceType === "first") nextProps.titlePg = true;
2576
- if (op.referenceType === "even") nextProps.evenAndOddHeaders = true;
2577
- } else {
2578
- 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.");
2579
- nextRefs = nextRefs.filter(({ type }) => type !== op.referenceType);
2580
- 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);
2581
- }
2582
- if (kind === "header") nextProps.headerReferences = nextRefs;
2583
- else nextProps.footerReferences = nextRefs;
2584
- let next = withSectionProperties(document, op.sectionIndex, nextProps);
2585
- next = kind === "header" ? {
2586
- ...next,
2587
- package: {
2588
- ...next.package,
2589
- headers: nextParts
2590
- }
2591
- } : {
2592
- ...next,
2593
- package: {
2594
- ...next.package,
2595
- footers: nextParts
2596
- }
2597
- };
2598
- if (op.type === DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER && op.referenceType === "even") next = {
2599
- ...next,
2600
- package: {
2601
- ...next.package,
2602
- settings: {
2603
- ...next.package.settings ?? { defaultTabStop: 720 },
2604
- evenAndOddHeaders: true
2605
- }
2606
- }
2607
- };
2608
- if (next.package.document.sections) {
2609
- const sections = next.package.document.sections.map((section, index) => {
2610
- if (index !== op.sectionIndex) return section;
2611
- const bound = new Map(kind === "header" ? section.headers : section.footers);
2612
- const part = nextParts.get(op.story.rId);
2613
- if (op.type === DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER && part) bound.set(op.referenceType, part);
2614
- else bound.delete(op.referenceType);
2615
- return kind === "header" ? {
2616
- ...section,
2617
- headers: bound
2618
- } : {
2619
- ...section,
2620
- footers: bound
2621
- };
2622
- });
2623
- next = {
2624
- ...next,
2625
- package: {
2626
- ...next.package,
2627
- document: {
2628
- ...next.package.document,
2629
- sections
2630
- }
2631
- }
2632
- };
2633
- }
2634
- return storyLifecycleEdit(document, next, op);
2635
- };
2636
- //#endregion
2637
- //#region src/ops/comments.ts
2638
- /** Semantic comment definitions and anchors, with narrow exact-state inverses. */
2639
- const fail = (op, message, reason = DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH) => Result.err(new DocumentOpRefusal({
2640
- opType: op.type,
2641
- reason,
2642
- message
2643
- }));
2644
- const validId = (id) => Number.isInteger(id) && id >= 0 && id <= 2147483647;
2645
- const anchorId = (node) => {
2646
- switch (node.type) {
2647
- case "commentRangeStart":
2648
- case "commentRangeEnd":
2649
- case "commentReference": return node.id;
2650
- default: return;
2651
- }
2652
- };
2653
- const anchorsIn = (document) => {
2654
- const anchors = [];
2655
- for (const story of documentStories(document)) for (const { paragraph } of storyParagraphs(storyBody(document, story))) for (const span of leafSpans(paragraph.content)) if (isCommentAnchor(span.node)) anchors.push({
2656
- story,
2657
- blockId: paragraph.paraId ?? "",
2658
- ...span
2659
- });
2660
- return anchors;
2661
- };
2662
- /**
2663
- * Root comments without any owned source anchor. Loaded packages may carry
2664
- * them; they stay preserved as read-only entries rather than refusing the
2665
- * document, and no comment operation may create or target one.
2666
- */
2667
- const orphanRootCommentIds = (document) => {
2668
- const comments = document.package.document.comments ?? [];
2669
- const ids = new Set(comments.map(({ id }) => id));
2670
- const anchored = new Set(anchorsIn(document).map(({ node }) => anchorId(node)));
2671
- return new Set(comments.filter(({ id, parentId }) => (parentId === void 0 || !ids.has(parentId)) && !anchored.has(id)).map(({ id }) => id));
2672
- };
2673
- /**
2674
- * Shared loaded-comment activation contract; legacy parentId revision associations stay explicit.
2675
- * `allowedOrphans` names unanchored root comments the caller accepts ("all" for a loaded package).
2676
- */
2677
- const commentDocumentIssue = (document, allowedOrphans = /* @__PURE__ */ new Set()) => {
2678
- const comments = document.package.document.comments ?? [];
2679
- const byId = new Map(comments.map((comment) => [comment.id, comment]));
2680
- if (comments.some(({ id }) => !validId(id)) || byId.size !== comments.length) return "Comment identities must be unique bounded integers.";
2681
- const anchors = anchorsIn(document);
2682
- if (anchors.some(({ node }) => !byId.has(anchorId(node) ?? -1))) return "A comment anchor has no definition.";
2683
- for (const comment of comments) {
2684
- const own = anchors.filter(({ node }) => anchorId(node) === comment.id);
2685
- const starts = own.filter(({ node }) => node.type === "commentRangeStart");
2686
- const ends = own.filter(({ node }) => node.type === "commentRangeEnd");
2687
- const references = own.filter(({ node }) => node.type === "commentReference");
2688
- const start = starts.at(0);
2689
- const end = ends.at(0);
2690
- if (starts.length !== ends.length || starts.length > 1 || references.length > 1) return "Comment anchors are unbalanced or duplicated.";
2691
- if (start && end && (!sameStory(start.story, end.story) || anchors.indexOf(start) > anchors.indexOf(end))) return "Comment range boundaries must be ordered in one story.";
2692
- const parent = comment.parentId === void 0 ? void 0 : byId.get(comment.parentId);
2693
- if (!parent && own.length === 0 && allowedOrphans !== "all" && !allowedOrphans.has(comment.id)) return "A root or revision-associated comment needs an owned source anchor.";
2694
- if (comment.parentId !== void 0 && !validId(comment.parentId)) return "A comment parent identity is invalid.";
2695
- const visited = /* @__PURE__ */ new Set([comment.id]);
2696
- let current = parent;
2697
- while (current) {
2698
- if (visited.has(current.id)) return "Comment parent relations cannot cycle.";
2699
- visited.add(current.id);
2700
- current = current.parentId === void 0 ? void 0 : byId.get(current.parentId);
2701
- }
2702
- }
2703
- };
2704
- /** Allocate from the package's annotation domains without a hidden mutable counter. */
2705
- const freshCommentId = (document) => {
2706
- let maximum = -1;
2707
- for (const comment of document.package.document.comments ?? []) maximum = Math.max(maximum, comment.id, comment.parentId ?? -1);
2708
- for (const { node } of anchorsIn(document)) maximum = Math.max(maximum, anchorId(node) ?? -1);
2709
- for (const key of packageIdentityKeys(document.package)) {
2710
- if (!Object.values(IDENTITY_SPACES).some((space) => key.startsWith(`${space}:`))) continue;
2711
- maximum = Math.max(maximum, Number(key.slice(key.lastIndexOf(":") + 1)));
2712
- }
2713
- if (!Number.isInteger(maximum) || maximum >= 2147483647) return Result.err(new DocumentOpRefusal({
2714
- opType: DOCUMENT_OP_TYPES.CREATE_COMMENT,
2715
- reason: DOCUMENT_OP_REFUSAL_REASONS.INVALID_NEW_ID,
2716
- message: "The package annotation id space is exhausted."
2717
- }));
2718
- return Result.ok(maximum + 1);
2719
- };
2720
- const propertyPresence = (record, key) => {
2721
- if (!Object.hasOwn(record, key)) return "absent";
2722
- return Reflect.get(record, key) === void 0 ? "undefined" : "present";
2723
- };
2724
- const capture = (document, ids, addressed) => {
2725
- const body = document.package.document;
2726
- const relationships = [];
2727
- let relationshipIndex = 0;
2728
- for (const [key, relationship] of document.package.relationships ?? []) {
2729
- if (isCommentRelationship(relationship.type)) relationships.push({
2730
- index: relationshipIndex,
2731
- key,
2732
- relationship
2733
- });
2734
- relationshipIndex += 1;
2735
- }
2736
- const records = [];
2737
- for (const [index, comment] of (body.comments ?? []).entries()) if (ids.has(comment.id)) records.push({
2738
- index,
2739
- comment
2740
- });
2741
- const anchors = [];
2742
- for (const { story, blockId } of addressed) {
2743
- const found = findStoryBody(document, story);
2744
- const paragraph = found && storyParagraphs(found).find(({ paragraph: value }) => idKey(value.paraId ?? "") === idKey(blockId))?.paragraph;
2745
- if (paragraph) anchors.push({
2506
+ const restoreAnchors = ({ document, anchors, op }) => {
2507
+ let current = document;
2508
+ for (const { story, blockId, content } of anchors) {
2509
+ const body = findStoryBody(current, story);
2510
+ const location = body && storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(blockId));
2511
+ if (!location) return fail(op, "An owned comment paragraph is missing.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2512
+ const changed = replaceParagraphs({
2513
+ document: current,
2746
2514
  story,
2747
- blockId,
2748
- content: paragraph.content
2515
+ at: location,
2516
+ count: 1,
2517
+ replacement: [{
2518
+ ...location.paragraph,
2519
+ content: cloneModel([...content])
2520
+ }]
2749
2521
  });
2522
+ if (changed.isErr()) return fail(op, changed.error.message, changed.error.reason);
2523
+ current = changed.value;
2750
2524
  }
2751
- return {
2752
- relationshipPresence: propertyPresence(document.package, "relationships"),
2753
- relationships,
2754
- listPresence: propertyPresence(body, "comments"),
2755
- records,
2756
- anchors
2757
- };
2525
+ return Result.ok(current);
2758
2526
  };
2759
- const changedAnchors = (before, after) => {
2760
- const anchors = [];
2761
- for (const story of documentStories(before)) {
2762
- const next = new Map(storyParagraphs(storyBody(after, story)).map(({ paragraph }) => [idKey(paragraph.paraId ?? ""), paragraph]));
2763
- for (const { paragraph } of storyParagraphs(storyBody(before, story))) if (paragraph.content !== next.get(idKey(paragraph.paraId ?? ""))?.content) anchors.push({
2764
- story,
2765
- blockId: paragraph.paraId ?? "",
2766
- content: paragraph.content
2527
+ const restore = (document, op) => {
2528
+ const ids = new Set(op.ids);
2529
+ if (ids.size !== op.ids.length || op.ids.some((id) => !validId(id)) || !structurallyEqual(capture(document, ids, op.expected.anchors), op.expected)) return fail(op, "The comment inverse is stale.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2530
+ if (op.state.records.some(({ comment, index }) => !ids.has(comment.id) || !Number.isInteger(index) || index < 0) || new Set(op.state.records.map(({ comment }) => comment.id)).size !== op.state.records.length) return fail(op, "The restored comment records do not match the owned identities.");
2531
+ if (!op.scaffoldIds || !structurallyEqual(scaffoldDelta(op.expected, op.state), op.scaffoldIds)) return fail(op, "The comment inverse scaffold identities do not match its owned cuts.");
2532
+ const allowed = /* @__PURE__ */ new Set([...(op.scaffoldIds.revision ?? []).map((id) => `${IDENTITY_SPACES.REVISION}:${id}`), ...(op.scaffoldIds.control ?? []).map((id) => `${IDENTITY_SPACES.CONTROL}:${id}`)]);
2533
+ const identities = (state) => identityKeysIn(state.anchors).filter((id) => !allowed.has(id)).toSorted();
2534
+ if (!structurallyEqual(identities(op.expected), identities(op.state))) return fail(op, "The comment inverse changes an unowned identified record.");
2535
+ if (op.state.anchors.length !== op.expected.anchors.length || op.state.anchors.some((entry, index) => {
2536
+ const expected = op.expected.anchors.at(index);
2537
+ if (!expected || !sameStory(entry.story, expected.story) || idKey(entry.blockId) !== idKey(expected.blockId)) return true;
2538
+ const seams = /* @__PURE__ */ new Set([...ownedSeams(entry.content, ids), ...ownedSeams(expected.content, ids)]);
2539
+ const preserved = (content) => normalizedWithoutAnchors({
2540
+ content,
2541
+ ids,
2542
+ seams
2767
2543
  });
2768
- }
2769
- return anchors;
2770
- };
2771
- const scaffoldDelta = (before, after) => {
2772
- const old = new Set(identityKeysIn(before.anchors));
2773
- const next = new Set(identityKeysIn(after.anchors));
2774
- const changed = [...old].filter((id) => !next.has(id)).concat([...next].filter((id) => !old.has(id)));
2775
- const values = (space) => changed.filter((key) => key.startsWith(`${space}:`)).map((key) => Number(key.slice(key.indexOf(":") + 1)));
2776
- return {
2777
- revision: values(IDENTITY_SPACES.REVISION),
2778
- control: values(IDENTITY_SPACES.CONTROL)
2779
- };
2780
- };
2781
- /** Remove only owned anchors, then merge scaffolding with the shared exact field predicate. */
2782
- const ownedSeams = (content, ids) => {
2783
- let references = 0;
2784
- return leafSpans(content).flatMap(({ node, before }) => {
2785
- const id = anchorId(node);
2786
- if (id === void 0 || !ids.has(id)) return [];
2787
- const position = before.offset - references;
2788
- if (node.type === "commentReference") references++;
2789
- return [position];
2544
+ const unowned = (content) => leafSpans(content).filter(({ node }) => {
2545
+ const id = anchorId(node);
2546
+ return id !== void 0 && !ids.has(id);
2547
+ }).map(({ node }) => node);
2548
+ return !structurallyEqual(preserved(entry.content), preserved(expected.content)) || !structurallyEqual(unowned(entry.content), unowned(expected.content));
2549
+ })) return fail(op, "A comment inverse cannot replace text or unowned anchors.");
2550
+ const anchors = restoreAnchors({
2551
+ document,
2552
+ op,
2553
+ anchors: op.state.anchors
2790
2554
  });
2791
- };
2792
- const normalizedWithoutAnchors = ({ content, ids, seams, start = 0 }) => {
2793
- let normalized = [];
2794
- let position = start;
2795
- for (const node of withoutAnchors(content, ids)) {
2796
- const children = childNodes(node);
2797
- const normalizedNode = children === void 0 ? node : rebuildNode(node, normalizedWithoutAnchors({
2798
- content: children,
2799
- ids,
2800
- seams,
2801
- start: position
2802
- }));
2803
- if (seams.has(position)) normalized = mergeAlike(normalized, [normalizedNode]);
2804
- else normalized.push(normalizedNode);
2805
- position += leafSpans([normalizedNode]).at(-1)?.after.offset ?? 0;
2806
- }
2807
- return normalized;
2808
- };
2809
- const isCommentRelationship = (type) => Object.values(COMMENT_PART_RELATIONSHIPS).some((part) => part.type === type);
2810
- /** Keep the same part ids as the packager: numeric rId maximum plus one. */
2811
- const reconcileRelationships = (document) => {
2812
- const comments = document.package.document.comments ?? [];
2813
- const relationships = new Map(document.package.relationships ?? []);
2814
- let next = Math.max(0, ...[...relationships.keys()].map((id) => Number(/^rId(\d+)$/u.exec(id)?.at(1) ?? 0))) + 1;
2815
- const extended = comments.some((comment) => comment.parentId !== void 0 || comment.done !== void 0);
2816
- for (const [kind, part] of Object.entries(COMMENT_PART_RELATIONSHIPS)) {
2817
- const needed = kind === "comments" ? comments.length > 0 : extended;
2818
- const matching = [...relationships].filter(([, relationship]) => relationship.type === part.type);
2819
- if (needed && matching.length === 0) {
2820
- const id = `rId${next++}`;
2821
- relationships.set(id, {
2822
- id,
2823
- type: part.type,
2824
- target: part.target
2825
- });
2826
- }
2827
- if (kind === "commentsExtended" && !needed) for (const [id] of matching) relationships.delete(id);
2555
+ if (anchors.isErr()) return anchors;
2556
+ const comments = (document.package.document.comments ?? []).filter(({ id }) => !ids.has(id));
2557
+ for (const { index, comment } of op.state.records) {
2558
+ if (index > comments.length) return fail(op, "A restored comment declaration position is stale.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2559
+ comments.splice(index, 0, cloneModel(comment));
2828
2560
  }
2829
- if (structurallyEqual([...relationships], [...document.package.relationships ?? []])) return document;
2830
- return {
2831
- ...document,
2832
- package: {
2833
- ...document.package,
2834
- relationships
2835
- }
2836
- };
2837
- };
2838
- const edited = (before, after, op, ids) => {
2839
- if (op.type !== DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE) after = reconcileRelationships(after);
2840
- const invalid = contractViolation(after);
2841
- if (invalid) return fail(op, invalid.message, invalid.reason);
2842
- const issue = commentDocumentIssue(after, orphanRootCommentIds(before));
2843
- if (issue) return fail(op, issue);
2844
- const anchors = changedAnchors(before, after);
2845
- const prior = capture(before, ids, anchors);
2846
- const next = capture(after, ids, anchors);
2847
- if (structurallyEqual(prior, next)) return Result.ok({
2848
- document: before,
2849
- inverse: [],
2850
- touched: {
2851
- modified: [],
2852
- inserted: [],
2853
- removed: []
2854
- }
2855
- });
2856
- return Result.ok({
2857
- document: after,
2858
- inverse: [{
2859
- type: DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE,
2860
- ids: [...ids],
2861
- scaffoldIds: scaffoldDelta(prior, next),
2862
- expected: cloneModel(next),
2863
- state: cloneModel(prior)
2864
- }],
2865
- touched: {
2866
- modified: anchors.map(({ blockId }) => blockId),
2867
- inserted: [],
2868
- removed: []
2869
- }
2870
- });
2871
- };
2872
- const withComments = (document, comments, presence = "present") => {
2873
- const body = { ...document.package.document };
2874
- switch (presence) {
2561
+ if (op.state.listPresence !== "present" && comments.length > 0) return fail(op, "A missing comment list cannot discard unowned definitions.");
2562
+ const relationships = [...anchors.value.package.relationships ?? []].filter(([, relation]) => !isCommentRelationship(relation.type));
2563
+ for (const { index, key, relationship } of op.state.relationships) {
2564
+ const existing = op.expected.relationships.find((entry) => entry.key === key);
2565
+ if (existing && !structurallyEqual(existing.relationship, relationship)) return fail(op, "A comment inverse cannot alter an existing relationship payload.");
2566
+ if (!isCommentRelationship(relationship.type) || relationship.id !== key || index < 0 || index > relationships.length || relationships.some(([id]) => id === key)) return fail(op, "The comment inverse cannot replace an unowned relationship.");
2567
+ relationships.splice(index, 0, [key, cloneModel(relationship)]);
2568
+ }
2569
+ if (op.state.relationshipPresence !== "present" && relationships.length > 0) return fail(op, "A missing relationship map cannot discard unowned relationships.");
2570
+ const restored = withComments(anchors.value, comments, op.state.listPresence);
2571
+ const pkg = { ...restored.package };
2572
+ switch (op.state.relationshipPresence) {
2875
2573
  case "present":
2876
- body.comments = comments;
2574
+ pkg.relationships = new Map(relationships);
2877
2575
  break;
2878
2576
  case "undefined":
2879
- Reflect.set(body, "comments", void 0);
2577
+ Reflect.set(pkg, "relationships", void 0);
2880
2578
  break;
2881
2579
  case "absent":
2882
- delete body.comments;
2580
+ delete pkg.relationships;
2883
2581
  break;
2884
- default: return presence;
2885
2582
  }
2886
- return {
2887
- ...document,
2888
- package: {
2889
- ...document.package,
2890
- document: body
2583
+ return edited(document, {
2584
+ ...restored,
2585
+ package: pkg
2586
+ }, op, ids);
2587
+ };
2588
+ const revisionRange = (document, story, revisionId) => {
2589
+ const body = findStoryBody(document, story);
2590
+ if (!body) return void 0;
2591
+ const spans = storyParagraphs(body).flatMap(({ paragraph }) => {
2592
+ const leaves = leafSpans(paragraph.content);
2593
+ const position = (gap) => ({
2594
+ story,
2595
+ blockId: paragraph.paraId ?? "",
2596
+ offset: gap.offset,
2597
+ zeroWidthBefore: gap.zeroWidthBefore
2598
+ });
2599
+ if (paragraph.propertyChanges?.some(({ info }) => info.id === revisionId) || paragraph.pPrMark?.info.id === revisionId) {
2600
+ const start = leaves.at(0)?.before ?? {
2601
+ offset: 0,
2602
+ zeroWidthBefore: 0
2603
+ };
2604
+ const end = leaves.at(-1)?.after ?? start;
2605
+ return [{
2606
+ from: position(start),
2607
+ to: position(end)
2608
+ }];
2891
2609
  }
2610
+ return leaves.flatMap((span) => {
2611
+ return [span.node, ...span.ancestors].some((node) => (node.type === "insertion" || node.type === "deletion" || node.type === "moveFrom" || node.type === "moveTo") && node.info.id === revisionId || node.type === "run" && node.propertyChanges?.some(({ info }) => info.id === revisionId)) ? [{
2612
+ from: position(span.before),
2613
+ to: position(span.after)
2614
+ }] : [];
2615
+ });
2616
+ });
2617
+ const first = spans.at(0);
2618
+ const last = spans.at(-1);
2619
+ return first && last ? {
2620
+ from: first.from,
2621
+ to: last.to
2622
+ } : void 0;
2623
+ };
2624
+ const remainingIds = (document, ids) => {
2625
+ const used = new Set(packageIdentityKeys(document.package));
2626
+ return {
2627
+ ...ids?.revision === void 0 ? {} : { revision: ids.revision.filter((id) => !used.has(`${IDENTITY_SPACES.REVISION}:${id}`)) },
2628
+ ...ids?.control === void 0 ? {} : { control: ids.control.filter((id) => !used.has(`${IDENTITY_SPACES.CONTROL}:${id}`)) }
2892
2629
  };
2893
2630
  };
2894
- const withoutAnchors = (nodes, ids) => {
2895
- let changed = false;
2896
- const kept = [];
2897
- for (const node of nodes) {
2898
- const id = anchorId(node);
2899
- if (id !== void 0 && ids.has(id)) {
2900
- changed = true;
2901
- continue;
2631
+ const create = (document, op, applyOps) => {
2632
+ const comments = document.package.document.comments ?? [];
2633
+ if (!validId(op.comment.id) || comments.some(({ id }) => id === op.comment.id) || anchorsIn(document).some(({ node }) => anchorId(node) === op.comment.id) || new Set(packageIdentityKeys(document.package)).has(`${IDENTITY_SPACES.REVISION}:${op.comment.id}`)) return fail(op, "The fresh comment identity is invalid or already used.", DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION);
2634
+ if (Object.hasOwn(op.comment, "parentId")) return fail(op, "Comment parent ownership belongs to the anchor discriminator.");
2635
+ if (op.comment.content.length === 0 || op.comment.content.some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return fail(op, "Comment paragraphs need explicit package paragraph identities.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID);
2636
+ let comment = cloneModel(op.comment);
2637
+ let positions = [];
2638
+ let range;
2639
+ switch (op.anchor.kind) {
2640
+ case "reply": {
2641
+ const parentId = op.anchor.parentId;
2642
+ if (!comments.some(({ id }) => id === parentId)) return fail(op, "The parent comment does not exist.");
2643
+ comment = {
2644
+ ...comment,
2645
+ parentId: op.anchor.parentId
2646
+ };
2647
+ const anchors = anchorsIn(document);
2648
+ const parentById = new Map(comments.map(({ id, parentId: owner }) => [id, owner]));
2649
+ const visited = /* @__PURE__ */ new Set();
2650
+ let anchorOwner = parentId;
2651
+ let parentAnchors = [];
2652
+ while (anchorOwner !== void 0 && !visited.has(anchorOwner)) {
2653
+ visited.add(anchorOwner);
2654
+ const owner = anchorOwner;
2655
+ parentAnchors = anchors.filter(({ node }) => anchorId(node) === owner);
2656
+ if (parentAnchors.length > 0) break;
2657
+ const next = parentById.get(owner);
2658
+ anchorOwner = typeof next === "number" && parentById.has(next) ? next : void 0;
2659
+ }
2660
+ if (parentAnchors.length === 0) return fail(op, "The parent comment has no representable owned anchors.");
2661
+ positions = parentAnchors.toReversed().map(({ story, blockId, node, after }) => {
2662
+ switch (node.type) {
2663
+ case "commentRangeStart":
2664
+ case "commentRangeEnd":
2665
+ case "commentReference": return {
2666
+ at: {
2667
+ story,
2668
+ blockId,
2669
+ offset: after.offset,
2670
+ zeroWidthBefore: after.zeroWidthBefore
2671
+ },
2672
+ content: [{
2673
+ type: node.type,
2674
+ id: comment.id
2675
+ }]
2676
+ };
2677
+ default: return {
2678
+ at: {
2679
+ story,
2680
+ blockId,
2681
+ offset: after.offset,
2682
+ zeroWidthBefore: after.zeroWidthBefore
2683
+ },
2684
+ content: []
2685
+ };
2686
+ }
2687
+ });
2688
+ break;
2902
2689
  }
2903
- const children = childNodes(node);
2904
- const filtered = children === void 0 ? void 0 : withoutAnchors(children, ids);
2905
- if (filtered === children || filtered === void 0) {
2906
- kept.push(node);
2907
- continue;
2690
+ case "revision": {
2691
+ const revisionId = op.anchor.revisionId;
2692
+ if (!validId(revisionId) || comments.some(({ id }) => id === revisionId)) return fail(op, "Revision association cannot ambiguously name a comment parent.");
2693
+ range = revisionRange(document, op.anchor.story, op.anchor.revisionId);
2694
+ if (!range) return fail(op, "The associated revision has no representable source range.");
2695
+ comment = {
2696
+ ...comment,
2697
+ parentId: op.anchor.revisionId
2698
+ };
2699
+ if (range.from.blockId === range.to.blockId && range.from.offset === range.to.offset && range.from.zeroWidthBefore === range.to.zeroWidthBefore) {
2700
+ positions = [{
2701
+ at: range.from,
2702
+ content: [{
2703
+ type: "commentReference",
2704
+ id: comment.id
2705
+ }]
2706
+ }];
2707
+ range = void 0;
2708
+ }
2709
+ break;
2908
2710
  }
2909
- changed = true;
2910
- const next = rebuildNode(node, filtered);
2911
- if (!isEmptyRecord(next)) kept.push(next);
2711
+ case "point":
2712
+ positions = [{
2713
+ at: op.anchor.at,
2714
+ content: [{
2715
+ type: "commentReference",
2716
+ id: comment.id
2717
+ }]
2718
+ }];
2719
+ break;
2720
+ case "range":
2721
+ range = {
2722
+ from: op.anchor.from,
2723
+ to: op.anchor.to
2724
+ };
2725
+ break;
2726
+ default:
2727
+ op.anchor;
2728
+ return fail(op, "The comment anchor discriminator is invalid.");
2729
+ }
2730
+ if (range) {
2731
+ if (!sameStory(range.from.story, range.to.story)) return fail(op, "A comment range must stay in one story.", DOCUMENT_OP_REFUSAL_REASONS.CROSS_BLOCK_RANGE);
2732
+ const body = findStoryBody(document, range.from.story);
2733
+ if (!body) return fail(op, "The comment story does not exist.", DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND);
2734
+ const paragraphs = storyParagraphs(body).map(({ paragraph }) => paragraph);
2735
+ const fromIndex = paragraphs.findIndex(({ paraId }) => idKey(paraId ?? "") === idKey(range.from.blockId));
2736
+ const toIndex = paragraphs.findIndex(({ paraId }) => idKey(paraId ?? "") === idKey(range.to.blockId));
2737
+ const fromParagraph = paragraphs.at(fromIndex);
2738
+ const toParagraph = paragraphs.at(toIndex);
2739
+ if (fromIndex < 0 || toIndex < 0 || !fromParagraph || !toParagraph) return fail(op, "A comment boundary paragraph does not exist.", DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND);
2740
+ const fromGap = range.from.zeroWidthBefore === void 0 ? defaultInsertionGap(fromParagraph.content, range.from.offset) : {
2741
+ offset: range.from.offset,
2742
+ zeroWidthBefore: range.from.zeroWidthBefore
2743
+ };
2744
+ const toGap = range.to.zeroWidthBefore === void 0 ? defaultInsertionGap(toParagraph.content, range.to.offset) : {
2745
+ offset: range.to.offset,
2746
+ zeroWidthBefore: range.to.zeroWidthBefore
2747
+ };
2748
+ if (fromIndex > toIndex || fromIndex === toIndex && compareGaps(fromGap, toGap) > 0) return fail(op, "A comment range cannot run backwards.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET);
2749
+ positions = [{
2750
+ at: {
2751
+ ...range.to,
2752
+ zeroWidthBefore: toGap.zeroWidthBefore
2753
+ },
2754
+ content: [{
2755
+ type: "commentRangeEnd",
2756
+ id: comment.id
2757
+ }, {
2758
+ type: "commentReference",
2759
+ id: comment.id
2760
+ }]
2761
+ }, {
2762
+ at: {
2763
+ ...range.from,
2764
+ zeroWidthBefore: fromGap.zeroWidthBefore
2765
+ },
2766
+ content: [{
2767
+ type: "commentRangeStart",
2768
+ id: comment.id
2769
+ }]
2770
+ }];
2771
+ }
2772
+ let current = withComments(document, [...comments, comment]);
2773
+ for (const { at, content } of positions) {
2774
+ const inserted = applyOps(current, [{
2775
+ type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
2776
+ at,
2777
+ slice: {
2778
+ content,
2779
+ openStart: 0,
2780
+ openEnd: 0
2781
+ },
2782
+ newIds: remainingIds(current, op.newIds)
2783
+ }]);
2784
+ if (inserted.isErr()) return Result.err(inserted.error);
2785
+ current = inserted.value.document;
2786
+ }
2787
+ return edited(document, current, op, /* @__PURE__ */ new Set([comment.id]));
2788
+ };
2789
+ const applyCommentOp = (document, op, applyOps) => {
2790
+ if (op.type === DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE) {
2791
+ if (!Array.isArray(op.ids) || !op.expected || !op.state || !Array.isArray(op.expected.relationships) || !Array.isArray(op.state.relationships) || !Array.isArray(op.expected.records) || !Array.isArray(op.expected.anchors) || !Array.isArray(op.state.records) || !Array.isArray(op.state.anchors)) return fail(op, "The comment inverse payload is invalid.");
2792
+ return restore(document, op);
2793
+ }
2794
+ const issue = commentDocumentIssue(document, "all");
2795
+ if (issue) return fail(op, issue);
2796
+ const orphans = orphanRootCommentIds(document);
2797
+ if (op.type === DOCUMENT_OP_TYPES.CREATE_COMMENT) {
2798
+ if (op.anchor?.kind === "reply" && orphans.has(op.anchor.parentId)) return fail(op, "A comment without a source anchor is preserved read-only.");
2799
+ if (!op.comment || typeof op.comment.author !== "string" || !Array.isArray(op.comment.content) || !op.anchor || typeof op.anchor !== "object") return fail(op, "The comment creation payload is invalid.");
2800
+ return create(document, op, applyOps);
2801
+ }
2802
+ const comments = document.package.document.comments ?? [];
2803
+ const comment = comments.find(({ id }) => id === op.id);
2804
+ if (!comment) return fail(op, "The comment does not exist.");
2805
+ if (orphans.has(comment.id)) return fail(op, "A comment without a source anchor is preserved read-only.");
2806
+ if (op.type === DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT) {
2807
+ if (!Array.isArray(op.content) || op.content.length === 0 || op.content.some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return fail(op, "Comment content needs explicit paragraph identities.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID);
2808
+ if (op.patch && Object.keys(op.patch).some((key) => key !== "author" && key !== "initials" && key !== "date")) return fail(op, "A content edit cannot change comment ownership.");
2809
+ if (op.patch && Object.hasOwn(op.patch, "author") && (op.patch.author === null || op.patch.author === void 0)) return fail(op, "A comment must retain an author.");
2810
+ const updated = {
2811
+ ...comment,
2812
+ ...applyFormattingPatch({
2813
+ author: comment.author,
2814
+ ...Object.hasOwn(comment, "initials") ? { initials: comment.initials } : {},
2815
+ ...Object.hasOwn(comment, "date") ? { date: comment.date } : {}
2816
+ }, op.patch ?? {}),
2817
+ content: cloneModel([...op.content])
2818
+ };
2819
+ if (op.patch?.initials === null) delete updated.initials;
2820
+ if (op.patch?.date === null) delete updated.date;
2821
+ return edited(document, withComments(document, comments.map((value) => value === comment ? updated : value)), op, /* @__PURE__ */ new Set([comment.id]));
2822
+ }
2823
+ if (op.type === DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION) {
2824
+ if (op.status !== "open" && op.status !== "resolved") return fail(op, "Comment resolution status is invalid.");
2825
+ return edited(document, withComments(document, comments.map((value) => value === comment ? {
2826
+ ...comment,
2827
+ done: op.status === "resolved"
2828
+ } : value)), op, /* @__PURE__ */ new Set([comment.id]));
2829
+ }
2830
+ const parentIsComment = comment.parentId !== void 0 && comments.some(({ id }) => id === comment.parentId);
2831
+ if (op.scope !== "thread" && op.scope !== "reply" || op.scope === "reply" !== parentIsComment) return fail(op, "Comment deletion scope must match root or reply ownership.");
2832
+ const ids = /* @__PURE__ */ new Set([comment.id]);
2833
+ for (let previousSize = -1; previousSize !== ids.size;) {
2834
+ previousSize = ids.size;
2835
+ for (const value of comments) if (value.parentId !== void 0 && ids.has(value.parentId)) ids.add(value.id);
2912
2836
  }
2913
- return changed ? kept : nodes;
2914
- };
2915
- const restoreAnchors = ({ document, anchors, op }) => {
2916
2837
  let current = document;
2917
- for (const { story, blockId, content } of anchors) {
2918
- const body = findStoryBody(current, story);
2919
- const location = body && storyParagraphs(body).find(({ paragraph }) => idKey(paragraph.paraId ?? "") === idKey(blockId));
2920
- if (!location) return fail(op, "An owned comment paragraph is missing.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2921
- const changed = replaceParagraphs({
2838
+ for (const story of documentStories(document)) for (const { paragraph } of storyParagraphs(storyBody(document, story))) {
2839
+ const seams = new Set(ownedSeams(paragraph.content, ids));
2840
+ if (seams.size === 0) continue;
2841
+ const content = normalizedWithoutAnchors({
2842
+ content: paragraph.content,
2843
+ ids,
2844
+ seams
2845
+ });
2846
+ if (content === paragraph.content) continue;
2847
+ const changed = restoreAnchors({
2922
2848
  document: current,
2923
- story,
2924
- at: location,
2925
- count: 1,
2926
- replacement: [{
2927
- ...location.paragraph,
2928
- content: cloneModel([...content])
2849
+ op,
2850
+ anchors: [{
2851
+ story,
2852
+ blockId: paragraph.paraId ?? "",
2853
+ content: asParagraphContent(content)
2929
2854
  }]
2930
2855
  });
2931
- if (changed.isErr()) return fail(op, changed.error.message, changed.error.reason);
2856
+ if (changed.isErr()) return changed;
2932
2857
  current = changed.value;
2933
2858
  }
2934
- return Result.ok(current);
2859
+ return edited(document, withComments(current, comments.filter(({ id }) => !ids.has(id)), comments.every(({ id }) => ids.has(id)) ? "absent" : "present"), op, ids);
2935
2860
  };
2936
- const restore = (document, op) => {
2937
- const ids = new Set(op.ids);
2938
- if (ids.size !== op.ids.length || op.ids.some((id) => !validId(id)) || !structurallyEqual(capture(document, ids, op.expected.anchors), op.expected)) return fail(op, "The comment inverse is stale.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2939
- if (op.state.records.some(({ comment, index }) => !ids.has(comment.id) || !Number.isInteger(index) || index < 0) || new Set(op.state.records.map(({ comment }) => comment.id)).size !== op.state.records.length) return fail(op, "The restored comment records do not match the owned identities.");
2940
- if (!op.scaffoldIds || !structurallyEqual(scaffoldDelta(op.expected, op.state), op.scaffoldIds)) return fail(op, "The comment inverse scaffold identities do not match its owned cuts.");
2941
- const allowed = /* @__PURE__ */ new Set([...(op.scaffoldIds.revision ?? []).map((id) => `${IDENTITY_SPACES.REVISION}:${id}`), ...(op.scaffoldIds.control ?? []).map((id) => `${IDENTITY_SPACES.CONTROL}:${id}`)]);
2942
- const identities = (state) => identityKeysIn(state.anchors).filter((id) => !allowed.has(id)).toSorted();
2943
- if (!structurallyEqual(identities(op.expected), identities(op.state))) return fail(op, "The comment inverse changes an unowned identified record.");
2944
- if (op.state.anchors.length !== op.expected.anchors.length || op.state.anchors.some((entry, index) => {
2945
- const expected = op.expected.anchors.at(index);
2946
- if (!expected || !sameStory(entry.story, expected.story) || idKey(entry.blockId) !== idKey(expected.blockId)) return true;
2947
- const seams = /* @__PURE__ */ new Set([...ownedSeams(entry.content, ids), ...ownedSeams(expected.content, ids)]);
2948
- const preserved = (content) => normalizedWithoutAnchors({
2949
- content,
2950
- ids,
2951
- seams
2952
- });
2953
- const unowned = (content) => leafSpans(content).filter(({ node }) => {
2954
- const id = anchorId(node);
2955
- return id !== void 0 && !ids.has(id);
2956
- }).map(({ node }) => node);
2957
- return !structurallyEqual(preserved(entry.content), preserved(expected.content)) || !structurallyEqual(unowned(entry.content), unowned(expected.content));
2958
- })) return fail(op, "A comment inverse cannot replace text or unowned anchors.");
2959
- const anchors = restoreAnchors({
2960
- document,
2961
- op,
2962
- anchors: op.state.anchors
2861
+ //#endregion
2862
+ //#region src/ops/storyLifecycle.ts
2863
+ /** Explicit story lifecycle and section property edits, with exact JSON-safe inverses. */
2864
+ const refuse$5 = (op, message) => Result.err(new DocumentOpRefusal({
2865
+ opType: op.type,
2866
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STRUCTURE_MISMATCH,
2867
+ message
2868
+ }));
2869
+ /** This total projection forces an ownership decision when the body model gains a field. */
2870
+ const bodyValues = (body) => ({
2871
+ content: body.content,
2872
+ background: body.background ?? null,
2873
+ finalSectionProperties: body.finalSectionProperties ?? null,
2874
+ comments: body.comments ?? null
2875
+ });
2876
+ /** Capture only fields owned by the lifecycle delta; absent values survive JSON as null. */
2877
+ const captureStoryParts = (document, owned) => {
2878
+ const body = document.package.document;
2879
+ const values = bodyValues(body);
2880
+ const pkg = document.package;
2881
+ const parts = {};
2882
+ if (owned.body !== void 0) {
2883
+ const fields = {};
2884
+ if (owned.body.content !== void 0) fields.content = values.content;
2885
+ if (owned.body.background !== void 0) fields.background = values.background;
2886
+ if (owned.body.finalSectionProperties !== void 0) fields.finalSectionProperties = values.finalSectionProperties;
2887
+ if (owned.body.comments !== void 0) fields.comments = values.comments;
2888
+ parts.body = fields;
2889
+ }
2890
+ if (owned.sections !== void 0) parts.sections = owned.sections.map(({ index, properties, headers, footers }) => {
2891
+ const fields = { index };
2892
+ const section = body.sections?.at(index);
2893
+ if (!section) return fields;
2894
+ if (properties !== void 0) fields.properties = section.properties;
2895
+ if (headers !== void 0) fields.headers = section.headers ? [...section.headers] : null;
2896
+ if (footers !== void 0) fields.footers = section.footers ? [...section.footers] : null;
2897
+ return fields;
2963
2898
  });
2964
- if (anchors.isErr()) return anchors;
2965
- const comments = (document.package.document.comments ?? []).filter(({ id }) => !ids.has(id));
2966
- for (const { index, comment } of op.state.records) {
2967
- if (index > comments.length) return fail(op, "A restored comment declaration position is stale.", DOCUMENT_OP_REFUSAL_REASONS.STALE);
2968
- comments.splice(index, 0, cloneModel(comment));
2899
+ if (owned.headers !== void 0) parts.headers = pkg.headers ? [...pkg.headers] : null;
2900
+ if (owned.footers !== void 0) parts.footers = pkg.footers ? [...pkg.footers] : null;
2901
+ if (owned.footnotes !== void 0) parts.footnotes = pkg.footnotes ?? null;
2902
+ if (owned.endnotes !== void 0) parts.endnotes = pkg.endnotes ?? null;
2903
+ if (owned.settings !== void 0) parts.settings = pkg.settings ?? null;
2904
+ const undefinedFields = [];
2905
+ const bodyKeys = Object.keys(owned.body ?? {}).filter((key) => key in values).filter((key) => Object.hasOwn(body, key) && Reflect.get(body, key) === void 0);
2906
+ if (bodyKeys.length > 0) undefinedFields.push({
2907
+ target: "body",
2908
+ keys: bodyKeys
2909
+ });
2910
+ const packageKeys = Object.keys(owned).filter((key) => key !== "body" && key !== "sections" && key !== "undefinedFields").filter((key) => Object.hasOwn(pkg, key) && Reflect.get(pkg, key) === void 0);
2911
+ if (packageKeys.length > 0) undefinedFields.push({
2912
+ target: "package",
2913
+ keys: packageKeys
2914
+ });
2915
+ for (const fields of owned.sections ?? []) {
2916
+ const section = body.sections?.at(fields.index);
2917
+ if (!section) continue;
2918
+ const keys = Object.keys(fields).filter((key) => key !== "index").filter((key) => Object.hasOwn(section, key) && Reflect.get(section, key) === void 0);
2919
+ if (keys.length > 0) undefinedFields.push({
2920
+ target: "section",
2921
+ index: fields.index,
2922
+ keys
2923
+ });
2969
2924
  }
2970
- if (op.state.listPresence !== "present" && comments.length > 0) return fail(op, "A missing comment list cannot discard unowned definitions.");
2971
- const relationships = [...anchors.value.package.relationships ?? []].filter(([, relation]) => !isCommentRelationship(relation.type));
2972
- for (const { index, key, relationship } of op.state.relationships) {
2973
- const existing = op.expected.relationships.find((entry) => entry.key === key);
2974
- if (existing && !structurallyEqual(existing.relationship, relationship)) return fail(op, "A comment inverse cannot alter an existing relationship payload.");
2975
- if (!isCommentRelationship(relationship.type) || relationship.id !== key || index < 0 || index > relationships.length || relationships.some(([id]) => id === key)) return fail(op, "The comment inverse cannot replace an unowned relationship.");
2976
- relationships.splice(index, 0, [key, cloneModel(relationship)]);
2925
+ if (undefinedFields.length > 0) parts.undefinedFields = undefinedFields;
2926
+ return parts;
2927
+ };
2928
+ /** Immutable operations share unowned fields; section content is a derived mirror. */
2929
+ const changedParts = (before, after) => {
2930
+ const oldBody = before.package.document;
2931
+ const newBody = after.package.document;
2932
+ const body = {};
2933
+ if (oldBody.content !== newBody.content) body.content = oldBody.content;
2934
+ if (oldBody.background !== newBody.background) body.background = oldBody.background ?? null;
2935
+ if (oldBody.finalSectionProperties !== newBody.finalSectionProperties) body.finalSectionProperties = oldBody.finalSectionProperties ?? null;
2936
+ if (oldBody.comments !== newBody.comments) body.comments = oldBody.comments ?? null;
2937
+ const sections = [];
2938
+ if (oldBody.sections !== newBody.sections) for (const [index, section] of (oldBody.sections ?? []).entries()) {
2939
+ const next = newBody.sections?.at(index);
2940
+ if (section === next) continue;
2941
+ const changes = { index };
2942
+ if (section.properties !== next?.properties) changes.properties = section.properties;
2943
+ if (section.headers !== next?.headers) changes.headers = section.headers ? [...section.headers] : null;
2944
+ if (section.footers !== next?.footers) changes.footers = section.footers ? [...section.footers] : null;
2945
+ if (Object.keys(changes).length > 1) sections.push(changes);
2946
+ }
2947
+ const parts = {};
2948
+ if (Object.keys(body).length > 0) parts.body = body;
2949
+ if (sections.length > 0) parts.sections = sections;
2950
+ if (before.package.headers !== after.package.headers) parts.headers = before.package.headers ? [...before.package.headers] : null;
2951
+ if (before.package.footers !== after.package.footers) parts.footers = before.package.footers ? [...before.package.footers] : null;
2952
+ if (before.package.footnotes !== after.package.footnotes) parts.footnotes = before.package.footnotes ?? null;
2953
+ if (before.package.endnotes !== after.package.endnotes) parts.endnotes = before.package.endnotes ?? null;
2954
+ if (before.package.settings !== after.package.settings) parts.settings = before.package.settings ?? null;
2955
+ return captureStoryParts(before, parts);
2956
+ };
2957
+ const restoreParts = (document, parts) => {
2958
+ const pkg = { ...document.package };
2959
+ let body = document.package.document;
2960
+ if (parts.body !== void 0) {
2961
+ body = { ...body };
2962
+ const fields = parts.body;
2963
+ if (fields.content !== void 0) {
2964
+ const existingBlocks = body.content;
2965
+ body = withBodyContent(body, fields.content.map((block, index) => {
2966
+ const previous = existingBlocks.at(index);
2967
+ return previous && structurallyEqual(block, previous) ? previous : block;
2968
+ }));
2969
+ }
2970
+ if (fields.background !== void 0) if (fields.background === null) delete body.background;
2971
+ else body.background = fields.background;
2972
+ if (fields.finalSectionProperties !== void 0) if (fields.finalSectionProperties === null) delete body.finalSectionProperties;
2973
+ else body.finalSectionProperties = fields.finalSectionProperties;
2974
+ if (fields.comments !== void 0) if (fields.comments === null) delete body.comments;
2975
+ else body.comments = fields.comments;
2976
+ }
2977
+ if (parts.headers !== void 0) if (parts.headers === null) delete pkg.headers;
2978
+ else pkg.headers = new Map(parts.headers.map(([rId, part]) => {
2979
+ const previous = pkg.headers?.get(rId);
2980
+ return [rId, previous && structurallyEqual(previous, part) ? previous : part];
2981
+ }));
2982
+ if (parts.footers !== void 0) if (parts.footers === null) delete pkg.footers;
2983
+ else pkg.footers = new Map(parts.footers.map(([rId, part]) => {
2984
+ const previous = pkg.footers?.get(rId);
2985
+ return [rId, previous && structurallyEqual(previous, part) ? previous : part];
2986
+ }));
2987
+ if (parts.sections !== void 0 && body.sections !== void 0) {
2988
+ const sections = [...body.sections];
2989
+ for (const fields of parts.sections) {
2990
+ const previous = sections.at(fields.index);
2991
+ if (!previous) return panic("Owned lifecycle section is missing after staleness validation.");
2992
+ const section = { ...previous };
2993
+ if (fields.properties !== void 0) section.properties = fields.properties;
2994
+ if (fields.headers !== void 0) if (fields.headers === null) delete section.headers;
2995
+ else section.headers = new Map(fields.headers.map(([variant, part]) => {
2996
+ const rId = section.properties.headerReferences?.find(({ type }) => type === variant)?.rId;
2997
+ const owned = rId === void 0 ? void 0 : pkg.headers?.get(rId);
2998
+ return [variant, owned && structurallyEqual(owned, part) ? owned : part];
2999
+ }));
3000
+ if (fields.footers !== void 0) if (fields.footers === null) delete section.footers;
3001
+ else section.footers = new Map(fields.footers.map(([variant, part]) => {
3002
+ const rId = section.properties.footerReferences?.find(({ type }) => type === variant)?.rId;
3003
+ const owned = rId === void 0 ? void 0 : pkg.footers?.get(rId);
3004
+ return [variant, owned && structurallyEqual(owned, part) ? owned : part];
3005
+ }));
3006
+ sections[fields.index] = section;
3007
+ }
3008
+ body = {
3009
+ ...body,
3010
+ sections
3011
+ };
3012
+ }
3013
+ pkg.document = body;
3014
+ if (parts.footnotes !== void 0) if (parts.footnotes === null) delete pkg.footnotes;
3015
+ else {
3016
+ const current = new Map(pkg.footnotes?.map((note) => [note.id, note]));
3017
+ pkg.footnotes = parts.footnotes.map((note) => {
3018
+ const previous = current.get(note.id);
3019
+ return previous && structurallyEqual(previous, note) ? previous : note;
3020
+ });
3021
+ }
3022
+ if (parts.endnotes !== void 0) if (parts.endnotes === null) delete pkg.endnotes;
3023
+ else {
3024
+ const current = new Map(pkg.endnotes?.map((note) => [note.id, note]));
3025
+ pkg.endnotes = parts.endnotes.map((note) => {
3026
+ const previous = current.get(note.id);
3027
+ return previous && structurallyEqual(previous, note) ? previous : note;
3028
+ });
2977
3029
  }
2978
- if (op.state.relationshipPresence !== "present" && relationships.length > 0) return fail(op, "A missing relationship map cannot discard unowned relationships.");
2979
- const restored = withComments(anchors.value, comments, op.state.listPresence);
2980
- const pkg = { ...restored.package };
2981
- switch (op.state.relationshipPresence) {
2982
- case "present":
2983
- pkg.relationships = new Map(relationships);
3030
+ if (parts.settings !== void 0) if (parts.settings === null) delete pkg.settings;
3031
+ else pkg.settings = parts.settings;
3032
+ for (const fields of parts.undefinedFields ?? []) switch (fields.target) {
3033
+ case "body":
3034
+ for (const key of fields.keys) {
3035
+ if (!parts.body || !Object.hasOwn(parts.body, key) || Reflect.get(parts.body, key) !== null) return panic("Undefined body metadata names an unowned field.");
3036
+ Reflect.set(pkg.document, key, void 0);
3037
+ }
2984
3038
  break;
2985
- case "undefined":
2986
- Reflect.set(pkg, "relationships", void 0);
3039
+ case "package":
3040
+ for (const key of fields.keys) {
3041
+ if (!Object.hasOwn(parts, key) || Reflect.get(parts, key) !== null) return panic("Undefined package metadata names an unowned field.");
3042
+ Reflect.set(pkg, key, void 0);
3043
+ }
2987
3044
  break;
2988
- case "absent":
2989
- delete pkg.relationships;
3045
+ case "section": {
3046
+ const owned = parts.sections?.find(({ index }) => index === fields.index);
3047
+ const section = pkg.document.sections?.at(fields.index);
3048
+ if (!owned || !section) return panic("Undefined section metadata names an unowned section.");
3049
+ for (const key of fields.keys) {
3050
+ if (!Object.hasOwn(owned, key) || Reflect.get(owned, key) !== null) return panic("Undefined section metadata names an unowned field.");
3051
+ Reflect.set(section, key, void 0);
3052
+ }
2990
3053
  break;
3054
+ }
2991
3055
  }
2992
- return edited(document, {
2993
- ...restored,
3056
+ return {
3057
+ ...document,
2994
3058
  package: pkg
2995
- }, op, ids);
3059
+ };
2996
3060
  };
2997
- const revisionRange = (document, story, revisionId) => {
2998
- const body = findStoryBody(document, story);
2999
- if (!body) return void 0;
3000
- const spans = storyParagraphs(body).flatMap(({ paragraph }) => {
3001
- const leaves = leafSpans(paragraph.content);
3002
- const position = (gap) => ({
3003
- story,
3004
- blockId: paragraph.paraId ?? "",
3005
- offset: gap.offset,
3006
- zeroWidthBefore: gap.zeroWidthBefore
3007
- });
3008
- if (paragraph.propertyChanges?.some(({ info }) => info.id === revisionId) || paragraph.pPrMark?.info.id === revisionId) {
3009
- const start = leaves.at(0)?.before ?? {
3010
- offset: 0,
3011
- zeroWidthBefore: 0
3012
- };
3013
- const end = leaves.at(-1)?.after ?? start;
3014
- return [{
3015
- from: position(start),
3016
- to: position(end)
3017
- }];
3061
+ /** Traverse changed blocks only; shared records cannot add, remove or modify an ID. */
3062
+ const changedParagraphs = (before, after) => {
3063
+ const oldParagraphs = /* @__PURE__ */ new Map();
3064
+ const newParagraphs = /* @__PURE__ */ new Map();
3065
+ const collect = (oldContent = [], newContent = []) => {
3066
+ if (oldContent === newContent) return;
3067
+ const oldBlocks = new Set(oldContent);
3068
+ const newBlocks = new Set(newContent);
3069
+ for (const [blocks, shared, output] of [[
3070
+ oldContent,
3071
+ newBlocks,
3072
+ oldParagraphs
3073
+ ], [
3074
+ newContent,
3075
+ oldBlocks,
3076
+ newParagraphs
3077
+ ]]) for (const block of blocks) {
3078
+ if (shared.has(block)) continue;
3079
+ for (const { paragraph } of storyParagraphs({ content: [block] })) output.set(paragraph.paraId ?? "", paragraph);
3018
3080
  }
3019
- return leaves.flatMap((span) => {
3020
- return [span.node, ...span.ancestors].some((node) => (node.type === "insertion" || node.type === "deletion" || node.type === "moveFrom" || node.type === "moveTo") && node.info.id === revisionId || node.type === "run" && node.propertyChanges?.some(({ info }) => info.id === revisionId)) ? [{
3021
- from: position(span.before),
3022
- to: position(span.after)
3023
- }] : [];
3024
- });
3025
- });
3026
- const first = spans.at(0);
3027
- const last = spans.at(-1);
3028
- return first && last ? {
3029
- from: first.from,
3030
- to: last.to
3031
- } : void 0;
3032
- };
3033
- const remainingIds = (document, ids) => {
3034
- const used = new Set(packageIdentityKeys(document.package));
3081
+ };
3082
+ collect(before.package.document.content, after.package.document.content);
3083
+ for (const key of ["headers", "footers"]) {
3084
+ const oldParts = before.package[key];
3085
+ const newParts = after.package[key];
3086
+ if (oldParts === newParts) continue;
3087
+ for (const rId of /* @__PURE__ */ new Set([...oldParts?.keys() ?? [], ...newParts?.keys() ?? []])) collect(oldParts?.get(rId)?.content, newParts?.get(rId)?.content);
3088
+ }
3089
+ for (const key of ["footnotes", "endnotes"]) {
3090
+ const oldNotes = before.package[key];
3091
+ const newNotes = after.package[key];
3092
+ if (oldNotes === newNotes) continue;
3093
+ const oldParts = new Map(oldNotes?.map((note) => [note.id, note]));
3094
+ const newParts = new Map(newNotes?.map((note) => [note.id, note]));
3095
+ for (const id of /* @__PURE__ */ new Set([...oldParts.keys(), ...newParts.keys()])) collect(oldParts.get(id)?.content, newParts.get(id)?.content);
3096
+ }
3035
3097
  return {
3036
- ...ids?.revision === void 0 ? {} : { revision: ids.revision.filter((id) => !used.has(`${IDENTITY_SPACES.REVISION}:${id}`)) },
3037
- ...ids?.control === void 0 ? {} : { control: ids.control.filter((id) => !used.has(`${IDENTITY_SPACES.CONTROL}:${id}`)) }
3098
+ oldParagraphs,
3099
+ newParagraphs
3038
3100
  };
3039
3101
  };
3040
- const create = (document, op, applyOps) => {
3041
- const comments = document.package.document.comments ?? [];
3042
- if (!validId(op.comment.id) || comments.some(({ id }) => id === op.comment.id) || anchorsIn(document).some(({ node }) => anchorId(node) === op.comment.id) || new Set(packageIdentityKeys(document.package)).has(`${IDENTITY_SPACES.REVISION}:${op.comment.id}`)) return fail(op, "The fresh comment identity is invalid or already used.", DOCUMENT_OP_REFUSAL_REASONS.ID_COLLISION);
3043
- if (Object.hasOwn(op.comment, "parentId")) return fail(op, "Comment parent ownership belongs to the anchor discriminator.");
3044
- if (op.comment.content.length === 0 || op.comment.content.some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return fail(op, "Comment paragraphs need explicit package paragraph identities.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID);
3045
- let comment = cloneModel(op.comment);
3046
- let positions = [];
3047
- let range;
3048
- switch (op.anchor.kind) {
3049
- case "reply": {
3050
- const parentId = op.anchor.parentId;
3051
- if (!comments.some(({ id }) => id === parentId)) return fail(op, "The parent comment does not exist.");
3052
- comment = {
3053
- ...comment,
3054
- parentId: op.anchor.parentId
3055
- };
3056
- const anchors = anchorsIn(document);
3057
- const parentById = new Map(comments.map(({ id, parentId: owner }) => [id, owner]));
3058
- const visited = /* @__PURE__ */ new Set();
3059
- let anchorOwner = parentId;
3060
- let parentAnchors = [];
3061
- while (anchorOwner !== void 0 && !visited.has(anchorOwner)) {
3062
- visited.add(anchorOwner);
3063
- const owner = anchorOwner;
3064
- parentAnchors = anchors.filter(({ node }) => anchorId(node) === owner);
3065
- if (parentAnchors.length > 0) break;
3066
- const next = parentById.get(owner);
3067
- anchorOwner = typeof next === "number" && parentById.has(next) ? next : void 0;
3068
- }
3069
- if (parentAnchors.length === 0) return fail(op, "The parent comment has no representable owned anchors.");
3070
- positions = parentAnchors.toReversed().map(({ story, blockId, node, after }) => {
3071
- switch (node.type) {
3072
- case "commentRangeStart":
3073
- case "commentRangeEnd":
3074
- case "commentReference": return {
3075
- at: {
3076
- story,
3077
- blockId,
3078
- offset: after.offset,
3079
- zeroWidthBefore: after.zeroWidthBefore
3080
- },
3081
- content: [{
3082
- type: node.type,
3083
- id: comment.id
3084
- }]
3085
- };
3086
- default: return {
3087
- at: {
3088
- story,
3089
- blockId,
3090
- offset: after.offset,
3091
- zeroWidthBefore: after.zeroWidthBefore
3092
- },
3093
- content: []
3094
- };
3095
- }
3096
- });
3097
- break;
3102
+ const storyLifecycleEdit = (before, after, op) => {
3103
+ const invalid = contractViolation(after);
3104
+ if (invalid) return Result.err(new DocumentOpRefusal({
3105
+ opType: op.type,
3106
+ reason: invalid.reason,
3107
+ message: invalid.message
3108
+ }));
3109
+ const prior = changedParts(before, after);
3110
+ const next = captureStoryParts(after, prior);
3111
+ const { oldParagraphs, newParagraphs } = changedParagraphs(before, after);
3112
+ const oldIds = new Set(oldParagraphs.keys());
3113
+ const newIds = new Set(newParagraphs.keys());
3114
+ return Result.ok({
3115
+ document: after,
3116
+ inverse: [{
3117
+ type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
3118
+ expected: cloneModel(next),
3119
+ parts: cloneModel(prior)
3120
+ }],
3121
+ touched: {
3122
+ modified: [...newIds].filter((id) => oldIds.has(id) && !structurallyEqual(oldParagraphs.get(id), newParagraphs.get(id))),
3123
+ inserted: [...newIds].filter((id) => !oldIds.has(id)),
3124
+ removed: [...oldIds].filter((id) => !newIds.has(id))
3098
3125
  }
3099
- case "revision": {
3100
- const revisionId = op.anchor.revisionId;
3101
- if (!validId(revisionId) || comments.some(({ id }) => id === revisionId)) return fail(op, "Revision association cannot ambiguously name a comment parent.");
3102
- range = revisionRange(document, op.anchor.story, op.anchor.revisionId);
3103
- if (!range) return fail(op, "The associated revision has no representable source range.");
3104
- comment = {
3105
- ...comment,
3106
- parentId: op.anchor.revisionId
3107
- };
3108
- if (range.from.blockId === range.to.blockId && range.from.offset === range.to.offset && range.from.zeroWidthBefore === range.to.zeroWidthBefore) {
3109
- positions = [{
3110
- at: range.from,
3111
- content: [{
3112
- type: "commentReference",
3113
- id: comment.id
3114
- }]
3115
- }];
3116
- range = void 0;
3117
- }
3118
- break;
3126
+ });
3127
+ };
3128
+ /** Ordered section breaks; the final section follows every paragraph sectPr. */
3129
+ const sectionEnds = (body) => body.content.flatMap((block, index) => block.type === "paragraph" && block.sectionProperties !== void 0 ? [{
3130
+ index,
3131
+ properties: block.sectionProperties
3132
+ }] : []);
3133
+ const sectionPropertiesAt = (document, sectionIndex) => {
3134
+ if (!Number.isInteger(sectionIndex) || sectionIndex < 0) return void 0;
3135
+ const ends = sectionEnds(document.package.document);
3136
+ if (sectionIndex > ends.length) return void 0;
3137
+ return ends.at(sectionIndex)?.properties ?? document.package.document.finalSectionProperties ?? document.package.document.sections?.at(sectionIndex)?.properties ?? {};
3138
+ };
3139
+ const withSectionProperties = (document, sectionIndex, properties) => {
3140
+ const body = document.package.document;
3141
+ const end = sectionEnds(body).at(sectionIndex);
3142
+ let next = { ...body };
3143
+ if (end) {
3144
+ const content = [...body.content];
3145
+ const paragraph = content.at(end.index);
3146
+ if (paragraph?.type === "paragraph") content[end.index] = {
3147
+ ...paragraph,
3148
+ sectionProperties: properties
3149
+ };
3150
+ next = withBodyContent(body, content);
3151
+ } else next.finalSectionProperties = properties;
3152
+ if (next.sections) next.sections = next.sections.map((section, index) => index === sectionIndex ? {
3153
+ ...section,
3154
+ properties
3155
+ } : section);
3156
+ return {
3157
+ ...document,
3158
+ package: {
3159
+ ...document.package,
3160
+ document: next
3119
3161
  }
3120
- case "point":
3121
- positions = [{
3122
- at: op.anchor.at,
3123
- content: [{
3124
- type: "commentReference",
3125
- id: comment.id
3126
- }]
3127
- }];
3162
+ };
3163
+ };
3164
+ const undefinedFieldsIssue = (parts) => {
3165
+ for (const fields of parts.undefinedFields ?? []) switch (fields.target) {
3166
+ case "body":
3167
+ if (fields.keys.some((key) => !parts.body || !Object.hasOwn(parts.body, key) || Reflect.get(parts.body, key) !== null)) return "Undefined body metadata must name owned null fields.";
3128
3168
  break;
3129
- case "range":
3130
- range = {
3131
- from: op.anchor.from,
3132
- to: op.anchor.to
3133
- };
3169
+ case "package":
3170
+ if (fields.keys.some((key) => !Object.hasOwn(parts, key) || Reflect.get(parts, key) !== null)) return "Undefined package metadata must name owned null fields.";
3134
3171
  break;
3135
- default:
3136
- op.anchor;
3137
- return fail(op, "The comment anchor discriminator is invalid.");
3138
- }
3139
- if (range) {
3140
- if (!sameStory(range.from.story, range.to.story)) return fail(op, "A comment range must stay in one story.", DOCUMENT_OP_REFUSAL_REASONS.CROSS_BLOCK_RANGE);
3141
- const body = findStoryBody(document, range.from.story);
3142
- if (!body) return fail(op, "The comment story does not exist.", DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND);
3143
- const paragraphs = storyParagraphs(body).map(({ paragraph }) => paragraph);
3144
- const fromIndex = paragraphs.findIndex(({ paraId }) => idKey(paraId ?? "") === idKey(range.from.blockId));
3145
- const toIndex = paragraphs.findIndex(({ paraId }) => idKey(paraId ?? "") === idKey(range.to.blockId));
3146
- const fromParagraph = paragraphs.at(fromIndex);
3147
- const toParagraph = paragraphs.at(toIndex);
3148
- if (fromIndex < 0 || toIndex < 0 || !fromParagraph || !toParagraph) return fail(op, "A comment boundary paragraph does not exist.", DOCUMENT_OP_REFUSAL_REASONS.BLOCK_NOT_FOUND);
3149
- const fromGap = range.from.zeroWidthBefore === void 0 ? defaultInsertionGap(fromParagraph.content, range.from.offset) : {
3150
- offset: range.from.offset,
3151
- zeroWidthBefore: range.from.zeroWidthBefore
3152
- };
3153
- const toGap = range.to.zeroWidthBefore === void 0 ? defaultInsertionGap(toParagraph.content, range.to.offset) : {
3154
- offset: range.to.offset,
3155
- zeroWidthBefore: range.to.zeroWidthBefore
3156
- };
3157
- if (fromIndex > toIndex || fromIndex === toIndex && compareGaps(fromGap, toGap) > 0) return fail(op, "A comment range cannot run backwards.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_OFFSET);
3158
- positions = [{
3159
- at: {
3160
- ...range.to,
3161
- zeroWidthBefore: toGap.zeroWidthBefore
3162
- },
3163
- content: [{
3164
- type: "commentRangeEnd",
3165
- id: comment.id
3166
- }, {
3167
- type: "commentReference",
3168
- id: comment.id
3169
- }]
3170
- }, {
3171
- at: {
3172
- ...range.from,
3173
- zeroWidthBefore: fromGap.zeroWidthBefore
3174
- },
3175
- content: [{
3176
- type: "commentRangeStart",
3177
- id: comment.id
3178
- }]
3179
- }];
3180
- }
3181
- let current = withComments(document, [...comments, comment]);
3182
- for (const { at, content } of positions) {
3183
- const inserted = applyOps(current, [{
3184
- type: DOCUMENT_OP_TYPES.INSERT_CONTENT,
3185
- at,
3186
- slice: {
3187
- content,
3188
- openStart: 0,
3189
- openEnd: 0
3190
- },
3191
- newIds: remainingIds(current, op.newIds)
3192
- }]);
3193
- if (inserted.isErr()) return Result.err(inserted.error);
3194
- current = inserted.value.document;
3172
+ case "section": {
3173
+ const owned = parts.sections?.find(({ index }) => index === fields.index);
3174
+ if (!owned || fields.keys.some((key) => !Object.hasOwn(owned, key) || Reflect.get(owned, key) !== null)) return "Undefined section metadata must name owned null fields.";
3175
+ break;
3176
+ }
3195
3177
  }
3196
- return edited(document, current, op, /* @__PURE__ */ new Set([comment.id]));
3197
3178
  };
3198
- const applyCommentOp = (document, op, applyOps) => {
3199
- if (op.type === DOCUMENT_OP_TYPES.RESTORE_COMMENT_STATE) {
3200
- if (!Array.isArray(op.ids) || !op.expected || !op.state || !Array.isArray(op.expected.relationships) || !Array.isArray(op.state.relationships) || !Array.isArray(op.expected.records) || !Array.isArray(op.expected.anchors) || !Array.isArray(op.state.records) || !Array.isArray(op.state.anchors)) return fail(op, "The comment inverse payload is invalid.");
3201
- return restore(document, op);
3179
+ const applyStoryLifecycle = (document, op) => {
3180
+ if (op.type === DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS) {
3181
+ const metadataIssue = undefinedFieldsIssue(op.parts);
3182
+ if (metadataIssue) return refuse$5(op, metadataIssue);
3183
+ if (!structurallyEqual(captureStoryParts(document, op.expected), op.expected)) return Result.err(new DocumentOpRefusal({
3184
+ opType: op.type,
3185
+ reason: DOCUMENT_OP_REFUSAL_REASONS.STALE,
3186
+ message: "Story lifecycle inverse is stale."
3187
+ }));
3188
+ return storyLifecycleEdit(document, restoreParts(document, cloneModel(op.parts)), op);
3202
3189
  }
3203
- const issue = commentDocumentIssue(document, "all");
3204
- if (issue) return fail(op, issue);
3205
- const orphans = orphanRootCommentIds(document);
3206
- if (op.type === DOCUMENT_OP_TYPES.CREATE_COMMENT) {
3207
- if (op.anchor?.kind === "reply" && orphans.has(op.anchor.parentId)) return fail(op, "A comment without a source anchor is preserved read-only.");
3208
- if (!op.comment || typeof op.comment.author !== "string" || !Array.isArray(op.comment.content) || !op.anchor || typeof op.anchor !== "object") return fail(op, "The comment creation payload is invalid.");
3209
- return create(document, op, applyOps);
3190
+ const properties = sectionPropertiesAt(document, op.sectionIndex);
3191
+ if (!properties) return refuse$5(op, "The section does not exist.");
3192
+ if (op.type === DOCUMENT_OP_TYPES.SET_SECTION_PROPS) {
3193
+ const nextProps = applyFormattingPatch(properties, op.patch) ?? {};
3194
+ let next = withSectionProperties(document, op.sectionIndex, nextProps);
3195
+ if (op.patch.evenAndOddHeaders !== void 0 && (op.patch.evenAndOddHeaders !== null || next.package.settings !== void 0)) {
3196
+ const settings = { ...next.package.settings ?? { defaultTabStop: 720 } };
3197
+ if (op.patch.evenAndOddHeaders === null) delete settings.evenAndOddHeaders;
3198
+ else settings.evenAndOddHeaders = op.patch.evenAndOddHeaders;
3199
+ next = {
3200
+ ...next,
3201
+ package: {
3202
+ ...next.package,
3203
+ settings
3204
+ }
3205
+ };
3206
+ }
3207
+ return storyLifecycleEdit(document, next, op);
3210
3208
  }
3211
- const comments = document.package.document.comments ?? [];
3212
- const comment = comments.find(({ id }) => id === op.id);
3213
- if (!comment) return fail(op, "The comment does not exist.");
3214
- if (orphans.has(comment.id)) return fail(op, "A comment without a source anchor is preserved read-only.");
3215
- if (op.type === DOCUMENT_OP_TYPES.UPDATE_COMMENT_CONTENT) {
3216
- if (!Array.isArray(op.content) || op.content.length === 0 || op.content.some(({ paraId }) => paraId === void 0 || !isParaId(paraId))) return fail(op, "Comment content needs explicit paragraph identities.", DOCUMENT_OP_REFUSAL_REASONS.INVALID_BLOCK_ID);
3217
- if (op.patch && Object.keys(op.patch).some((key) => key !== "author" && key !== "initials" && key !== "date")) return fail(op, "A content edit cannot change comment ownership.");
3218
- if (op.patch && Object.hasOwn(op.patch, "author") && (op.patch.author === null || op.patch.author === void 0)) return fail(op, "A comment must retain an author.");
3219
- const updated = {
3220
- ...comment,
3221
- ...applyFormattingPatch({
3222
- author: comment.author,
3223
- ...Object.hasOwn(comment, "initials") ? { initials: comment.initials } : {},
3224
- ...Object.hasOwn(comment, "date") ? { date: comment.date } : {}
3225
- }, op.patch ?? {}),
3226
- content: cloneModel([...op.content])
3209
+ const kind = op.story.kind;
3210
+ const refs = kind === "header" ? properties.headerReferences : properties.footerReferences;
3211
+ const parts = kind === "header" ? document.package.headers : document.package.footers;
3212
+ const nextParts = new Map(parts);
3213
+ let nextRefs = [...refs ?? []];
3214
+ const nextProps = { ...properties };
3215
+ if (op.type === DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER) {
3216
+ 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.");
3217
+ if (op.content.length === 0 || storyParagraphs({ content: op.content }).length === 0) return refuse$5(op, "A header/footer needs an addressable paragraph.");
3218
+ const part = {
3219
+ type: kind,
3220
+ hdrFtrType: op.referenceType,
3221
+ content: cloneModel(op.content)
3227
3222
  };
3228
- if (op.patch?.initials === null) delete updated.initials;
3229
- if (op.patch?.date === null) delete updated.date;
3230
- return edited(document, withComments(document, comments.map((value) => value === comment ? updated : value)), op, /* @__PURE__ */ new Set([comment.id]));
3231
- }
3232
- if (op.type === DOCUMENT_OP_TYPES.SET_COMMENT_RESOLUTION) {
3233
- if (op.status !== "open" && op.status !== "resolved") return fail(op, "Comment resolution status is invalid.");
3234
- return edited(document, withComments(document, comments.map((value) => value === comment ? {
3235
- ...comment,
3236
- done: op.status === "resolved"
3237
- } : value)), op, /* @__PURE__ */ new Set([comment.id]));
3238
- }
3239
- const parentIsComment = comment.parentId !== void 0 && comments.some(({ id }) => id === comment.parentId);
3240
- if (op.scope !== "thread" && op.scope !== "reply" || op.scope === "reply" !== parentIsComment) return fail(op, "Comment deletion scope must match root or reply ownership.");
3241
- const ids = /* @__PURE__ */ new Set([comment.id]);
3242
- for (let previousSize = -1; previousSize !== ids.size;) {
3243
- previousSize = ids.size;
3244
- for (const value of comments) if (value.parentId !== void 0 && ids.has(value.parentId)) ids.add(value.id);
3245
- }
3246
- let current = document;
3247
- for (const story of documentStories(document)) for (const { paragraph } of storyParagraphs(storyBody(document, story))) {
3248
- const seams = new Set(ownedSeams(paragraph.content, ids));
3249
- if (seams.size === 0) continue;
3250
- const content = normalizedWithoutAnchors({
3251
- content: paragraph.content,
3252
- ids,
3253
- seams
3223
+ nextParts.set(op.story.rId, part);
3224
+ nextRefs.push({
3225
+ type: op.referenceType,
3226
+ rId: op.story.rId
3254
3227
  });
3255
- if (content === paragraph.content) continue;
3256
- const changed = restoreAnchors({
3257
- document: current,
3258
- op,
3259
- anchors: [{
3260
- story,
3261
- blockId: paragraph.paraId ?? "",
3262
- content: asParagraphContent(content)
3263
- }]
3228
+ if (op.referenceType === "first") nextProps.titlePg = true;
3229
+ if (op.referenceType === "even") nextProps.evenAndOddHeaders = true;
3230
+ } else {
3231
+ 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.");
3232
+ nextRefs = nextRefs.filter(({ type }) => type !== op.referenceType);
3233
+ 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);
3234
+ }
3235
+ if (kind === "header") nextProps.headerReferences = nextRefs;
3236
+ else nextProps.footerReferences = nextRefs;
3237
+ let next = withSectionProperties(document, op.sectionIndex, nextProps);
3238
+ next = kind === "header" ? {
3239
+ ...next,
3240
+ package: {
3241
+ ...next.package,
3242
+ headers: nextParts
3243
+ }
3244
+ } : {
3245
+ ...next,
3246
+ package: {
3247
+ ...next.package,
3248
+ footers: nextParts
3249
+ }
3250
+ };
3251
+ if (op.type === DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER && op.referenceType === "even") next = {
3252
+ ...next,
3253
+ package: {
3254
+ ...next.package,
3255
+ settings: {
3256
+ ...next.package.settings ?? { defaultTabStop: 720 },
3257
+ evenAndOddHeaders: true
3258
+ }
3259
+ }
3260
+ };
3261
+ if (next.package.document.sections) {
3262
+ const sections = next.package.document.sections.map((section, index) => {
3263
+ if (index !== op.sectionIndex) return section;
3264
+ const bound = new Map(kind === "header" ? section.headers : section.footers);
3265
+ const part = nextParts.get(op.story.rId);
3266
+ if (op.type === DOCUMENT_OP_TYPES.CREATE_HEADER_FOOTER && part) bound.set(op.referenceType, part);
3267
+ else bound.delete(op.referenceType);
3268
+ return kind === "header" ? {
3269
+ ...section,
3270
+ headers: bound
3271
+ } : {
3272
+ ...section,
3273
+ footers: bound
3274
+ };
3264
3275
  });
3265
- if (changed.isErr()) return changed;
3266
- current = changed.value;
3276
+ next = {
3277
+ ...next,
3278
+ package: {
3279
+ ...next.package,
3280
+ document: {
3281
+ ...next.package.document,
3282
+ sections
3283
+ }
3284
+ }
3285
+ };
3267
3286
  }
3268
- return edited(document, withComments(current, comments.filter(({ id }) => !ids.has(id)), comments.every(({ id }) => ids.has(id)) ? "absent" : "present"), op, ids);
3287
+ return storyLifecycleEdit(document, next, op);
3269
3288
  };
3270
3289
  //#endregion
3271
3290
  //#region src/ops/gaps.ts
@@ -13602,7 +13621,7 @@ const validateDocumentBatch = (value) => {
13602
13621
  message: "Batch must contain plain JSON data"
13603
13622
  }));
13604
13623
  const encoded = Result.try(() => JSON.stringify(value));
13605
- if (encoded.isErr() || new TextEncoder().encode(encoded.value).byteLength > 262144) return Result.err(new BatchRejection({
13624
+ if (encoded.isErr() || encodeUtf8(encoded.value).byteLength > 262144) return Result.err(new BatchRejection({
13606
13625
  reason: BATCH_REJECTION_REASONS.INVALID_BATCH,
13607
13626
  message: "Batch exceeds its JSON wire size limit"
13608
13627
  }));
@@ -13613,7 +13632,7 @@ const validateDocumentBatch = (value) => {
13613
13632
  }));
13614
13633
  const decoded = decodeDocumentBatch(normalized.value);
13615
13634
  if (decoded.isErr()) return decoded;
13616
- if (new TextEncoder().encode(JSON.stringify(decoded.value)).byteLength > 262144) return Result.err(new BatchRejection({
13635
+ if (encodeUtf8(JSON.stringify(decoded.value)).byteLength > 262144) return Result.err(new BatchRejection({
13617
13636
  reason: BATCH_REJECTION_REASONS.INVALID_BATCH,
13618
13637
  message: "Captured batch exceeds its JSON wire size limit"
13619
13638
  }));
@@ -13677,7 +13696,7 @@ const validateSequencedBatch = (value) => {
13677
13696
  };
13678
13697
  /** Parse the wire representation without propagating parser exceptions. */
13679
13698
  const parseDocumentBatch = (json) => {
13680
- if (new TextEncoder().encode(json).byteLength > 262144) return Result.err(new BatchRejection({
13699
+ if (encodeUtf8(json).byteLength > 262144) return Result.err(new BatchRejection({
13681
13700
  reason: BATCH_REJECTION_REASONS.INVALID_BATCH,
13682
13701
  message: "Batch exceeds its JSON wire size limit"
13683
13702
  }));
@@ -14464,4 +14483,4 @@ const createClient = (document) => {
14464
14483
  };
14465
14484
  };
14466
14485
  //#endregion
14467
- 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, allocateCommentAnchorIds, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, commentDocumentIssue, compareGaps, compileEditorIntent, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, documentStories, editorParagraphGroups, editorPositionAtPhysicalPosition, findStoryBody, formattingEquals, freshCommentId, idKey, inlineLeafSpans, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, packageParagraphIds, packageResourcesOpOf, paragraphLength, paragraphLogicalText, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, registerParagraphPropertySnapshot, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, storyBody, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, zeroWidthLeavesAt };
14486
+ 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, allocateCommentAnchorIds, applyDocumentOp, applyDocumentOpEnvelope, applyDocumentOps, captureDocumentOp, combineEdits, commentDocumentIssue, compareGaps, compileEditorIntent, createClient, createEditorIntentIdAllocator, createSequencer, defaultInsertionGap, documentStories, editorParagraphGroups, editorPositionAtPhysicalPosition, findStoryBody, formattingEquals, freshCommentId, idKey, inlineLeafSpans, isTextOnlyRun, mapTocBookmarkPosition, mergeRunContent, normalizeForOps, noteUsesCustomMark, packageParagraphIds, packageResourcesOpOf, paragraphLength, paragraphLogicalText, paragraphVisibleText, parseDocumentBatch, physicalOffsetAtVisibleOffset, physicalPositionAtEditorOffset, planTrackedDeletion, planTrackedReplace, reconcileDocumentPartRelationships, registerParagraphPropertySnapshot, revisionIdDemand, runsMergeable, sameStory, sectionPropertiesAt, storyBody, toOpEnvelope, transformBatch, validateDocumentBatch, validateOpsDocument, validateSequencedBatch, withBodyContent, zeroWidthLeavesAt };